##實戰c++中的vector系列--creating vector of local structure、vector of structs initialization
之前一直沒有使用過`vector<struct>,現在就寫一個簡短的代碼:?
`
~~~
#include <vector>
#include <iostream>
int main() {
struct st { int a; };
std::vector<st> v;
v.resize(4);
for (std::vector<st>::size_type i = 0; i < v.size(); i++) {
v.operator[](i).a = i + 1; // v[i].a = i+1;
}
for (int i = 0; i < v.size(); i++)
{
std::cout << v[i].a << std::endl;
}
}
~~~
用VS2015編譯成功,運行結果:?
1?
2?
3?
4
但是,這是C++11之后才允許的,之前編譯器并不允許你寫這樣的語法,不允許vector容器內放local structure。
更進一步,如果struct里面有好幾個字段呢?
~~~
#include<iostream>
#include<string>
#include<vector>
using namespace std;
struct subject {
string name;
int marks;
int credits;
};
int main() {
vector<subject> sub;
//Push back new subject created with default constructor.
sub.push_back(subject());
//Vector now has 1 element @ index 0, so modify it.
sub[0].name = "english";
//Add a new element if you want another:
sub.push_back(subject());
//Modify its name and marks.
sub[1].name = "math";
sub[1].marks = 90;
sub.push_back({ "Sport", 70, 0 });
sub.resize(8);
//sub.emplace_back("Sport", 70, 0 );
for (int i = 0; i < sub.size(); i++)
{
std::cout << sub[i].name << std::endl;
}
}
~~~
但是上面的做法不好,我們應該先構造對象,后進行push_back 也許更加明智。?
subject subObj;?
subObj.name = s1;?
sub.push_back(subObj);
這個就牽扯到一個問題,為什么不使用emplace_back來替代push_back呢,這也是我們接下來討論 話題。
- 前言
- 構造、operator=和assign區別
- 將迭代器轉換為索引
- copy set to vector(別混淆了reserve和resize)
- 使用vector構造二維數組
- 可怕的迭代器失效(vector重新申請內存)
- 可怕的迭代器失效之二(刪除vector中元素)
- vector<unique_ptr<>>初始化(所有權轉移)
- vector<unique_ptr<>>作為函數的參數
- vector<unique_ptr<>>賦值給vector<unique_ptr<>>
- creating vector of local structure、vector of structs initialization
- 知道emplace_back為何優于push_back嗎?
- emplace_back造成的引用失效
- vector的一些異常
- vector的遍歷(stl算法、vector迭代器(不要在循環中判斷不等于end())、operator[])
- 使用sort算法對vector進行排序(對vector<string>排序、使用穩定的排序std::stable_sort())
- vector應用之STL的find、find_if、find_end、find_first_of、find_if_not(C++11)
- 使用sort算法對vector<unique_ptr<string>>進行排序(sort函數“應輸入 2 個參數,卻提供了 3 個)
- 對vector<自定義類>使用std::find 和 std::find_if 算法