程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> vector,vectorc++

vector,vectorc++

編輯:C++入門知識

vector,vectorc++


摘自<<C++ Primer>> 5th, chapter 3

 

vector

  a class template; a collection of objects, all of which have the same type

1  初始化

  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  添加元素

  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  操作

  v.empty()

  v.size()      return the number of elements in v

  v[n]           return a 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.

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved