Column exchange in C ++

I have a std matrix defined as:

std::vector<std::vector<double> > Qe(6,std::vector<double>(6));

and vector v, which:

v{0, 1, 3, 2, 4, 5};

I would like to swap columns 3 and 2 of the Qe matrix as indicated in vector v.

Matlab is as easy as writing Qe=Qe(:,v);

I wonder if there is an easy way besides the for loop to do this in C ++.

Thanks in advance.

+4
source share
3 answers

Given that you implemented this as a vector of vectors, you can use a simple exchange:

std::swap(Qe[2], Qe[3]);

This should be of constant complexity. Of course, this will depend on whether you are treating your data as columns or rows. However, if you frequently swap columns, you will need to arrange the data accordingly (that is, for the code above to work).

for, ( ++), for ( , ), :

std::for_each(Qe.begin(), Qe.end(), [](std::vector<double> &v) {std::swap(v[2], v[3]); });

, - for . for :

for (auto &v : Qe) 
    std::swap(v[2], v[3]);

... std::for_each, ++ 11 for , , , std::for_each , (IOW, std::for_each ).

+3

, .

  • , . O (1)
  • , , for. ()

std::vector<std::vector<double>> , , .

, for . , , , (, v), .

//untested code and inefficient, just an example:
vector<vector<double>> ReorderColumns(vector<vector<double>> A, vector<int> order)
{
    vector<vector<double>> B;
    for (int i=0; i<order.size(); i++)
    {
        B[i] = A[order[i]];
    }
    return B;
}

: , , , . .

+1

If you are in the script line. Perhaps the following functions will work:

// To be tested
std::vector<std::vector<double> >::iterator it;
for (it = Qe.begin(); it != Qe.end(); ++it)
{
    std::swap((it->second)[2], (it->second)[3]);
}

In this case, I do not see another solution that would avoid the O (n) loop.

0
source

Source: https://habr.com/ru/post/1568013/


All Articles