響應(yīng)式網(wǎng)站的寬度張家港seo建站
vector
?是 C++ 標(biāo)準(zhǔn)庫的動(dòng)態(tài)數(shù)組。
在C語言中一般初學(xué)者會(huì)使用malloc,int[n]等方式來創(chuàng)建靜態(tài)數(shù)組,但是這種方式繁瑣且容易出錯(cuò)。我們做算法題一般使用動(dòng)態(tài)數(shù)組vector, 并且在刷題網(wǎng)站的題目給的輸入一般也是vector類型。
?示例:vector的初始化如下:
#include <vector>int n = 7, m = 8;// 初始化一個(gè) int 型的空數(shù)組 nums
vector<int> nums;// 初始化一個(gè)大小為 n 的數(shù)組 nums,數(shù)組中的值默認(rèn)都為 0
vector<int> nums(n);// 初始化一個(gè)元素為 1, 3, 5 的數(shù)組 nums
vector<int> nums{1, 3, 5};// 初始化一個(gè)大小為 n 的數(shù)組 nums,其值全都為 2
vector<int> nums(n, 2);// 初始化一個(gè)二維 int 數(shù)組 dp
vector<vector<int>> dp;// 初始化一個(gè)大小為 m * n 的布爾數(shù)組 dp,
// 其中的值都初始化為 true
vector<vector<bool>> dp(m, vector<bool>(n, true));
vector的操作示例:
?
#include <iostream>
#include <vector>
using namespace std;int main() {int n = 10;// 數(shù)組大小為 10,元素值都為 0vector<int> nums(n);cout << nums.empty() << endl; // 輸出 0 (false)cout << nums.size() << endl; // 輸出:10nums.push_back(20); // 在數(shù)組尾部插入一個(gè)元素 20cout << nums.size() << endl; // 輸出:11cout << nums.back() << endl; // 得到數(shù)組最后一個(gè)元素的引用 輸出:20nums.pop_back(); // 刪除數(shù)組的最后一個(gè)元素(無返回值)cout << nums.size() << endl; // 輸出:10nums[0] = 11; // 可以通過方括號直接取值或修改cout << nums[0] << endl; // 輸出:11nums.insert(nums.begin() + 3, 99); // 在索引 3 處插入一個(gè)元素 99nums.erase(nums.begin() + 2); // 刪除索引 2 處的元素swap(nums[0], nums[1]); // 交換 nums[0] 和 nums[1]// 遍歷數(shù)組// 0 11 99 0 0 0 0 0 0 0for (int i = 0; i < nums.size(); i++) {cout << nums[i] << " ";}cout << endl;
}
另外,根據(jù)數(shù)組的特性,利用索引訪問元素很高效,從尾部刪除元素也是很高效的;但是從中間或者頭部刪除或增加元素需要數(shù)據(jù)搬移,很低效。