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

半城伤御伤魂 提交于 2019-12-31 01:28:06

问题


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<vector<int> >.

Is it possible to use unique() on this? Something like:

vector<vector<int> > myvec;
//blah blah do something to myvec
vector<vector<int> >::interator it = unique(myvec.begin(), myvec.end());

Would the range myvec.begin() to it be unique?


回答1:


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;
}



回答2:


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



来源:https://stackoverflow.com/questions/3773015/using-unique-on-a-vector-of-vectors-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!