在 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