Hi there,

I need to change columns to rows and vice-versa.

Example:

1001 AA AB AC AD
1002 CC DD EE FF
1003 AA BB CC CC
1004 DD DD DD DD

to

1001 1002 1003 1004
AA CC AA DD
AB DD BB DD
AC EE CC DD
AD FF CC DD

What is the best manner to do this? Matrix or using "getline()" and take element by element using a vector?

Anyone has a simple example for that?

Thanks a lot!

If you have a matrix in row major order, you can simply swap the indices to use column major order:

#include <iomanip>
#include <iostream>

using namespace std;

int main()
{
    const int n = 4;
    
    int mat[4][4] = {
        {1,   2,  3,  4},
        {5,   6,  7,  8},
        {9,  10, 11, 12},
        {13, 14, 15, 16}
    };
    
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++)
            cout << setw(3) << mat[i][j];
        cout << '\n';
    }
    
    cout << '\n';
    
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++)
            cout << setw(3) << mat[j][i];
        cout << '\n';
    }
}

Thanks Narue!

I will try a matrix of STRINGS for that. Thanks a lot!

Narue and other friends,

I'm trying this code to invert a string matrix but I had problem. I have a file with 70.000 lines and 1500 columns.

Eclipse Message: " This application has requested the Runtime to terminate it in an unusual way."

Could you help me please?

vector<vector<string> > RotateVec;
	vector<string> lineVec;
	ifstream IN_inverteRowColumn;
	IN_inverteRowColumn.open("data.txt");
	if(IN_inverteRowColumn)
	{
		string val = "";
		while(!IN_inverteRowColumn.eof())
		{
			IN_inverteRowColumn >> val;
			lineVec.push_back(val);
			if(IN_inverteRowColumn.peek() == '\n')
			{
				RotateVec.push_back(lineVec);
				lineVec.clear();
			}
		}
		IN_inverteRowColumn.close();

		// PRINTING CORRECT ORDER
		for(int nn=0; nn < RotateVec.size();nn++)
			for(int k=0; k< RotateVec[nn].size();k++)
				cout << RotateVec[nn][k] << " ";
		cout << endl;

                // INVERTED
		for(int g=0; g < RotateVec.size();g++)
			for(int d =0;d <RotateVec[g].size();d++)
				cout << RotateVec[d][g] << " ";
		cout << endl;

	}
	else
		cout << "FILE WAS NOT OPENED!" << endl;

Narue, I tried the idea of your code for string and receiving data from a file, but I failed.

Can you help me please?

Can you show me a short sample reading 2 rows and 3 columns from a file (Strings) ?

This article has been dead for over six months. Start a new discussion instead.