Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ : How can I push values into a vector only if that value isn't stored in the vector already?

Tags:

c++

If for example, I was just pushing 200 random numbers into a vector, how can I ensure that duplicates will not be pushed in?

like image 271
Calvin Avatar asked Jan 29 '26 13:01

Calvin


2 Answers

You need to check if the vector already contains the value, if not the push new value, i.e.

std::vector<int>::iterator it;
it = find (myvector.begin(), myvector.end(), newvalue);
if (it == myvector.end()) {
    // newvalue is not found
}

But this could be costly since find method would be checking every value inside myvector. Instead using set or map data structure can be more efficient.

like image 132
miradham Avatar answered Jan 31 '26 03:01

miradham


seems like a map could be a helpful structure instead of a Vector. If you must stick to a Vector then you need to divide your task into two parts; duplication detection and then insertion. Again, your could insert into a map and then read that out into the Vector. In either case the problem is - intrinsically - two problems. Good luck!

like image 32
Monza Avatar answered Jan 31 '26 04:01

Monza



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!