need STL set in insertion order

后端 未结 6 404
谎友^
谎友^ 2020-12-31 02:27

How to store elements in set in insertion order. for example.

setmyset;

myset.insert(\"stack\");
myset.insert(\"overflow\");

6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-31 03:01

    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 your dummy entries in insertion order (try out here):

    #include 
    #include 
    #include 
    #include 
    
    using namespace std::string_literals;
    
    template 
    void insertCallOrdered(boost::bimap& mymap, const T& element) {
      // We use size() as index, therefore indexing with 0, 1, ... 
      // as we add elements to the bimap.
      mymap.insert({ element, mymap.size() });
    }
    
    int main() {
      boost::bimap mymap;
    
      insertCallOrdered(mymap, "stack"s);
      insertCallOrdered(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;
      }
    }
    

提交回复
热议问题