Using “unique()” on a vector of vectors in C++

前端 未结 2 1569
情深已故
情深已故 2021-01-21 02:27

I hope this is not a duplicate question, but if it is, feel free to point me in the right direction.

I have a vector >.

Is i

相关标签:
2条回答
  • 2021-01-21 02:52

    Yes, as long as your vector is sorted. See unique () STL documentation for details.

    Here is an example of usage:

    #include <vector>
    #include <string>
    #include <algorithm>
    #include <string>
    #include <iostream>
    
    using namespace std;
    
    int main ()
    {
        vector< vector<string> > v;
    
        v.push_back (vector<string> ());
        v.back ().push_back ("A");
    
        v.push_back (vector<string> ());
        v.back ().push_back ("A");
    
        v.push_back (vector<string> ());
        v.back ().push_back ("B");
    
        for (vector< vector<string> >::iterator it = v.begin (); it != v.end (); ++it)
            for (vector<string>::iterator j = it->begin (), j_end = it->end (); j != j_end; ++j)
                cout << *j << endl;
    
        cout << "-------" << endl;
    
        vector< vector<string> >::iterator new_end = unique (v.begin (), v.end ());
        for (vector< vector<string> >::iterator it = v.begin (); it != new_end; ++it)
            for (vector<string>::iterator j = it->begin (), j_end = it->end (); j != j_end; ++j)
                cout << *j << endl;
    }
    
    0 讨论(0)
  • 2021-01-21 03:14

    Looks like it should work -- it would call the == operator on two vector<int> objects so that should work.

    Note that the operator works on groups of duplicates so you may have to sort your outer vector if your duplicates are not grouped already.

    Ref: http://www.sgi.com/tech/stl/unique.html

    0 讨论(0)
提交回复
热议问题