I need to access each element in a vector and also know what index the element is in.
So far I could come up with two ways
for (iterator it= aVector.begin(), int index= 0; it!= aVector.end(); ++it, ++index)
leaving the type signature. also it looks like i can't use auto
for (int index = 0; index < aVector.size(); ++index) { // access using [] }
Which one is more efficient or is there a better way to do this?
Access an element in vector using vector::at() reference at(size_type n); reference at(size_type n); It returns the reference of element at index n in vector. If index n is out of range i.e. greater then size of vector then it will throw out_of_range exception.
Use a for loop and reference pointer In C++ , vectors can be indexed with []operator , similar to arrays. To iterate through the vector, run a for loop from i = 0 to i = vec. size() . Where i is the index.
The most idiomatic way is to make your function take iterators: template<typename It> It::value_type maxsubarray(It begin, It end) { ... } and then use it like this: std::vector<int> nums(...); auto max = maxsubarray(begin(nums) + 2, end(nums));
For a vector or other random-access container, it makes little difference. I would probably choose the second because it's easier to read, and is probably marginally faster since there's only one loop variable to update. Another alternative is:
for (auto it = aVector.begin(); it != aVector.end(); ++it) { int index = std::distance(aVector.begin(), it); }
For non-random-access containers, []
isn't available, and std::distance
is inefficient; in that case, if you need the index, the first method would be better (although you'll need to fix it so it doesn't try to declare two differently-typed variables in the for-initialiser).
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