在结构向量中查找 [英] Find in Vector of a Struct

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

问题描述

我在有结构的情况下编写了以下程序

I made the following program where there is a struct

struct data
{
   int integers; //input of integers
   int times; //number of times of appearance
}

并且有一个该结构的向量

and there is a vector of this struct

std::vector<data> inputs;

然后我将从文件中获取一个current_int的整数

and then I'll get from a file an integer of current_int

std::fstream openFile("input.txt")
int current_int; //current_int is what I want to check if it's in my vector of struct (particularly in inputs.integers)
openFile >> current_int;

,我想检查current_int是否已存储在我的向量输入中. 我已经尝试过研究如何在向量中查找数据,并且应该使用这样的迭代器:

and I wanna check if current_int is already stored in my vector inputs. I've tried researching about finding data in a vector and supposedly you use an iterator like this:

it = std::find(inputs.begin(),inputs.end(),current_int)

但是,如果它在结构中,则可以正常工作吗?请帮忙.

but will this work if it's in a struct? Please help.

推荐答案

两个变体的find :

  • find()搜索纯值.如果您的向量为data,则传递给find()的值应为data.
  • find_if()接受一个谓词,并返回该谓词返回true的第一个位置.
  • find() searches for a plain value. In you case you have a vector of data, so the values passed to find() should be data.
  • find_if() takes a predicate, and returns the first position where the predicates returns true.

使用后者,您可以轻松地匹配结构的一个字段:

Using the latter, you can easily match one field of your struct:

auto it = std::find_if(inputs.begin(), inputs.end(), 
                       [current_int] (const data& d) { 
                          return d.integers == current_int; 
                       });

请注意,上面使用的是C ++ 11 lambda函数.在早期版本的C ++中执行此操作需要您创建函子.

Note that the above uses a C++11 lambda function. Doing this in earlier versions of C++ requires you to create a functor instead.

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

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