set vs unordered_set for fastest iteration

前端 未结 5 1532
无人及你
无人及你 2021-02-13 02:18

In my application I have the following requirements -

  1. The data structure will be populated just once with some values (not key/value pairs). The values may be r

5条回答
  •  闹比i
    闹比i (楼主)
    2021-02-13 03:00

    I highly recommend you not to use in such this case. set is binary tree, and unordered_set is hash table - so they use lots of memory, and have slow iteration speed and bad locality of reference. If you have to insert/remove/find data frequently, set or unordered_set good choice, but now you need to just read, store, sort data once and only use data many times.

    In this case, sorted vector can be such a good choice. vector is dynamic array, so it has low overhead.

    Just directly, see the code.

    std::vector data;
    
    int input;
    for (int i = 0; i < 10; i++)
    {
        std::cin >> input;
        data.push_back(input); // store data
    }
    
    std::sort(data.begin(), data.end()); // sort data
    

    That's all. All your data is ready.

    If you need to remove duplicates like set, just use unique - erase after sorting.

    data.erase(
        std::unique(data.begin(), data.end()),
        data.end()
        );
    

    Notice that you should use lower_bound, upper_bound and equal_range rather than find or find_if to use the benefits of sorted data.

提交回复
热议问题