vector 常見用法及模擬

文章目錄

  • 1. vector的介紹與使用
    • 1.1 vector的構造
    • 1.2 vector iterator 的使用
    • 1.3 有關大小和容量的操作
    • 1.4 vector 增刪查改
    • 1.5 vector 迭代器失效問題(重點)
    • 1.6 vector 中二維數組的使用
  • 2. vector 的模擬實現
    • 2.1 拷貝構造和賦值重載的現代寫法
    • 2.2 memcpy 拷貝問題
    • 2.3 vector.h

1. vector的介紹與使用

1.1 vector的構造

構造函數接口說明
vector ();無參構造
vector (size_type n, const value_type& val =value_type());構造并初始化n個val
vector (const vector& x);拷貝構造
vector (InputIterator first, InputIterator last);使用迭代器進行初始化構造
#include <iostream>
using namespace std;
#include <vector>int main()
{vector<int> v1; // 無參構造vector<int> v2(10, 1); // 構造并初始化10個1vector<int> v3(v2); // 拷貝構造vector<int> v4(v3.begin(), v3.end()); // 使用迭代器構造return 0;
}

在這里插入圖片描述

1.2 vector iterator 的使用

iterator 的使用接口說明
begin + end獲取第一個數據位置的iterator/const_iterator, 獲取最后一個數據的下一個位置的iterator/const_iterator
rbegin + rend獲取最后一個數據位置的reverse_iterator,獲取第一個數據前一個位置的reverse_iterator

在這里插入圖片描述
在這里插入圖片描述

int main()
{vector<int> v1; v1.push_back(1);v1.push_back(2);v1.push_back(3);for (auto it = v1.begin(); it != v1.end(); ++it){cout << *it << " ";}cout << endl;for (auto it = v1.rbegin(); it != v1.rend(); ++it) // 注意是++{cout << *it << " ";}cout << endl;return 0;
}

在這里插入圖片描述

1.3 有關大小和容量的操作

容量空間接口說明
size獲取數據個數
capacity獲取容量大小
empty判斷是否為空
resize改變vector的size
reserve改變vector的capacity
  • capacity的代碼在vs和g++下分別運行會發現,vs下capacity是按1.5倍增長的,g++是按2倍增長的。這個問題經常會考察,不要固化的認為,vector增容都是2倍,具體增長多少是根據具體的需求定義的。vs是PJ版本STL,g++是SGI版本STL。
  • reserve只負責開辟空間,如果確定知道需要用多少空間,reserve可以緩解vector增容的代價缺陷問題。
  • resize在開空間的同時還會進行初始化,影響size。
int main()
{size_t sz;vector<int> v;sz = v.capacity();cout << "making v grow:\n";for (int i = 0; i < 100; ++i){v.push_back(i);if (sz != v.capacity()){sz = v.capacity();cout << "capacity changed: " << sz << '\n';}}return 0;
}
  • vs:運行結果:vs下使用的STL基本是按照1.5倍方式擴容
    making foo grow:
    capacity changed: 1
    capacity changed: 2
    capacity changed: 3
    capacity changed: 4
    capacity changed: 6
    capacity changed: 9
    capacity changed: 13
    capacity changed: 19
    capacity changed: 28
    capacity changed: 42
    capacity changed: 63
    capacity changed: 94
    capacity changed: 141

  • g++運行結果:linux下使用的STL基本是按照2倍方式擴容
    making foo grow:
    capacity changed: 1
    capacity changed: 2
    capacity changed: 4
    capacity changed: 8
    capacity changed: 16
    capacity changed: 32
    capacity changed: 64
    capacity changed: 128

1.4 vector 增刪查改

vector 增刪查改接口說明
push_back尾插
pop_back尾刪
find查找(這不是vector的成員函數
insert在pos之前插入val
erase刪除pos位置的數據
swap交換兩個vector的數據空間
operator[]像數組一樣訪問
int main()
{vector<int> v;v.push_back(1); // 尾插v.push_back(2);v.push_back(3);v.push_back(4);for (auto it = v.begin(); it != v.end(); ++it)cout << *it << ' ';cout << endl;v.pop_back(); // 尾刪for (auto it = v.begin(); it != v.end(); ++it)cout << *it << ' ';cout << endl;auto pos = find(v.begin(), v.end(), 2); // 查找v.insert(pos, 5); // 插入for (auto it = v.begin(); it != v.end(); ++it)cout << *it << ' ';cout << endl;pos = find(v.begin(), v.end(), 1);v.erase(pos); // 刪除vector<int> v1;for (auto it = v1.begin(); it != v1.end(); ++it)cout << *it << ' ';cout << endl;v.swap(v1); // 交換for (auto it = v.begin(); it != v.end(); ++it)cout << *it << ' ';cout << endl;for (auto it = v1.begin(); it != v1.end(); ++it)cout << *it << ' ';cout << endl;cout << v1[2] << endl; //像數組一樣訪問return 0;
}

運行結果:
在這里插入圖片描述

1.5 vector 迭代器失效問題(重點)

迭代器的主要作用就是讓算法能夠不用關心底層數據結構,其底層實際就是一個指針,或者是對指針進行了封裝,比如:vector的迭代器就是原生態指針T* 。因此迭代器失效,實際就是迭代器底層對應指針所指向的空間被銷毀了,而使用一塊已經被釋放的空間,造成的后果是程序崩潰(即如果繼續使用已經失效的迭代器,程序可能會崩潰)。

可能造成vector可能會導致其迭代器失效的操作有:

  1. 引起底層空間改變的操作,都可能會導致迭代器失效,比如:resize、reserve、insert、assign、push_back等。(簡單來說,就是vector擴容問題,vector舊空間被釋放掉,又訪問了舊空間,很明顯是野指針問題)
    解決方法:完成上述操作之后,重新給 it 賦值就行。
  2. 指定位置元素的刪除操作–erase
    被刪除元素之后的迭代器失效:所有指向被刪除元素及其之后元素的迭代器、指針或引用都會失效,因為這些元素的位置已經發生了移動
    所以,你可以發現 erase 的返回值是一個迭代器,可以用以修正迭代器失效問題。
    值得一提的是 vs 和 g++ 的區別:
    vs 上因為檢查比較嚴格,所以迭代器失效會直接報錯,而 g++ 檢查并沒有那么嚴格,還是能輸出。
    • vs:
      在這里插入圖片描述
    • g++:
      在這里插入圖片描述
  3. 其實 string 在擴容、刪除之后,也會出現迭代器失效的問題,但是其實大部分時候其實我們都是把它當成數組來處理。

1.6 vector 中二維數組的使用

int main()
{int n, m;cin >> n >> m;vector<vector<int>> vv(n, (vector<int>(m, 0)));return 0;
}

其實也好理解,<>號中存的是模板參數,而二維數組就是每個一維元素里存的都是一個一維數組,后面的 (n, vector(m, 0)) 就表示 n 個一維數組,這一維數組中的每個元素都是 m 個用 0 填充的一維數組。
當然,每個一維數組也可以用 reverse 重置大小,用以實現不規則數組。

2. vector 的模擬實現

vector 其實就只有三個指針而已:
_start:指向動態分配內存塊的起始位置(即首個元素的地址)
_finish:指向最后一個有效元素的下一個位置
_end_of_storage:指向當前分配內存塊的末尾地址

值得一講的地方有兩點,一點是拷貝構造和賦值重載的現代寫法,另一點是 vector 使用 memcpy 拷貝問題

2.1 拷貝構造和賦值重載的現代寫法

和 string 類一樣,先實現一個交換數據域的類內 swap 成員函數,再利用編譯器自己去構造一個我們要拷貝的對象,最后直接交換就可以了。

		void swap(vector<T>& v){std::swap(_start, v._start);std::swap(_finish, v._finish);std::swap(_end_of_storage, v._end_of_storage);}// 現代寫法vector(const vector<T>& v){vector<T> tmp(v.begin(), v.end());swap(tmp);}vector<T>& operator=(vector<T> v){swap(v);return *this;}

2.2 memcpy 拷貝問題

memcpy是按字節去拷貝,是淺拷貝,但是因為 vector 本身具有我們在堆上申請的資源,需要深拷貝,此時使用 memcpy 就會出現問題了,所以這里我們并不能使用memcpy,而是需要自己手動實現深拷貝。

		void reserve(size_t n){if (n > capacity()){size_t old_size = size();T* tmp = new T[n];//memcpy(tmp, _start, old_size * sizeof(T));for (size_t i = 0; i < old_size; i++){tmp[i] = _start[i];}delete[] _start;_start = tmp;_finish = tmp + old_size;_end_of_storage = tmp + n;}}

2.3 vector.h

前面說過模板最好不要進行頭源文件分離,因為這樣容易造成鏈接錯誤,所以這里代碼全都放在 vector.h 中。

#pragma once
#include <assert.h>
#include <iostream>
#include <list>namespace zkp
{template<class T>class vector{public:typedef T* iterator;typedef const T* const_iterator;vector() = default;//vector(const vector<T>& v)//{//	reserve(v.size());//	for (auto& e : v)//	{//		push_back(e);//	}	//}// 需要一個迭代器模板函數,存在著多種不同類型的迭代器template<class InputIterator>vector(InputIterator first, InputIterator last){while (first != last){push_back(*first);++first;}}vector(size_t n, const T& val = T()){reserve(n);for (size_t i = 0; i < n; ++i){push_back(val);}}vector(int n, const T& val = T()){reserve(n);for (int i = 0; i < n; ++i){push_back(val);}}void clear(){_finish = _start;}/* 樸素寫法vector<T>& operator=(const vector<T>& v){if (this != &v){clear();reserve(v.size());for (auto& e : v){push_back(e);}}return *this;}*/void swap(vector<T>& v){std::swap(_start, v._start);std::swap(_finish, v._finish);std::swap(_end_of_storage, v._end_of_storage);}// 現代寫法vector(const vector<T>& v){vector<T> tmp(v.begin(), v.end());swap(tmp);}vector<T>& operator=(vector<T> v){swap(v);return *this;}~vector(){if (_start){delete[] _start;_start = _finish = _end_of_storage = nullptr;//cout << _start << " " << _finish << " " << _end_of_storage << endl;}}iterator begin(){return _start;}iterator end(){return _finish;}const_iterator begin() const{return _start;}const_iterator end() const{return _finish;}void reserve(size_t n){if (n > capacity()){size_t old_size = size();T* tmp = new T[n];//memcpy(tmp, _start, old_size * sizeof(T));for (size_t i = 0; i < old_size; i++){tmp[i] = _start[i];}delete[] _start;_start = tmp;_finish = tmp + old_size;_end_of_storage = tmp + n;}}void resize(size_t n, T val = T()){if (n < size()){_finish = _start + n;}else{reserve(n);while (_finish < _start + n){*_finish = val;++_finish;}}}size_t size() const{return _finish - _start;}size_t capacity() const{return _end_of_storage - _start;}bool empty() const{return _start == _finish;}void push_back(const T& x){// 擴容if (_finish == _end_of_storage){reserve(capacity() == 0 ? 4 : 2 * capacity());}*_finish = x;++_finish;}void pop_back(){assert(empty());--_finish;}iterator insert(iterator pos, const T& x){if (_finish == _end_of_storage){size_t len = pos - _start;reserve(capacity() == 0 ? 4 : 2 * capacity());pos = _start + len;}auto end = _finish - 1;while (end >= pos){*(end + 1) = *end;--end;}*pos = x;++_finish;return pos;}T& operator[](size_t i){assert(i < size());return _start[i];}const T& operator[](size_t i) const{assert(i < size());return _start[i];}private:iterator _start = nullptr;iterator _finish = nullptr;iterator _end_of_storage = nullptr;};template<class T>void print_vector(const vector<T>& v){// 規定,沒有實例化的類模板里面取東西,編譯器不能區分這里const_iterator// 是類型還是靜態成員變量// typename vector<T>::const_iterator it = v.begin();auto it = v.begin();while (it != v.end()){cout << *it << " ";++it;}cout << endl;}template<class Container>void print_container(const Container& v){/*auto it = v.begin();while (it != v.end()){cout << *it << " ";++it;}cout << endl;*/for (auto e : v){cout << e << " ";}cout << endl;}void test_vector1(){vector<int> v;v.push_back(1);v.push_back(2);v.push_back(3);v.push_back(4);v.push_back(5);for (size_t i = 0; i < v.size(); i++){cout << v[i] << " ";}cout << endl;auto it = v.begin();while (it != v.end()){cout << *it << " ";++it;}cout << endl;for (auto e : v){cout << e << " ";}cout << endl;print_vector(v);vector<double> vd;vd.push_back(1.1);vd.push_back(2.1);vd.push_back(3.1);vd.push_back(4.1);vd.push_back(5.1);print_vector(vd);}void test_vector2(){vector<int> v;v.push_back(1);v.push_back(2);v.push_back(3);v.push_back(4);//v.push_back(5);print_vector(v);v.insert(v.begin() + 2, 30);print_vector(v);int x;cin >> x;auto p = find(v.begin(), v.end(), x);if (p != v.end()){// insert以后p就是失效,不要直接訪問,要訪問就要更新這個失效的迭代器的值//v.insert(p, 40);//(*p) *= 10;p = v.insert(p, 40);(*(p + 1)) *= 10;}print_vector(v);}void test_vector3(){std::vector<int> v;v.push_back(1);v.push_back(2);v.push_back(3);v.push_back(4);print_container(v);// 刪除所有的偶數auto it = v.begin();while (it != v.end()){if (*it % 2 == 0){it = v.erase(it);}else{++it;}}print_container(v);}void test_vector4(){int i = int();int j = int(1);int k(2);vector<int> v;v.resize(10, 1);v.reserve(20);print_container(v);cout << v.size() << endl;cout << v.capacity() << endl;v.resize(15, 2);print_container(v);v.resize(25, 3);print_container(v);v.resize(5);print_container(v);}void test_vector5(){vector<int> v1;v1.push_back(1);v1.push_back(2);v1.push_back(3);v1.push_back(4);print_container(v1);vector<int> v2 = v1;print_container(v2);vector<int> v3;v3.push_back(10);v3.push_back(20);v3.push_back(30);v1 = v3;print_container(v1);print_container(v3);}void test_vector6(){vector<int> v1;v1.push_back(1);v1.push_back(2);v1.push_back(3);v1.push_back(4);v1.push_back(4);v1.push_back(4);vector<int> v2(v1.begin(), v1.begin() + 3);print_container(v1);print_container(v2);list<int> lt;lt.push_back(10);lt.push_back(10);lt.push_back(10);lt.push_back(10);vector<int> v3(lt.begin(), lt.end());print_container(lt);vector<string> v4(10, "111111111");print_container(v4);vector<int> v5(10);print_container(v5);vector<int> v6(10, 1);print_container(v6);vector<int> v7(10, 1);print_container(v7);}void test_vector7(){vector<string> v;v.push_back("11111111111111111111");v.push_back("11111111111111111111");v.push_back("11111111111111111111");v.push_back("11111111111111111111");print_container(v);v.push_back("11111111111111111111");print_container(v);}
} 

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/pingmian/80387.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/80387.shtml
英文地址,請注明出處:http://en.pswp.cn/pingmian/80387.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

數據結構與算法分析實驗11 實現順序查找表

實現順序查找表 1.上機名稱2.上機要求3.上機環境4.程序清單(寫明運行結果及結果分析)4.1 程序清單4.1.1 頭文件4.1.2 實現文件4.1.3 源文件 4.2 實現展效果示 上機體會 1.上機名稱 實現順序查找表 順序查找表的基本概念 順序查找表是一種線性數據結構&#xff0c;通常用于存儲…

實踐官方的 A2A SDK Python

內容列表 ? 注意? 我的環境? A2A SDK Python 注意 這只是一個原型&#xff0c;并且在快速的變化&#xff0c;本篇教程也隨時可能過期&#xff0c;可以在A2AProtocol blog最終更新的文章。 我的環境 ? Python 3.13? uv: uv 0.7.2 (Homebrew 2025-04-30)? Warp? Olla…

langchain 接入國內搜索api——百度AI搜索

為什么使用百度AI搜索 學習langchain的過程中&#xff0c;遇到使用search api的時候&#xff0c;發現langchain官方文檔中支持的搜索工具大多是國外的&#xff0c;例如google search或bing search&#xff0c;收費不說&#xff0c;很多還連接不上&#xff08;工具 | LangChain…

[強化學習的數學原理—趙世鈺老師]學習筆記01-基本概念

[強化學習的數學原理—趙世鈺老師]學習筆記01-基本概念 1.1 網格世界的例子1.2 狀態和動作1.3 狀態轉移1.4 策略1.5 獎勵1.6 軌跡、回報、回合1.6.1 軌跡和回報1.6.2 回合 1.7 馬爾可夫決策過程 本人為強化學習小白&#xff0c;為了在后續科研的過程中能夠較好的結合強化學習來…

Java開發經驗——阿里巴巴編碼規范經驗總結2

摘要 這篇文章是關于Java開發中阿里巴巴編碼規范的經驗總結。它強調了避免使用Apache BeanUtils進行屬性復制&#xff0c;因為它效率低下且類型轉換不安全。推薦使用Spring BeanUtils、Hutool BeanUtil、MapStruct或手動賦值等替代方案。文章還指出不應在視圖模板中加入復雜邏…

Java大師成長計劃之第18天:Java Memory Model與Volatile關鍵字

&#x1f4e2; 友情提示&#xff1a; 本文由銀河易創AI&#xff08;https://ai.eaigx.com&#xff09;平臺gpt-4o-mini模型輔助創作完成&#xff0c;旨在提供靈感參考與技術分享&#xff0c;文中關鍵數據、代碼與結論建議通過官方渠道驗證。 在Java多線程編程中&#xff0c;線程…

js前端分片傳輸大文件+mongoose后端解析

最近一直在完善mongoose做webserver的項目&#xff0c;其中程序升級要通過前端傳輸升級包到服務器。 因為第一次寫前端代碼&#xff0c;分片傳輸的邏輯&#xff0c;網上一堆&#xff0c;大同小異&#xff0c;而且版本啊&#xff0c;API不一致的問題&#xff0c;導致頭疼的很。后…

MiniMind:3塊錢成本 + 2小時!訓練自己的0.02B的大模型。minimind源碼解讀、MOE架構

大家好&#xff0c;我是此林。 目錄 1. 前言 2. minimind模型源碼解讀 1. MiniMind Config部分 1.1. 基礎參數 1.2. MOE配置 2. MiniMind Model 部分 2.1. MiniMindForCausalLM: 用于語言建模任務 2.2. 主干模型 MiniMindModel 2.3. MiniMindBlock: 模型的基本構建塊…

引言:Client Hello 為何是 HTTPS 安全的核心?

當用戶在瀏覽器中輸入 https:// 時&#xff0c;看似簡單的操作背后&#xff0c;隱藏著一場加密通信的“暗戰”。Client Hello 作為 TLS 握手的首個消息&#xff0c;不僅決定了后續通信的加密強度&#xff0c;還可能成為攻擊者的突破口。據統計&#xff0c;超過 35% 的網站因 TL…

Dockerfile 完全指南:從入門到最佳實踐

Dockerfile 完全指南&#xff1a;從入門到最佳實踐 1. Dockerfile 簡介與作用 Dockerfile 是一個文本文件&#xff0c;包含了一系列用于構建 Docker 鏡像的指令。它允許開發者通過簡單的指令定義鏡像的構建過程&#xff0c;實現自動化、可重復的鏡像構建。 主要作用&#xf…

Python httpx庫終極指南

一、發展歷程與技術定位 1.1 歷史演進 起源&#xff1a;httpx 由 Encode 團隊開發&#xff0c;于 2019 年首次發布&#xff0c;目標是提供一個現代化的 HTTP 客戶端&#xff0c;支持同步和異步操作&#xff0c;并兼容 HTTP/1.1 和 HTTP/2。背景&#xff1a; requests 庫雖然功…

app加固

1、什么是加固? 我們之前講的逆向,大多數都是用加密算法去加密一些明文字符串,然后把得到的結果用 Base64、Hex等進行編碼后提交。加固其實也一樣&#xff0c;只不過他通常加密的是 dex文件而已。但是 dex 文件加密以后&#xff0c;安卓系統是沒法直接運行的。所以加固的核心&…

Win全兼容!五五 Excel Word 轉 PDF 工具解決多場景轉換難題

各位辦公小能手們&#xff01;今天給你們介紹一款超牛的工具——五五Excel Word批量轉PDF工具V5.5版。這玩意兒專注搞批量格式轉換&#xff0c;能把Excel&#xff08;.xls/.xlsx&#xff09;和Word&#xff08;.doc/.docx&#xff09;文檔唰唰地變成PDF格式。 先說說它的核心功…

springCloud/Alibaba常用中間件之Nacos服務注冊與發現

文章目錄 SpringCloud Alibaba:依賴版本補充六、Nacos:服務注冊與發現1、下載安裝Nacos2、服務注冊1. 導入依賴(這里以服務提供者為例)2. 修改配置文件和主啟動類3. 創建業務類4. 測試 3.服務映射1. 導入依賴2. 修改配置文件和主啟動類3. 創建業務類和RestTemplate配置類用來提…

uniapp中score-view中的文字無法換行問題。

項目場景&#xff1a; 今天遇到一個很惡心的問題&#xff0c;uniapp中的文字突然無法換行了。得..就介樣 原因分析&#xff1a; 提示&#xff1a;經過一fan研究后發現 scroll-view為了能夠橫向滾動設置了white-space: nowrap; 強制不換行 解決起來最先想到的是&#xff0c;父…

【STM32 學習筆記】I2C通信協議

注&#xff1a;通信協議的設計背景 3:00~10:13 I2C 通訊協議(Inter&#xff0d;Integrated Circuit)是由Phiilps公司開發的&#xff0c;由于它引腳少&#xff0c;硬件實現簡單&#xff0c;可擴展性強&#xff0c; 不需要USART、CAN等通訊協議的外部收發設備&#xff0c;現在被廣…

【網絡原理】數據鏈路層

目錄 一. 以太網 二. 以太網數據幀 三. MAC地址 四. MTU 五. ARP協議 六. DNS 一. 以太網 以太網是一種基于有線或無線介質的計算機網絡技術&#xff0c;定義了物理層和數據鏈路層的協議&#xff0c;用于在局域網中傳輸數據幀。 二. 以太網數據幀 1&#xff09;目標地址 …

控制臺打印帶格式內容

1. 場景 很多軟件會在控制臺打印帶顏色和格式的文字&#xff0c;需要使用轉義符實現這個功能。 2. 詳細說明 2.1.轉義符說明 樣式開始&#xff1a;\033[參數1;參數2;參數3m 可以多個參數疊加&#xff0c;若同一類型的參數&#xff08;如字體顏色&#xff09;設置了多個&…

[6-2] 定時器定時中斷定時器外部時鐘 江協科技學習筆記(41個知識點)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 V 30 31 32 33 34 35 36 37 38 39 40 41

數據庫的脫敏策略

數據庫的脫敏策略&#xff1a;就是屏蔽敏感的數據 脫敏策略三要求&#xff1a; &#xff08;1&#xff09;表對象 &#xff08;2&#xff09;生效條件&#xff08;脫敏列、脫敏函數&#xff09; &#xff08;3&#xff09;二元組 常見的脫敏策略規則&#xff1a; 替換、重排、…