c++ - map 的查找功能有困难

标签 c++ visual-c++

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

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

    };

当我尝试用 m_iter = accounts_map.find(account) 分配 m_iter 时,我收到错误,没有运算符“=”匹配这些操作数。我仔细检查以确保 map 迭代器与实际 map 的类型相同。我不确定哪里不对。

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 成员也是 const。当在 const map 上调用 find() 时,它返回一个 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);

关于c++ - map 的查找功能有困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53713439/

相关文章:

c++ - OpenGL 纹理三角形

c++ - 为什么 union 不允许其元素具有用户定义的构造函数?

c++ - 错误 : ISO C++ forbids declaration of ‘iterator’ with no type

c++ - 由于在 Qt 中拖放导致未知的间歇性崩溃

c++ - C++ 中的什么数据类型等同于 vb6 中的 const CURRENCY?

C++程序深奥地卡住

c++ - const char [22 ]' to ' LPCWSTR'

visual-studio - 存储新类的默认目录?

c++ - #include 在查找预编译头文件时跳过 -- 查找预编译头文件时文件意外结束

c++ - TGridOptions 上二进制表达式的无效操作数