2016/03/06

【C++】Vector 快速使用




1. Headers

?
1
2
#include < algorithm>
#include < vector>

2. 快速使用

(1) 宣告

?
1
2
3
int myints[] = {1,2,3,4,5,4,3,2,1};
vector< int> v1;
v1.assign(myints, myints+9);


(2) 清除、resize、size、empty

?
1
2
3
4
v1.clear();
v1.resize(10);
v1.size();
v1.empty();
v1.erase(iterator);

(3) 加入元素

?
1
2
for (int i=0; i< v1.size(); i++) v1.push_back(i);
for (int i=0; i< v1.size(); i++) v1[i] = i;

(4) Sort, Binary search, find

?
1
2
3
sort(v1.begin(), v1.end());
if (binary_search(v2.begin(), v2.end(), 3))
    cout << "found: 3\n";
vector<int>::iterator it;
it = find(v.begin(), find.end(), 3);
if (it!=v2.end()) out << *it << endl; //found
else cout<<"not found\n" << endl;


(5) 二維

?
1
2
3
4
vector<int> row;
row.assign(m, 0); //設10個0
vector<vector<int>> v;
v.assign(n, row); //n行row