need STL set in insertion order

后端 未结 6 427
谎友^
谎友^ 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:09

    I'm just wondering why nobody has suggested using such a nice library as Boost MultiIndex. Here's an example how to do that:

    #include 
    #include 
    #include 
    #include 
    #include 
    
    #include 
    
    template
    using my_set = boost::multi_index_container<
        T,
        boost::multi_index::indexed_by<
            boost::multi_index::sequenced<>,
            boost::multi_index::ordered_unique>
        >
    >;
    
    int main() {
        my_set set;
        set.push_back(10);
        set.push_back(20);
        set.push_back(3);
        set.push_back(11);
        set.push_back(1);
        
        // Prints elements of the set in order of insertion.
        const auto &index = set.get<0>();
        for (const auto &item : index) {
            std::cout << item << " ";
        }
    
        // Prints elements of the set in order of value.
        std::cout << "\n";
        const auto &ordered_index = set.get<1>();
        for (const auto &item : ordered_index) {
            std::cout << item << " ";
        }
    }
    

提交回复
热议问题