访问 c++映射使用与索引不同的类
假设你有一个类:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
添加构造函数:
Add a constructor:
map
的[]
运算符仅将模板化类作为其参数。相反,您想要的是生成具有您想要的值的类的特定实例的某种方式。在此示例中,添加一个构造函数,让您指定x
应具有的值。然后使用
或者你可以只使用
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 valuex
should have.And then use
Or you can just use
which does the same thing, calling
SomeClass
's constructor implicitly.您不能使用 yes[3],因为这将要求映射存储 SomeClass 和 int 类型的键;
另外,请考虑每次向映射添加新元素时,某个元素的“索引”位置可能会发生变化,因为元素始终按键元素排序。
如果您需要查看某个时间点的元素 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.