简体   繁体   English

std :: list按索引删除元素

[英]std::list remove element by index

I have a std::list full of objects. 我有一个充满对象的std :: list。 Whenever I add a object, I want to store that objects index in the list, so later on I can remove it from the list. 每当添加对象时,我都希望将该对象索引存储在列表中,因此以后可以将其从列表中删除。

What I want to do in pseudo code 我想用伪代码做什么

myList.pushBack(element);
int index = myList.getIndexOfLastElement();

myList.erase(index);

For performance reasons I can't search by value. 由于性能原因,我无法按价值搜索。

To clarify: I have element a(index 0), b(index 1), c(index 2), d(index 3) 澄清一下我有元素a(索引0),b(索引1),c(索引2),d(索引3)

If I delete element b, I still want to be able to access c by 2. 如果删除元素b,我仍然希望能够通过2访问c。

I'd suggest using std::list::iterator instead of integer indices. 我建议使用std::list::iterator而不是整数索引。 std::list::erase() does not invalidate iterators. std::list::erase()不会使迭代器无效。

auto index = myList.insert(myList.end(), element);

myList.erase(index);

You'll need to map the index s to the iterator for that element. 您需要将index map到该元素的迭代器。 Something like: 就像是:

auto pos = myList.cbegin();
map<int, decltype(pos)> m;

// bump pos for every myList.pushBack(element);
int index = myList.getIndexOfLastElement();
m[index] = pos;

// then you can erase with
myList.erase(m[index]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM