Iterating over unique elements of `std::multiset`

前端 未结 1 1389
刺人心
刺人心 2021-02-20 00:26

All I need is to know if something exists and how many times it exist. I will iterate over the existent things and query how much of that exists.

My implementation so fa

1条回答
  •  半阙折子戏
    2021-02-20 01:32

    Three possible approaches:

    • Use std::unique to create a temporary collection of unique values. This might make the code a little more readable, but less efficient.
    • Advance your iterator by using std::multiset::upper_bound rather than increments: for( auto each = a.begin(); each != a.end(); each=a.upper_bound(*each)) - that way you don't need the if check insider your loop, plus it is guaranteed to be logarithmic in size. Pretty cool (didn't know that before I looked it up). For the following suggestion, all credit goes to @MarkRansom: Using std::upper_bound from , you can specify a range in which to look for the upper bound. In your case, you already have a good candidate for the start of that range, so this method is likely to be more efficient, depending on the implementation in your standard library.
    • If this is a real performance problem for you and the previous solution still isn't good enough, consider switching to map or even unordered_map where the unsigned just keeps track of the number of equivalent things you have. That implies rewriting your insertion/deletion code though.

    0 讨论(0)
提交回复
热议问题