如何访问 C++ 中通过引用传递的列表/向量的元素
问题是通过引用传递列表/向量向量
int main(){
list<int> arr;
//Adding few ints here to arr
func1(&arr);
return 0;
}
void func1(list<int> * arr){
// How Can I print the values here ?
//I tried all the below , but it is erroring out.
cout<<arr[0]; // error
cout<<*arr[0];// error
cout<<(*arr)[0];//error
//How do I modify the value at the index 0 ?
func2(arr);// Since it is already a pointer, I am passing just the address
}
void func2(list<int> *arr){
//How do I print and modify the values here ? I believe it should be the same as above but
// just in case.
}
与列表有什么不同吗?提前致谢。
任何详细解释这些内容的链接都会有很大帮助。再次感谢。
The problem is passing lists/vectors by reference
int main(){
list<int> arr;
//Adding few ints here to arr
func1(&arr);
return 0;
}
void func1(list<int> * arr){
// How Can I print the values here ?
//I tried all the below , but it is erroring out.
cout<<arr[0]; // error
cout<<*arr[0];// error
cout<<(*arr)[0];//error
//How do I modify the value at the index 0 ?
func2(arr);// Since it is already a pointer, I am passing just the address
}
void func2(list<int> *arr){
//How do I print and modify the values here ? I believe it should be the same as above but
// just in case.
}
Is the vectors any different from the lists ? Thanks in advance.
Any links where these things are explained elaborately will be of great help. Thanks again.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不是通过引用传递列表,而是通过指针传递列表。在《C talk》中,两者是相等的,但由于C++中有引用类型,所以区别很明显。
要通过引用传递,请使用 &而不是 * - 并“正常”访问,即
要通过指针传递,您需要用星号取消引用指针(并注意运算符的存在),即
没有
operator[]std::list
中的代码>。You aren't passing the
list
by reference, but by a pointer. In "C talk" the two are equal, but since there is a reference type in C++, the distinction is clear.To pass by reference, use & instead of * - and access "normally", i.e.
To pass by pointer, you need to derefer the pointer with an asterisk (and do take note of operator presedence), i.e.
There is no
operator[]
instd::list
.在您的示例中,未指定 func1() 的返回类型。所以我指定了它。您可以从
void
更改为其他类型。另外,不要忘记指定func2()
和main()
的返回类型。如果你想使用下标运算符
[]
,那么你必须使用std::vector
,如list<>
不会重载operator[]
。在这种情况下,您可以这样写:我仍然假设 arr 是指向 vector的指针。
也许,您想稍微修改一下您的代码,如下所示:
In your example, return type of func1() is not specified. So I specified it. You may change from
void
to some other type. Also don't forget to specify return type forfunc2()
andmain()
too.If you want to use subscript operator
[]
, then you've to usestd::vector<int>
, aslist<>
doesn't overloadoperator[]
. In that case, you can write :I'm still assuming
arr
is pointer tovector<int>
.Maybe, you would like to modify your code a little bit, like this: