如果你能有重名不能使用地圖,這樣你就可以使用這樣的事情:
struct Person
{
Person(const std::string & n, int v) : name(n), val(v) {}
std::string name;
int val;
};
int main()
{
std::vector<Person> people;
people.push_back(Person("Jeff", 0));
people.push_back(Person("Jill", 1));
...
}
如果你想獨特的名字,你可以做這樣的事情:
std::map<std::string, int> people;
people["Jeff"] = 0;
people["Jill"] = 1;
或
std::map<std::string, Person> people;
people["Jeff"] = Person("Jeff",0);
people["Jill"] = Person("Jill",1);
如果您使用此代碼很多,你可以清理重複的殘餘。
template<typename K, typename V>
struct BuildMap
{
BuildMap() : map_() {}
BuildMap<K,V>& operator()(const K & key, const V & value)
{
map_[key]=value;
return *this;
}
std::map<K,V> operator()() { return map_; }
std::map<K,V> map_;
};
std::map<std::string,int> people = BuildMap<std::string,int>()
("Jeff", 0)
("Jill", 1)
("John", 1)
();
希望這給你一些想法。
我會建議你不要實施類似** JSON的東西:使用現有的庫或實現真正的JSON標準。 – ereOn 2010-07-19 07:35:40
你想要什麼?數據結構的文本表示?或者只是用這些數據寫一個「文字」? – dan04 2010-07-19 07:36:37
你的問題是什麼?你想*存儲*或*解析*這些數據? – Philipp 2010-07-19 07:40:24