Swapping Columns in a Vector Array

Jonathan Anderson (5)
I have a simple program that takes a .csv file and produces a vector. I am then hoping to manipulate this vector in many different ways.

The matrix is linked to a list of tasks, which I am changing the order of in the hope of finding the most efficient system.

I am struggling with swapping the columns in a Vector, rather than just the rows, and also with counting only the upper triangle parts of the vector, i.e all the numbers on the first row, all but one of the numbers on the second row, etc.

This is a sample of my code so far

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int main ()
{
    // read the file
    std::vector<std::vector<int> > csv = readCSV("data file.csv");

    // swap lines 2 and 8
    swap(csv[2], csv[8]);

    // print the array
    for(size_t i=0; i<csv.size(); ++i)
    {
        for(size_t j=0; j<csv[i].size(); ++j)
        {
            cout << csv[i][j] << "\t";
        }
        cout << endl;
    }
    system("PAUSE");
    return 0;
}


At the point where I swap two rows, I want to swap the same two columns, is there a way to facilitate that?

Thanks
Darkmaster (341)
there is no command to get a column, but you can get each element of a column

first column:

1
2
3
4
5
6
7
csv[0][0];
csv[1][0];
csv[2][0];
.
.
.
csv[n][0];
Jonathan Anderson (5)
Thank you, thats provided me to the solution to that issue.
Is there anyway to count the upper triangle efficiently other than adding all the elements in it?
Darkmaster (341)
what do you mean with "count"?
Jonathan Anderson (5)
I suppose I want to do a countif function, based on whether the column number is greater than the row number and if the value is greater than 1, just not sure how to code that. I can do the non zero bit its just the column number being greater than the row that im struggling with
Jonathan Anderson (5)
I currently have a very rudimentary solution that adds all the numbers in the range i want, literally an int = csv[1][1]+csv..+csv[2][2]+...+csv[n][n]. I was just hoping there was a much more efficient way to do this process
Darkmaster (341)
is this a n x m matrix?

if yes, the columns are csv[0].size() and the rows are csv.size()
fun2code (1063)
I suppose I want to do a countif function, based on whether the column number is greater than the row number and if the value is greater than 1, just not sure how to code that.


Changing your words slightly...

...if the column number is greater than the row number and if the value is greater than 1


Translating...

1
2
if(  (colNum > rowNum) && (value > 1) )
    count = count + 1;
Last edited on
Cubbi (1583)
If every row has the same number of fields, perhaps it would be a good idea to switch to some matrix library (such as boost.ublas, or even boost. multi array) - they have easy ways to access individual column. Even std::valarray has one.
Registered users can post here. Sign in or register to post.