Sunday, June 23, 2013

std::vector

C++中std的vector十分方便,可以解決多數動態大小的問題,是索引值的方式和array更是相同,而新的值用pushback加入。

#include <cstdio>
#include <vector>

using namespace std;

int main(){

 vector<int> myVector;

 // setter: push new
 myVector.push_back(2); // index = 0
 myVector.push_back(5); // index = 1
 myVector.push_back(1); // index = 2

 // getter: by index
 printf("%d\n", myVector[1]); // 5

 // get size
 int size = myVector.size();
 printf("size = %d\n", size);

 return 0;
}