Saturday, July 18, 2015

some tricks in using vector.size() in C++

In the container vector, size() is used to indicate how many space have been occupied by the assigned values:

vector<int> test; //the test.size() is 0;
test.push_back(1);//the test.size() is 1...

Andy usually we can use this to control for loop like:

for (int i=0; i<test.size();i++){

}


But the tricky thing is that if you define this way:

vector<int> test(100); //the test.size() is 100, regardless that no value is assigned!
test[1]=1; // the test.size() is still 100;
test[2]=1; // the test.size() is still 100; this kind of assignment apparently doesn't change the size of  test. But if you defind like: vector<int> test;, you can't use this kind of assignment as not space inside.

test.push_back(1);//the test.size() is now 101...

In such case, you should be careful when using this to control the for loop.

BTW, another way for for loop is using the iterator direcly:

  for (std::vector<int>::iterator it = myvector.begin() ; it != myvector.end(); ++it){
}

No comments:

Post a Comment