Is there a sorted container in the STL?

前端 未结 3 1024
离开以前
离开以前 2020-12-16 09:33

Is there a sorted container in the STL?

What I mean is following: I have an std::vector, where Foo is a custom made class. I a

3条回答
  •  囚心锁ツ
    2020-12-16 10:09

    C++ do have sorted container e.g std::set and std::map

    int main() 
    { 
        //ordered set
        set s; 
        s.insert(5); 
        s.insert(1); 
        s.insert(6); 
        s.insert(3); 
        s.insert(7); 
        s.insert(2); 
    
        cout << "Elements of set in sorted order: "; 
        for (auto it : s) 
            cout << it << " "; 
    
        return 0; 
    } 
    

    Output: Elements of set in sorted order: 1 2 3 5 6 7

    int main() 
    { 
        // Ordered map 
        std::map order; 
    
        // Mapping values to keys 
        order[5] = 10; 
        order[3] = 5; 
        order[20] = 100; 
        order[1] = 1; 
    
       // Iterating the map and printing ordered values 
       for (auto i = order.begin(); i != order.end(); i++) { 
           std::cout << i->first << " : " << i->second << '\n'; 
    } 
    

    Output:
    1 : 1

    3 : 5

    5 : 10

    20 : 100

提交回复
热议问题