2011-07-13 38 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