簡體   English   中英

迭代映射並使用該對作為參考參數C​​ ++ 11

[英]Iterate over map and use the pair as reference parameter C++11

我有一個std::map 我想迭代它並使用結果作為函數的參數。 編譯似乎抱怨我的對象是左值,但我無法弄清楚為什么它被認為是左值。

void my_function(std::pair<std::string, std::string>& my_arg){
    //do stuff, modify elements from the pair
}

std::map<std::string, std::string> my_map;
// fill the map with values...

for(auto& element : my_map){
    my_function(element);
}

我可能會使用迭代器來解決這個問題,但我想學習如何用c ++ 11方法來解決這個問題。

std::map及其迭代器的value_typestd::pair<const std::string, std::string>而不是std::pair<std::string, std::string> 換句話說,鍵在C ++映射中始終是常量。

std::map<std::string, std::string>::value_typestd::pair<const std::string, std::string> :注意const 如果允許您修改對中的鍵,則可能違反了映射條目按鍵排序的不變量。 由於您使用了不同的pair類型,因此引用無法綁定到實際對象。

為了保持一致性(特別是如果你在某個時候模板化它),我會定義你的函數:

void my_function(std::map<std::string, std::string>::value_type& my_arg){
    //do stuff, modify elements from the pair
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM