網站首頁 編程語言 正文
容量(capacity)和大小(size)的區別
vector 容器的容量(用 capacity 表示),指的是在不分配更多內存的情況下,容器可以保存的最多元素個數;而 vector 容器的大小(用 size 表示),指的是它實際所包含的元素個數。
對于一個 vector 對象來說,通過該模板類提供的 capacity() 成員函數,可以獲得當前容器的容量;通過 size() 成員函數,可以獲得容器當前的大小。例如:
#include <iostream> #include <vector> using namespace std; int main() { std::vector<int>value{ 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47 }; value.reserve(20); cout << "value 容量是:" << value.capacity() << endl; cout << "value 大小是:" << value.size() << endl; return 0; }
程序輸出結果為:
value 容量是:20
value 大小是:15
結合該程序的輸出結果,下圖可以更好的說明 vector 容器容量和大小之間的關系:
顯然,vector 容器的大小不能超出它的容量,在大小等于容量的基礎上,只要增加一個元素,就必須分配更多的內存。注意,這里的“更多”并不是 1 個。換句話說,當 vector 容器的大小和容量相等時,如果再向其添加(或者插入)一個元素,vector 往往會申請多個存儲空間,而不僅僅只申請 1 個。
一旦 vector 容器的內存被重新分配,則和 vector 容器中元素相關的所有引用、指針以及迭代器,都可能會失效,最穩妥的方法就是重新生成。
容器擴容的本質
vector 容器擴容的過程需要經歷以下 3 步:
- 完全棄用現有的內存空間,重新申請更大的內存空間(一般是原空間的1.5倍);
- 將舊內存空間中的數據,按原有順序移動到新的內存空間中;
- 最后將舊的內存空間釋放。
由此可見,vector 擴容是非常耗時的。為了降低再次分配內存空間時的成本,每次擴容時 vector 都會申請比用戶需求量更多的內存空間(這也就是 vector 容量的由來,即 capacity>=size),以便后期使用。
emplace_back()和push_back()的區別
vector中可以用來從容器末尾添加元素的函數有 2 個,分別是 push_back() 和 emplace_back() 函數。
push_back()函數的功能是在 vector 容器尾部添加一個元素,用法也非常簡單,比如:
#include <iostream> #include <vector> using namespace std; int main() { vector<int> values{}; values.push_back(1); values.push_back(2); for (int i = 0; i < values.size(); i++) { cout << values[i] << " "; } return 0; }
運行程序,輸出結果為:
1 2
emplace_back()函數是 C++ 11 新增加的,其功能和 push_back() 相同,都是在 vector 容器的尾部添加一個元素。
emplace_back() 成員函數的用法也很簡單,這里直接舉個例子:
#include <iostream> #include <vector> using namespace std; int main() { vector<int> values{}; values.emplace_back(1); values.emplace_back(2); for (int i = 0; i < values.size(); i++) { cout << values[i] << " "; } return 0; }
運行結果為:
1 2
emplace_back() 和 push_back() 的區別,就在于底層實現的機制不同。push_back() 向容器尾部添加元素時,首先會創建這個元素,然后再將這個元素拷貝或者移動到容器中(如果是拷貝的話,事后會自行銷毀先前創建的這個元素);而 emplace_back() 在實現時,則是直接在容器尾部創建這個元素,省去了拷貝或移動元素的過程。(可以看作是零拷貝的實現)
為了讓大家清楚的了解它們之間的區別,我們創建一個包含類對象的 vector 容器,如下所示:
#include <vector> #include <iostream> using namespace std; class testDemo { public: testDemo(int num):num(num){ std::cout << "調用構造函數" << endl; } testDemo(const testDemo& other) :num(other.num) { std::cout << "調用拷貝構造函數" << endl; } testDemo(testDemo&& other) :num(other.num) { std::cout << "調用移動構造函數" << endl; } private: int num; }; int main() { cout << "emplace_back:" << endl; std::vector<testDemo> demo1; demo1.emplace_back(2); cout << "push_back:" << endl; std::vector<testDemo> demo2; demo2.push_back(2); }
運行結果為:
emplace_back:
調用構造函數
push_back:
調用構造函數
調用移動構造函數
在此基礎上,讀者可嘗試將 testDemo 類中的移動構造函數注釋掉,再運行程序會發現,運行結果變為:
emplace_back:
調用構造函數
push_back:
調用構造函數
調用拷貝構造函數
由此可以看出,push_back() 在底層實現時,會優先選擇調用移動構造函數,如果沒有才會調用拷貝構造函數。
顯然完成同樣的操作,push_back() 的底層實現過程比 emplace_back() 更繁瑣,換句話說,emplace_back() 的執行效率比 push_back() 高。因此,在實際使用時,建議大家優先選用 emplace_back()。
emplace()和insert()的區別
insert() 函數的功能是在 vector 容器的指定位置插入一個或多個元素。
下面的例子,演示了如何使用 insert() 函數向 vector 容器中插入元素。
#include <iostream> #include <vector> #include <array> using namespace std; int main() { std::vector<int> demo{1,2}; //第一種格式用法 demo.insert(demo.begin() + 1, 3);//{1,3,2} //第二種格式用法 demo.insert(demo.end(), 2, 5);//{1,3,2,5,5} //第三種格式用法 std::array<int,3>test{ 7,8,9 }; demo.insert(demo.end(), test.begin(), test.end());//{1,3,2,5,5,7,8,9} //第四種格式用法 demo.insert(demo.end(), { 10,11 });//{1,3,2,5,5,7,8,9,10,11} for (int i = 0; i < demo.size(); i++) { cout << demo[i] << " "; } return 0; }
運行結果為:
1 3 2 5 5 7 8 9 10 11
emplace()是 C++ 11 標準新增加的成員函數,用于在 vector 容器指定位置之前插入一個新的元素。emplace() 每次只能插入一個元素,而不是多個。
該函數的語法格式如下:
iterator emplace (const_iterator pos, args...);
其中,pos 為指定插入位置的迭代器;args… 表示與新插入元素的構造函數相對應的多個參數;該函數會返回表示新插入元素位置的迭代器。
舉個例子:
#include <vector> #include <iostream> using namespace std; int main() { std::vector<int> demo1{1,2}; //emplace() 每次只能插入一個 int 類型元素 demo1.emplace(demo1.begin(), 3); for (int i = 0; i < demo1.size(); i++) { cout << demo1[i] << " "; } return 0; }
運行結果為:
3 1 2
既然 emplace() 和 insert() 都能完成向 vector 容器中插入新元素,那么誰的運行效率更高呢?答案是 emplace()。在說明原因之前,通過下面這段程序,就可以直觀看出兩者運行效率的差異:
#include <vector> #include <iostream> using namespace std; class testDemo { public: testDemo(int num) :num(num) { std::cout << "調用構造函數" << endl; } testDemo(const testDemo& other) :num(other.num) { std::cout << "調用拷貝構造函數" << endl; } testDemo(testDemo&& other) :num(other.num) { std::cout << "調用移動構造函數" << endl; } testDemo& operator=(const testDemo& other); private: int num; }; testDemo& testDemo::operator=(const testDemo& other) { this->num = other.num; return *this; } int main() { cout << "insert:" << endl; std::vector<testDemo> demo2{}; demo2.insert(demo2.begin(), testDemo(1)); cout << "emplace:" << endl; std::vector<testDemo> demo1{}; demo1.emplace(demo1.begin(), 1); return 0; }
運行結果為:
insert:
調用構造函數
調用移動構造函數
emplace:
調用構造函數
注意,當拷貝構造函數和移動構造函數同時存在時,insert() 會優先調用移動構造函數。
可以看到,通過 insert() 函數向 vector 容器中插入 testDemo 類對象,需要調用類的構造函數和移動構造函數(或拷貝構造函數);而通過 emplace() 函數實現同樣的功能,只需要調用構造函數即可。
簡單的理解,就是 emplace() 在插入元素時,是在容器的指定位置直接構造元素,而不是先單獨生成,再將其復制(或移動)到容器中。因此,在實際使用中,推薦大家優先使用 emplace()。
附:如果vector是空的,并且沒有分配空間,切忌用下標進行訪問,會出錯!!!
int main() { vector<int>v; v[0]=1; return 0; }
成功編譯,但是運行的時候報錯Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)。因此,當vector為空的時候,一定要用push_back()添加值。
但是,如果在定義動態數組v之后,經過了resize 或reserve之后,就可以通過下標訪問
vector<int>v; // v.resize(5); //也可以 v.reserve(5); v[0]=1;
resize的時候會給vector里面填充0,而reserve不會
vector<int> v1; v1.reserve(5); for(int i=0;i<v1.size();i++) { cout<<v1[i]<<" "; } cout<<endl; vector<int> v2; v2.resize(5); for(int i=0;i<v2.size();i++) { cout<<v2[i]<<" "; }
運行結果:
總結
原文鏈接:https://blog.csdn.net/TABE_/article/details/122202695
相關推薦
- 2022-05-08 C#使用Unity實現IOC_實用技巧
- 2022-06-07 Python必備技巧之函數的使用詳解_python
- 2022-07-01 Python判斷Nan值的五種方式小結_python
- 2022-12-08 一文帶你搞懂Go如何讀寫Excel文件_Golang
- 2022-05-18 一起來了解React的Hook_React
- 2022-06-16 C#實現二叉查找樹_C#教程
- 2022-04-28 sql?server?累計求和實現代碼_MsSql
- 2023-06-20 Python實用技巧之臨時文件的妙用_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支