C++, std::transform 按索引替换项目

标签 c++ vector transform replace indices

有2个未排序的int v1和v2 vector ,其中v1包含v2的一个子集

v1: 8 12 4 17
v2: 6 4 14 17 9 0 5 12 8 

有什么办法,如何用 v2 中的位置索引替换 v1 的项目?

v1: 8 7 1 3

用2个for循环写这样的算法是没有问题的...

但是有没有使用 std::transform 的解决方案?

最佳答案

std::transform 与调用 std::find 的函数对象组合:

#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>

struct find_functor
{
  std::vector<int> &haystack;

  find_functor(std::vector<int> &haystack)
    : haystack(haystack)
  {}

  int operator()(int needle)
  {
    return std::find(haystack.begin(), haystack.end(), needle) - haystack.begin();
  }
};

int main()
{
  std::vector<int> v1 = {8, 12,  4, 17};
  std::vector<int> v2 = {6,  4, 14, 17, 9, 0, 5, 12, 8};

  // in c++11:
  std::transform(v1.begin(), v1.end(), v1.begin(), [&v2](int x){
    return std::find(v2.begin(), v2.end(), x) - v2.begin();
  });

  // in c++03:
  std::transform(v1.begin(), v1.end(), v1.begin(), find_functor(v2));

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

  return 0;
}

输出:

$ g++ -std=c++0x test.cpp
$ ./a.out 
v1: 8 7 1 3 

关于C++, std::transform 按索引替换项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9041631/

相关文章:

c++ - 使用单应性绕x/y轴旋转

c++ - 单线程程序明显使用多核

c++ - 模板 :Name resolution:Dependent template arguments : -->can any one tell some more examples for this statement?

c++ - QtWidget 窗口的 QQuickView 子窗口

c++ - std::vector保留区的成本比预期的高

C++ std::vector<>::iterator 不是指针,为什么?

c++ - 使用转换填充 vector 后,新的 c++11 for 循环不起作用

c++ - 内存访问回调?

java移动一个旋转的形状

css - 旋转变换在 FF 中无法正常工作,在 IE 中根本无法工作