Python dictionary equivalent?

Hey all,

I was wondering if there was anything in the c++ std lib similar to the python dictionary. I know of maps/multimaps but from what I can tell it only allows for ONE mapping between a key/value pair. I need something that can keep separate tallies but also normalize them, like for example: {"red":4, "blue":10, "green":2} and then once normalized: {"red":0.25, "blue": 0.625, "green": 0.125}.

Thanks!
closed account (N85iE3v7)
Perhaps, you could use the STL container map.

http://www.cplusplus.com/reference/stl/map/

There are some tricky issues to sort them, like functors , but that is just a piece of cake compared to regular C.
This is an example for a function that normalizes the values in a map:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
#include <map>
using namespace std;

template <class Key,class Val> void normalize(std::map<Key,Val>& myMap)
{
  Val sum=Val();
  for (auto& vp : myMap)sum+=vp.second;
  for (auto& vp : myMap)vp.second/=sum;
}

int main()
{
  map<string,double> myMap({{"red",4},{"blue",10},{"green",2}});
  normalize(myMap);
  for (auto& vp : myMap)cout << vp.first << ": " << vp.second << endl;
}
Ok, cool! That looks like a good place to start.

Now I'm trying to create a Counter class that mimics the python functionality by using multimaps. Right now it can just handle counters of the sort

In particular, I'm trying to write a function, increment_count(int key, double value), that does the following: if the key is not present in the mapping, add the pair (key,0) to the mapping. If it is present, then bump up the value by 1. I can do the latter, but I'm not sure exactly how I can write a conditional that checks if the key exists in the mapping. The function multimap::find seems to hold the answer, because it will make the iterator point to end if the key was not found, but then how would I get an if statement to check if the iterator is pointing to the end? Something like it (the iterator) == multimap::end doesn't seem to work.
closed account (N85iE3v7)
Have you tried to use something like

1
2
3
4
5
 
while ( iterator != multimap.end() ) 
{
 // ...
}


instead of using the == operator ?

@Althar , hey which compiler do I need to compile that code ? It certainly has some C++0x features I can see. Just curious, looks like a very fast and smart implementation.
Topic archived. No new replies allowed.