[英]C++, with vector<int[2]> can I push_back({someNum1,someNum2})?
I have the vector: 我有矢量:
vector<int[2]> storeInventory; //storeInventory[INDEX#]{ITEMNUM, QUANTITY}
and I am wanting to use the push_back()
method to add new arrays to the inventory vector. 我想使用
push_back()
方法将新数组添加到清单向量中。 Something similar to this: 与此类似的东西:
const int ORANGE = 100001;
const int GRAPE = 100002
storeInventory.push_back({GRAPE,24});
storeInventory.push_back{ORANGE, 30};
However, when I try using the syntax as I have above I get the error Error: excpeted an expression
. 但是,当我尝试使用上面的语法时,我得到错误
Error: excpeted an expression
。 Is what I am trying just not possible, or am I just going about it the wrong way? 我正在尝试的是不可能的,还是我只是以错误的方式去做?
Built-in arrays are not Assignable or CopyConstructible . 内置数组不是可分配的或CopyConstructible 。 This violates container element requirements (at least for C++03 and earlier).
这违反了容器元素要求(至少对于C ++ 03和更早版本)。 In other words, you can't have
std::vector
of int[2]
elements. 换句话说,你不能拥有
int[2]
元素的std::vector
。 You have to wrap your array type to satisfy the above requirements. 您必须包装数组类型以满足上述要求。
As it has already been suggested, std::array
in a perfect candidate for a wrapper type in C++11. 正如已经提出的那样,
std::array
是C ++ 11中包装类型的完美候选者。 Or you can just do 或者你可以做到
struct Int2 {
int a[2];
};
and use std::vector<Int2>
. 并使用
std::vector<Int2>
。
If it's only vector of int[2] you could use: 如果它只是int [2]的向量,你可以使用:
std::vector<std::pair<int, int>> vec
Adding elements: 添加元素:
int a, b;
vec.push_back(std::make_pair(a, b));
storeInventory.push_back({GRAPE, 24});
storeInventory.push_back({ORANGE, 30});
You can try this. 你可以试试这个。 I think you forgot parentheses.
我想你忘记了括号。
I don't believe it's possible to pass arrays like that. 我不相信它可以传递这样的数组。 Consider using
std::array
instead: 考虑使用
std::array
代替:
vector<std::array<int, 2> > storeInventory;
storeInventory.push_back({{GRAPE,24}});
C样式数组不可复制,因此不能用作std::vector
的元素类型。
只需使用std::vector<int *>
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.