用c++创建一个数据类型是int型的二维vector容器
时间: 2023-09-11 08:12:25 浏览: 108
可以使用以下代码来创建一个数据类型为int的二维vector容器:
```cpp
#include <vector>
int main() {
int rows = 3; // 行数
int cols = 4; // 列数
// 创建一个二维vector容器
std::vector<std::vector<int>> myVector(rows, std::vector<int>(cols));
// 对容器进行赋值
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
myVector[i][j] = i * cols + j;
}
}
// 输出容器中的值
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
std::cout << myVector[i][j] << " ";
}
std::cout << std::endl;
}
return 0;
}
```
这段代码创建了一个3行4列的二维vector容器,并对容器进行了赋值。最后,通过嵌套的循环输出了容器中的值。你可以根据自己的需求修改行数和列数,并对容器中的元素进行操作。
相关问题
如何用vector容器创建一个二维数组,其中第一维存储int,第二维存储float
在C++中,可以使用STL库中的`std::vector`容器创建一个二维数组,其中第一维是整型`int`,第二维是浮点型`float`。虽然`vector`本身是单维度的,但可以通过嵌套的方式来模拟二维数组。以下是创建过程:
```cpp
#include <vector>
// 定义一个二维向量,其中外层存储int,内层存储float
std::vector<std::vector<float>> twoDimensionalArray(int numRows, int numCols) {
std::vector<std::vector<float>> array(numRows, std::vector<float>(numCols)); // 创建指定大小的二维vector
for (int i = 0; i < numRows; ++i) { // 遍历每一行
for (int j = 0; j < numCols; ++j) { // 遍历每一列
// 在这里可以根据需要给每个元素赋值,例如初始化为0.0f
array[i][j] = 0.0f;
}
}
return array;
}
```
在这个示例中,`twoDimensionalArray`函数接受两个参数`numRows`和`numCols`,分别表示二维数组的行数和列数,然后返回一个预定义大小的二维`vector`。内部的`std::vector<float>`用于存储每个元素。
用c++写一个使用智能指针 创建一个二维vector指针对象的例子
示例代码:
#include <iostream>
#include <memory>int main()
{
// 创建一个二维vector指针
std::unique_ptr<std::vector<std::vector<int>>> vec2d_ptr(new std::vector<std::vector<int>>()); // 使用智能指针添加一维vector
vec2d_ptr->push_back(std::vector<int>()); // 添加一维vector中的元素
vec2d_ptr->at(0).push_back(10);
vec2d_ptr->at(0).push_back(20);
vec2d_ptr->at(0).push_back(30); // 打印元素
for (const auto &vec : *vec2d_ptr) {
for (const auto &val : vec)
std::cout << val << " ";
std::cout << std::endl;
} return 0;
}
阅读全文
相关推荐















