CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jan 2003
    Posts
    15

    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;

    }

  2. #2
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,725
    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.

  3. #3
    Join Date
    Feb 2002
    Posts
    5,757
    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
  •  





Click Here to Expand Forum to Full Width

Featured