[英]Most readable (in code terms) way to fill a map<string, string> with data on construction in C++03
我有一個map<string, string>
,我需要在構造時使用默認對填充它。 例如"Sam" : "good", "ram" : "bad"
。 在C ++ 03中,如何用構造上的代碼術語最容易理解?
boost::assign::map_list_of
允許您使用一些漂亮的語法來做到這一點,但是如果您不能使用Boost,則可以編寫自己的語法。
#include <map>
#include <string>
template< class Key, class Type, class Traits = std::less<Key>,
class Allocator = std::allocator< std::pair <const Key, Type> > >
class MapInit
{
std::map<Key, Type, Traits, Allocator> myMap_;
/* Disallow default construction */
MapInit();
public:
typedef MapInit<Key, Type, Traits, Allocator> self_type;
typedef typename std::map<Key, Type, Traits, Allocator>::value_type value_type;
MapInit( const Key& key, const Type& value )
{
myMap_[key] = value;
}
self_type& operator()( const Key& key, const Type& value )
{
myMap_[key] = value;
return *this;
}
operator std::map<Key, Type, Traits, Allocator>()
{
return myMap_;
}
};
int main()
{
std::map<int, std::string> myMap =
MapInit<int, std::string>(10, "ten")
(20, "twenty")
(30, "thirty");
}
您可以在C ++ 03中執行此操作的唯一方法是執行
mapName["Key"] = "Value";
如果您有很多,則可以使用一個函數對其進行初始化。
map<std::string,std::string> makeMap() {
map<std::string,std::string> example;
example["Sam"] = "good";
example["Ram"] = "bad";
return example;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.