|
-
January 29th, 2003, 05:39 AM
#1
Remove Elements from Vector
Hi
I am trying to remove elements from vector "clusters" if they exist in vector "removeCluster".
Any help is appreciated.
--------------------------------------------------------------------
#include <iostream>
#include <string>
#include <vector>
int main()
{
vector<int> clusters;
vector<int> removeClusters;
for (int i = 0; i < 10; i++)
{
clusters.push_back(i);
}
for (int i = 0; i < (clusters.size() ) ; i++)
{
cout << "Cluster Vector " << clusters[i] << endl;
}
removeClusters.push_back(3);
removeClusters.push_back(1);
removeClusters.push_back(11);
for (int i = 0; i < (removeClusters.size() ) ; i++)
{
cout << "Remove Cluster Vector " << removeClusters[i] << endl;
}
// update remain cluster vector
for (int i = 0; i < clusters.size(); i++)
{
for (int j = 0; j < removeClusters.size(); j++)
{
if ( removeClusters[j] == clusters[i] )
{
cout << " Found " << clusters[i] << endl;
}
}
}
return 0;
}
-
January 29th, 2003, 07:46 AM
#2
To remove all elements of a certain value from a vector or string,
you use the "erase-remove" idiom (requires #include <algorithm>):
Code:
v.erase( std::remove( v.begin() , v.end() , VALUE_TO_REMOVE ) , v.end() );
So for your case, you could do the following:
Code:
for (int j = 0; j < removeClusters.size(); ++j)
{
clusters.erase( std::remove(clusters.begin(),clusters.end(),removeClusters[j]) , clusters.end() );
}
Note: erasing from a vector is expensive, so if the
vector to remove from is large, this could be time
consuming. If that is the case,you would need to
explore alternative container solutions.
-
January 29th, 2003, 03:52 PM
#3
remove() does not delete one or more elements from a vector. It moves one or more elements to the end of the vectors. For removal and deallocation, use erase() as mentioned.
Kuphryn
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|