Nick
Nick

Reputation: 1639

Error in assignment of a vector (extract from a vector of vector) to another vector with operator =

I extrapolated this code of example from my real code:

vector<vector<unsigned short int> > v;
vector<unsigned short int> c;
vector< vector<unsigned short int> >  *suffC;
vector<unsigned short int> d;
int index =0;

c.push_back(2);
c.push_back(3);
v[0]=c;

suffC = &v;
d = suffC[index];

The last instruction gives me error at compile time. It is as if for the compiler the two operands (of operator =) were two different types. Where am I wrong?

Upvotes: 1

Views: 70

Answers (2)

devis
devis

Reputation: 1

The size of v is zero on defualt, which would be compile error when we use the overload character [].

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727097

Following C's rules, C++ treats pointers in two ways:

  • As pointers, by letting you apply * to them, and
  • As arrays, by letting you apply subscript operator [] to them.

When you apply a subscript to a pointer suffC, C++ uses the second option - it treats your pointer as an array of vectors of vectors. In order to get the correct assignment, apply * to your pointer first, and then apply subscript. This would ensure that the custom subscript operator of std::vector is applied.

Note that \[\] has higher precedence than *, so you would need to put parentheses around *suffC:

(*suffC)[...]

Upvotes: 2

Related Questions