謠言指出,vector 效能操作比 C 之 malloc、memcpy、memset、memcmp 來得慢。還在謠傳這謠言的,麻煩開 Optimize 測一次,覺得結果有誤,多測幾次也無妨。
note 到後面愈來愈心虛,技巧概念就那一、二個而已。
零、變數假設
Code Snippet
- typedef int Type; // Type can be class
- const Type Val=1; // a value of Type
- const size_t xCount=2;
- const size_t yCount=3;
壹、一維初始化並給值
Code Snippet
- // v1[xCount=2] = {0,0}
- vector<Type> v1(xCount);
- // v2[xCount=2] = {Val,Val}
- vector<Type> v2(xCount, Val);
貮、二維初始配置並給值
Code Snippet
- // Type v1[xCount][yCount] = {{0,0,0},{0,0,0}}
- // Method 1
- vector< vector<Type> > v1( xCount);
- for(size_t i=0; i<xCount; ++i)
- v1[i].resize(yCount);
- // Type v1[xCount][yCount] = {{0,0,0},{0,0,0}}
- // Method 2
- vector< vector<Type> > v2(xCount, vector<Type>(yCount) );
- // Type v1[xCount][yCount] = {{val,val,val},{val,val,val}}
- // Method 3
- vector< vector<Type> > v3(xCount, vector<Type>(yCount, Val));
參、一維變更大小
Code Snippet
- vector<Type> v1;
- v1.resize(xCount); /* v1[xCount=2] = {0,0} */
- v1.resize(3,Val) ; /* v1[3] = {0,0,Val} */
- v1.resize(5) ; /* v1[5] = {0,0,Val,0,0} */
肆、二維變更大小
Code Snippet
- // resize v1[xCount][yCount] = {0}
- vector<vector<Type> > v1;
- v1.resize( xCount, vector<Type>(yCount) );
- // resize v2[xCount][yCount] = {Val,Val,Val,...}
- vector<vector<Type> > v2;
- v2.resize( xCount, vector<Type>(yCount, Val));
- //(!) be care here
- vector<vector<Type> > v3;
- v3.resize( xCount, vector<Type>(yCount)); // v3 = {0.0,...}
- v3.resize( xCount, vector<Type>(yCount,Val));
- // v3 = {0,0,0,...} still.
伍、完整複製
Code Snippet
- vector<Type> v2;
- vector<Type> v1(3);
- for(size_t i=0; i<v1.size(); ++i) v1[i] = i;
- v2 = v1; // v2 = {0,1,2}
陸、部份複製
Code Snippet
- // include <algorithm>
- vector<Type> v2;
- vector<Type> v1(10);
- for(size_t i=0; i<v1.size(); ++i) v1[i] = i;
- // give v2 size
- v2.resize(10);
- // v2[5:8] = v1[2:5], 也可初始化時複製
- copy(v1.begin()+2, v1.begin()+5, v2.begin()+5);
柒、全部設定相同值
Code Snippet
- // include <algorithm>
- // for 1 dim
- vector<Type> v1(10);
- for(size_t i=0; i<v1.size(); ++i) v1[i] = i;
- fill(v1.begin(), v1.end(), Val);
- // for 2 dim
- vector< vector<Type> > v2(xCount, vector<Type>(yCount));
- fill(v2.begin(), v2.end(), vector<Type>(yCount, Val));
剩下的沒什麼技巧問題,只有看過、沒看過問題。
實在是記不下去了,把 C++ Reference vector 、Algorithm 範例翻一翻,
vector 操作應就會比 C 強很多了。
全站熱搜