Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a vector except one specific element?

Tags:

c++

stl

vector

I have a vector with some values. How can I copy it to another vector, so all the values but a specific one (located at position x - x will be a parameter of course) would be copied?

Moreover, I would like to use the value from location x for something else, so I prefer it will be saved.

Is there an easy way to do it?

like image 860
Adibe7 Avatar asked Nov 02 '25 11:11

Adibe7


1 Answers

How to copy stl vector except one specific value?

You can use std::copy_if:

std::vector<T> v = ....;
std::vector<T> out;
T x = someValue;
std::copy_if(v.begin(), v.end(), std::back_inserter(out), 
             [x](const T& t) { return t != x; });

If you don't have C++11 support, you can use std::remove_copy_if and adjust the predicate's logic accordingly.

like image 168
juanchopanza Avatar answered Nov 05 '25 03:11

juanchopanza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!