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

后端 未结 8 907
不思量自难忘°
不思量自难忘° 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 18:05

    vector  numbers {10,20,30,40};
    vector  *ptr {nullptr};
    
    ptr = &numbers;
    
    for(auto num: *ptr){
     cout << num << endl;
    }
    
    
    cout << (*ptr).at(2) << endl; // 20
    
    cout << "-------" << endl;
    
    cout << ptr -> at(2) << endl; // 20
    

提交回复
热议问题