我有一个std::map<boost::shared_ptr<some_class>, class_description> class_map;,其中class_description是:

//Each service provides us with rules
struct class_description
{
    //A service must have
    std::string name;
            // lots of other stuff...
};


我还有另一个std::map<boost::shared_ptr<some_class>, class_description> class_map_new;

如果以前在<boost::shared_ptr<some_class>, class_description>中没有这样的class_map_newclass_map,则需要从class_description插入name对。怎么做这样的事情?

最佳答案

std::map::insert不允许重复,因此您可以简单地尝试插入新值:

//Each service provides us with rules
struct class_description
{
   //A service must have
   std::string name;
   // lots of other stuff...
};

std::map<boost::shared_ptr<some_class>, class_description> class_map;
std::map<boost::shared_ptr<some_class>, class_description> class_map_new;

// insert the new values into the class_map
// using C++0x for simplicity...
for(auto new_obj = class_map_new.cbegin(), end = class_map_new.cend();
    new_obj != end; ++new_obj)
{
    auto ins_result = class_map.insert(*new_obj);

    if(false == ins_result.second)
    {
        // object was already present,
        // ins_result.first holds the iterator
        // to the current object
    }
    else
    {
        // object was successfully inserted
    }
}

关于c++ - 如何更新这样的 map 结构?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6676669/

10-11 23:15