Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I would like to know if we can sort a pre created set. When I first create the set s_p2, I sort using a different element point.getLength(). but after user input i would like to sort the items according to the x value point.getX(). How i do this ?

It seems like set container does not have a sort function. And i am advised to use vector. But sets are able to store unique elements only.

Q1: How can i sort a set depending on the criteria

Q2: If set is unable to do this than which STL container is the best choice and how can i sort the elements in the container.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
178 views
Welcome To Ask or Share your Answers For Others

1 Answer

You cannot resort a set, how it sorts is part of the type of the particular set. A given set has a fixed set order that cannot be changed.

You could create a new set with the same data relatively easily. Just create a new set that sorts based on the new criteria.

If you want to use the two sets in the same code, you'll have to abstract the access to the underlying set.

Now, if you are doing rare reads and modifications, using a vector that you sort manually is often a better idea. You can remove duplicates by using the std::unique-erase idiom.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...