通过指针读取数组元素的值时出错 [英] Error while reading the value of an array element by pointer

查看:196
本文介绍了通过指针读取数组元素的值时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码将矢量写入地图容器:

I use the following code for writing the vector to map container:

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));



当我尝试读取存储在向量中的数组的第二个元素的值时,指向存储在地图容器中的指针: br />


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:

std::vector<int *> *my_ptr;
my_ptr = my_map[1];
int out = my_ptr[0][1];



然后我收到错误:


then I get an error:

Cannot convert 'int * &' to 'int'



如何修复此代码?


How to fix this code?

推荐答案

my_array是一个包含2个整数值的数组,356和41,到目前为止都很好;)...



我假设my_vector被声明为std ::矢量< INT * GT; ?那么是一个指向整数的指针的向量,或者在你的情况下,我假设你打算将它作为指向数组的指针的向量(或者更确切地说是指向数组的FIRST元素的指针向量)?



当你调用my_vector.push_back时,一切都很好,指向数组第一个元素的指针在那里,my_vector有1个元素。



所以现在你想要一个可以包含多个数组向量的键控集合....(思考集合集合的目的)。地图键入一个整数,该值是一个指向数组中第一项指针向量的指针。



所以你访问向量,使用整数键:



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:

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





my_ptr现在是一个指向数组第一个元素指针向量的指针。









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

OR

my_ptr == &my_vector;





为了像my_vector一样访问my_ptr,它需要被解除引用:





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

int out = (*my_ptr)[0][1];


这篇关于通过指针读取数组元素的值时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆