tags:

views:

51

answers:

2

I have a function where I provide a pointer to a std::vector.

I want to make x = to vector[element] but i'm getting compiler errors.

I'm doing:

void Function(std::vector<int> *input)
{
   int a;
   a = *input[0];
}

What is the right way to do this? Thanks

+8  A: 

Should be:

void Function(std::vector<int> *input)
{
    // note: why split the initialization of a onto a new line?
    int a = (*input)[0]; // this deferences the pointer (resulting in)
                         // a reference to a std::vector<int>), then
                         // calls operator[] on it, returning an int.
}

Otherwise you've got *(input[0]), which is *(input + 0), which is *input. Of course, why not just do:

void Function(std::vector<int>& input)
{
    int a = input[0];
}

And if you don't modify input, mark it as const:

void Function(const std::vector<int>& input)
{
    int a = input[0];
}
GMan
Ok thanks! I'd never heard of this
Milo
Thanks for the tips, I'v never used the const keyword in that way!
Milo
No problem. I recommend getting a good book so you can learn C++ properly; we have a list here: http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list
GMan
I don't have much money for books unfortunately. I'v learned most of my c++ from you kind geniuses here at StackOverflow! Thanks for the list though, if I do get some extra money I'll defiantly look into a good book :-)
Milo
+1  A: 

You could also go an a syntactic sugar diet and write a = input->operator[](0) ;-)

FredOverflow