Reputation: 9262
Continuing from my last question C++ template class map I have implemented the function to insert some values. This function inserts the same value for a range of keys. If the key exists in the map it should overwrite the old values. Is the function eventually correct and efficient? Could you suggest a better way to implement it?
void insert_ToMap( K const& keyBegin, K const& keyEnd, const V& value)
{
if(!(keyBegin < keyEnd))
return;
const_iterator it;
for(int j=keyBegin; j<keyEnd; j++)
{
it = my_map.find(j);
if(it==my_map.end())
{
my_map.insert(pair<K,V>(j,value));
}
else
{
my_map.erase(it);
my_map.insert(pair<K,V>(j, value));
}
}
}
I try:
int main()
{
template_map<int,int> Map1 (10);
Map1.insert_ToMap(3,6,20);
Map1.insert_ToMap(4,14,30);
Map1.insert_ToMap(34,37,12);
for (auto i = Map1.begin(); i != Map1.end(); i++)
{
cout<< i->first<<" "<<i->second<<std::endl;
}
}
Upvotes: 2
Views: 3000
Reputation: 477650
To insert whether or not the key exists:
typedef std:::map<K, V> map_type;
std::pair<typename map_type::iterator, bool> p
= my_map.insert(std::pair<K const &, V const &>(key, new_value));
if (!p.second) p.first->second = new_value;
This construction takes advantage of the fact that insert
already performs a find()
, and if the insertion fails, you can immediately use the resulting iterator to overwrite the mapped value.
There is a certain hidden cost here: The insertion always makes a copy of the element, whether or not it actually succeeds. To avoid even that, we can use a slightly more verbose approach using lower_bound()
to search for the purported key and simultaneously provide the correct insertion position for the new element:
typename map_type::iterator it = my_map.lower_bound(key);
if (it == my_map.end() || it->first != key)
{
my_map.insert(it, std::pair<K const &, V const &>(key, new_value)); // O(1) !
}
else
{
it->second = new_value;
}
The two-argument version of insert()
operates in constant time if the insertion hint (the iterator in the first argument) is the correct position for the insertion, which is precisely what lower_bound()
provides.
Upvotes: 5