地图查找功能的困难

马修

我无法弄清楚为什么这不能编译。这只是基本的类声明,省略了构造函数/析构函数和其他函数。消息也在其他地方正确定义。

#include <vector>
#include <map>
using namespace std;
class SmartCarrier {
        map<string, vector <Message *>> accounts_map;
        void SearchMessage() const;

    };

当我尝试使用 m_iter 分配时,m_iter = accounts_map.find(account)出现错误,没有运算符“=”与这些操作数匹配。我再次检查以确保地图迭代器与实际地图的类型相同。我不确定什么是不正确的。

void SmartCarrier::SearchMessage() const {
        string account;
        map<string, vector<Message *>>::iterator m_iter;
        cout << "Enter an account: ";
        cin >> account;
        try {
            m_iter = accounts_map.find(account);
            if (m_iter != accounts_map.end) {
                  //code to display account information
            } else {
                throw 'e';
            }
        } catch (char e) {
            cout << "Error: Account not found\n";
        }
    }
雷米勒博

SearchMessage()被声明为const,所以它的this参数指向一个const SmartCarrier对象,所以它的accounts_map成员也是constfind()上调用const map,它返回一个const_iterator代替iterator

此外,accounts_map.end需要accounts_map.end()改为。

此外,以您的方式使用异常只是浪费了您可以(并且应该)摆脱的开销。

试试这个:

void SmartCarrier::SearchMessage() const {
    string account;
    cout << "Enter an account: ";
    cin >> account;
    map<string, vector<Message *>>::const_iterator m_iter = accounts_map.find(account);
    if (m_iter != accounts_map.end()) {
        //code to display account information
    } else {
        cout << "Error: Account not found\n";
    }
}

如果您使用的是 C++11 或更高版本,请考虑使用auto而不是const_iterator显式使用,这也将修复错误:

auto m_iter = accounts_map.find(account);

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章