简体   繁体   中英

How can I copy two vectors to other vector in C++

I have two vectors. I want to make a new vector which contains the values of these two vectors. I found that a fast way can be use as

vector<int> original_vector
vector<int> copy_to_vector(original_vector)

However, it does not show how to copy two vectors (above only for one to other). Now my problem is

vector<int> original_vector1
vector<int> original_vector2
//Copy original_vector1 and original_vector2 to copy_to_vector
// Note that original_vector1 or original_vector2 maybe empty
vector<int> copy_to_vector

How can I do it in C++. I am using g++ in Ubuntu

My current solution is

  std::vector<U32> copy_to_vector(original_vector1);
  copy_to_vector.insert(copy_to_vector.end(), original_vector2.begin(), original_vector2.end());
vector<int> copy_to_vector(original_vector1)   
copy_to_vector.reserve(original_vector1.size() + original_vector2.size()); 
copy_to_vector.insert( copy_to_vector.end(), original_vector2.begin(), original_vector2.end());

This solution works fine if one of the vectors or both of them are empty

live demo

It's often a good idea to encapsulate operations like this in a utility function.

RVO takes are of eliding the copy of the return value so this code is as efficient as inlining the operations, but more maintainable and easier to reason about:

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

// utility function to return a new vector which is the
// result of v1 with v2 appended. order is preserved
std::vector<int> combine(const std::vector<int>& v1,
                         const std::vector<int>& v2)
{
    std::vector<int> result;
    result.reserve(v1.size() + v2.size());
    result = v1;
    result.insert(result.end(), v2.begin(), v2.end());
    return result;
}

int main()
{
    using namespace std;

    vector<int> x = { 1, 2, 3 };
    vector<int> y = { 4, 5, 6 };

    auto z = combine(x, y);

    copy(begin(z), end(z), ostream_iterator<int>(cout, "\n"));

    return 0;
}

Use std::back_inserter

#include <iterator>  // back_inserter
#include <algorithm> // copy

vector<int> copy_to_vector;
copy_to_vector.reserve( original_vector1.size() + original_vector2.size() ) // reserve memory for both vectors at once
copy_to_vector = original_vector1;   
std::copy(original_vector2.begin(),original_vector2.end(),std::back_inserter(copy_to_vector));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM