[ create a new paste ] login | about

Link: http://codepad.org/AqB0Omux    [ raw code | output | fork ]

C++, pasted on Jun 20:
#include <map>
#include <iostream>
#include <string>

using namespace std;

template<typename Key, typename T>
multimap<T, Key> swap(map<Key, T>& sourceMap) {
     typedef map<Key, T> sourceType;
     typedef typename sourceType::const_iterator sourceIterator;
     const sourceIterator sourceEnd = sourceMap.end();
     multimap<T, Key> resultMap;
     typedef multimap<T, Key> resultType;
     typedef typename resultType::const_iterator resultIterator;
     const resultIterator resultEnd = resultMap.end();
     for (sourceIterator i = sourceMap.begin(); i != sourceEnd; i++) {
          if (resultMap.find(i->second) == resultEnd) {
              resultMap.insert(make_pair(i->second, i->first));
          }
     }
     return resultMap;
}

int main() {

  map <string, unsigned int> testMap;
  testMap["aEnumeration1"] = 0;
  testMap["aEnumeration2"] = 1;
  testMap["aEnumeration3"] = 2;
  testMap["aEnumeration3"] = 2;
  multimap <unsigned int, string> swappedMap = swap(testMap);
  for (unsigned int i = 0; i < swappedMap.size(); i++) {
    cout<< "The current (key) element of a multimap <unsigned int, string> is: " << swappedMap.find(i)->first <<endl;
    cout<< "The current (mapped) element of a multimap <unsigned int, string> is: " << swappedMap.find(i)->second <<endl;
  }

}


Output:
1
2
3
4
5
6
The current (key) element of a multimap <unsigned int, string> is: 0
The current (mapped) element of a multimap <unsigned int, string> is: aEnumeration1
The current (key) element of a multimap <unsigned int, string> is: 1
The current (mapped) element of a multimap <unsigned int, string> is: aEnumeration2
The current (key) element of a multimap <unsigned int, string> is: 2
The current (mapped) element of a multimap <unsigned int, string> is: aEnumeration3


Create a new paste based on this one


Comments: