C ++ STL map with custom comparator storing null pointers

I am trying to write a copy constructor for an object managing an STL map containing pointers, where the key is a string. However, when I try to insert new values ​​into the map, the pointers are NULL:

// ...
for(std::map<std::string, data_base*, order>::const_iterator it = other.elements.begin();
it != other.elements.end(); ++it){
    data_base *t = it->second->clone();
    std::cout << "CLONE: " << std::hex << t << std::endl;
    elements[it->first] = t;
    std::cout << "INSERTED: " << std::hex << elements[it->first] << std::endl;
}
// ...

other- copied object and elementsmap. The method clone()returns a pointer to a new object (via new).

By executing the code above, I get something like:

CLONE: 0xcfbbc0
INSERTED: 0

I am not a very experienced programmer, and this problem is probably easy to fix, but I did not find any solution to find it.

Thanks so much for your time.

+3
source share
2 answers

I see no problems with this code except maybe

std::map<std::string, data_base*, order>::const_iterator it

order , ( ).

, - , [] ke, ptr.

order, - (std:: less), , , order . , , .


, :

#include <map>
#include <string>
#include <iostream>

struct Data 
{ 
    int k; 

    Data* clone() { return new Data(); }
};

typedef std::map< std::string, Data* > DataMap;

DataMap data_map;


int main()
{
    data_map[ "hello" ] = new Data();
    data_map[ "world" ] = new Data();

    DataMap other_map;

    for( DataMap::const_iterator it = data_map.begin(); it != data_map.end(); ++it)
    {
            Data*t = it->second->clone();
            std::cout << "CLONE: " << std::hex << t << std::endl;
            other_map[it->first] = t;
            std::cout << "INSERTED: " << std::hex << other_map[it->first] << std::endl;
    }

    std::cin.ignore();

    return 0;
}

VS2010SP1 :

CLONE: 00034DD0
INSERTED: 00034DD0
CLONE: 00035098
INSERTED: 00035098

, , , - .

+4

, . , order . , std::less<T>, , , .

// ...
typedef std::map<std::string, data_base*, order> string_db_map;
for(string_db_map::const_iterator it = other.elements.begin();
    it != other.elements.end();
    ++it)
{
    data_base *t = it->second->clone();
    std::cout << "CLONE: " << std::hex << t << std::endl;
    std::pair<string_db_map::iterator, bool) result = elements.insert(
        string_db_map::value_type( it->first, t));
    if ( !result.second ) 
    {
        std::cout << "element['" << it->first << "'] was already present, and replaced." << std::endl;
    }
    std::coud << "INSERTED [iterator]: " << std::hex << (*result.first).second << std::endl;
    std::cout << "INSERTED [indexed]: " << std::hex << elements[it->first] << std::endl;
}
// ...
0

All Articles