在结构向量中查找元素 [英] Finding an element in a vector of structures
本文介绍了在结构向量中查找元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我按照 https://stackoverflow.com/a/590005/1729501 的说明回答了下面写了代码。
I followed this https://stackoverflow.com/a/590005/1729501 answer and wrote below code.
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
using namespace std;
struct alpha {
int x;
int y;
};
struct find_element
{
int y;
find_element(int y) : y(y) {}
bool operator ==( const alpha& l) const
{
return y == l.y;
}
};
int main() {
std::vector<alpha> vAlpha;
vAlpha[0].x = 10;
vAlpha[0].y = 100;
for(std::vector<alpha>::iterator it = vAlpha.begin(); it != vAlpha.end(); ++it) {
int k = 100;
// trying to find k in the complete vector
if (vAlpha.end() == std::find_if( vAlpha.begin(), vAlpha.end(), find_element(k))) {
cout << " not found! ";
} else {
cout << " found ";
}
}
return 0;
}
这会产生编译错误
In file included from /usr/include/c++/4.7/algorithm:63:0,
from prog.cpp:2: /usr/include/c++/4.7/bits/stl_algo.h: In instantiation of
‘_RandomAccessIterator std::__find_if(_RandomAccessIterator,
_RandomAccessIterator, _Predicate, std::random_access_iterator_tag) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<alpha*,
std::vector<alpha> >; _Predicate = find_element]’:
/usr/include/c++/4.7/bits/stl_algo.h:4490:41: required from ‘_IIter
std::find_if(_IIter, _IIter, _Predicate) [with _IIter =
__gnu_cxx::__normal_iterator<alpha*, std::vector<alpha> >; _Predicate = find_element]’ prog.cpp:30:88: required from here /usr/include/c++/4.7/bits/stl_algo.h:210:4: error: no match for call
to ‘(find_element) (alpha&)’
如果我移动 find_element
main()
内的结构,我得到以下错误,
If I move the find_element
structure inside main()
, I get below error,
prog.cpp: In function ‘int main()’: prog.cpp:31:88: error: no matching
function for call to ‘find_if(std::vector<alpha>::iterator,
std::vector<alpha>::iterator, main()::find_element)’ prog.cpp:31:88:
note: candidate is: In file included from
/usr/include/c++/4.7/algorithm:63:0,
from prog.cpp:2:
有人可以告诉我正确的语法吗?
Could someone please tell me the correct syntax?
推荐答案
你应该为算法提供函数调用运算符( )
,而不是等于运算符 ==
。
You should provide the algorithm with function call operator ()
, not equality operator ==
.
struct find_element
{
int y;
find_element(int y) : y(y) {}
bool operator () ( const alpha& l) const
{
return y == l.y;
}
};
它在C ++中称为functor。有关详细信息,请参见此答案。
It is called functor in C++. See this answer for more detailed information.
这篇关于在结构向量中查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文