标签:
摘自<<C++ Primer>> 5th, chapter 3
vector 容器
a class template; a collection of objects, all of which have the same type
1 initializing
vector<T> v1
vector<T> v2(v1) vector<T> v2 = v1;
vector<T> v3(n, val) vector<T> v4(n);
vector<T> v5{a, b, c...} vector<T> v5= {a, b, c...}
例1):
vector<int> ivec; // initally empty vector<int> ivec2(ivec); vector<string> svec(10, "hi!"); //10 elements, each is a string "hi!" vector<string> articles = {"a", "an", "the"}; vector<int> v1(10, 1); // 10 elements with value 1 vector<int> v2{10, 1}; // 2 elements with values 10 and 1
2 adding elements
It‘s better to create an empty vector and use push_back to add elements at run time.
例 2):
vector<int> ivec; for(int i = 0; i != 100; i++) ivec.push_back(i); sting s; vector<sting> svec; while(cin > s) { svec.push_back(s); }
3 operations
v.empty()
v.size() return the number of elements in v
v[n] returna reference to the element at positon n in v
v1 = v2
v1 = {a, b, c...}
v1 == v1 v1 != v2
<, <=, >, >=
例 3):
vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9}; for(auto &i: v) // for each element in v (i is a reference) i * = i; for(auto i: v) cout << i << " "; cout < endl;
4 using subscripts
1) computing a vector index
// count the number of grades by clusters of ten: // 0~9, 10~19, ..., 90~99, 100 vector<unsigned> scores(11, 0); unsigned grade; while(cin >> grade) { if (grade <= 100) ++scores[grade/10]; }
2) subscripting does not add elements
vector<int> ivec; for(decltype(ivec.size()) ix = 0; ix != 10; ++ix) ivec[ix] = ix; // disaster: ivec has no elements ivec.push_back(ix);
the subscript operator on vector(and sting) fetches an existing element; it does not add an element.
标签:
原文地址:http://www.cnblogs.com/xinxue/p/5240642.html