Concatenating two std::vectors

如何连接两个std::vector


vector1.insert( vector1.end(), vector2.begin(), vector2.end() );

If you are using C++11, and wish to move the elements rather than merely copying them, you can use std::move_iterator (http://en.cppreference.com/w/cpp/iterator/move_iterator) along with insert (or copy):

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

int main(int argc, char** argv) {
  std::vector<int> dest{1,2,3,4,5};
  std::vector<int> 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<int>(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 <vector>
#include <iostream>
#include <iterator>

int main(int argc, char** argv) {
  std::vector<std::vector<int>> dest{{1,2,3,4,5}, {3,4}};
  std::vector<std::vector<int>> 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.


我会使用插入功能,如下所示:

vector<int> a, b;
//fill with data
b.insert(b.end(), a.begin(), a.end());
链接地址: http://www.djcxy.com/p/53950.html

上一篇: 如何通过索引擦除std :: vector <>中的元素?

下一篇: 连接两个std ::向量