分配整数向量

时间:2015-04-14 08:02:59

标签: c++ vector

我是c ++的新手。我正在为每个设备实现DHCP指纹 EX:

MOTOROLA = 01 33 03 06 15 26 28 51 58 59
windows 8= 01 15 03 06 44 46 47 31 33 121 249 43

我正在使用Hash Map来获取此键值对,并且代码如下:

#include <map>
#include <vector>
int main()
{
    std::map<std::string, vector<int> > data;
    data["Motorola"] = {01,33,03,06,15,26,28,51,58,59};
    return 0;
}

但是我在{token。

之前得到的错误就像预期的主要表达一样

3 个答案:

答案 0 :(得分:1)

鉴于您对使用gcc 3.4.6(其日期为2006年)的评论,您无法使用C ++ 11功能。

假设您无法升级编译器,则需要执行以下操作。

#include <map>
#include <vector>
#include <string>
int main()
{
    std::map<std::string, std::vector<int> > data;
    int temp[] = {01,33,03,06,15,26,28,51,58,59};
    std::vector<int> temp_as_vec(temp, temp + 10);

    data["Motorola"] = temp_as_vec;
    return 0;
}

10只是temp中元素的数量。

答案 1 :(得分:0)

请注意std::map不是哈希映射实现,而是二叉树实现。如果您正在寻找hashmap,则应使用std::unordered_map

#include <map>
#include <vector>
#include <iostream>

int main()
{
    std::map<std::string, std::vector<int> > data;
    data.emplace("Motorola", std::vector<int> {01,33,03,06,15,26,28,51,58,59} ); 

    return 0;
}

对于与C ++ 98兼容的gcc编译器,请使用以下代码:

#include <map>
#include <vector>
#include <iostream>

int main()
{
    std::map<std::string, std::vector<int> > data;
    int array[]={01,33,03,06,15,26,28,51,58,59} ;
    std::vector<int> temp( array, array+10);
    data["Motorola"]=temp ; 

    return 0;
}

答案 2 :(得分:0)

注意:

这整篇文章是在你拥有符合c ++ 11标准的编译器的前提下编写的,你没有。


我没有在C ++ 11编译器上测试过这个(仅在C ++ 14上),但我注意到了:

1)你忘了在地图的实例化中对矢量进行限定。

2)你没有包括字符串。

3)我还建议您确保为编译器启用c ++ 11模式,如其他地方所述。

#include <map>
#include <vector>
#include <string> //was excluded
int main()
{
    //was ...std::map<std::string, vector<int> > data;
    std::map<std::string, std::vector<int> > data;
    //This should work for c++11 and c++14, as {...} instantiates
    // an initializer_list<int>, for which std::vector has a
    // conversion constructor         
    data["Motorola"] = {01,33,03,06,15,26,28,51,58,59};
    return 0;
}

此致

沃纳