编写一个将二维向量顺时针旋转90度的函数

huangapple go评论87阅读模式
英文:

Writing a function to rotate a 2d vector 90 degrees clockwise

问题

我试图将一个二维向量顺时针旋转,但无法使其适用于非正方形向量。这是我的尝试:

bool Pgm::Clockwise() {
    int i, j, k;
    vector<vector<int>> tempPixel;
    for (i = 0; i < Pixels.size(); i++) {
        tempPixel.push_back(Pixels.at(i));
    }

    for (j = 0; j < tempPixel.size(); j++) {
        tempPixel.push_back(vector<int>());
        for (k = 0; k < tempPixel.at(0).size(); k++) {
            tempPixel.at(j).push_back(Pixels.at(j));
        }
    }

    return true;
}
英文:

I am trying to rotate a 2d vector clockwise but I am unable to get it to work for vectors that are not square.

Here is what I tried

 bool Pgm::Clockwise(){
    int i, j, k;
    vector &lt;vector &lt;int&gt; &gt; tempPixel;
    for (i = 0; i &lt; Pixels.size(); i++) {
        tempPixel.push_back(Pixels.at(i));
    }

    for (j = 0; j &lt; tempPixel.size(); j++) {
        tempPixel.push_back(vector&lt;int&gt;());
        for (k = 0; k &lt; tempPixel.at(0).size(); k++) {
            tempPixel.at(j).push_back(Pixels.at(j));
        }
    }

    return true;
}

答案1

得分: 1

这个函数接受一个二维向量作为输入,并返回一个顺时针旋转90度的新二维向量。它首先创建一个具有交换维度的新向量rotated,然后通过按适当的顺序从输入向量复制元素来填充它。希望这能帮助您了解它的工作原理。

英文:
#include &lt;vector&gt;

std::vector&lt;std::vector&lt;int&gt;&gt; rotateClockwise(std::vector&lt;std::vector&lt;int&gt;&gt; v) {
    int n = v.size();
    int m = v[0].size();

    // create new vector with swapped dimensions
    std::vector&lt;std::vector&lt;int&gt;&gt; rotated(m, std::vector&lt;int&gt;(n));

    // populate the new vector
    for (int i = 0; i &lt; n; i++) {
        for (int j = 0; j &lt; m; j++) {
            rotated[j][n-i-1] = v[i][j];
        }
    }

    return rotated;
}

This function takes a 2D vector as input and returns a new 2D vector that is rotated 90 degrees clockwise. It first creates a new vector rotated with dimensions swapped, then populates it by copying the elements from the input vector in the appropriate order.
i hope this will help you to get an idea..

huangapple
  • 本文由 发表于 2023年2月18日 01:46:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75487645.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定