c++ - 如何在 C++ 的 map STL 中将键作为类插入

标签 c++ dictionary stl

下面的程序有什么问题,为什么我不能用类作为键来初始化 map

#include <iostream>
#include <map>

#include <utility>

using namespace std;

class User
{
    int value_1;
    int value_2;
public:
    User( int num_1, int num_2)
    {
        value_1 = num_1;
        value_2 = num_2;
    }
    int getId(){
        return value_1;
    }
    int getUid(){
        return value_2;
    }
    bool operator< (const User& userObj) const
    {
        if(userObj.value_1 < this->value_1)
            return true;
    }
};

int main()
{
    std::map<User, int> m_UserInfoMap;

    m_UserInfoMap.insert(std::make_pair<User, int>(User(1,2), 100) );
    m_UserInfoMap.insert(std::make_pair<User, int>(User(3,4), 120) );
    m_UserInfoMap.insert(std::make_pair<User, int>(User(5,6), 300) );
    std::map<User, int>::iterator it = m_UserInfoMap.begin();
    for(; it != m_UserInfoMap.end(); it++)
    {
        std::cout<<it->first.getId()<<" :: "<<it->second<<std::endl;
    }
    return 0;
}

在上面的程序中,如果我尝试将 key 添加为一个类,则会出错。 并请告知初始化 map 的不同方法。

最佳答案

std::map value_typestd::pair<const Key, T> , 表示 key 保存为 const .所以你不能像std::cout<<it->first.getId()那样调用非常量成员函数.

你应该改变User::getId() (和 User::getUid() )到 const 成员函数。如:

int getId() const {
//          ~~~~~
    return value_1;
}
int getUid() const {
//           ~~~~~
    return value_2;
}

顺便说一句:当 if 时你没有返回任何东西条件在 operator< 中失败.

bool operator< (const User& userObj) const
{
    if(userObj.value_1 < this->value_1)
        return true;
    else
        return false;  // return for else case
}

或者只是

bool operator< (const User& userObj) const
{
    return userObj.value_1 < this->value_1;
}

关于c++ - 如何在 C++ 的 map STL 中将键作为类插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38692580/

相关文章:

c++ - boost .Asio : The I/O operation has been aborted because of either a thread exit or an application request

c# - 复杂的 LINQ 查询与复杂的 for 循环

c# - 在 C# 中创建三级嵌套字典

c++ - 二叉树的层序遍历

c++ - 数独递归回溯,反递归太早

python - 在 C 和 Python 之间传递 C++ 指针

swift - 我如何在 Swift 中比较两个字典?

c++ - STL vector 删除后的无效迭代器

c++ - random_shuffle 线程安全吗?如果不是,则使用 rand_r

c++ - 强制 format_to_n 使用终止零