I'm a smidge rusty on using map and need a lil' help; I've declared the below.
std::map<std::string, std::vector<double>> myMap;
I'm periodically reading JSON data, where the ordering of data may sometimes change, or new data elements appear. Other parts of my code will loop through the JSON and extract two variables (jsonLabel, a string), and the associated value as a double (latestDouble).
If jsonLabel already exists, I want to add the associated latestDouble to the end of the vector; if it doesn't exist, make the new Key and start a vector.
I've tried the below; however I keep crashing. I'm presuming it's because map actually isn't smart enough to insert latestDouble at the end of the vector in the map.
myMap.insert(std::make_pair(jsonLabel, latestDouble));
Pseudo Example:
JSON parse #1: [A,43],[B,10],[C,9]
JSON parse #2: [A,10],[C,4],[B,3] /// Change in ordering
JSON parse #2: [A,8],[B,7],[C,2],[D,1] /// New element
Should result in:
A: 43,10,8
B: 10,3,7
C: 9,4,2
D: 1
Thanks for any help!
If the string in jsonLabel already exists as a key in the map, then insert will not insert anything into the map.
And the map insert function is to insert into the map itself. The pair should be a pair of the key and value types (where the value should be a vector of doubles).
What you seem to want is simply
myMap[jsonLabel].push_back(latestDouble);
The operator[] function will create a default-constructed value if the key doesn't exist, and as such will create an empty vector for you.
Related
I have a map that maps strings to vectors of strings:
std::unordered_map<std::string, std::vector<std::string>>> myMap;.
Is there a nice way (as little code as possible while still being readable) to append a value to the vector of a given key?
How to handle the case of adding a value to a vector for a new key for which the vector hasn't been initialized yet?
You want:
myMap["key"].push_back("string");
If the vector for this key doesn't exist, it will be created automatically.
//I am reading data from file and storing data into structure.Here "obj" is a object of structure.
Also note that my file have outer map key multiple times means when i am reading from file then some field of structure has common value and i am using that common value as a key of outer loop.
If I have only single value of outer key then it works fine but when more than one value of key then it fails.
typedef std::map<double,Order_Msg,std::greater<double> >InnerMap;
typedef std::map<int, InnerMap> OuterMap;
InnerMap buy_detailsmap;
OuterMap buy_tokenmap;
//one way
buy_tokenmap.insert(make_pair(obj.token,InnerMap()));
buy_detailsmap.insert(make_pair(obj.orderId,obj));
//another way
buy_detailsmap.insert (std::pair<double,Order_Msg>(obj.orderId,obj));
buy_tokenmap.insert(std::make_pair(obj.token,buy_detailsmap));
I tried both but its not working properly.
It isn't clear why you need buy_detailsmap, as it is de-coupled from buy_detailsmap. Unless you really need insert's semantics, you could simply use operator[]:
buy_tokenmap[obj.token][obj.orderId] = obj;
I have a file containing a list of couples. Each couple contains a 64 bit integer, that is an hash computed over a string, and a value that is an integer.
I want to load the list in a hash map in the main memory.
And then search values using the original string (I have the hash function).
For Example the file could be like:
keys values
78243536 12
38735342 20
32353498 18
if I want to search a term for example "pippo" I can use hashfunction("pippo").
The question is: can I use std::map computed on these hash? How can I insert directly the hash values inside the map without having the original string?
A map is a mapping between keys of a given type and values. The interface of the map is defined in a way that you may either iterate through the whole map or search for a specific element using the key in the map. In your case you want to be able to search not by a key in the map but using another element that is somehow relevant to this key. You can not do this with bare map but you can create a helper function to handle that for you:
map<long long, int> my_map;
.... so some stuff ...
map<long long, int>::iterator find_by_string(const std::string& s) {
return my_map.find(hash_code(s));
}
Hashing operation is irreversible (multiple strings can have the same hash value), so hash value cannot be used as a unique key and what you are trying to do is not possible.
I need a container to store a value (int) according to two attributes, source (int) and destination (int) i.e. when a source sends something to a destination, I need to store it as an element in a container. The source is identified by a unique int ID (an integer from 0-M), where M is in the tens to hundreds, and so is the destination (0-N). The container will be updated by iterations of another function.
I have been using a vector(vector(int)) which means goes in the order of source(destination(value)). A subsequent process needs to check this container, to see if an element exists in for a particular source, and a particular destination - it will need to differentiate between an empty 'space' and a filled one. The container has the possibility of being very sparse.
The value to be stored CAN be 0 so I haven't had success trying to find out if the space is empty, since I can't seem to do something like container[M][N].empty().
I have no experience with maps, but I have seen another post that suggests a map might be useful, and an std::map<int, int> seems to be similar to a vector<vector<int>>.
To summarise:
Is there a way to check if a specific vector of vector 'space' is empty (since I can't compare it to 0)
Is a std::map<int, int> better for this purpose, and how do I use one?
I need a container to store a value (int) according to two attributes,
source (int) and destination (int)
std::map<std::pair<int, int>, int>
A subsequent process needs to check this container, to see if an
element exists in for a particular source, and a particular
destination - it will need to differentiate between an empty 'space'
and a filled one.
std::map::find
http://www.cplusplus.com/reference/map/map/find/
The container has the possibility of being very sparse.
Use a std::map. The "correct" choice of a container is based on how you need to find things and how you need to insert/delete things. If you want to find things fast, use a map.
First of all, assuming you want an equivalent structure of
vector<vector<int>>
you would want
std::map<int,std::vector<int>>
because for each key in a map, there is one unique value only.
If your sources are indexed very closely sequentially as 0...N, will be doing a lot of look-ups, and few deletions, you should use a vector of vectors.
If your sources have arbitrary IDs that do not closely follow a sequential order or if you are going to do a lot of insertions/deletions, you should use a map<int,vector<int>> - usually implemented by a binary tree.
To check the size of a vector, you use
myvec.size()
To check whether a key exists in a map, you use
mymap.count(ID) //this will return 0 or 1 (we cannot have more than 1 value to a key)
I have used maps for a while and even though I'm nowhere close to an expert, they've been very convenient for me to use for storing and modifying connections between data.
P.S. If there's only up to one destination matching a source, you can proceed with
map<int,int>
Just use the count() method to see whether a key exists before reading it
If you want to keep using a vector but want to add a check for whether the item contains a valid value, look at boost::optional. The type would now be std::vector<std::vector<boost::optional<int>>>.
You can also use a map, but the key into the map needs to be both IDs not just one.
std::map<std::pair<int,int>,int>
Edit: std::pair implements a comparison operator operator< that should be sufficient for use in a map, see http://en.cppreference.com/w/cpp/utility/pair/operator_cmp.
Map is a container class that is used to store the aggregate data... Its very easy to retreive the datas stored in it as it uses hash algorithm for retrieval.
map is a key value pair...The data can be retrieved with the corresponding key...
Here in this declaration below I'm defining that the key has to be integer(4 bytes) and data as the string value...
typedef map<INT32U,string> EventMapType;
I searched for the example program of using map in wikipedia... But i could not understand the example given over there..I need to know how the datas and keys are stored in the map and how it is retreived through the key...I am new to MFC...
Beata,
I just did a quick google and came up with http://erunways.com/c-using-the-standard-template-library-stl-map-example/ I won't just copy paste that code here... it's only about 50 lines.
I suggest you read through that code, and then compile and run it (as is). If you run into problems or just stuff that doesn't make sense to you, then ask specific questions here. K?
Cheers. Keith.
map does not use hashing. It can't, because the constraints do not require hashable keys. It is ordinarily implemented as a binary search tree, sorted by key. Thus, it requires keys be <-comparable
In contrast, C++0x will provide an unordered_map, which does use hashing.
If you want specific help, you should tell us what code you've tried so far, and which examples you don't understand.
the STL's map class allows you to store data by any type of key instead of simply by a numerical key, the way you must access an array or vector. So instead of having to compute a hash function and then access an array, you can just let the map class do it for you.
typedef map<INT32U,string> MyEventMapType;
MyEventMapType EventMapType;
Use below as reference code.
To Store values :
EventMapType[key1] = string1 ;
EventMapType[key2] = string2 ;
EventMapType[key3] = string3 ;
To check the value at key1 ...
if(EventMapType.find("key1") == EventMapType.end())
{
std::cout<<"string1 is not in the map!"<<endl;
}
For more read the documentation
Iterators can also be used as a general means for accessing the data stored in a map; you can use the basic technique from before of getting an iterator: