Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get index of element in std::deque

Tags:

c++

deque

I have a deque and I have an object that belongs to the deque.

std::deque<Item> items;
// full deque with objects
// ...
Item &item = items[5];

Now I want to get index of that element in the deque:

size_t index = &item - &*m_items.begin();

I expect index to be equal to 5, but I get something bigger than deque's size.

Of course, I can run through the deque looking for my object, but is it possible to get index of element in O(1)?

like image 673
Nick Avatar asked Sep 03 '25 04:09

Nick


2 Answers

You can't compute the index of an element in a std::deque<T> based on its address as the elements in a std::deque<T> are not store in contiguous memory. At best, you could use an iterator and subtract the begin() iterator from the location. Note, however, that adding or removing elements to a std::deque<T> invalidates all iterator even though pointers or references to objects are not invalidated.

like image 108
Dietmar Kühl Avatar answered Sep 04 '25 21:09

Dietmar Kühl


This depends on there having been no reference invalidations, but you can use std::find_if to find the element by address, then use std::distance to get the index.

Item &item = items[5];
Item* p = &item;
auto it = std::find_if(items.begin(),
                       items.end(),
                       [p](const Item& i) {return p == &i;});

auto idx = std::distance(items.begin(), it);

The easier option would be to keep an iterator instead of a reference.

like image 27
juanchopanza Avatar answered Sep 04 '25 19:09

juanchopanza