简体   繁体   中英

Accessing elements in std::vector<std::reference_wrapper<Type>>

I'm trying to do some work with a vector of reference_wrappers, and running into some issues. Here's what I got:

std::vector<std::reference_wrapper<Type>> vec;
//Some stuff...
for(int i = 0; i < vec.size(); i++)
{
        if(&vec[i] == &vec)
    {
        return true;
    }
}

This is not working. I am completely new to std::reference_wrapper, so I guess I'm not sure how to work with it. This above example gives me a 'lacks a cast' error.

I have another spot where I do something like:

vec[i].someMethod();

Which yields:

__gnu_cxx::__alloc_traits<std::allocator<std::reference_wrapper<Type> > >::value_type’ has no member named 'someMethod()'

I'm using GCC4.8

Some simple example

int i = 10;
std::vector<std::reference_wrapper<int>> v;

v.push_back( std::ref( i ) );

std::cout << v[0] << std::endl;
std::cout << v[0].get() << std::endl;

In your case the construction will look as

vec[i].get().someMethod();

PS I did not look through your updated post.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM