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!)
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.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With