tags:

views:

625

answers:

2

How would I get my variables out of a vector?

I can't use the binary insertion operators or the equal operators.

Earlier, I declared a vector<someStruct> *vObj and allocated it, then returned the vObj and called it in this function:

vector<sameStruct> firstFunc();

for (unsigned int x = 0; x < v->size(); x++)
{
   v[x];
}

when I debug it, v[x] now has the full contents of the original vector, as it did before without the subscript/index.

But I don't think I've done anything to progress beyond that.

I just have about 4 variables inside my vector; when I debug it, it has the information that I need, but I can't get to it.

+1  A: 

To use the [] operator to access elements you must do so on object, not a pointer to an object.

Try;

(*vec)[x];

E.g.

for (int i = 0; i < vec->size(); i++)
{
  printf("Value at %d is %d\n", i, (*vec)[i]);
}

Note that when calling functions on a pointer you usually use the -> operator instead of the . operator, but you could easily do (*vec).some_func(); instead.

Operators such as [], --, ++ and so on can act both on objects and pointers. With objects they act as function calls, but on pointers they act as mathematical operations on the address.

For example;

pointer[nth];
*(pointer + nth);

Have exactly the same effect - they return the nth object from the start of the pointer. (note the location of the * in the second example, it's called after the offset is applied.

Two other tips;

You can also avoid the need to dereference like this by passing the vector as a reference, not a pointer. It's not always a suitable option but it does lead to cleaner code.

void my_func(std::vector<int>& vector)
{
  // vector can then be used as a regular variable
}

If you're going to be passing vectors of a specific type to functions a lot then you can use a typedef both for clarity and to save on typing.

typedef std::vector<int> IntVector;

void my_func(IntVector& vector)
{
}
Andrew Grant
+1  A: 

As it is written v is a pointer to a vector of structs.

When you index directly into v all you are doing is pointer arithmatic. v[x] is the vector of structs at position x (assuming that v is an array if it is just a single object at the end of the pointer then v[x] for x>0 is just garbage). This is because it is applying the [x] not to the vector pointed to by v but to the pointer v itself.

You need to dereference the pointer and then index into the vector using something like:

(*v)[x];

At this point you have a reference to the object at the xth position of the vector to get at its member functions / variables use:

(*v)[x].variable;

or

(*v)[x].memberfunction(parameters);

If you do not want to dereference the vector then access the element within it you might try something like:

v->at(x);
v->at(x).variable;
v->at(x).memberfunction;

This way you are accessing a member function of an object in exactly the same manner as when you called:

v->size();

I hope that this helps.

James Matta