1. 程式人生 > >C++:vector遍歷,拷貝,插入

C++:vector遍歷,拷貝,插入

vector遍歷:

類C遍歷,按插入順序

vector<int> a = {1,2,3,4,5};
for(int i=0;i<a.size();i++) printf("%d%s",a[i],i==a.size()-1?"\n":" ");

迭代器遍歷

vector<int> a = {1,2,3,4,5};
for(vector<int>::iterator p=a.begin();p!=a.end();p++) printf("%d%s",*p,p==a.end()-1?"\n":" ");

類const迭代器訪問,不可對原始vector進行修改

vector<int> a = {1,2,3,4,5};
for(auto p = a.cbegin();p!=a.cend();p++) printf("%d%s",*p,p==a.cend()-1?"\n":" ");

自適應指標遍歷,結尾會多一個空格

vector<int> a = {1,2,3,4,5};
for(auto p:a) printf("%d ",p);

vector拷貝

int型vector

宣告時拷貝,深拷貝

vector<int> a = {1,2,3,4,5};
vector<int>
b(a); a.clear(); for(auto p:b) printf("%d ",p);

賦值拷貝,深拷貝

vector<int> a = {1,2,3,4,5};
vector<int> b;
b = a;
a.clear();
for(auto p:b) printf("%d ",p);

assign分配,深拷貝

vector<int> a = {1,2,3,4,5};
vector<int> b;
b.assign(a.cbegin(), a.cend());
a.clear();
for(auto p:b) printf
("%d ",p);

追加插入,深拷貝

vector<int> a = {1,2,3,4,5};
vector<int> b;
b.insert(b.cend(),a.cbegin(), a.cend());
a.clear();
for(auto p:b) printf("%d ",p);

struct型vector

宣告時拷貝,深拷貝

struct Node{
    int n;
    Node(int nn){n = nn;}
};
vector<Node> a;
for(int i=1;i<=5;i++) a.push_back(Node(i));
vector<Node> b(a);
a.clear();
for(auto p:b) printf("%d ",p.n);

賦值拷貝,深拷貝

struct Node{
    int n;
    Node(int nn){n = nn;}
};
vector<Node> a;
for(int i=1;i<=5;i++) a.push_back(Node(i));
vector<Node> b = a;
a.clear();
for(auto p:b) printf("%d ",p.n);

vector插入

插入單個數據:

vector<int> a = {1,2,3,4,5};
a.insert(a.cbegin(),0);
for(auto t:a) printf("%d ",t); //輸出0 1 2 3 4 5

插入重複的單個數據:

vector<int> a = {1,2,3,4,5};
a.insert(a.cbegin(),2,0);
for(auto t:a) printf("%d ",t); //輸出0 0 1 2 3 4 5

插入一個數組:

vector<int> a = {1,2,3,4,5};
vector<int> b = {6,7};
a.insert(a.cbegin(),b.cbegin(),b.cbegin()+1);
for(auto t:a) printf("%d ",t); //輸出6 1 2 3 4 5