Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I iterate over a vector and also know the index of the element?

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?

like image 785
unj2 Avatar asked Sep 19 '12 13:09

unj2


People also ask

How do you find the index element of a vector?

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.

How do you iterate through a vector element?

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.

How do I pass a vector to a specific 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));


1 Answers

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

like image 153
Mike Seymour Avatar answered Sep 23 '22 05:09

Mike Seymour