C++,下标运算符重载。
俺是菜鸟,对运算符重载一直模模糊糊,请问
假设有这么个例子,我想画股票的涨幅线
公司名称 时间 值
baidu 8:00 2
google 8:00 10
sogou 8:00 6
baidu 9:00 3
google 9:00 10
sogou 9:00 7.。。
假设float data[3][20];//假设data[0],画的是baidu
那怎么设计 float data[baidu][20];//掉用的就是baidu呢
请高手指点
[解决办法]
float 的下标运算是默认类型无法重载
或者你可以把baidu之类的定义为一个整数,或者用自己定义的数据结构这样可以重载字符串的下标运算
[解决办法]
size_t const baidu = 0; 然后把 baidu 当符号用.
[解决办法]
//OK了,拿去玩吧,,要想牛B点还可以改改
#include<iostream>
#include<vector>
#include<map>
#include<string>
using namespace std;
class record{
public:
string operator [](int i){
return vs[i];
}
std::vector<string> vs;//include time and value
};
class table{
public:
std::map<string,record> mrecord;
void insert(string name,string times,string value){
record re;
re.vs.push_back(times);
re.vs.push_back(value);
mrecord.insert(pair <string, record> ( name, re ));
}
record operator [](string str){
std::map<string,record>::iterator i;
i = mrecord.find(str);
return i->second;
}
};
int main(){
table t;
t.insert("google","8:00","20");
cout<<t["google"][1]<<endl;
return 0;
}
[解决办法]
enum {
baidu =0,
google,
sogou
};