CPP/STL/Set/BoundedInsert

From ProgrammingExamples
< CPP‎ | STL/Set
Revision as of 10:47, 13 July 2012 by Daviddoria (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

BoundedInsert.cpp

#include <set>
#include <iterator>
#include <iostream>
#include <algorithm>
 
template<typename T>
std::set<T>& bounded_insert(std::set<T>& s, std::size_t max, T val) {
    s.insert(val);
    while(s.size() > max) 
        s.erase(std::max_element(s.begin(), s.end()));    
    return s;
}
 
int main() {
    std::set<int> s;
    bounded_insert(s, 10, 0); 
    bounded_insert(s, 10, 1); 
    bounded_insert(s, 10, 3); 
    bounded_insert(s, 10, 4); 
    bounded_insert(s, 10, 5); 
    bounded_insert(s, 10, 6); 
    bounded_insert(s, 10, 7); 
    bounded_insert(s, 10, 8); 
    bounded_insert(s, 10, 9); 
    bounded_insert(s, 10, 10);
    bounded_insert(s, 10, 2); 
    bounded_insert(s, 10, 20);
    std::copy(s.begin(), s.end(), std::ostream_iterator<int>(std::cout, " "));
}

CMakeLists.txt

cmake_minimum_required(VERSION 2.6)
 
Project(BoundedInsert)
 
ADD_EXECUTABLE(BoundedInsert BoundedInsert.cpp)