Created
December 28, 2017 15:13
-
-
Save mtao/172c73a4a7abdf7a5724b71523a5fbe8 to your computer and use it in GitHub Desktop.
stupidly joked that ``c++ is turning into compiled python'' and was sent ``pairs = dict(enumerate([1, 5, 4, 3, 2])); print(pairs)''
This file contains hidden or 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 <map> | |
#include <tuple> | |
#include <iostream> | |
template <typename IteratorType> | |
struct enumerate { | |
using value_type = std::pair<int,std::remove_pointer_t<IteratorType>>; | |
struct enum_iter { | |
IteratorType it; | |
int idx = 0; | |
value_type operator*() { return value_type(idx,*it); } | |
bool operator==(const enum_iter& o) { return it == o.it; } | |
bool operator!=(const enum_iter& o) { return it != o.it; } | |
enum_iter& operator++() { ++it; ++idx; return *this; } | |
}; | |
enumerate(const IteratorType& b, const IteratorType& e): m_cur(b), m_end(e) {} | |
enum_iter begin() const { return enum_iter{m_cur}; } | |
enum_iter end() const { return enum_iter{m_end}; } | |
private: | |
IteratorType m_cur; | |
IteratorType m_end; | |
}; | |
template <typename T> | |
auto make_enumerate(const T& c) { | |
return enumerate<typename T::iterator>(c.begin(),c.end()); | |
} | |
template <typename T> | |
auto make_enumerate(const std::initializer_list<T>& c) { | |
return enumerate<const T*>(c.begin(),c.end()); | |
} | |
template <typename ContainerType> | |
auto make_map(const ContainerType& c) { | |
using pair_type = typename ContainerType::value_type; | |
using key_type = typename pair_type::first_type; | |
using value_type = typename pair_type::second_type; | |
return std::map<key_type,value_type>(c.begin(),c.end()); | |
} | |
template <typename K,typename V> | |
std::ostream& operator<<(std::ostream& os, const std::map<K,V>& m) { | |
os << "{"; | |
for(auto&& [k,v]: m) { | |
os << k << ":" << v << ", "; | |
} | |
os << "}"; | |
} | |
int main() { | |
auto mymap = make_map(make_enumerate({1,5,4,3,2})); | |
std::cout << mymap << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment