在 C++ STL 中声明向量数组
本文将演示有关如何在 C++ 中声明向量数组的多种方法。
使用 C 语言样式数组符号声明 C++ 中的向量数组
向量的固定数组可以用 C 语言样式的方括号表示法 []
来声明。此方法本质上定义了具有固定行数和可变列数的二维数组。如果需要,可以使用 push_back
函数调用添加列,并通过 arr[x][y]
表示法访问元素。在下面的例子中,我们将十个随机整数值压入数组的每一列,从而得到十乘十的矩阵。
#include <iostream>
#include <vector>
#include <iomanip>
using std::cout; using std::vector;
using std::endl; using std::setw;
using std::array;
int main()
{
vector<int> arr_vectors[10];
for (auto &vec : arr_vectors) {
for (int i = 0; i < 10; ++i) {
vec.push_back(rand() % 100);
}
}
for (auto &item : arr_vectors) {
for (auto &i : item) {
cout << setw(3) << i << "; ";
}
cout << endl;
}
return EXIT_SUCCESS;
}
输出:
83; 86; 77; 15; 93; 35; 86; 92; 49; 21;
62; 27; 90; 59; 63; 26; 40; 26; 72; 36;
11; 68; 67; 29; 82; 30; 62; 23; 67; 35;
29; 2; 22; 58; 69; 67; 93; 56; 11; 42;
29; 73; 21; 19; 84; 37; 98; 24; 15; 70;
13; 26; 91; 80; 56; 73; 62; 70; 96; 81;
5; 25; 84; 27; 36; 5; 46; 29; 13; 57;
24; 95; 82; 45; 14; 67; 34; 64; 43; 50;
87; 8; 76; 78; 88; 84; 3; 51; 54; 99;
32; 60; 76; 68; 39; 12; 26; 86; 94; 39;
使用 std::vector
声明 C++ 中的向量数组
或者,可以使用 std::vector
容器声明一个可变的向量数组。以下代码段演示了四乘四整数矩阵的声明和初始化。请注意,构造函数的第二个参数是另一个将其元素初始化为零的 vector
构造函数。可以使用相同的 arr[x][y]
表示法访问对象的元素。从正面来看,可以使用 std::vector
容器的内置函数动态扩展行和列。
#include <iostream>
#include <vector>
#include <iomanip>
using std::cout; using std::vector;
using std::endl; using std::setw;
using std::array;
constexpr int LENGTH = 4;
constexpr int WIDTH = 4;
int main()
{
vector<vector<int>> vector_2d(LENGTH, vector<int> (WIDTH, 0));
vector_2d[2][2] = 12;
cout << vector_2d[2][2] << endl;
vector_2d.at(3).at(3) = 99;
cout << vector_2d[3][3] << endl;
cout << endl;
return EXIT_SUCCESS;
}
输出:
12
99
向量的向量迭代可以使用两层嵌套的基于范围的循环来完成。请注意,访问元素别名是内部 for
循环中的向量元素。
#include <iostream>
#include <vector>
#include <iomanip>
using std::cout; using std::vector;
using std::endl; using std::setw;
using std::array;
constexpr int LENGTH = 4;
constexpr int WIDTH = 4;
int main()
{
vector<vector<int>> vector_2d(LENGTH, vector<int> (WIDTH, 0));
std::srand(std::time(nullptr));
for (auto &item : vector_2d) {
for (auto &i : item) {
i = rand() % 100;
cout << setw(2) << i << "; ";
}
cout << endl;
}
cout << endl;
for (auto &item : vector_2d) {
for (auto &i : item) {
i *= 3;
}
}
for (auto &item : vector_2d) {
for (auto &i : item) {
cout << setw(3) << i << "; ";
}
cout << endl;
}
return EXIT_SUCCESS;
}
输出:
62; 85; 69; 73;
22; 55; 79; 89;
26; 89; 44; 66;
32; 40; 64; 32;
186; 255; 207; 219;
66; 165; 237; 267;
78; 267; 132; 198;
96; 120; 192; 96;
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn