Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass vector elements by reference in c++?

Tags:

c++

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...

like image 632
user2381422 Avatar asked Dec 12 '25 22:12

user2381422


2 Answers

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]);
like image 105
Andy Prowl Avatar answered Dec 15 '25 10:12

Andy Prowl


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.

like image 20
djechlin Avatar answered Dec 15 '25 11:12

djechlin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!