C++打印出地图值

use*_*866 45 c++ printing dictionary for-loop std-pair

所以我有这样的地图:

map<string, pair<string,string> > myMap;
Run Code Online (Sandbox Code Playgroud)

我使用以下方法在地图中插入了一些数据:

myMap.insert(make_pair(first_name, make_pair(middle_name, last_name)));
Run Code Online (Sandbox Code Playgroud)

我的问题是,如何打印出地图中的所有数据?请举例说明我的参考.

Arm*_*yan 75

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 << "\n";
}
Run Code Online (Sandbox Code Playgroud)

在C++ 11中,您不需要拼出来map<string, pair<string,string> >::const_iterator.您可以使用auto

for(auto it = myMap.cbegin(); it != myMap.cend(); ++it)
{
    std::cout << it->first << " " << it->second.first << " " << it->second.second << "\n";
}
Run Code Online (Sandbox Code Playgroud)

注意使用cbegin()cend()功能.

更简单,您可以使用基于范围的for循环:

for(auto elem : myMap)
{
   std::cout << elem.first << " " << elem.second.first << " " << elem.second.second << "\n";
}
Run Code Online (Sandbox Code Playgroud)

  • @Paul:我将其编辑为“const auto&amp;”以避免复制元素。希望这就是你的意思。除此之外,不,最后一个并不慢 (2认同)

Jer*_*fin 23

如果您的编译器支持(至少部分)C++ 11,您可以执行以下操作:

for (auto& t : myMap)
    std::cout << t.first << " " 
              << t.second.first << " " 
              << t.second.second << "\n";
Run Code Online (Sandbox Code Playgroud)

对于C++ 03,我将使用std::copy插入运算符:

typedef std::pair<string, std::pair<string, string> > T;

std::ostream &operator<<(std::ostream &os, T const &t) { 
    return os << t.first << " " << t.second.first << " " << t.second.second;
}

// ...
std:copy(myMap.begin(), myMap.end(), std::ostream_iterator<T>(std::cout, "\n"));
Run Code Online (Sandbox Code Playgroud)

  • 使用引用`&`避免在循环迭代期间进行复制. (3认同)

hon*_*onk 6

C ++ 17开始,您可以将基于范围的for循环结构化绑定一起用于迭代地图。由于减少了代码中所需firstsecond成员的数量,因此提高了可读性:

std::map<std::string, std::pair<std::string, std::string>> myMap;
myMap["x"] = { "a", "b" };
myMap["y"] = { "c", "d" };

for (const auto &[k, v] : myMap)
    std::cout << "m[" << k << "] = (" << v.first << ", " << v.second << ") " << std::endl;
Run Code Online (Sandbox Code Playgroud)

输出:

m [x] =(a,b)
m [y] =(c,d)

关于Coliru的代码

  • 好更新!您可能希望将参数作为 for 循环中的 const 引用。 (2认同)