Concatenating two std::vectors

后端 未结 25 2334
予麋鹿
予麋鹿 2020-11-22 12:00

How do I concatenate two std::vectors?

25条回答
  •  心在旅途
    2020-11-22 12:28

    If you are using C++11, and wish to move the elements rather than merely copying them, you can use std::move_iterator along with insert (or copy):

    #include 
    #include 
    #include 
    
    int main(int argc, char** argv) {
      std::vector dest{1,2,3,4,5};
      std::vector src{6,7,8,9,10};
    
      // Move elements from src to dest.
      // src is left in undefined but safe-to-destruct state.
      dest.insert(
          dest.end(),
          std::make_move_iterator(src.begin()),
          std::make_move_iterator(src.end())
        );
    
      // Print out concatenated vector.
      std::copy(
          dest.begin(),
          dest.end(),
          std::ostream_iterator(std::cout, "\n")
        );
    
      return 0;
    }
    

    This will not be more efficient for the example with ints, since moving them is no more efficient than copying them, but for a data structure with optimized moves, it can avoid copying unnecessary state:

    #include 
    #include 
    #include 
    
    int main(int argc, char** argv) {
      std::vector> dest{{1,2,3,4,5}, {3,4}};
      std::vector> src{{6,7,8,9,10}};
    
      // Move elements from src to dest.
      // src is left in undefined but safe-to-destruct state.
      dest.insert(
          dest.end(),
          std::make_move_iterator(src.begin()),
          std::make_move_iterator(src.end())
        );
    
      return 0;
    }
    

    After the move, src's element is left in an undefined but safe-to-destruct state, and its former elements were transfered directly to dest's new element at the end.

提交回复
热议问题