Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers to elements of std::vector and std::list

I'm having a std::vector with elements of some class ClassA. Additionally I want to create an index using a std::map<key,ClassA*> which maps some key value to pointers to elements contained in the vector.

Is there any guarantee that these pointers remain valid (and point to the same object) when elements are added at the end of the vector (not inserted). I.e, would the following code be correct:

std::vector<ClassA> storage; std::map<int, ClassA*> map;  for (int i=0; i<10000; ++i) {   storage.push_back(ClassA());   map.insert(std::make_pair(storage.back().getKey(), &(storage.back())); } // map contains only valid pointers to the 'correct' elements of storage 

How is the situation, if I use std::list instead of std::vector?

like image 915
MartinStettner Avatar asked Jul 20 '10 07:07

MartinStettner


People also ask

Can you use pointers with vectors?

An alternative method uses a pointer to access the vector. w = new std::vector<int>(); The new operator creates a new, empty vector of ints and returns a pointer to that vector. We assign that pointer to the pointer variable w , and use w for the remainder of the code to access the vector we created with new .

What is the difference between std::list and std :: vector?

Hence std::list provides some extra functions for Sorting, Splicing, Removing elements and identifying unique elements. Vector provides the random access and hence can be used with STL algorithms that uses Random Access Iterators.

Is STD Vector a pointer?

std::vector::dataReturns a direct pointer to the memory array used internally by the vector to store its owned elements.


1 Answers

Vectors - No. Because the capacity of vectors never shrinks, it is guaranteed that references, pointers, and iterators remain valid even when elements are deleted or changed, provided they refer to a position before the manipulated elements. However, insertions may invalidate references, pointers, and iterators.

Lists - Yes, inserting and deleting elements does not invalidate pointers, references, and iterators to other elements

like image 158
DumbCoder Avatar answered Oct 12 '22 02:10

DumbCoder