0

私はを持っており、map<string, string>構築時にデフォルトのペアで埋める必要があります。のように"Sam" : "good", "ram" : "bad"。C ++ 03で、構築に関するコード用語で最も読みやすくする方法は?

4

2 に答える 2

3

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");
}
于 2012-09-17T03:11:41.340 に答える
1

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;
}
于 2012-09-17T02:58:31.243 に答える