Letokteren Letokteren - 3 months ago 14
C++ Question

Class std::vector<Object> has no member named 'x'

I get the error message mentioned in the title when I try to compile something similar to the following.

class Object{
public:
Object(){
//Something
}
void x(){
//Something
}
}

void function(std::vector<Object>* things){
int someNumber;
//Some algorithm to get the value of someNumber.
things->resize(someNumber);
for(int i=0;i<someNumber;i++){
things[i].x();
}
}

int main(){
vector<Object> things;
function(&things);
return 0;
}


What could be causing the trouble?

Answer

You are passing a pointer to your vector so when you use [] it is treating things like an array of vectors.

void function(std::vector<Object>* things)
{
    things[0]; // element of array of vectors (vector<Object>)
}

Try passing your vector by reference:

void function(std::vector<Object>& things)
{
    things[0]; // element of passed in vector (Object)
}

In C++ when you use [] on a pointer it assumes you are accessing an array whose beginning is indicated by the pointer.

So in your case it is assuming you have an array of vectors and [] is selecting one of the vectors from that array.

You want to use [] to access the vector's elements so you need to pass in your vector by reference as indicated or dereference the pointer before using []:

vector<Object>* things;

(*things)[0]; // dereference the pointer then access the elements