简体   繁体   English

为向量的向量赋值

[英]assigning values to vectors of vectors

i have created a vector of vectors or 2d arrays of size nxn . 我创建了一个向量或大小为nxn的2d数组的向量。 i want to assign some n-2 values to each position to this vector, ie for example grid[1][2]=3 and the values 3 should not be same for other position in a vector only grid[1][2] should have the value 3. could anybody help me with the code, also can we use srand function to do this? 我想为该矢量的每个位置分配一些n-2值,即例如grid [1] [2] = 3,而对于仅矢量的其他位置,值3不应相同grid [1] [2]应该具有值3.有人可以帮助我编写代码吗,也可以使用srand函数来做到这一点吗? Thanks 谢谢

Assuming that you don't have any limitation on the random number generated, here is an example that populates and then print 2D vector array: 假设您对生成的随机数没有任何限制,下面是一个示例,该示例填充然后打印2D向量数组:

int n = 3;
std::vector<int> usedNumbers(n*n);
std::vector<std::vector<int>> vec(n);
for (int i = 0; i < n; i++)
{
    vec[i].resize(n);
    for (int j = 0; j < n; j++)
    {
        int randNum;
        while (std::find(usedNumbers.begin(), usedNumbers.end(), randNum = rand()) != usedNumbers.end()){}
        usedNumbers.push_back(randNum);
        vec[i][j] = randNum;
    }
}
// print the 2 dimentional vector
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
    std::cout << "i:" << i << " j:" << j << " vec: " << vec[i][j] << std::endl;

This reference code also assumes that the random number should be unique in the entire 2D array. 该参考代码还假设随机数在整个2D数组中应该是唯一的。

you can play with the rand() function to reflect the maximum number you want (for example, random number x should be in the range of 0 < x < n), but a better option would be to use random . 您可以使用rand()函数来反映所需的最大数字(例如,随机数x应该在0 <x <n的范围内),但是更好的选择是使用random

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM