码迷,mamicode.com
首页 > 其他好文 > 详细

vector

时间:2016-03-04 01:53:52      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:

摘自<<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
View Code

 

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);
}
View Code

 

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;
View Code

 

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];
}
View Code

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);
View Code

  the subscript operator on vector(and sting) fetches an existing element; it does not add an element.

 

vector

标签:

原文地址:http://www.cnblogs.com/xinxue/p/5240642.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!