Created
July 13, 2020 20:10
-
-
Save hnrck/b02727abb7724474b30cd4cb791f5825 to your computer and use it in GitHub Desktop.
Different way to manipulate/display a container
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <algorithm> | |
#include <iostream> | |
#include <iterator> | |
#include <map> | |
#include <numeric> | |
#include <sstream> | |
#include <utility> | |
template<class t_pair> | |
std::string to_string(const t_pair &pair) { | |
auto ss = std::stringstream(); | |
ss << pair.first << ": " << pair.second; | |
return ss.str(); | |
} | |
template<class t_pair> | |
class pair_adaptor final { | |
private: | |
const t_pair &pair_; | |
public: | |
pair_adaptor(const t_pair &pair) : pair_(pair) {} | |
friend std::ostream &operator<<(std::ostream &os, const pair_adaptor<t_pair> &pa) { | |
return os << to_string(pa.pair_); | |
} | |
}; | |
int main() { | |
auto m = std::map<int, int>{}; | |
{ | |
m.insert(std::make_pair<int, int>(0, 3)); | |
m.insert(std::make_pair<int, int>(4, 6)); | |
m.insert(std::make_pair<int, int>(8, 9)); | |
} | |
{ | |
std::cout << "Iterator based iterations:" << std::endl; | |
for (auto it = std::begin(m); it != std::end(m); ++it) { | |
std::cout << to_string(*it) << "\n"; | |
} | |
} | |
{ | |
std::cout << "Range based iterations:" << std::endl; | |
for (const auto &e: m) { | |
std::cout << to_string(e) << "\n"; | |
} | |
} | |
{ | |
std::cout << "Copy:" << std::endl; | |
std::copy(std::begin(m), std::end(m), | |
std::ostream_iterator<pair_adaptor<std::map<int, int>::value_type>>(std::cout, "\n")); | |
} | |
{ | |
std::cout << "For each:" << std::endl; | |
std::for_each(std::begin(m), std::end(m), | |
[](const auto &p) { | |
std::cout << pair_adaptor<std::map<int, int>::value_type>(p) << "\n"; | |
} | |
); | |
} | |
{ | |
std::cout << "Transformation:" << std::endl; | |
std::transform(std::begin(m), std::end(m), std::ostream_iterator<std::string>(std::cout, "\n"), | |
to_string<std::pair<int, int>>); | |
} | |
{ | |
std::cout << "Accumulate:" << std::endl; | |
auto s = std::accumulate(std::next(std::begin(m)), std::end(m), to_string(*std::begin(m)), | |
[=](std::string s, std::pair<int, int> p) { | |
return std::move(s) + "\n" + to_string(p); | |
}); | |
std::cout << s; | |
} | |
std::flush(std::cout); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment