i was solving a program to prevent duplicate values on map, i have written the following program
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
*/
#include <map>
#include <limits>
#include<iostream>
using namespace std;
template<typename K, typename V>
class interval_map {
std::map<K,V> m_map;
public:
// constructor associates whole range of K with val by inserting (K_min, val)
// into the map
interval_map( V const& val) {
m_map.insert(m_map.end(),std::make_pair(std::numeric_limits<K>::lowest(),val));
}
void assign( K const& keyBegin, K const& keyEnd, V const& val ) {
if (!(keyBegin < keyEnd)) {
return;
}
else {
if (m_map.rbegin() != m_map.rend()) {
//get the previous key value
auto prev_value = m_map.rbegin()->second;
//compare with current value
if (prev_value == val) {
cout << "duplicate";
//duplicate entry values are restricted, do nothing
}
else {
for (auto i = keyBegin; i<keyEnd; i++) {
cout << i << endl;
m_map[i] = val;
}
}
}
}
}
// look-up of the value associated with key
V const& operator[]( K const& key ) const {
return ( --m_map.upper_bound(key) )->second;
}
};
int main(int argc, char** argv) {
interval_map<unsigned int,char> test('m');
test.assign(2,4,'k');
test.assign(4,7, 'k');
cout << test[5];
return 0;
}
the cout << test[5] returns k even though it not assigned to map before.How is it possible, did it do anything wrong , or is this the default behaviour of operand [] ? The above program creates keys with in intervals and assign the same value to them.For example test.assign(2,4, 'k') creates keys from to 2,3 and assign the value k to it.The idea is to prevent duplication of the values between keys generated by consecutive assign method.
Aucun commentaire:
Enregistrer un commentaire