#include #include #include #include #include #include template > class sorted_insert_iterator { public: using value_type = void; using difference_type = void; using pointer = void; using reference = void; using iterator_category = std::output_iterator_tag; sorted_insert_iterator(Container& c, Compare comp = {}) : container{c}, comp{comp} { } sorted_insert_iterator& operator*() { return *this; } sorted_insert_iterator& operator++() { return *this; } sorted_insert_iterator& operator++(int) { return *this; } sorted_insert_iterator& operator=(typename Container::value_type const& value) { auto it {std::lower_bound(std::begin(container), std::end(container), value, comp)}; container.insert(it, value); return *this; } private: Container& container; Compare comp; }; template > sorted_insert_iterator sorted_inserter(Container& c, Compare comp = {}) { return sorted_insert_iterator{c, comp}; } int main() { std::map m { {1, 2}, {5, 6} }; *sorted_inserter(m)++ = std::make_pair(3, 4); assert((m == std::map{{1,2},{3,4},{5,6}})); std::list lst { "c" }; *sorted_inserter(lst)++ = "a"; *sorted_inserter(lst)++ = "b"; *sorted_inserter(lst)++ = "a"; assert((lst == std::list{"a", "a", "b", "c"})); std::vector v { 5, 7, 3, 12, -5 }; { std::vector res {}; copy(std::begin(v), std::end(v), sorted_inserter(res)); assert((res == std::vector{-5, 3, 5, 7, 12 })); } { std::vector res {}; copy(std::begin(v), std::end(v), sorted_inserter(res, std::greater{})); assert((res == std::vector{12, 7, 5, 3, -5})); } { std::vector res {}; copy(std::begin(v), std::end(v), sorted_inserter, std::greater>(res)); assert((res == std::vector{12, 7, 5, 3, -5})); } }