【问题标题】:你如何在 C++ 中计算自定义数据表
【发布时间】:2022-01-23 16:37:54
【问题描述】:

我正在尝试找出一张看起来像这样的桌子。我有两个多图,我想将一张地图中的所有数据放在 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';
        }

【问题讨论】:

  • 您面临的主要问题是什么?您是否在格式化列或遍历不同大小的容器时遇到问题?请贴出你目前写的代码。

标签: c++11


【解决方案1】:

发布的代码有两个连续的循环,因此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 罗

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-17
    • 2015-03-17
    • 1970-01-01
    • 2016-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    相关资源
    最近更新 更多