2

I am using some containers. There is a problem with reference to the reference vector and can not be detected normally.

error C2039: 'vecMsg' : is not a member of 'std::_Vector_iterator <std::_Vector_val>std::_Simple_types<T2 &>>>'

Why can not recognize the member variables?

vector<T1> vec1;
vector<T2> vec2;

vector<T1>::iterater iVec1;
vector<T2>::iterater iVec2;
vector<T2&>::iterater iInVec;

struct T1
{
public:
   vector<T2&> inVec;
}

struct T2
{
public:
    vector<std::string> vecMsg;
}

input some data in vec1.inVec

for(iVec1 = vec1.begin(); iVec1 != vec1.end(); iVec1++)
{
    for(iVec2 = vec2.begin(); iVec2 != vec2.end(); iVec2++)
    {
            // blaa if

            iVec1->inVec.push_back(*iVec2);

    }
}

access vecMsg In vec1.inVec

for(iVec1 = vec1.begin(); iVec1 != vec1.end(); iVec1++)
{
    for(iInVec = iVec1->inVec.begin(); iInVec != iVec1->inVec.end(); iInVec++)
    {
        // Error occurs here.
        int nSize = iInVec->vecMsg.size();
    }
}
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
DDukDDak99
  • 341
  • 3
  • 12

2 Answers2

5

Generally, once you have initialized reference pointing to some object you can't change it. That's why you cannot create vector of references. Use vector of pointers or smart pointers for that.

nkdm
  • 1,220
  • 1
  • 11
  • 26
2

You can't have a ::std::vector of references. See this post for more details.

Is there a reason you can't use a ::std::vector<T2 *>?

Beware though - that vector holds raw pointers, so it won't be responsible for destroying the T2s it refers to...

Community
  • 1
  • 1
linguamachina
  • 5,785
  • 1
  • 22
  • 22
  • Ugh `std::shared_ptr`. –  Jul 27 '14 at 11:45
  • @πάνταῥεῖ: If you're referring to the problems with object cleanup, I'm fully aware of that. But there __are__ times when raw pointers are completely appropriate! – linguamachina Jul 27 '14 at 11:50
  • 2
    There is nothing inherently wrong with using a vector of raw pointers. Just don't try to delete the contents. Raw pointers are perfectly useful and practical tools, not every reference needs to own the pointee. – Puppy Jul 27 '14 at 12:05