Does the C++ standard library have a set ordered by insertion order?

前端 未结 6 401
春和景丽
春和景丽 2021-01-11 09:30

Does the C++ standard library have an \"ordered set\" datastructure? By ordered set, I mean something that is exactly the same as the ordinary std::set but that

6条回答
  •  天命终不由人
    2021-01-11 10:12

    [Disclaimer: I have given a similar answer to this question already]

    If you can use Boost, a very straightforward solution is to use the header-only library Boost.Bimap (bidirectional maps).

    Consider the following sample program that will display some dummy entries in insertion order (try out here):

    #include 
    #include 
    #include 
    #include 
    
    using namespace std::string_literals;
    
    template 
    void insertByOrder(boost::bimap& mymap, const T& element) {
      using pos = typename std::remove_reference::type::value_type;
      // We use size() as index, therefore indexing the elements with 0, 1, ...
      mymap.insert(pos(element, mymap.size()));
    }
    
    int main() {
      boost::bimap mymap;
    
      insertByOrder(mymap, "stack"s);
      insertByOrder(mymap, "overflow"s);
    
      // Iterate over right map view (integers) in sorted order
      for (const auto& rit : mymap.right) {
        std::cout << rit.first << " -> " << rit.second << std::endl;
      }
    }
    

    The funky type alias in insertByOrder() is needed to insert elements into a boost::bimap in the following line (see referenced documentation).

提交回复
热议问题