0

The code below generates the resulting output, that is perfectly fine which I need. But I want to save each of those modified vector<int> in an another vector and then get the output by printing vector<vector<int>> elements.

I got a template that delivers a formatted output of a vector, but it fails to print an element of vector<vector<int>>, check by un-commenting code snippets.

Why is this behavior?

How to first assign and then print vector<vector<int>> elements, such that output remains same as now?

Using C++14(4.9.2)

#include <iostream>
#include <vector>

using namespace std;

#define s(n)                        scanf("%d",&n)

template<typename T>
inline std::ostream &operator << (std::ostream & os,const std::vector<T>& v)
{
    bool first = true;
    os << "[";
    for(unsigned int i = 0; i < v.size(); i++)
    {
        if(!first)
            os << ", ";
        os << v[i];
        first = false;
    }
    return os << "]";
}

typedef vector<int> vi; 
typedef vector< vi > vvi; 

int main()
{
    int n = 4;
    // s(n);

    vi list(n, 1);

    // vvi rlist;
    // int count = 0;
    // rlist[count++] = list;
    cout << list << "\n";

    for (int i = 1; i <= n; ++i)
    {
        for (int j = n; j >= i; --j)
        {
            while(list[j] == list[j-1])
            {
                ++list[j];
                cout << list << "\n";
                // rlist[count++] = list;
            }
        } 
    }
    return 0;
}
  • You might be interested in [Pretty-print C++ STL containers](https://stackoverflow.com/questions/4850473/pretty-print-c-stl-containers) by KerrekSB. –  Feb 12 '15 at 06:41
  • you need to initialize `rlist` with a count in order to use square brackets. http://ideone.com/XY7pdJ – zahir Feb 12 '15 at 06:47

1 Answers1

0

You've commented out // rlist[count++] = list;

That's presumably because it fails. rlist is empty, it doesn't have element [0] yet so you can't assign to it. But you don't want to assign to [0], you want to create it. The easiest way to do this is rlist.push_back(list);.

MSalters
  • 173,980
  • 10
  • 155
  • 350