steviekm3
steviekm3

Reputation: 1043

How to use emplace with hint and map of maps?

I have a map of map of maps where I'm reading sorted data and inserting as follows:

Data:

a,a,a,a
a,a,a,b
a,a,a,c
...
z,z,z,z

Inserting like follows:

std::map<string,std::map<string,std::map<string,string>>> theMap;
// For each line:
theMap[v1][v2][v3]=v4

Is there way to do above but using emplace and hint for each of v elements ? I want to use the hint because data is sorted.

Upvotes: 0

Views: 377

Answers (2)

IanM_Matrix1
IanM_Matrix1

Reputation: 1594

The member function you want is emplace_hint and takes your hint iterator as the first parameter. It returns an iterator for the newly inserted item so you can increment it and use that as the hint for the next emplace.

Upvotes: 1

Joseph Ireland
Joseph Ireland

Reputation: 2505

Here's an example

#include <map>
#include <string>

template <typename Key, typename Val>
Val& sorted_insert(std::map<Key,Val>& map, const Key& key, const Val& val) {
    auto it = map.emplace_hint(map.end(),key, val);
    return it->second;
}

/// avoids calling default constructor unless necessary, which could do expensive allocations/deallocations
template <typename Key, typename Val>
Val& sorted_insert_default(std::map<Key,Val>& map, const Key& key) {
    auto it = map.emplace_hint(map.end(),std::piecewise_construct_t(), std::tie(key), std::make_tuple());
    return it->second;
}
using  map_t = std::map<std::string,std::map<std::string,std::map<std::string,std::string>>>;
void add_row(map_t& map, const std::string&v1, const std::string& v2, const std::string& v3, const std::string&v4) {
    sorted_insert(sorted_insert_default(sorted_insert_default(map,v1),v2),v3,v4);
}

Upvotes: 1

Related Questions