Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
3.11/5 (2 votes)
I use the following code for writing the vector to map container:
C++
int my_array[2];
my_array[0] = 356;
my_array[1] = 41;
 
my_vector.push_back(my_array);
 
std::map<int, std::vector<int *>*> my_map;
my_map.insert(std::pair<int, std::vector<int *>*> (1, &my_vector));

And when I try to read the value of the second element of the array, which is stored in a vector, a pointer to which is stored in the map container:
C++
std::vector<int *> *my_ptr;
my_ptr = my_map[1];
int out = my_ptr[0][1];

then I get an error:
C++
Cannot convert 'int * &' to 'int'

How to fix this code?
Posted
Comments
Richard MacCutchan 22-Sep-14 12:52pm    
The message is telling you that my_ptr[0][1] is returning a pointer to an integer, not an actual integer.
Igor-84 22-Sep-14 13:55pm    
Ok. How to get an actual integer from my_ptr[0][1]?
If I write this:
int out = (int)my_ptr[0][1];
Then I get a weird number 6357101.
Richard MacCutchan 23-Sep-14 4:00am    
You cannot cast an int* to an int and expect a sensible result. A cast just tells the compiler to treat one type as another, but it does not do any conversion.

In your code above my_ptr is a pointer to a vector of int*, so you need to extract the relevant pointer from the vector, and use that value to get the actual integer value. I'm not clear what you are trying to achieve by doing all this but I presume you have a good reason.

1 solution

my_array is an array of 2 integer values, 356 and 41, all good so far ;) ...

I am assuming that my_vector is declared as a std::vector<int*> ? So is a vector of pointers to integers, or in your case, I am assuming you intend it to be a vector of pointers to arrays (or rather a vector of pointers to the FIRST element of an array)?

When you call my_vector.push_back, it is all good, the pointer to the first element of the array is in there, my_vector has 1 element.

So now you want a keyed collection that can contain multiple vectors of arrays .... (ponders purpose of collections of collections of collections). the map is keyed on an integer and the value is a pointer to a vector of pointers to the first item in an array.

So you access the vector, using the integer key:

C++
std::vector<int> *my_ptr; 
my_ptr = my_map[1];
</int>


my_ptr is now a pointer to a vector of pointers to the first element of an array.

OR

C++
my_ptr == &my_vector;


In order to access my_ptr as you would my_vector, it needs to be dereferenced:

C++
int out = (*my_ptr)[0][1];
 
Share this answer
 
Comments
Igor-84 23-Sep-14 7:01am    
Thank you very much! It works!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900