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

From KratosWiki
(Difference between revisions)
Jump to: navigation, search
 
Line 2: Line 2:
  
 
a good reference can be found at the page  
 
a good reference can be found at the page  
[[http://en.wikipedia.org/wiki/Vector_(C++)| wikipedia link]]
+
[[http://en.wikipedia.org/wiki/Vector_(C%2B%2B) wikipedia link]]
  
 
please read CAREFULLY the part that describes the use of iterators when the array is reallocated
 
please read CAREFULLY the part that describes the use of iterators when the array is reallocated

Latest revision as of 13:28, 9 September 2010

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