Ben*_* Uy 1 c++ struct vector find
我制作了以下程序,其中有一个结构
struct data
{
int integers; //input of integers
int times; //number of times of appearance
}
Run Code Online (Sandbox Code Playgroud)
并且有这个结构的向量
std::vector<data> inputs;
Run Code Online (Sandbox Code Playgroud)
然后我会从一个文件中得到一个整数 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;
Run Code Online (Sandbox Code Playgroud)
我想检查 current_int 是否已经存储在我的向量输入中。我试过研究在向量中查找数据,据说你使用这样的迭代器:
it = std::find(inputs.begin(),inputs.end(),current_int)
Run Code Online (Sandbox Code Playgroud)
但是如果它在结构中,这会起作用吗?请帮忙。
有两种变体find:
find()搜索一个普通值。在您的情况下,您有一个 的向量data,因此传递给的值find()应该是data。find_if() 接受一个谓词,并返回谓词返回 true 的第一个位置。使用后者,您可以轻松匹配结构的一个字段:
auto it = std::find_if(inputs.begin(), inputs.end(),
[current_int] (const data& d) {
return d.integers == current_int;
});
Run Code Online (Sandbox Code Playgroud)
请注意,上面使用了 C++11 lambda 函数。在早期版本的 C++ 中这样做需要您创建一个函子。