我希望在一个向量中查找结构体,但是我遇到了一些麻烦。我阅读了几篇有关此问题的帖子,但它们都只搜索结构体中的一个元素:我想在搜索时能够比较结构体的多个元素。我的结构体和向量定义如下:
struct subscription {
int tournamentid;
int sessionid;
int matchid;
bool operator==(const subscription& m) const {
return ((m.matchid == matchid)&&(m.sessionid==sessionid)&&(m.tournamentid==tournamentid));
}
};
vector<subscription> subscriptions;
接下来,我想在订阅向量中搜索一个结构体,但由于sessionid和matchid的组合是唯一的,所以我需要同时搜索这两个字段。只搜索其中一个将导致多个结果。
subscription match;
match.tournamentid = 54253876;
match.sessionid = 56066789;
match.matchid = 1108;
subscriptions.push_back(match);
it = find(subscriptions.begin(), subscriptions.end(), match);
在编译过程中,find函数出现以下错误:
这说明操作符定义不正确,需要如何解决?有没有人能帮我?如何搜索结构体的多个元素而不仅仅是一个元素?main.cpp:245:68: error: no match for ‘operator=’ in ‘it = std::find [with _IIter = __gnu_cxx::__normal_iterator >, _Tp = echo_client_handler::subscription](((echo_client_handler*)this)->echo_client_handler::subscriptions.std::vector<_Tp, _Alloc>::begin with _Tp = echo_client_handler::subscription, _Alloc = std::allocator, std::vector<_Tp, _Alloc>::iterator = __gnu_cxx::__normal_iterator >, typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer = echo_client_handler::subscription*, ((echo_client_handler*)this)->echo_client_handler::subscriptions.std::vector<_Tp, _Alloc>::end with _Tp = echo_client_handler::subscription, _Alloc = std::allocator, std::vector<_Tp, _Alloc>::iterator = __gnu_cxx::__normal_iterator >, typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer = echo_client_handler::subscription*, (*(const echo_client_handler::subscription*)(& match)))’
it
的定义是什么? - Yakov Galkait
的声明吗? - thitonit
定义为vector<subscription>::iterator
了,你做到了吗? - Naveenvector<int>::iterator it;
...谢谢你指出我的错误! - Rogier