Reputation: 37
I have a vector full of sets, I am using this piece of code to look for an int in the vector:
for(int j = 0; j <= vector.size(); ++j){
if(vector[j].find(find) != vector[j].end())
std::cout << "FOUND: " << propagator << "\n";
}
}
This will output when 'find' is found, is there anyway of returning the position of that set in the vector
For example if find = 5, and my vector contained the elements:
[0] 2 3
[1] 4 5
Is there anyway I could return the set at position 1, eventually I want to remove the whole set from the array
I have been using
for(int j = 0; j <= vector.size(); ++j){
if(vector[j].find(find) != vector[j].end())
vector.erase (vector.begin()+j);
}
Upvotes: 0
Views: 331
Reputation: 310930
It is not difficult to return the position. For example you could use standard algorithm std::find_if
and then apply function std::distance
to determine the position. Or you can write the function yourself using a loop
std::vector<std::set<int>>::size_type i = 0;
while ( i < v.size() && v[i].find( key ) == v[i].end() ) ++i;
if ( i != v.size() ) v.erase( std::next( v.begin(), i ) );
or
auto it = std::find_if( v.begin(), v.end(),
[&]( const std::set<int> &s )
[
return ( s.find(key ) != s.end() );
} );
if ( it != v.end() ) v.erase( it );
If you need to delete all elements of the vector that contain a given value (key) then you can use standard algorithm std::remove_if
along with member function erase
Upvotes: 3
Reputation: 8607
Additional note: you are going beyond the limit of your vector in this line:
for(int j = 0; j <= vector.size(); ++j){
You have to iterate while j < vector.size()
. Although you can do it with an int
, the type to do it fussily correct is size_t
(that matches vector<T>::size()
:
for(size_t j = 0; j < vector.size(); ++j){
Upvotes: 0
Reputation: 18242
Use what you already have, no need to loop and search again:
vector.erase(vector.begin() + j);
Unless you're wanting to delete multiple sets at a time? That could get (only slightly) more complicated.
Upvotes: 0