How to access the contents of a vector from a pointer to the vector in C++?

后端 未结 8 882
不思量自难忘°
不思量自难忘° 2020-11-30 17:26

I have a pointer to a vector. Now, how can I read the contents of the vector through pointer?

8条回答
  •  一整个雨季
    2020-11-30 17:52

    Do you have a pointer to a vector because that's how you've coded it? You may want to reconsider this and use a (possibly const) reference. For example:

    #include 
    #include 
    
    using namespace std;
    
    void foo(vector* a)
    {
        cout << a->at(0) << a->at(1) << a->at(2) << endl;
        // expected result is "123"
    }
    
    int main()
    {
        vector a;
        a.push_back(1);
        a.push_back(2);
        a.push_back(3);
    
        foo(&a);
    }
    

    While this is a valid program, the general C++ style is to pass a vector by reference rather than by pointer. This will be just as efficient, but then you don't have to deal with possibly null pointers and memory allocation/cleanup, etc. Use a const reference if you aren't going to modify the vector, and a non-const reference if you do need to make modifications.

    Here's the references version of the above program:

    #include 
    #include 
    
    using namespace std;
    
    void foo(const vector& a)
    {
        cout << a[0] << a[1] << a[2] << endl;
        // expected result is "123"
    }
    
    int main()
    {
        vector a;
        a.push_back(1);
        a.push_back(2);
        a.push_back(3);
    
        foo(a);
    }
    

    As you can see, all of the information contained within a will be passed to the function foo, but it will not copy an entirely new value, since it is being passed by reference. It is therefore just as efficient as passing by pointer, and you can use it as a normal value rather than having to figure out how to use it as a pointer or having to dereference it.

提交回复
热议问题