Custom inserter for std::copy

后端 未结 2 1461
心在旅途
心在旅途 2020-12-16 21:03

Given a std::vector which holds objects of MyClass. How can I create another vector which holds just data of one member of MyClass using std::copy?

2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-16 21:27

    You want to use std::transform not std::copy and std::bind to bind to a pointer to a member variable:

    #include 
    #include 
    #include 
    #include 
    #include 
    
    struct foo {
      int a;
    };
    
    int main() {
      const std::vector f = {{0},{1},{2}};
      std::vector 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(std::cout, "\n"));
    }
    

    My example is C++11, but if you skip the handy vector initalization and use boost::bind instead this works just as well without C++11.

提交回复
热议问题