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

发布于 2024-10-27 11:41:16 字数 509 浏览 1 评论 0原文

假设你有一个类:

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";

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

Suppose you have a class:

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

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

};

And then you have this:

map<SomeClass, string> yeah;

Obviously this will work:

yeah[SomeClass()] = "woot";

But is there a way to get something like this:

yeah[3] = "huh";

working? I mean, I tried setting operator<(int rhs) in addition to the other operator, but no dice. Is this possible at all?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

困倦 2024-11-03 11:41:16

添加构造函数:

SomeClass(int y){
    x = y;
}

Add a constructor:

SomeClass(int y){
    x = y;
}
白芷 2024-11-03 11:41:16

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[SomeClass(3)] = "huh";

或者你可以只使用

yeah[3] = "huh";

which 做同样的事情,隐式调用 SomeClass 的构造函数。

map's [] operator only takes the templated class as its parameter. What you want instead is some way of generating a specific instance of your class that has the values you want. In this example, add a constructor that lets you specify the value x should have.

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

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

};

And then use

yeah[SomeClass(3)] = "huh";

Or you can just use

yeah[3] = "huh";

which does the same thing, calling SomeClass's constructor implicitly.

凉墨 2024-11-03 11:41:16

您不能使用 yes[3],因为这将要求映射存储 SomeClassint 类型的键;
另外,请考虑每次向映射添加新元素时,某个元素的“索引”位置可能会发生变化,因为元素始终按键元素排序。
如果您需要查看某个时间点的元素 no j,您可以使用映射上的迭代器。

You can't use yeah[3] as this will require the map to store keys of both SomeClass and int type;
Also, consider that each time you add a new element to the map, the "indexed" position of a certain element can change, as the elements are always mainteined ordered by the key element.
If you need to look at a certain point in time for the element no j, you can use probably use an iterator on the map.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文