Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing subvector in a vector

Tags:

c++

vector

I have

vector<int> my_vector;
vector<int> other_vector;

with my_vector.size() == 20 and other_vector.size() == 5.

Given int n, with 0 < n < 14, I would like to replace the subvector (my_vector[n], myvector[n+1], ..., myvector[n+4]) with other_vector.

For sure with the stupid code

 for(int i=0; i<5; i++)
 {
      my_vector[n+i] = other_vector[i];
 }

I'm done, but I was wondering if is there a more efficient way to do it. Any suggestion?

(Of course the numbers 20 and 5 are just an example, in my case I have bigger size!)

like image 213
888 Avatar asked Dec 07 '12 09:12

888


People also ask

How do you replace an element in a vector?

To replace an element in Java Vector, set() method of java. util. Vector class can be used. The set() method takes two parameters-the indexes of the element which has to be replaced and the new element.

Can vector elements be changed?

vector:: assign() is an STL in C++ which assigns new values to the vector elements by replacing old ones. It can also modify the size of the vector if necessary.

How do I replace a vector in another C++?

The best option to conditionally replace values in a vector in C++ is using the std::replace_if function. It assigns a new value to all the elements in the specified range for which the provided predicate holds true .


1 Answers

In C++11, a friendly function std::copy_n is added, so you can use it:

 std::copy_n(other_vector.begin(), 5, &my_vector[n]);

In C++03, you could use std::copy as other answers has already mentioned.

like image 101
Nawaz Avatar answered Sep 21 '22 11:09

Nawaz