Vector pointer

Jul 3, 2011 at 1:48pm
I'm looking for some assistance in understanding a pointer to a vector. Suppose I have the following:

 
std::vector<string> string_vector;


This statement instantiates a vector of type string with zero elements.

Now, if I have:

 
std::vector<string> * p_string_vector;

Does this mean p_string_vector is essentially a vector of pointers (contains addresses of the elements of the vector)?

How would I dereference each element of p_string_vector to get the string (not the address)?

Thanks in advance!

L.
Jul 3, 2011 at 1:53pm
It is a pointer to a vector of strings. p_string_vector itself is a pointer, and when you dereference it you get the vector of strings.

This is a vector of pointers, which is different:
std::vector<std::string*> vector_of_string_pointers;

You would access the elements the same way, except that since they are pointers you probably want to get what they are pointing to by dereferencing them.
Jul 3, 2011 at 2:04pm
Great. Now that I think about it, this makes sense. It follows the same format as standard pointers:

1
2
int i = 0; // holds the value 0
int * i = &i;  // holds the address of i 


How does one deal with iterations of std::vector<string>* p_string_vector ?

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14

//snippet of code
std:vector<string> string_vector;  
string_vector.push_back ("Hello ");
string_vector.push_back ("World!");

std:vector<string> * p_string_vector = &string_vector;  // i would like to iterate across this and cout the value

std::vector<string>::iterator it;  // instantiate the iterator  (is there a special iterator for pointers?)

for (it=p_string_vector.begin(); it!=p_string_vector.end(); ++it)
{
std::cout << *it << std::endl;
}
Jul 3, 2011 at 2:11pm
begin() and end() are member functions of std::vector<>. Since you have a pointer to one of those, you use pointer syntax to call the member functions. Eg., p_string_vector->begin().

Jul 3, 2011 at 2:17pm
Man, you guys are awesome. By far, the best resource I've found on the web.

Thanks again!!
Topic archived. No new replies allowed.