使用不同于索引的类访问C++映射

使用不同于索引的类访问C++映射,c++,stl,associative-array,C++,Stl,Associative Array,假设您有一个类: class SomeClass{ public: int x; SomeClass(){ x = rand(); } bool operator<(const SomeClass& rhs) const{ return x < rhs.x; } }; 但有没有办法得到这样的东西: yeah[3] = "huh"; 工作?我的意思是,我尝试设置运算符添

假设您有一个类:

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

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

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

yeah[3] = "huh";
工作?我的意思是,我尝试设置运算符添加构造函数:

SomeClass(int y){
    x = y;
}
添加构造函数:

SomeClass(int y){
    x = y;
}
map的[]运算符仅将模板化类作为其参数。相反,您需要的是以某种方式生成具有所需值的类的特定实例。在本例中,添加一个构造函数,用于指定x应该具有的值

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

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

};
或者你可以用

yeah[3] = "huh";
它也做同样的事情,隐式调用SomeClass的构造函数。

map的[]操作符只将模板类作为其参数。相反,您需要的是以某种方式生成具有所需值的类的特定实例。在本例中,添加一个构造函数,用于指定x应该具有的值

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

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

};
或者你可以用

yeah[3] = "huh";
这与隐式调用SomeClass的构造函数的作用相同。

您不能使用yeah[3],因为这需要映射来存储SomeClass和int类型的键; 此外,考虑每次向映射中添加新元素时,某个元素的索引位置可以改变,因为元素总是由键元素排序。 如果您需要查看元素no j的某个时间点,您可以在映射上使用迭代器。

您不能使用yeah[3],因为这需要映射存储SomeClass和int类型的键; 此外,考虑每次向映射中添加新元素时,某个元素的索引位置可以改变,因为元素总是由键元素排序。
如果需要查看元素no j的某个时间点,则可以在映射上使用迭代器。

在该上下文中,3是什么意思?地图上的第三项?在这种情况下,3是什么意思?映射中的第三项?由于构造函数没有显式标记,因此没有必要为映射索引调用它。嗯;已足够。由于构造函数没有显式标记,因此无需为映射索引调用它。嗯;已足够。如果存在可用的转换,编译器将尝试将int转换为SomeClass。其中一个转换是SomeClass上的单参数构造函数,如果定义了该构造函数,则将使用该构造函数。如果存在可用的转换,编译器将尝试将int转换为SomeClass。其中一个转换将是某个类上的单参数构造函数,如果该类已定义,则将使用该构造函数。