简体   繁体   中英

Delete from i-th element of std::multiset to the end

i is k in my code, just used i for the future users.

std::multiset<std::pair<Point::FT, int> > res;
res.erase(res.begin() + k, res.end());

Error:

no match for operator +

How can I achieve this functionality?

Use std::next to advance the iterator k positions

res.erase(std::next(res.begin(), k), res.end());

The reason your code fails to compile is because std::multiset iterators are BidirectionalIterators , so they only implement pre/post increment/decrement operators, so you need to walk the iterator the desired number of positions, which std::next will do for you.

The iterator operator+ requires that it operate on random access iterators, because addition for non-random-access iterators is a linear operation. The iterators used by a multiset are bidirectional, so you can't do direct addition.

@Praetorian answered the question exactly as written, but I'm going to argue that you're trying to solve the wrong problem/asking the wrong question.

If you want to use indexing in your container, you should strongly prefer vector instead (possibly sorted from time to time). Alternately maybe you know the key of the item you want to erase from to the end. Then you can use logarithmic time find to find the iterator and erase from there to the end.

If you actually need a sorted, indexable, ordered container, I would suggest boost::multi_index instead of any standard container.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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