C++中vector容器的注意事項總結
容量(capacity)和大?。╯ize)的區(qū)別
vector 容器的容量(用 capacity 表示),指的是在不分配更多內(nèi)存的情況下,容器可以保存的最多元素個數(shù);而 vector 容器的大?。ㄓ?size 表示),指的是它實際所包含的元素個數(shù)。
對于一個 vector 對象來說,通過該模板類提供的 capacity() 成員函數(shù),可以獲得當前容器的容量;通過 size() 成員函數(shù),可以獲得容器當前的大小。例如:
#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 容器的大小不能超出它的容量,在大小等于容量的基礎上,只要增加一個元素,就必須分配更多的內(nèi)存。注意,這里的“更多”并不是 1 個。換句話說,當 vector 容器的大小和容量相等時,如果再向其添加(或者插入)一個元素,vector 往往會申請多個存儲空間,而不僅僅只申請 1 個。
一旦 vector 容器的內(nèi)存被重新分配,則和 vector 容器中元素相關的所有引用、指針以及迭代器,都可能會失效,最穩(wěn)妥的方法就是重新生成。
容器擴容的本質
vector 容器擴容的過程需要經(jīng)歷以下 3 步:
- 完全棄用現(xiàn)有的內(nèi)存空間,重新申請更大的內(nèi)存空間(一般是原空間的1.5倍);
- 將舊內(nèi)存空間中的數(shù)據(jù),按原有順序移動到新的內(nèi)存空間中;
- 最后將舊的內(nèi)存空間釋放。
由此可見,vector 擴容是非常耗時的。為了降低再次分配內(nèi)存空間時的成本,每次擴容時 vector 都會申請比用戶需求量更多的內(nèi)存空間(這也就是 vector 容量的由來,即 capacity>=size),以便后期使用。
emplace_back()和push_back()的區(qū)別
vector中可以用來從容器末尾添加元素的函數(shù)有 2 個,分別是 push_back() 和 emplace_back() 函數(shù)。
push_back()函數(shù)的功能是在 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()函數(shù)是 C++ 11 新增加的,其功能和 push_back() 相同,都是在 vector 容器的尾部添加一個元素。
emplace_back() 成員函數(shù)的用法也很簡單,這里直接舉個例子:
#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() 的區(qū)別,就在于底層實現(xiàn)的機制不同。push_back() 向容器尾部添加元素時,首先會創(chuàng)建這個元素,然后再將這個元素拷貝或者移動到容器中(如果是拷貝的話,事后會自行銷毀先前創(chuàng)建的這個元素);而 emplace_back() 在實現(xiàn)時,則是直接在容器尾部創(chuàng)建這個元素,省去了拷貝或移動元素的過程。(可以看作是零拷貝的實現(xiàn))
為了讓大家清楚的了解它們之間的區(qū)別,我們創(chuàng)建一個包含類對象的 vector 容器,如下所示:
#include <vector> #include <iostream> using namespace std; class testDemo { public: testDemo(int num):num(num){ std::cout << "調(diào)用構造函數(shù)" << endl; } testDemo(const testDemo& other) :num(other.num) { std::cout << "調(diào)用拷貝構造函數(shù)" << endl; } testDemo(testDemo&& other) :num(other.num) { std::cout << "調(diào)用移動構造函數(shù)" << 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:
調(diào)用構造函數(shù)
push_back:
調(diào)用構造函數(shù)
調(diào)用移動構造函數(shù)
在此基礎上,讀者可嘗試將 testDemo 類中的移動構造函數(shù)注釋掉,再運行程序會發(fā)現(xiàn),運行結果變?yōu)椋?/span>
emplace_back:
調(diào)用構造函數(shù)
push_back:
調(diào)用構造函數(shù)
調(diào)用拷貝構造函數(shù)
由此可以看出,push_back() 在底層實現(xiàn)時,會優(yōu)先選擇調(diào)用移動構造函數(shù),如果沒有才會調(diào)用拷貝構造函數(shù)。
顯然完成同樣的操作,push_back() 的底層實現(xiàn)過程比 emplace_back() 更繁瑣,換句話說,emplace_back() 的執(zhí)行效率比 push_back() 高。因此,在實際使用時,建議大家優(yōu)先選用 emplace_back()。
emplace()和insert()的區(qū)別
insert() 函數(shù)的功能是在 vector 容器的指定位置插入一個或多個元素。
下面的例子,演示了如何使用 insert() 函數(shù)向 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 標準新增加的成員函數(shù),用于在 vector 容器指定位置之前插入一個新的元素。emplace() 每次只能插入一個元素,而不是多個。
該函數(shù)的語法格式如下:
iterator emplace (const_iterator pos, args...);
其中,pos 為指定插入位置的迭代器;args… 表示與新插入元素的構造函數(shù)相對應的多個參數(shù);該函數(shù)會返回表示新插入元素位置的迭代器。
舉個例子:
#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 << "調(diào)用構造函數(shù)" << endl; } testDemo(const testDemo& other) :num(other.num) { std::cout << "調(diào)用拷貝構造函數(shù)" << endl; } testDemo(testDemo&& other) :num(other.num) { std::cout << "調(diào)用移動構造函數(shù)" << 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:
調(diào)用構造函數(shù)
調(diào)用移動構造函數(shù)
emplace:
調(diào)用構造函數(shù)
注意,當拷貝構造函數(shù)和移動構造函數(shù)同時存在時,insert() 會優(yōu)先調(diào)用移動構造函數(shù)。
可以看到,通過 insert() 函數(shù)向 vector 容器中插入 testDemo 類對象,需要調(diào)用類的構造函數(shù)和移動構造函數(shù)(或拷貝構造函數(shù));而通過 emplace() 函數(shù)實現(xiàn)同樣的功能,只需要調(diào)用構造函數(shù)即可。
簡單的理解,就是 emplace() 在插入元素時,是在容器的指定位置直接構造元素,而不是先單獨生成,再將其復制(或移動)到容器中。因此,在實際使用中,推薦大家優(yōu)先使用 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()添加值。
但是,如果在定義動態(tài)數(shù)組v之后,經(jīng)過了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]<<" "; }
運行結果:
總結
到此這篇關于C++中vector容器注意事項的文章就介紹到這了,更多相關C++?vector容器注意內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
深入理解C++中的new和delete并實現(xiàn)對象池
這篇文章主要介紹了C++中的new和delete并實現(xiàn)對象池,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-09-09C語言的abs()函數(shù)和div()函數(shù)你了解嗎
這篇文章主要為大家詳細介紹了C語言的abs()函數(shù)和div()函數(shù),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-02-02