模板推导:移植到C++11

Template deduction: porting to C++11

以下代码对于 C++14 编译器是合法的

// g++ -std=c++14 -pedantic -pthread main.cpp
// output: 1 2 3 4 5 1 1 1 
#include <algorithm>
#include <vector>
#include <functional>
#include <iterator>
#include <iostream>

int main()
{
  std::vector<int> a = { 1, 2, 3, 2, 4, 5, 1, 1, 3, 5, 1, 5 }, b = { 2, 5, 5, 3 }, c;

  std::copy_if(a.begin(), a.end(), std::back_inserter(c), 
    std::bind(std::less<>(),   // this won't work in pre-C++14
      std::bind(
        std::count<std::vector<int>::iterator, int>, 
          std::bind(static_cast<std::vector<int>::iterator (std::vector<int>::*)()>(&std::vector<int>::begin), &c), 
          std::bind(static_cast<std::vector<int>::iterator (std::vector<int>::*)()>(&std::vector<int>::end), &c), 
          std::placeholders::_1
      ),
      std::bind(
        std::minus<>(), // this won't work in pre-C++14
          std::bind(
            std::count<std::vector<int>::iterator, int>, 
              a.begin(), 
              a.end(), 
              std::placeholders::_1
          ),
          std::bind(
            std::count<std::vector<int>::iterator, int>, 
              b.begin(), 
              b.end(), 
              std::placeholders::_1
          )
      )
    )
  );

  std::copy(c.begin(), c.end(), std::ostream_iterator<int>(std::cout, " "));
  std::cout << std::endl;
}

它旨在从向量 a 的元素创建向量 c,不包括与向量 b 中元素的计数和值匹配的元素。例如。如果 a 包含三个 2 和 b - 其中两个,则 c 中只会出现一个 2。

a) 如何将此代码改编为适用于 C++11? less<> 和 minus<> 参数将是 ...::difference_type 的直观飞跃不起作用,编译器消息也没有帮助

b) 当前版本按顺序删除最后的匹配项。什么代码会删除 first 个匹配项?

真正的答案是不使用 bind()。使用 lambda:

std::copy_if(a.begin(), a.end(), std::back_inserter(c), [&](int elem){
    return std::count(c.begin(), c.end(), elem) <
        std::count(a.begin(), a.end(), elem) - std::count(b.begin(), b.end(), elem);
});

这比 std::bind() 的解决方案短 far,在 C++11 中工作,并且更容易 far了解。而且我们也不需要手动模板推导。

我们也可以这样写:

std::copy_if(a.begin(), a.end(), std::back_inserter(c), [&](int& elem){
    return std::count(&elem + 1, &a[a.size()], elem) >=
        std::count(b.begin(), b.end(), elem);
});

请注意,我现在参考 elem。这也让您更容易了解如何实施您建议的扩展,删除第一个匹配项。这只是改变我们比较的 aelem 的哪一侧:

std::copy_if(a.begin(), a.end(), std::back_inserter(c), [&](int& elem) {
    return std::count(&a[0], &elem, elem) >=
        std::count(b.begin(), b.end(), elem);
});