I am newbee here as well as in template programming. I have a dictionary (means, it could be either std::map
or std::vector<std::pair<type1, type2>>
or std::set<std::pair<, >
> ...) I wanted to write an algorithm, which act like standard library algorithms using the iterators of the passed container.
Following is the idea.
#include <iostream>
#include <algorithm>
#include <type_traits>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <iterator>
// two different types
enum EnumA { one, two, three, four, five, six};
enum EnumB { one, three, four, six};
// TypeA TypeB
using map = std::map<EnumA, EnumB>;
// or std::vector<std::pair<EnumA, EnumB>>
// or std::set<std::pair<EnumA, EnumB>>
// or std::array<std::pair<EnumA, EnumB>, 3>
const map itemMap{ // the map
{EnumA::one, EnumB::one},
{EnumA::three, EnumB::three},
{EnumA::six, EnumB::six},
};
template<typename Iterator, typename B>
/* type of KEY(first) of the map/container from the iterator???*/ AfromB(Iterator begin, Iterator end, B bObj)
{
static_assert(begin != end); // container should not be empty!
using Type = typename std::iterator_traits<Iterator>::value_type;
using AType = decltype( /* how to find the type of KEY(first) of the map/container? */);
using BType = decltype(/* how to find the type of VALUE(second) of the map/container? */);
auto iter = std::find_if(begin, end, [bObj](const Type& entry) { return entry.second == bObj;});
return iter != end ? iter->first; // if not found return the first element match
}
// will do BfromA(Iterator begin, Iterator end, B bObj) similarly afterwards
int main()
{
EnumA aEnum = EnumA(itemMap.cbegin(), itemMap.cend(), EnumB::six); // I can use it like
}
There you can see in the code, I do not know how to find the type of key/ first and value/second of the pair in the dictionary. After googling, I found I can find the type of key-value pair by
using Type = typename std::iterator_traits<Iterator>::value_type;
but not for the individuals of that pair. Is it possible to find? Im using C++11.
Sorry for the bad English. Thanks for the help.
Aucun commentaire:
Enregistrer un commentaire