在向量中查找结构体

5

我希望在一个向量中查找结构体,但是我遇到了一些麻烦。我阅读了几篇有关此问题的帖子,但它们都只搜索结构体中的一个元素:我想在搜索时能够比较结构体的多个元素。我的结构体和向量定义如下:

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)))’

这说明操作符定义不正确,需要如何解决?有没有人能帮我?如何搜索结构体的多个元素而不仅仅是一个元素?

你能否将你的实际代码发布在像ideone.com这样的网站上吗?这段代码在我的VC10上编译通过。 - Naveen
你的代码还没有完成。it的定义是什么? - Yakov Galka
2
请问您能展示一下 it 的声明吗? - thiton
我假设你已经将it定义为vector<subscription>::iterator了,你做到了吗? - Naveen
愚蠢的错误...我把它定义为vector<int>::iterator it;...谢谢你指出我的错误! - Rogier
运行正常:http://ideone.com/3aZXl - hmjd
1个回答

7
也许您没有为 it 指定类型?
std::vector<subscription>::iterator it = 
    find(subscriptions.begin(), subscriptions.end(), match);

谢谢...我真是太蠢了!我把它定义为vector<int>::iterator it;现在编译通过了! - Rogier

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接