本文介紹了如何打印出 C++ 地圖值?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我有一個像這樣的 map
:
map<string, pair<string,string> > myMap;
我已經使用以下方法將一些數據插入到我的地圖中:
And I've inserted some data into my map using:
myMap.insert(make_pair(first_name, make_pair(middle_name, last_name)));
我現在如何打印地圖中的所有數據?
How can I now print out all the data in my map?
推薦答案
for(map<string, pair<string,string> >::const_iterator it = myMap.begin();
it != myMap.end(); ++it)
{
std::cout << it->first << " " << it->second.first << " " << it->second.second << "
";
}
在C++11中,你不需要拼出map
.您可以使用 auto
In C++11, you don't need to spell out map<string, pair<string,string> >::const_iterator
. You can use auto
for(auto it = myMap.cbegin(); it != myMap.cend(); ++it)
{
std::cout << it->first << " " << it->second.first << " " << it->second.second << "
";
}
注意 cbegin()
和 cend()
函數的使用.
Note the use of cbegin()
and cend()
functions.
更簡單的是,您可以使用基于范圍的 for 循環:
Easier still, you can use the range-based for loop:
for(const auto& elem : myMap)
{
std::cout << elem.first << " " << elem.second.first << " " << elem.second.second << "
";
}
這篇關于如何打印出 C++ 地圖值?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!