删除结构 c++ 向量中的重复项 [英] Remove duplicates in vector of structure c++

查看:33
本文介绍了删除结构 c++ 向量中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following structure. I want to store the structure in a vector. Second i want to remove duplicate values on (context). What am I doing wrong?

#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 >, std::vector::iterator,main()::__lambda0&)'|

main.cpp|23|error: no matching function for call to 'std::vector::erase(__gnu_cxx::__normal_iterator >, std::vector::iterator, main()::__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;
}

推荐答案

vector::erase() 不采用谓词.您对 std::unique 的谓词应该检查相等性.

vector::erase() does not take a predicate. And your predicate to std::unique should check for equality.

这篇关于删除结构 c++ 向量中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆