0

最初に構造体型で実際のオブジェクトを作成および定義せずに、int キーと構造体である値を含むデータをマップに追加するにはどうすればよいですか? 基本的に私は持っています:

struct myStruct { string name2; int aCnt; std::list<string> theItems; };

// Now I define a map
std::map<string, myStruct> myMap;

// Now I want to add items to myMap.  
mymap["ONE"] = {"TEN", 3, {"p1","p2","p3"}};  // But this doesn't seem to work

// I know I could do something like
myStruct myst;
myst.name2 = "TEN";
myst.aCnt = 3;
...blah blah

mymap["ONE"] = myst;

// But I don't want to have to write all of those lines especially because
// this is being done as an initialization of the map.

ありがとう!

4

1 に答える 1

0

C++11 を使用している場合、このコードは既に機能しています。

#include <iostream>
#include <map>
#include <string>
#include <list>
using namespace std;


struct myStruct { string name2; int aCnt; std::list<string> theItems; };
int main()
{

        // Now I define a map
        std::map<string, myStruct> myMap;

        // Now I want to add items to myMap.
        myMap["ONE"] = {"TEN", 3, {"p1","p2","p3"}};  // But this doesn't seem to work





        return 0;
}

そしてコンパイルします:

burgos@germany:~/test$ g++ struct.cpp -o struct -std=c++11
burgos@germany:~/test$

そうでない場合は運が悪いですが、すべての主要なコンパイラは c++11 の初期化をサポートする必要があります。最新バージョンを入手してください。

于 2013-09-06T21:19:49.743 に答える