如何更新这样的地图结构?

时间:2011-07-13 09:15:10

标签: c++ boost join map std

我有一个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_new class_map,我需要从class_descriptionname插入class_map对。怎么做这个?

2 个答案:

答案 0 :(得分:1)

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
    }
}

答案 1 :(得分:1)

你想要的是copy_if的“stl like”算法。没有一个,但你可以在网上找到一个例子,或者通过查看count_if和remove_copy_if的代码来编写自己的例子。