謠言指出,vector 效能操作比 C 之 malloc、memcpy、memset、memcmp 來得慢。還在謠傳這謠言的,麻煩開 Optimize 測一次,覺得結果有誤,多測幾次也無妨。

note 到後面愈來愈心虛,技巧概念就那一、二個而已。

 

零、變數假設

 

Code Snippet
  1. typedef int  Type;    // Type can be class
  2. const Type   Val=1;   // a value of Type
  3. const size_t xCount=2;
  4. const size_t yCount=3;

 

壹、一維初始化並給值

 

Code Snippet
  1. // v1[xCount=2] = {0,0}
  2. vector<Type> v1(xCount);
  3. // v2[xCount=2] = {Val,Val}
  4. vector<Type> v2(xCount, Val);

 

貮、二維初始配置並給值

 

Code Snippet
  1. // Type v1[xCount][yCount] = {{0,0,0},{0,0,0}}
  2. // Method 1
  3. vector< vector<Type> > v1( xCount);
  4. for(size_t i=0; i<xCount; ++i)
  5.     v1[i].resize(yCount);
  6.  
  7. // Type v1[xCount][yCount] = {{0,0,0},{0,0,0}}
  8. // Method 2
  9. vector< vector<Type> > v2(xCount, vector<Type>(yCount) );
  10.  
  11. // Type v1[xCount][yCount] = {{val,val,val},{val,val,val}}
  12. // Method 3
  13. vector< vector<Type> > v3(xCount, vector<Type>(yCount, Val));

 

參、一維變更大小

 

Code Snippet
  1. vector<Type> v1;    
  2. v1.resize(xCount); /* v1[xCount=2] = {0,0}   */
  3. v1.resize(3,Val) ; /* v1[3] = {0,0,Val}      */
  4. v1.resize(5)     ; /* v1[5] = {0,0,Val,0,0}  */

 

肆、二維變更大小

 

Code Snippet
  1. // resize v1[xCount][yCount] = {0}
  2. vector<vector<Type> > v1;
  3. v1.resize( xCount, vector<Type>(yCount) );
  4.  
  5. // resize v2[xCount][yCount] = {Val,Val,Val,...}
  6. vector<vector<Type> > v2;
  7. v2.resize( xCount, vector<Type>(yCount, Val));
  8.  
  9. //(!) be care  here
  10. vector<vector<Type> > v3;
  11. v3.resize( xCount, vector<Type>(yCount)); // v3 = {0.0,...}
  12. v3.resize( xCount, vector<Type>(yCount,Val));
  13. // v3 = {0,0,0,...} still.

 

伍、完整複製

 

Code Snippet
  1. vector<Type> v2;
  2. vector<Type> v1(3);
  3. for(size_t i=0; i<v1.size(); ++i) v1[i] = i;
  4. v2 = v1; // v2 = {0,1,2}

 

陸、部份複製

 

Code Snippet
  1. // include <algorithm>
  2. vector<Type> v2;
  3. vector<Type> v1(10);
  4. for(size_t i=0; i<v1.size(); ++i) v1[i] = i;
  5.  
  6. // give v2 size
  7. v2.resize(10);
  8. // v2[5:8] = v1[2:5], 也可初始化時複製
  9. copy(v1.begin()+2, v1.begin()+5, v2.begin()+5);

 

柒、全部設定相同值

 

Code Snippet
  1. // include <algorithm>
  2. // for 1 dim
  3. vector<Type> v1(10);
  4. for(size_t i=0; i<v1.size(); ++i) v1[i] = i;
  5. fill(v1.begin(), v1.end(), Val);
  6.  
  7. // for 2 dim
  8. vector< vector<Type> > v2(xCount, vector<Type>(yCount));
  9. fill(v2.begin(), v2.end(), vector<Type>(yCount, Val));

 

剩下的沒什麼技巧問題,只有看過、沒看過問題。

實在是記不下去了,把 C++ Reference vector 、Algorithm 範例翻一翻,

vector 操作應就會比 C 強很多了。

edisonx 發表在 痞客邦 PIXNET 留言(0) 人氣()