前几天网友问我c++里面的vector的使用,现在对vector进行简单总结,共享CSDN网友。说明:东西比较简单,如果你很牛,请直接关闭本页!
首先是vector的声明:
#include <vector> using namespace std; // 在这里声明 ... vector<int> i; ... 或者 #include <vector> ... std::vector<int> i; // 在这里显式声明 |
1.vector 的数据的存入和输出: view plaincopy to clipboardprint? vector<CString> v; for(int i =0;i<40;i++) { CString s; s.Format("%d",i); v.push_back(s); } CString ss ; for(int j =0;j<v.size();j++) { ss+=v[j]+","; } MessageBox(ss); vector<CString> v; for(int i =0;i<40;i++) { CString s; s.Format("%d",i); v.push_back(s); } CString ss ; for(int j =0;j<v.size();j++) { ss+=v[j]+","; } MessageBox(ss); 注:你也可以用v.begin()和v.end() 来得到vector开始的和结束的元素地址的指针位置。你也可以这样做: view plaincopy to clipboardprint? vector<CString> v; for(int i =0;i<40;i++) { CString s; s.Format("%d",i); v.push_back(s); } CString ss ; vector<CString>::iterator iter; for( iter = v.begin(); iter != v.end(); iter++ ) { ss+= *iter+","; } MessageBox(ss); vector<CString> v; for(int i =0;i<40;i++) { CString s; s.Format("%d",i); v.push_back(s); } CString ss ; vector<CString>::iterator iter; for( iter = v.begin(); iter != v.end(); iter++ ) { ss+= *iter+","; } MessageBox(ss); 2.对于二维vector的定义(开始就固定长度) view plaincopy to clipboardprint? vector< vector<CString> > Array( 10, vector<CString>(0) ); for( int j = 0; j < 10; j++ ) { for (int i = 0; i < 9; i++ ) { CString s; s.Format("%d",i); Array[ i ].push_back(s); } } CString ss; for( int jj = 0; jj < 10; jj++ ) { for(int ii = 0; ii < Array[ jj ].size(); ii++ ) { ss+=Array[jj][ii]; } } MessageBox(ss); vector< vector<CString> > Array( 10, vector<CString>(0) ); for( int j = 0; j < 10; j++ ) { for (int i = 0; i < 9; i++ ) { CString s; s.Format("%d",i); Array[ i ].push_back(s); } } CString ss; for( int jj = 0; jj < 10; jj++ ) { for(int ii = 0; ii < Array[ jj ].size(); ii++ ) { ss+=Array[jj][ii]; } } MessageBox(ss); 3.定义一个行列都是变化的数组 view plaincopy to clipboardprint? int i = 0, j = 0; vector< vector<CString> > Array; vector< CString > line; for( j = 0; j < 10; j++ ) { Array.push_back( line );//要对每一个vector初始化,否则不能存入元素。 for ( i = 0; i < 9; i++ ) { CString s; s.Format("%d",i); Array[ j ].push_back( s ); } } CString ss; for(int jj = 0;jj<Array.size();jj++) { for(int ii =0;ii<Array[jj].size();ii++) { ss+=Array[jj][ii]; } } MessageBox(ss); |