我一直在使用<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);
以上两种分配工作方式。
EDIT2:我没有使用c++11
答案 0 :(得分:6)
使用C ++ 11,您可以尝试:
tree[3]=vector<int>({2,1,0});
除此之外,问题可以使用更多细节和一些你已经尝试过的代码......
答案 1 :(得分:5)
由于您要求C ++ 03答案,这个(比C ++ 11更详细)解决方案将起作用。
tree[3].push_back(2);
tree[3].push_back(1);
tree[3].push_back(0);
答案 2 :(得分:1)
您考虑过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));
}
答案 3 :(得分:0)
正如Daniel Frey所指出的那样,你可以使用
tree[3] = vector<int>({2,1,0})
在类似python的伪代码中,这里使用的向量构造函数是
def vector(arr)
原帖建议您尝试使用
形式的构造函数def vector(*args)
不存在。
如果您不使用C ++ 11,请考虑使用vector
的{{3}}之一。
答案 4 :(得分:0)
没有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);
答案 5 :(得分: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
}
答案 6 :(得分:0)
请注意,以下两行没有达到您的期望:
tree[1] = vector<int>(0);
tree[2] = vector<int>(1, 0);
对应的vector's constructor的第一个参数是容器的初始大小。第二个参数是用来初始化容器元素的值。因此,第一行构造一个空向量,第二行构造一个具有一个初始化为0的元素的向量。
如其他答案所示,如果您不能使用push_back()
,则C++11 features是一个不错的选择。但是,一旦升级到C ++ 11,您还可以使用嵌套的list initialization来初始化地图,如下所示:
int main() {
std::map<int, std::vector<int>> tree{
{1, {0}}, {2, {1, 0}}, {3, {2, 1, 0}}, {4, { 3, 2, 1, 0 }}, {5, { 0 }}
};
for (auto const &kv : tree) {
std::cout << kv.first << " =>";
for (auto const &i : kv.second)
std::cout << " " << i;
std::cout << std::endl;
}
return 0;
}
输出:
1 => 0
2 => 1 0
3 => 2 1 0
4 => 3 2 1 0
5 => 0