[英]How to access the element of a list/vector that passed by reference in 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.
}
向量與列表有什么不同嗎? 提前致謝。
精心解釋這些內容的任何鏈接都將大有幫助。 再次感謝。
您不是通過引用傳遞list
,而是通過指針傳遞list
。 在“ C talk”中,兩者是相等的,但是由於C ++中存在引用類型,因此區別很明顯。
要通過引用傳遞,請使用&而不是*-並“正常”訪問,即
void func(list<int>& a) {
std::cout << a.size() << "\n";
}
要通過指針傳遞,您需要用星號取消引用指針(並注意操作員的存在),即
void func(list<int>* arr) {
std::cout << (*a).size() << "\n"; // preferably a->size();
}
std::list
沒有operator[]
。
//note the return type also!
void func1(list<int> * arr)
{
for (list<int>::iterator i= arr->begin() ; i!= arr->end(); i++ )
{
//treat 'i' as if it's pointer to int - the type of elements of the list!
cout<< *i << endl;
}
}
在您的示例中,未指定func1()的返回類型。 所以我指定了它。 您可以從void
更改為其他類型。 同樣不要忘記為func2()
和main()
指定返回類型。
如果要使用下標運算符[]
,則必須使用std::vector<int>
,因為list<>
不會重載operator[]
。 在這種情況下,您可以編寫:
for(std::vector<int>::size_type i = 0 ; i < arr->size() ; i++ )
{
cout << (*arr)[i] << endl;
}
我仍然假設arr
是指向vector<int>
指針。
也許您想對代碼進行一些修改,如下所示:
void func1(vector<int> & arr) // <-- note this change!
{
for(std::vector<int>::size_type i = 0 ; i < arr.size() ; i++ )
{
cout << arr[i] << endl;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.