首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ STL vector 完整使用指南:從初始化到進階操作

     編輯:關於C++

vector 是 C++ 標準模板庫(STL)中最常用的序列容器,本質是一個動態數組,支援隨機訪問、尾部常數時間插入/刪除、自動內存管理。本文系統梳理其聲明、初始化、常用成員函數與實戰技巧。

1. 常見聲明方式

vector<T> v;                    // 空 vector
vector<T> v(n);                 // n 個值初始化元素
vector<T> v(n, val);            // n 個 val 拷貝
vector<T> v(begin, end);        // 區間 [begin, end) 拷貝
vector<T> v(another);           // 拷貝構造
vector<vector<T>> v2d;         // 二維容器(注意 > > 中間要有空格,C++11 前否則報錯)

2. 必備頭文件與命名空間

#include <vector>
using namespace std;           // 或寫 using std::vector;

3. 核心成員函數速查表

分類函數說明
容量size()當前元素數量
capacity()已分配內存可容納元素數
reserve(n)預留至少 n 個元素空間,避免頻繁擴容
元素訪問operator[]無邊界檢查,速度快
at(idx)有邊界檢查,越界拋 out_of_range
front() / back()首/尾元素引用
data()返回底層數組指針(C++11)
修改器push_back(val)尾部插入,均攤 O(1)
pop_back()刪除尾部元素
insert(pos, val)指定位置插入,返回新元素迭代器
erase(pos) / erase(beg, end)刪除單個/區間,返回下一個有效迭代器
clear()清空所有元素,capacity 不變
其他swap(v)與另一 vector 交換內容(O(1))
assign(beg, end)用區間內容替換當前內容
resize(n, val)調整大小,不足填 val,超出截斷

4. 迭代器與遍歷

// 正向
for (auto it = v.begin(); it != v.end(); ++it) { /* *it */ }
// 逆向
for (auto it = v.rbegin(); it != v.rend(); ++it) { /* *it */ }
// 範圍 for (C++11)
for (auto& x : v) { /* x */ }

5. 實戰範例

5.1 創建與填充

vector<int> v;
for (int i = 0; i < 10; ++i) v.push_back(i);  // 0~9

5.2 安全訪問對比

vector<int> v(5);
v.reserve(10);
try {
    int a = v[7];      // 不拋異常,未定義行為
    int b = v.at(7);   // 拋出 out_of_range
} catch (const exception& e) {
    cout << e.what();
}

5.3 刪除符合條件的元素(Erase-Remove 慣用法)

#include <algorithm>
vector<int> v = {1,2,3,2,4};
v.erase(remove(v.begin(), v.end(), 2), v.end()); // 刪除所有 2
// 配合 lambda 刪除滿足條件的元素
v.erase(remove_if(v.begin(), v.end(), [](int x){ return x % 2 == 0; }), v.end());

5.4 自定義結構體存儲

struct STResult { double Time, Xp, Yp; int id; };
vector<STResult> vec;
vec.push_back({0.1, 0.1, 0.1, 1});
assert(vec[0].id == 1);

6. 進階提示

  • 預留空間:大量 push_back 前調用 reserve() 可顯著提升性能。
  • swap 技巧:vector<T>().swap(v) 能真正釋放內存(C++11 可用 shrink_to_fit())。
  • 二維 vector:vector<vector<int>> mat(rows, vector<int>(cols)) 初始化矩陣。
  • 避免迭代器失效:insert/erase/resize 可能導致迭代器失效,操作後重新獲取。

7. 總結

vector 兼具數組的隨機訪問優勢與動態擴容靈活性,是 C++ 開發中最基礎也最重要的容器。熟練掌握其 API、迭代器慣用法及性能優化技巧,能讓代碼更簡潔、高效、安全。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved