繁体   English   中英

int和矢量地图 <int> 在c ++中

[英]Map of int and vector<int> in c++

我一直在使用<map> ,我将地图声明为

map <int , vector<int> > tree;

我正在尝试为它赋值。 我的目标是将多个值作为其键的元素。 像这样的东西:

0=null
1=>0
2=>1,0
3=>2,1,0
4=>3,2,1,0
5=>0

我试图像这样分配到地图但它不起作用。

tree[3]=vector<int>(2,1,0);

你能弄清楚问题出在哪里,或者我如何创建一个兼容Python字典的函数?

编辑: tree[1]=vector<int>(0); tree[2]=vector<int>(1,0); tree[1]=vector<int>(0); tree[2]=vector<int>(1,0); 以上两种分配工作方式。

编辑2:我没有使用c++11

使用C ++ 11,您可以尝试:

tree[3]=vector<int>({2,1,0});

除此之外,这个问题可以使用更多的细节和一些你已经尝试过的代码......

既然你要求C ++ 03答案,那么(比C ++ 11更详细)解决方案将起作用。

tree[3].push_back(2);
tree[3].push_back(1);
tree[3].push_back(0);

你考虑过std::multi_map吗?

#include <map>

int main()
{
    std::multimap<int, int> map;

    for (int i=1; i < 6; i++)
        for (int j=1; j < i; j++)
            map.insert(std::make_pair(i, j));
}

正如Daniel Frey指出的那样,你可以使用

tree[3] = vector<int>({2,1,0})

在类似python的伪代码中,这里使用的向量构造函数是

def vector(arr)

原帖建议您尝试使用表单的构造函数

def vector(*args)

哪个不存在。

如果您不使用C ++ 11,请考虑使用vector其他构造函数之一

没有C ++ 11,代码就不那么优雅了:

tree[0]; // create empty vector for index 0
tree[1].push_back(0);
tree[2].push_back(1);
tree[2].push_back(0);
tree[3].push_back(2);
tree[3].push_back(1);
tree[3].push_back(0);
tree[4].push_back(3);
tree[4].push_back(2);
tree[4].push_back(1);
tree[4].push_back(0);
tree[5].push_back(0);

我并不特别喜欢 va_args,但只要你(用户)不搞乱它,即混合类型,解决方案就会比大多数人更“整洁”。 另一个缺点是你的向量不能包含-1,但是你的示例没有显示它。

#include <vector>
#include <cstdarg>
#include <iostream>

//Unsafe but it works.
template<typename T>
std::vector<T> make_vector(T num, ...) {
    std::vector<T> result;
    va_list args;
    va_start(args,num);
    for(T i = num; i != -1; i = va_arg(args,T))
        result.push_back(i);
    va_end(args);
    return result;
}

int main() {
    std::vector<int> v = make_vector(0,1,2,3,-1); //-1 to stop
    //do stuff with vector v
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM