Here is a method for using a tuple as a key for unordered_map without using hash specialization:
#include <string> #include <tuple> #include <sstream> #include <iostream> #include <iomanip> #include <vector> #include <unordered_map> using namespace std; string fToStr(unordered_map<double,int>& dToI,float x) { static int keyVal=0; stringstream ss; auto iter = dToI.find(x); if(iter == dToI.end()) { dToI[x]=++keyVal; ss << keyVal; } else { ss << iter->second; } return ss.str(); } typedef tuple<int,char,char> TICC; const char ReservedChar=','; string getKey(TICC& t) { stringstream ss; ss << get<0>(t) << ReservedChar << get<1>(t) << ReservedChar << get<2>(t); return ss.str(); } int main() { unordered_map< string,TICC > tupleMp; vector<TICC> ticc={make_tuple(1, 'a', 'b'),make_tuple(1, 'b', 'c'),make_tuple(2, 'a', 'b')}; for(auto t : ticc) tupleMp[getKey(t)]=t; for(auto t : ticc) { string key = getKey(t); auto val = tupleMp[key]; cout << "tupleMp[" << key << "]={" << get<0>(val) << "," << get<1>(val) << ","<< get<2>(val) << "} "; } cout << endl; //for float tuple elements use a second float to int key map unordered_map< double,int > dToI; vector<float> v{1.234,1.234001,1.234001}; cout << "\nfloat keys: "; for(float f : v) cout << setprecision(7) << f << "=" << fToStr(dToI,f) << " "; cout << endl; return 0; }
Exit:
tupleMp[1,a,b]={1,a,b} tupleMp[1,b,c]={1,b,c} tupleMp[2,a,b]={2,a,b} float keys: 1.234=1 1.234001=2 1.234001=2
edW
source share