gpt4 book ai didi

c++ - 插入 vector 并调整 vector 的大小

转载 作者:太空宇宙 更新时间:2023-11-04 15:49:10 25 4
gpt4 key购买 nike

如何调整包含整数值的 vector 的大小。

std::vector<std::vecotr<int>> MyVector;
int value = 10;

//need to insert values as 2 rows and 3 columns, like
//Myvector[0][0] = value;
//Myvector[0][1] = value;
//Myvector[0][2] = value;
//Myvector[1][0] = value;
//Myvector[1][1] = value;
//Myvector[1][2] = value;

// ......
//here i have to resize the vector size to 4 rows and 5 cols using resize() function.

MyVector.resize(.......); //Hoe is this possible.

第一个问题是,我必须插入 2 行 3 列的值。为此,我如何使用 push_back 函数。之后需要调整到指定的大小。因为它是 vector 的 vector ,所以我对此感到担心。

最佳答案

您可以将 vector 的 vector 想象成一个矩阵,其中成员 vector 是“行”。

int main()
{
std::vector<std::vector<int> > MyVector;
//Create a row:
std::vector<int> subVector;
subVector.push_back(1);
subVector.push_back(2);
//put the row into the vector:
MyVector.push_back(subVector);
//create another row:
subVector.clear();
subVector.push_back(3);
subVector.push_back(4);
//put the second row into the vector
MyVector.push_back(subVector);
//access the first row and add an element to it:
MyVector[0].push_back(6);
//access the second row and add an element to it:
MyVector[1].push_back(6);
}

关于c++ - 插入 vector 并调整 vector 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11498748/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com