C++ 初始化 map<string, vector<string> >

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9950733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:25:25  来源:igfitidea点击:

initializing map<string, vector<string> >

c++mapinitialization

提问by Anand

I am initializing map<string, vector<string> >as follows:

我初始化map<string, vector<string> >如下:

map <string, vector<string> > dict;

dict["USA"].push_back("NYC");
dict["USA"].push_back("LA");
dict["USA"].push_back("Chicago");
dict["USA"].push_back("Dallas");

dict["India"].push_back("Delhi");
dict["India"].push_back("Bombay");

dict["Australia"].push_back("Melbourne");
dict["Australia"].push_back("Sydney");
dict["Australia"].push_back("Adelaide");

I find this cumbersome. The same thing can be done in tclas follows which is cleaner:

我觉得这很麻烦。同样的事情可以做tcl如下,这更干净:

array set dict {
USA {NYC LA Chicago Dallas}
India {Delhi Bombay}
Australia {Melbourne Sydney Adelaide}
}

Is there a more cleaner way to initialize in C++? My compiler is gcc 3.4.6

有没有更简洁的初始化方式C++?我的编译器是gcc 3.4.6

采纳答案by haavee

If you're not afraid of using a bit of C-style macros and some helper constructs you might find this slightly less irritable; the initialization of the map is done in one line; you only need to fill in the data (which you must do anyway).

如果你不害怕使用一点 C 风格的宏和一些辅助结构,你可能会发现这有点不那么烦躁;地图的初始化在一行中完成;您只需要填写数据(无论如何您都必须这样做)。

#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <utility>

using namespace std;

struct entry {
    string  key;
    string* vals;
    size_t  nvals;
};
#define NVAL(x) (sizeof(x)/sizeof(x[0]))

int main( void ) {
    // Create your data 
    string      usa[]      = {"NYC", "LA"};
    string      india[]    = {"Delhi", "Mumbai"};
    entry       dd[] = {
                          {"USA", usa, NVAL(usa)},
                          {"India", india, NVAL(india)}
                        };
    map<string, vector<string> > dict;

    // initialize the map
    for(unsigned int i=0; i<NVAL(dd); i++)
        dict.insert( make_pair(dd[i].key, vector<string>(dd[i].vals, dd[i].vals+dd[i].nvals)) );

    // Verify
    for( map<string,vector<string> >::const_iterator ptr=dict.begin();
         ptr!=dict.end(); ptr++) {
        cout << ptr->first << ": ";
        for( vector<string>::const_iterator eptr=ptr->second.begin();
             eptr!=ptr->second.end(); eptr++)
                cout << *eptr << " ";
        cout << endl;
    }
    return 0;
}

回答by Kerrek SB

Initialization had many limitations in the old C++. Your code is in fact not initializing anything at all; it's just calling a lot of member functions on an already initialized object.

初始化在旧的 C++ 中有很多限制。你的代码实际上根本没有初始化任何东西;它只是在一个已经初始化的对象上调用了很多成员函数。

In the current C++ (C++11) you caninitialize your map properly:

在当前的 C++ (C++11) 中,您可以正确地初始化您的地图:

std::map<std::string, std::vector<std::string>> const dict {
   { "USA", { "NYC", "LA", "Chicago" } },
   { "India", { "Delhi", "Bombay" }    }
};

回答by hatboyzero

If you're not opposed to using the Boost.Assign library and you are using C++ older than C++11, you can do it like this:

如果您不反对使用 Boost.Assign 库并且您使用的 C++ 早于 C++11,则可以这样做:

#include <boost/assign/list_of.hpp>
#include <boost/assign/std/vector.hpp>
#include <map>
#include <string>
#include <vector>

std::map<std::string, vector<std::string> > dict = boost::assign::map_list_of<std::string, std::vector<std::string> >
    ("USA",   boost::assign::list_of<std::string>("NYC")("LA")("Chicago")("Dallas"))
    ("India", boost::assign::list_of<std::string>("Delhi")("Bombay"))
;

回答by Luchian Grigore

You could do this, if C++11 is not available:

如果 C++11 不可用,您可以这样做:

map <string, vector<string> > dict;

string usa[] = { "NYC" , "LA" , "Chicago" , "Dallas" };
dict["USA"] = std::vector<string>(usa,usa+4);