How to Use the std::vector (and the kratos containers)

From KratosWiki
Jump to: navigation, search

The Kratos containers are mounted on the top of the std library. Correct usage REQUIRES understanding how the std::vector works

a good reference can be found at the page [wikipedia link]

please read CAREFULLY the part that describes the use of iterators when the array is reallocated

In any case, the problem one should be aware of is described in the following example:

 std::vector<int> a;
 a.reserve(10); //here the capacity is set to 10, but the vector is still empty
 a.push_back(2);
 std::vector<int>::iterator iii = a.begin();
 std::cout << *iii << std::endl; //outputs "2"
 //here we performs 20 push backs so to force reallocation of the array
 for(unsigned int i=0; i<20; i++)
       a.push_back(1);
 //as the array was reallocated, iii does not anymore point to the beginning of a.
 std::cout << *iii << std::endl; //THIS BREAKS THE MEMORY!
 a.begin() == iii //RETURNS FALSE!!
Personal tools
Categories