简体   繁体   中英

How to transpose a 2d vector using modern c++?

Say I have a matrix defined by:

vector<vector<T>> matrix;

For example, before transpose:

{{1, 2},
 {3, 4}}

After transpose:

{{1, 3},
 {2, 4}}

Naive for loop solution as requested:

    for(i = 0; i < rowSize; ++i){
        for(j = 0; j < colSize; ++j)
        {
            transposed[j][i]=original[i][j];
        }
    }

I am wondering what's the modern way in C++ to do a transpose on it? A naive solution is to use two for loops which is not what I am looking for. I am considering using for_each and std::transform . Can someone please make some suggestions? Thanks!

As always it completely depends on your needs. The most simple solution I can imagine is to not modify the data at all. Instead you can provide a wrapper that swaps the indices for access. Without guarantee for completeness or correctness (rather guaranteed to be incomplete and likely to have typos, but I hope you get the idea):

template <typename T>
struct transposed_ref {
    T& t;
    transposed_ref(T& t) : t(t) {}
    T::value_type& get(int x,int y) { return T[y][x]; }
};                                         //  ^  ^ --- note: swapped indices

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM