c++ - 使用与索引不同的类访问 C++ 映射

标签 c++ stl associative-array

假设你有一个类:

class SomeClass{
   public:
      int x;
      SomeClass(){
         x = rand();
      }

      bool operator<(const SomeClass& rhs) const{
         return x < rhs.x;
      }

};

然后你有这个:

map<SomeClass, string> yeah;

显然这会起作用:

yeah[SomeClass()] = "woot";

但是有没有办法得到这样的东西:

yeah[3] = "huh";

工作?我的意思是,除了其他运算符之外,我还尝试设置 operator<(int rhs) ,但没有骰子。这可能吗?

最佳答案

添加构造函数:

SomeClass(int y){
    x = y;
}

关于c++ - 使用与索引不同的类访问 C++ 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5451096/

相关文章:

javascript - 如果关联数组从正则表达式返回,则它是排序索引

javascript - 在关联数组 javascript 中搜索值

c++ - 测量 CPU 时钟速度

c++ - 功能指针与高速音频编程中的更简单开关

c++ - 从 std::string 中提取信息

c++ - C++ 中的 vector 问题

bash - 在 Bash 中将索引数组转换为关联数组

c++ - C++ 函数中返回字符串中最常见字符的错误。多字节字符?

c++ - 如何遍历类指针的 vector

c++ - 当我尝试定义这个 vector< pair< int , pair<int, int>>> vp(n)