有一个固定大小的向量向量,
vector<vector<int> > v(10);
我希望将其初始化为具有所有元素的一维向量,其初始化值为1。
我已经使用了Boost Assign,如下所示:
v = repeat(10,list_of(list_of(1)));
而且我遇到了编译错误
error: no matching function for call to ‘repeat(boost::assign_detail::generic_list<int>)’
怎么做到呢?
有一个固定大小的向量向量,
vector<vector<int> > v(10);
我希望将其初始化为具有所有元素的一维向量,其初始化值为1。
我已经使用了Boost Assign,如下所示:
v = repeat(10,list_of(list_of(1)));
而且我遇到了编译错误
error: no matching function for call to ‘repeat(boost::assign_detail::generic_list<int>)’
怎么做到呢?
这个不使用 boost::assign
,但能满足你的需求:
vector<vector<int>> v(10, vector<int>(10,1));
这将创建一个包含10个int
向量的向量,每个向量都包含10个int
。
你不需要使用boost
来实现所需的行为。以下代码创建一个vector
,其中包含10
个vector<int>
,每个vector<int>
中包含10
个值为1
的int
:
std::vector<std::vector<int>> v(10, std::vector<int>(10, 1));
>>
,即没有空格的 >
:p - krozaine我会尝试为那些刚接触C++的人解释一下。向量 mat
的优点是,您可以使用 []
运算符直接访问其元素,几乎没有任何代价。
int n(5), m(8);
vector<vector<int> > mat(n, vector<int>(m));
mat[0][0] =4; //direct assignment OR
for (int i=0;i<n;++i)
for(int j=0;j<m;++j){
mat[i][j] = rand() % 10;
}
当然,这不是唯一的方法。如果您不添加或删除元素,则还可以使用本地容器mat []
,它们只是指针。这是我最喜欢的方式,使用C ++:
int n(5), m(8);
int *matrix[n];
for(int i=0;i<n;++i){
matrix[i] = new int[m]; //allocating m elements of memory
for(int j=0;j<m;++j) matrix[i][j]= rand()%10;
}
#include <vector>
了。希望这样更清晰易懂!#include <vector>
#include <iostream>
using namespace std;
int main(){
int n; cin >> n;
vector<vector<int>> v(n);
//populate
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
int number; cin >> number;
v[i].push_back(number);
}
}
// display
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
cout << v[i][j] << " ";
}
cout << endl;
}
}
输入:
4
11 12 13 14
21 22 23 24
31 32 33 34
41 42 43 44
输出:
11 12 13 14
21 22 23 24
31 32 33 34
41 42 43 44