To store references in a vector?

Asked 2 years ago, Updated 2 years ago, 105 views

std::vector<int &> hello; If you try to save references of int together

"error C2528: 'pointer' : pointer to reference is illegal" An error appears.

I'm not good at using a pointer, so I'm going to use it as a reference, but why is this error coming up? Do I have to use a pointer?

c++ stl vector

2022-09-21 20:01

1 Answers

The type of the container element must be able to assign a value. However, once a reference is initialized, it is not possible to refer to other values A compilation error occurs.

From C++11, you can save the reference by using std::reference_wrapper.

The example below saves the reference to a vector to enable the vector's elements.

#include <iostream>
#include <vector>

class MyClass{
public:
    int x;
    MyClass(int y): x(y) {}
    void func(){
        std::cout<<"I am func" << std::endl;
    }
};
int main(){
    std::vector<std::reference_wrapper<MyClass>> vec;
    MyClass obj1(2);
    MyClass &obj_ref1=std::ref(obj1);
    vec.push_back(obj_ref1);
    for( auto ob : vec)
    {
        std::remove_reference<MyClass&>::type(ob).func();
        std::cout<<std::remove_reference<MyClass&>::type(ob).x<< std::endl;
    }

}


2022-09-21 20:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.