Choosing a STL container with uniqueness and which keeps insertion ordering

后端 未结 8 2078

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: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 collection;
        int indexGenerator;
    
        ...
    };
    

提交回复
热议问题