类的操作,之前写过比较长的C++代码之后,基本用法都知道了。注意:可以定义私有变量哦!
class MapSum {
private:
map<string, int> pairs;
public:
/** Initialize your data structure here. */
MapSum() {
}
void insert(string key, int val) {
if(pairs.find(key)==pairs.end())
pairs[key] =val;
else
pairs[key]=val;
}
int sum(string prefix) {
int result=0;
for(map<string, int>::iterator it= pairs.begin();it!=pairs.end();it++)
{
string a = it->first;
int b = it->second;
// search perfix from a
if(a.substr(0,prefix.size())==prefix)
result+=b;
}
return result;
}
};
/**
* Your MapSum object will be instantiated and called as such:
* MapSum obj = new MapSum();
* obj.insert(key,val);
* int param_2 = obj.sum(prefix);
*/