簡體   English   中英

用於std :: copy的自定義插入器

[英]Custom inserter for std::copy

給定一個std::vector來保存MyClass的對象。 如何使用std::copy創建另一個只保存MyClass成員數據的向量? 我想我必須實現一個自定義的back_inserter但到目前為止我無法弄清楚如何做到這一點。

struct MyClass {
   int a;
}

std::vector<MyClass> vec1;

// I could copy that to another vector of type MyClass using std::copy.
std::copy(vec1.begin(), vec1.end(); std::back_inserter(someOtherVec)

// However I want just the data of the member a, how can I do that using std::copy?
std::vector<int> vec2;

使用std::transform

std::transform(vec1.begin(), vec1.end(), std::back_inserter(vec2),
               [](const MyClass& cls) { return cls.a; });

(如果你不能使用C ++ 11,你可以自己創建一個函數對象:

struct AGetter { int operator()(const MyClass& cls) const { return cls.a; } };

std::transform(vec1.begin(), vec1.end(), std::back_inserter(vec2), AGetter());

或者如果你可以使用TR1,請使用std::tr1::bind

std::transform(vec1.begin(), vec1.end(), std::back_inserter(vec2),
               std::tr1::bind(&MyClass::a, std::tr1::placeholders::_1));

BTW,正如@Nawaz在下面評論的那樣,做一個.reserve()來防止在復制過程中不必要的重新分配。

vec2.reserve(vec1.size());
std::transform(...);

您希望使用std::transform而不是std::copystd::bind來綁定到成員變量的指針:

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

struct foo {
  int a;
};

int main() {
  const std::vector<foo> f = {{0},{1},{2}};
  std::vector<int> out;

  out.reserve(f.size());
  std::transform(f.begin(), f.end(), std::back_inserter(out), 
                 std::bind(&foo::a, std::placeholders::_1));

  // Print to prove it worked:
  std::copy(out.begin(), out.end(), std::ostream_iterator<int>(std::cout, "\n"));
}

我的例子是C ++ 11,但是如果你跳過方便的矢量初始化並使用boost::bind ,那么沒有C ++ 11也能正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM