Home > OS >  How do you cout a custom data table in c
How do you cout a custom data table in c

Time:12-23

I am trying to cout a table that looks like this. I have two multimaps and i would like to put all the data from one map in col1 and all the data from the other map in 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';
        }

CodePudding user response:

The posted code has two consecutive loops, so that the data contained in map2 will be printed only after the data in map1.

To arrange the output in two columns, the data from each map must be printed in the same row. Be carefull not to access each container out of bounds.

The following is just an example

#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';
    }
}

which outputs

   1  Alpha            2  Gamma     
   2  Beta             2  Delta     
                       3  Rho 
  •  Tags:  
  • c 11
  • Related