删除结构c ++向量中的重复项

时间:2014-09-12 15:14:09

标签: c++ vector structure unique duplicate-removal

我有以下结构。我想将结构存储在矢量中。其次,我想删除(context)上的重复值。我究竟做错了什么?


#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

//Structure
struct contextElement
{
  string context;
  float x;
};

int main()
{
  vector<contextElement> v1;
  v1.push_back({"1",1.0});
  v1.push_back({"2",2.0});
  v1.push_back({"1",1.0});
  v1.push_back({"1",1.0});
  //ERROR here
  auto comp = [] ( const contextElement& lhs, const contextElement& rhs ) {return lhs.context == rhs.context;};
  //Remove elements that have the same context
  v1.erase(std::unique(v1.begin(), v1.end(),comp));
  for(size_t i = 0; i < v1.size();i++)
  {
    cout << v1[i].context <<"  ";
  }
  cout << endl;
  return 0;
}

错误:

  

main.cpp | 23 |错误:没有匹配的调用函数   'std :: vector :: erase(__ gnu_cxx :: __ normal_iterator&gt;,std :: vector :: iterator,   主():: __ lambda0&安培)'|


可能的解决方案

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

//Structure
struct contextElement
{
  string context;
  float x;
};

int main()
{
  vector<contextElement> v1;
  v1.push_back({"1",1.0});
  v1.push_back({"2",2.0});
  v1.push_back({"1",1.0});
  v1.push_back({"1",1.0});
  //sort elements@HaniGoc: unique only removes consecutive duplicates. If you want to move all //duplicates, then either sort it first, or do something more complicated. –  Mike Seymour
  auto comp = [] ( const contextElement& lhs, const contextElement& rhs ) {return lhs.context < rhs.context;};
  sort(v1.begin(), v1.end(),comp);

  auto comp1 = [] ( const contextElement& lhs, const contextElement& rhs ) {return lhs.context == rhs.context;};
  auto last = std::unique(v1.begin(), v1.end(),comp1);
  v1.erase(last, v1.end());

  for(size_t i = 0; i < v1.size();i++)
  {
    cout << v1[i].context <<"  ";
  }
  return 0;
}

3 个答案:

答案 0 :(得分:6)

vector::erase()不接受谓词。你对std::unique的谓词应该检查是否相等。

答案 1 :(得分:3)

auto comp = [] ( const contextElement& lhs, const contextElement& rhs ) {return lhs.context == rhs.context;};
auto pred = []( const contextElement& lhs, const contextElement& rhs ) {return lhs.context < rhs.context;}
std::sort(v.begin(),v.end(),pred);
auto last = std::unique(v.begin(), v.end(),comp);
v.erase(last, v.end());

答案 2 :(得分:2)

不要将comp传递给erase;它只需要一个迭代器范围。

v1.erase(std::unique(v1.begin(), v1.end(), comp), v1.end());

请注意,这只会删除连续重复项。如果您要删除所有重复项,并且不介意更改顺序,请先排序:

std::sort(v1.begin(), v1.end(),
    [] ( const contextElement& lhs, const contextElement& rhs ) {
        return lhs.context < rhs.context;
    });