【问题标题】:Using "unique()" on a vector of vectors in C++在 C++ 中的向量向量上使用“unique()”
【发布时间】:2010-09-22 19:44:33
【问题描述】:

我希望这不是一个重复的问题,但如果是,请随时为我指出正确的方向。

我有一个vector<vector<int> >

是否可以在此使用unique()?比如:

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

myvec.begin()it 的范围是唯一的吗?

【问题讨论】:

  • 当然,这会产生一系列唯一的vector&lt;int&gt; s,而不是唯一的int s 的范围。
  • 是的,我想要一系列独特的vector&lt;int&gt;s。要获得一系列独特的ints,我可以在每个内部向量上使用 unique,这样就可以了。

标签: c++ algorithm stl vector unique


【解决方案1】:

是的,只要您的矢量已排序。有关详细信息,请参阅unique ()STL 文档。

这是一个使用示例:

#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】:

    看起来它应该可以工作——它会在两个 vector&lt;int&gt; 对象上调用 == 运算符,这样应该可以工作。

    请注意,该运算符适用于重复组,因此如果您的重复项尚未分组,您可能必须对外部向量进行排序。

    参考:http://www.sgi.com/tech/stl/unique.html

    【讨论】:

      猜你喜欢
      • 2016-11-16
      • 2015-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-21
      • 2021-05-22
      相关资源
      最近更新 更多