jeudi 15 novembre 2018

Template class map insert VS Non template map insert

I am trying to understand why the std::map.insert() function is behaving differently.

Example of template class std::map insert function:

        #include <iostream>
        #include <map>
        #include <limits>

        template<class K, class V>
        class container
        {
        private:
        std::map<K,V> m_map;
        public:
        container(const V Val)
        {
        m_map.insert(m_map.begin(),std::make_pair(std::numeric_limits<K>::lowest(),Val));
        }
        const V operator[](const K key)
        {
        return (--m_map.lower_bound(key))->second;
        }
        };

        int main()
        {
        container<unsigned int, char> c('A');
        std::cout<<std::numeric_limits<unsigned int>::lowest()<<":"<<c[std::numeric_limits<unsigned int>::lowest()]<<"\n";
        std::cout<<"1:"<<c[1]<<"\n";
        std::cout<<"2:"<<c[2]<<"\n";
        std::cout<<"3:"<<c[3]<<"\n";
        std::cout<<"4:"<<c[4]<<"\n";
        std::cout<<"5:"<<c[5]<<"\n";
        std::cout<<std::numeric_limits<unsigned int>::max()<<":"<<c[std::numeric_limits<unsigned int>::max()]<<"\n";
        return 0;
        }

Output:

0:A
1:A
2:A
3:A
4:A
5:A
4294967295:A

Example of Non-template std::map insert function:

            #include <iostream>
            #include <map>
            #include <limits>
            int main()
            {
            std::map<unsigned int, char> m_map;
            m_map.insert(m_map.begin(),std::make_pair(std::numeric_limits<unsigned int>::min(),'A'));
            std::cout<<std::numeric_limits<unsigned int>::min()<<":"<<m_map[std::numeric_limits<unsigned int>::min()]<<"\n";
            std::cout<<"1:"<<m_map[1]<<"\n";
            std::cout<<"2:"<<m_map[2]<<"\n";
            std::cout<<"3:"<<m_map[3]<<"\n";
            std::cout<<"4:"<<m_map[4]<<"\n";
            std::cout<<"5:"<<m_map[5]<<"\n";
            std::cout<<std::numeric_limits<unsigned int>::max()<<":"<<m_map[std::numeric_limits<unsigned int>::max()]<<"\n";
            return 0;
            }

Output:

0:A
1:
2:
3:
4:
5:
4294967295:

The output of the first example shows that all index from 0 -> 4294967295 has been assigned the character 'A'. In the second example, only the index zero(0) has been assigned the character 'A'.

Now my question is why the first example insert function assigned the same value to all keys in range even though I did only one insert and the second example insert function inserted exactly at one location I hinted.

Aucun commentaire:

Enregistrer un commentaire