重载向量下标运算符以采用char *或字符串 [英] Overload vector subscript operator to take a char * or string
问题描述
我试图重载下标运算符-我知道它是元素访问运算符-以采用char *或std :: string.
I am trying to overload the subscript operator -i know it as the element access operator- to take a char * or a std::string.
我有一个结构
struct foo
{
int Age;
const char *Name;
};
和一个std :: vector,它将保存该结构的多个实例.
and a std::vector that will be holding multiple instances of this struct.
std::vector<foo>bar;
我的目标是能够通过按其名称调用它们来访问bar中的每个foo.
my goal is to be able to access each foo in bar by calling them by their name.
std::cout<<"Simon's age is: "<<bar["simon"];
我一直在搜索google很长时间,试图找到一个例子或有待解决的事情,但是没有运气.
I've just been searching google for a long while trying to find an example or something to go off, with no luck.
我认为这会起作用
foo operator[](char *Name)
{
for(int i=0;i<bar.size();i++)
{
if(bar[i].Name == Name){return bar[i];}
}
}
但是显然我在做错事
我确实知道这可以通过std :: map来完成,但是我宁愿使用std :: vector,谢谢.
I do know this could be done with an std::map but i'd rather use an std::vector, thanks.
非常感谢您的帮助,但是您选择提供它.谢谢.
I would greatly appreciate your help however you choose to offer it. Thank you .
推荐答案
要执行所需的操作,需要从std :: vector继承.否则,您将无法重载其方法.
To do what you want requires inheriting from std::vector. Otherwise you can't overload its methods.
类似以下内容(未经测试).
Something like the following (untested).
struct fooVector : public std::vector<foo> {
typedef std::vector<foo> super;
using super::size;
...
foo& operator[](char const* Name) {
super& self=*this;
for(int i=0;i<size();i++)
{
if( ! strcmp( self[i].Name, Name) ){return self[i];}
}
// Need to do something reasonable if not found
}
};
这篇关于重载向量下标运算符以采用char *或字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!