Meg*_*sa3 0 c++ iterator vector stdvector
我正在尝试用随机数初始化一个双向量数组(确实是一个矩阵),但我一定有什么问题,而且我无法在这里或在谷歌中找到解决方案。
我有下一个“标准”定义,它用 0 初始化我的矩阵:
情况1:
int num_rows=5, num_cols=7;
std::vector<std::vector<int>> Matrix(num_rows, std::vector<int>(num_cols, 0));
Run Code Online (Sandbox Code Playgroud)
所以如果我做这样的事情:
案例二
std::vector<std::vector<int>> Matrix(num_rows, std::vector<int>(num_cols, rand()%100));
Run Code Online (Sandbox Code Playgroud)
我看到的是它rand()%100
被调用一次,所以如果它返回,34
那么我的所有矩阵都将填充该数字。
在这一点上,我尝试使用Case 1初始化和 double for 迭代器:
for ( std::vector<std::vector<int>>::iterator it1 = Matrix.begin(); it1 != Matrix.end(); ++it1 )
{
for ( std::vector<int>::iterator it2 = (*it1).begin(); it2 != (*it1).end(); ++ it2 )
{
std::cout << (*it2) << "\n"; //With that I can see every value on the matrix... right now all 0
}
}
Run Code Online (Sandbox Code Playgroud)
现在在那个循环中,我找不到逐项执行并为它们分配新值的方法。我很抱歉,因为我有良心,这是一个非常简单的问题,但在谷歌上找不到......
由于 it2 是我必须使用的 var,如果我尝试制作类似上面的下一个内容,它就无法编译,甚至智能感知也不会让我放置 de 'assign'(因为我错了 ofc):
it2.assign(...)
(*it2).assign(...)
it1->assign // Here intellisense works but i don't think this it my option.
//
Matrix(it2,rand()%100); // error
Matrix[it1][it2] = rand() % 100; // Desperate...like normal array?
Matrix.at(it2) = rand()%100;
Matrix.at(it1).at(it2) = rand() % 100;
Run Code Online (Sandbox Code Playgroud)
我认为这assign
是我在这种情况下需要的功能,因为 insert 会添加新元素,或者at
我尝试的一切都会给我一个错误,我不知道我还能尝试什么,或者我是否必须以不同的方式考虑它道路...
非常感谢!!
迭代器就像指针。最简单的事情就是*it2 = rand() % 100
在你的循环中赋值。
使用以下函数稍微复杂一点 <algorithm>
void fill_row(std::vector<int> & row)
{
std::generate(row.begin(), row.end(), [](){ return rand() % 100; });
}
void fill_matrix(std::vector<std::vector<int>> & mat)
{
std::for_each(mat.begin(), mat.end(), fill_row);
}
Run Code Online (Sandbox Code Playgroud)
std::generate将调用其函数参数的结果分配给每个元素。
std::for_each用每个元素调用它的函数参数