[英]C++ how to push_back an array int[10] to std::vector<int[10]>?
#include <vector>
using namespace std;
vector<int[60]> v;
int s[60];
v.push_back(s);
This code in Visual Studio 2015 community report a compile error: Visual Studio 2015社区中的此代码报告编译错误:
Error (active) no instance of overloaded function "std::vector<_Ty, _Alloc>::push_back [with _Ty=int [60], _Alloc=std::allocator]" matches the argument list 错误(活动)没有重载函数的实例“std :: vector <_Ty,_Alloc> :: push_back [with _Ty = int [60],_ Alloc = std :: allocator]”匹配参数列表
Error C2664 'void std::vector>::push_back(const int (&)[60])': cannot convert argument 1 from 'int' to 'int (&&)[60]' 错误C2664'void std :: vector> :: push_back(const int(&)[60])':无法将参数1从'int'转换为'int(&&)[60]'
Use std::array
, instead: 改为使用
std::array
:
#include <vector>
#include <array>
using namespace std;
int main()
{
vector<array<int, 10>> v;
array<int, 10> s;
v.push_back(s);
return 0;
}
But I also have to question the purpose of having a vector containing an array. 但我还要质疑包含数组的向量的目的。 Whatever is the underlying reason for that, there's likely to be a better way of accomplishing the same goals.
无论是什么原因,都可能有更好的方法来实现相同的目标。
You can do it like this: 你可以这样做:
#include <iostream>
#include <vector>
int main()
{
int t[10] = {1,2,3,4,5,6,7,8,9,10};
std::vector<int*> v;
v.push_back(t);
std::cout << v[0][4] << std::endl;
return 0;
}
To be more specific in this solution you do not actually store values of array t into vector v you just store pointer to array (and to be even more specific to first element of array) 更具体地说,在这个解决方案中,你实际上并没有将数组t的值存储到向量v中,只是存储指向数组的指针(并且更具体地说是数组的第一个元素)
I am not sure are you saying initialize a vector from an array, if yes here is a way to do it using vector's constructor: 我不确定你是说从数组初始化一个向量,如果是,这是一种使用vector的构造函数的方法:
int s[] = {1,2,3,4};
vector<int> v (s, s + sizeof(s)/sizeof(s[0]));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.