Choosing a STL container with uniqueness and which keeps insertion ordering

后端 未结 8 1983

I am unable to decide which STL container to use in the following case:

  1. I want to preserve the order of insertion of the elements
  2. The elements in the
相关标签:
8条回答
  • 2021-01-18 01:02

    Boost MultiIndex should be able to do exactly what you want - you can just use one sequenced index to get the "ordered by insertion order" requirement, and either a hashed_unique or ordered_unique index to get the uniqueness requirement.

    0 讨论(0)
  • 2021-01-18 01:04

    Implement a wrapper class over the container you choose (e.g. list, vector, deque), and rewrite the insertion/push_back methods to check that the inserted element is unique before inserting the element.

    Unfortunately,I don't know any STL container to match your criteria.

    0 讨论(0)
  • 2021-01-18 01:05

    No standard library container gives you what you want directly. I would start with a std::vector and write a free function to do the insert which does the find and the push_back for you. If this suffices, go no further. If you have performance problems, think about a more complicated solution.

    0 讨论(0)
  • 2021-01-18 01:19

    You could do this:

    • Create a wrapper around your element class with two members: your element, and an index. Let's call it 'InsertedElement'. The index will be the insertion order.

    • Define comparison operator for this class, which only takes into account your element, but not the index. This will ensure the uniqueness of elements, while remembering their insertion order.

    • Wrap a std::set and an insertion counter in another class. Then, when you want to insert a new element, either:

    • It already exists, nothing to do.
    • It does not: insert it in the map while giving it the current max index + 1.

    Something like:

    class CMagicContainer
    {
      public:
        std::set<InsertedElement> collection;
        int indexGenerator;
    
        ...
    };
    
    0 讨论(0)
  • 2021-01-18 01:20

    There might be a good built in way to do this, but one rather simple way is to use both a hash_map and a list. Check the hash_map before each insertion, then insert into both. You'll want to encapsulate this in a class, probably.

    0 讨论(0)
  • 2021-01-18 01:21

    If you already have boost installed, I like that option. Otherwise, why not just use a list or vector and add a check (find(k) == std::npos) on insertion? I suppose it could get kind of slow on a really, reallly large list, but for most cases it would work just fine.

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