我正在嘗試找出一張看起來像這樣的桌子。我有兩個多圖,我想將一張地圖中的所有資料放在 col1 中,將另一張地圖中的所有資料放在 col2 中。
Col 1 Col 2
------------------------------------------
item1 item4
item2 item9
item5 item3
item6
multimap <int, string> :: iterator col1;
for (col1 = map1.begin(); col1 != map1.end(); col1)
{
cout << col1->name << '\n';
}
multimap <int, string> :: iterator col2;
for (col2 = map2.begin(); col2 != map2.end(); col2)
{
cout << col2->name << '\n';
}
uj5u.com熱心網友回復:
貼出的代碼有兩個連續的回圈,所以map2只有在.map1
要將輸出安排在兩列中,每個地圖的資料必須列印在同一行中。注意不要越界訪問每個容器。
以下只是一個例子
#include <map>
#include <iomanip>
#include <iostream>
#include <string>
int main()
{
std::multimap <int, std::string> map1 {
{1, "Alpha"}, {2, "Beta"}
};
std::multimap <int, std::string> map2 {
{2, "Gamma"}, {2, "Delta"}, {3, "Rho"}
};
auto col1 = map1.cbegin();
auto col2 = map2.cbegin();
// I'm using a lambda just not to repeat code.
auto show = [](std::ostream& os, auto& it, auto last) -> std::ostream& {
if ( it != last)
{
os << std::setw(4) << std::right << it->first << " "
<< std::setw(10) << std::left << it->second;
it; // <- Advance only when an element is printed.
}
else
{
os << std::setw(16) << "";
}
return os;
};
while ( not (col1 == map1.cend() and col2 == map2.cend()) )
{
show(std::cout, col1, map1.cend()) << " ";
show(std::cout, col2, map2.cend()) << '\n';
}
}
哪個輸出
1 阿爾法 2 伽馬
2 Beta 2 三角洲
3 羅
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/421516.html
標籤:
