Concatenate vectors with std :: vector in C ++

1

I wanted to know how you could concatenate two fixes in C ++:

For example

a = {1,2,3,4,5} 
b = {6,7,8,9,10}
c = a + b
//El resultado c = {1,2,3,4,5,6,7,8,9,10} 
    
asked by Walk Rock 24.06.2018 в 06:25
source

2 answers

2

To concatenate these two arrays in a vector, only two simple lines of code are enough:

std::vector<int> c(std::begin(a),std::end(a));
c.insert(c.end(),std::begin(b),std::end(b));

The first creates the vector c and copies the content of the array a into it. The second one simply adds to the vector c the contents of the array b .

If, by some chance, you wanted to do it in another array you have to resort to the use of dynamic memory:

int size_a = std::distance(std::begin(a),std::end(a));
int size_b = std::distance(std::begin(b),std::end(b));
int* c = new int[size_a + size_b];

int* iter = std::copy(std::begin(a),std::end(a),c);
std::copy(std::begin(b),std::end(b),iter);
    
answered by 25.06.2018 / 08:13
source
1

There are several ways to do it here I leave some examples

Given the vectors:

std::vector<int> A = {...};
std::vector<int> B = {...};
std::vector<int> AB;

1.- Copy both vectors

//Así sólo se asigna la memoria necesaria una vez
AB.reserve(A.size() + B.size());
AB.insert(AB.end(), A.begin(), A.end());
AB.insert(AB.end(), B.begin(), B.end());

2.- Another way to copy

AB.reserve(A.size() + B.size());
std::copy(A.begin(), A.end(), std::back_inserter(AB));
std::copy(B.begin(), B.end(), std::back_inserter(AB));

3.- Another one more

AB = A;
AB.reserve(AB.size() + B.size());
AB.insert(AB.end(), B.begin(), B.end());

4.- Finally, if you are not going to need the vectors separately you can move the vector A and avoid making the copy of this vector

AB = std::move(A);
AB.reserve(AB.size() + B.size());
AB.insert(AB.end(), B.begin(), B.end());

As a final detail you can overload the operator + and + = if you want to use the syntax you use as an example

5 .-

template <typename T>
std::vector<T> operator+(const std::vector<T>& A, const std::vector<T>& B)
{
    std::vector<T> AB;
    AB.reserve( A.size() + B.size() );
    AB.insert( AB.end(), A.begin(), A.end() );        
    AB.insert( AB.end(), B.begin(), B.end() );        
    return AB;
}

template <typename T>
std::vector<T>& operator+=(std::vector<T>& A, const std::vector<T>& B)
{
    A.reserve( A.size() + B.size() );                
    A.insert( A.end(), B.begin(), B.end() ); 
    return A;
}

int main(int, char**) {
  std::vector<int> A = {1,2,3};
  std::vector<int> B = {4,5,6};
  std::vector<int> AB = A + B;
  //o 
  std::vector<int> BA;
  BA += B;
  BA += A;
  return 0;
}
    
answered by 04.07.2018 в 06:53