##實戰c++中的vector系列--使用vector構造二維數組
二維數組有時候被用到,但是很少有人會使用vector來構造一個二維數組。
首先,需要明確的是,在計算機的世界中,根本不存在二維數組,只是使用者的一個概念罷了。其實我們所謂的二維數組也必須是一段連續的內存。
很多情況下,我們可以把常規的二維數組用一個vector表示,只要索引對應即可。
那么,我若一意孤行呢,我就想vector里面放一個vector呢?
~~~
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector <vector<int>> array(3);
for (int i = 0; i <3; i++)
array[i].resize(3);
for (int i = 0; i <3; i++)
for (int j = 0; j <3; j++)
array[i][j] = (i*j);
for (int i = 0; i <3; i++)
{
for (int j = 0; j <3; j++)
cout <<array[i][j] << " ";
cout <<endl;
}
array.resize(5);
array[3].resize(3);
array[4].resize(3);
//現在是5X3的數組了
cout << endl << endl;
for (int i = 0; i <5; i++)
for (int j = 0; j <3; j++)
array[i][j] = (i*j);
for (int i = 0; i <5; i++)
{
for (int j = 0; j <3; j++)
cout <<array[i][j] << " ";
cout <<endl;
}
}
//輸出:
0 0 0
0 1 2
0 2 4
0 0 0
0 1 2
0 2 4
0 3 6
0 4 8
~~~
就是再使用“列”的時候,需要使用vector的resize方法,否則不能使用[]進行訪問的。
這里也不能用vector的reserve分配容量,原因上一篇博客已經分析過了。
其實我想說的就是,如果想要構建所謂的二維數組,最重要的就是要使用resize分配容量。
- 前言
- 構造、operator=和assign區別
- 將迭代器轉換為索引
- copy set to vector(別混淆了reserve和resize)
- 使用vector構造二維數組
- 可怕的迭代器失效(vector重新申請內存)
- 可怕的迭代器失效之二(刪除vector中元素)
- vector<unique_ptr<>>初始化(所有權轉移)
- vector<unique_ptr<>>作為函數的參數
- vector<unique_ptr<>>賦值給vector<unique_ptr<>>
- creating vector of local structure、vector of structs initialization
- 知道emplace_back為何優于push_back嗎?
- emplace_back造成的引用失效
- vector的一些異常
- vector的遍歷(stl算法、vector迭代器(不要在循環中判斷不等于end())、operator[])
- 使用sort算法對vector進行排序(對vector<string>排序、使用穩定的排序std::stable_sort())
- vector應用之STL的find、find_if、find_end、find_first_of、find_if_not(C++11)
- 使用sort算法對vector<unique_ptr<string>>進行排序(sort函數“應輸入 2 個參數,卻提供了 3 個)
- 對vector<自定義類>使用std::find 和 std::find_if 算法