I have a vector and I need to pass its elements to functions of the type:
bool doIt(MyClass &a);
so I need to do later:
vector<MyClass> v;
doIt(v[2]);
I am not sure if I am doing it right...
I am not sure if I am doing it right...
Yes, you are doing it right, except that in your sample code the vector v does not contain any element, so the index 2 is out-of-bounds, and this expression:
v[2]
Results in undefined behavior. This would be enough to fix it though (if MyClass is default-constructible):
vector<MyClass> v(3);
// ^
// Creates a vector of 3 default-constructed
// elements of type MyClass
doIt(v[2]);
Let's check the documentation!
http://www.cplusplus.com/reference/vector/vector/operator[]/
reference operator[] (size_type n);
const_reference operator[] (size_type n) const;
Returns a reference to the element at position n in the vector container.
Looks like you're good.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With