如何在c ++中使用map中的类型数组

时间:2014-07-23 08:09:44

标签: c++

我想要像字典这样的东西,因为这件事,我使用了地图。我想要"键"是一个int和"值"成为一个阵列。为了实现这一目标,我做了以下工作,但我不能再进一步了,

typedef std::string RelArr[2];
std::map<int,RelArr> mymap;

问题我无法将任何内容分配给&#34;值&#34;

mymap.insert(myintnumber,"ValueOfFirstIndex","ValueOfSecondIndex");

我收到此错误:

Multiple markers at this line
    - deduced conflicting types for parameter ‘_InputIterator’ (‘int’ and ‘const char*’)
    - candidates are:
    - no matching function for call to ‘std::map<int, std::basic_string<char> [2]>::insert(int, const char [3], const char 
     [19])’

1 个答案:

答案 0 :(得分:2)

这里有两个问题,第一个是数组无法分配,只能复制到,这使得它们无法放入容器中。请改用std::array

typedef std::array<std::string, 2> RelArr;

第二个问题是关于错误实际告诉你的是你使用std::map::insert函数错误,因为没有重载需要两个字符串文字。

如果您想在std::map中插入元素,只需要这样做。

mymap[myintnumber] = {{ "string1", "string2" }};

或者如果您迫切想要使用insert

auto ret = mymap.insert(std::make_pair<int, RelArr>(
                            myothernumber, {{"hello", "world"}}));
if (ret.second == true)
    std::cout << "Insertion was okay\n";
else
    std::cout << "Insertion failed\n";