multimap<T,S>: Zugriff
-
Ich habe eine multimap<T,S> und ein T t, und will jetzt das i-te S mit dem Key t ausgeben. Wie mache ich das?
-
Ich will quasi multimap<T,S> ansehen als ein map<T,vector<S>> MyMap und dann MyMap[t][i] machen.
-
Das geht nicht so einfach. Da musst du dir selbst einen Wrapper schreiben, z.B. so:
#include <map> #include <string> #include <vector> #include <utility> using namespace std; template<typename T, typename U> class my_map { private: multimap<T,U> m; public: U& operator()(T t, unsigned i) { pair< typename multimap<T,U>::iterator, typename multimap<T,U>::iterator > ret = m.equal_range(t); typename multimap<T,U>::iterator it = ret.first; for(unsigned x=0; x!=i; ++x, ++it); return it->second; } void insert(T t, U u) { m.insert( make_pair(t,u) ); } }; int main() { my_map<int,vector<string>> m; const char* s1[] = { "apfel", "birne" }; vector<string> v1(s1,s1+2); m.insert(0,v1); const char* s2[] = { "hund", "katze", "maus" }; vector<string> v2(s2,s2+3); m.insert(0,v2); const char* s3[] = { "pc", "cam", "tablet", "phone" }; vector<string> v3(s3,s3+4); m.insert(1,v3); vector<string>& test_1 = m(0,0); // apfel, birne vector<string>& test_2 = m(0,1); // hund, katze, maus vector<string>& test_3 = m(1,0); // pc, cam, tablet, phone }