0
votes

I'm adding two different elements to both std::list and std::set and I want the std::list to be sorted with the same order as of std::set. one way I tried is when the element is added to std::set, find that element then get the index of that element using std::distance(begin, found) and then insert the element to that index in std::list. is there any other way?

2
Why are you trying to do this? There may be a better overall solution to your problem rather than finding a may to keep a list and set synchronised. - Patrick
just keep the std::set and when you need the std:: list you create it from the std::set. - fabrizioM
std::set contains a 'key' and std::list contains a value related to the key. In that case i think using std::map would be a better idea. - cpx

2 Answers

4
votes

You should use the std::map, with the data you put in the set as key, and the data you put in the list as value.

This way your list elements will be ordered.

0
votes

It is too complicated a way! In fact std::set implemented as binary tree, and uses std::less for sorting (by default). Also this provides "stable" iterator, it is mean that iterator returned by std::set::insert will be valid until element explicitly erased. So you can put just inserted iterator to std::list. And wise verse - std::list has also stable iterator, so you can put items to list but place iterators to set. In last way just override std::less