2011-07-13 40 views
0

我有一个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;

我需要从class_map_new插入对<boost::shared_ptr<some_class>, class_description>class_map万一有在class_map之前,这样的name没有class_description。如何做这样的事情?

+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

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

+0

请注意'std :: copy_if' _is_在C++ 0x。 – ildjarn