【问题标题】:How to access the element of a list/vector that passed by reference in C++如何访问在 C++ 中通过引用传递的列表/向量的元素
【发布时间】:2011-06-05 16:38:32
【问题描述】:

问题是通过引用传递列表/向量

   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.
     }

向量与列表有什么不同吗?提前致谢。

任何详细解释这些内容的链接都会有很大帮助。再次感谢。

【问题讨论】:

  • 这甚至无法编译。
  • @prasoon :cmets 中的错误意味着编译时错误。关于如何以正确/正确的方式处理它的任何解决方案?
  • 我的意思是除了提到的错误之外,代码还有一些错误。缺少 mainfunc1func2 的返回类型。 main 应该返回一个 int
  • 我实际上主要是在使用 [] 运算符。但我刚刚发现它仅适用于矢量而不适用于列表。谢谢大家。
  • @bsoundra: 嗯,它是通过指针传递的,的引用,但是如果你传递 NULL 等会发生什么。如果你传递一个真正的引用,那么你不必担心 NULL 或类似的东西。有关详细信息,请参阅此:stackoverflow.com/questions/3224155/…

标签: c++ list vector pass-by-reference


【解决方案1】:

您不是通过引用传递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[]

【讨论】:

    【解决方案2】:
       //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&lt;int&gt;,因为list&lt;&gt; 不会重载operator[]。在这种情况下,你可以写:

    for(std::vector<int>::size_type i = 0 ; i < arr->size() ; i++ )
    {
        cout << (*arr)[i] << endl;
    }
    

    我仍然假设arr 是指向vector&lt;int&gt; 的指针。

    也许,您想稍微修改一下您的代码,如下所示:

       void func1(vector<int> & arr) // <-- note this change!
       {
             for(std::vector<int>::size_type i = 0 ; i < arr.size() ; i++ )
             {
                    cout << arr[i] << endl;
             }
       }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-05
      • 1970-01-01
      • 1970-01-01
      • 2015-04-26
      • 2021-12-28
      • 1970-01-01
      • 2021-12-28
      相关资源
      最近更新 更多