Skip to content

Question about ordered remove #90

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
tspiteri opened this issue Jan 13, 2019 · 3 comments · Fixed by #99
Closed

Question about ordered remove #90

tspiteri opened this issue Jan 13, 2019 · 3 comments · Fixed by #99

Comments

@tspiteri
Copy link

tspiteri commented Jan 13, 2019

I wanted to remove an element without perturbing the order of the remaining elements, and used something like the code below. Is there a better way than this? (In my case it is not really that important, this works just fine for me.)

type Map = IndexMap<K, V>;
fn remove_ordered(m: &mut Map, key: &K) -> Option<V> {
    let (index, _key, val) = m.swap_remove_full(key)?;
    if index < m.len() {
        let tail = m.len() - index - 1;
        let mut stack = Vec::with_capacity(tail);
        for _ in 0..tail {
            stack.push(m.pop().expect("disappearing elements"));
        }
        let (last_key, last_val) = m.pop().expect("disappearing elements");
        m.extend(stack.into_iter().rev());
        m.insert(last_key, last_val);
    }
    Some(val)
}
@cuviper
Copy link
Member

cuviper commented Jan 18, 2019

without perturbing the order of the remaining elements

Just to be clear, the relative order is preserved, but the indexes of all entries after the removed one will be shifted. Doing otherwise would require leaving a hole, which we decided against.

I think we should add an ordered remove method though. Within the crate, we should be able to fixup the trailing items without rehashing them, so it will be faster that what you have. I suggest we deprecate remove, as that just calls swap_remove, and then add a distinct ordered_remove or some such.

@dbeckwith
Copy link

Having an order-preserving remove is all that's stopping me from using this crate right now, would be perfect if that gets added!

@KabDeveloper
Copy link

@cuviper Hi,

Do order-preserving remove feature already added or not yet please ?

If not, is there any faster alternative function to preserve the orders ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants