Search code examples
c++c++11vectordeque

displaying a vector of deques in columns


I'm trying to display a vector of deques (std::vector<std::deque<int>> v) like this

v.at(0).at(0) v.at(1).at(0) v.at(2).at(0) v.at(3).at(0)
v.at(0).at(1) v.at(1).at(1) v.at(2).at(1) v.at(3).at(1)
v.at(0).at(2) v.at(1).at(2) v.at(2).at(2) v.at(3).at(2)
              v.at(1).at(3)               v.at(3).at(3)
                                          v.at(3).at(4)

The first part of the vector is fixed at 7, the size of the actual columns are dynamic however depending on what the user chooses to do.

I was attempting something like

int row = 0;
int column;

for (column = 0; column < v.at(row).size(); column++){
      cout << "v["<< row <<"]["<< column << "]" << v.at(row).at(column) << "\t";
  while (row < v.size()){
    cout << endl;      
    row++;
  }
}

I'm getting errors like

libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: vector
make: *** [Pile.h] Abort trap: 6

Having one of those blah brain days. Can someone help me print this out the way I want it?


Solution

  • Here is a demonstrative program that shows one of approaches to the task.

    #include <iostream>
    #include <iomanip>
    #include <vector>
    #include <deque>
    #include <algorithm>
    
    int main() 
    {
        std::vector<std::deque<int>> v =
        {
            { 0, 1, 2 },
            { 0, 1, 2, 3 },
            { 0, 1, 2 },
            { 0, 1, 2, 3, 4 }
        };
    
        size_t n = std::max_element( v.begin(), v.end(),
                                     []( const auto &x, const auto &y )
                                     {
                                        return x.size() < y.size();
                                     } )->size();
    
        for ( size_t i = 0; i < n; i++)
        {
            for ( size_t j = 0; j < v.size(); j++ )
            {
                std::cout << std::setw( 4 );
                if ( i < v[j].size() )
                {
                    std::cout << v[j][i];
                }
                else
                {
                    std::cout << "";
                }
            }
    
            std::cout << std::endl;
        }
    
        return 0;
    }
    

    Its output is

       0   0   0   0
       1   1   1   1
       2   2   2   2
           3       3
                   4