简体   繁体   English

使用指针简化C ++中的代码

[英]Using pointers to simplify my code in C++

Here's my code: 这是我的代码:

    void spin(double angle) {

    // Convert degrees to radians
    angle = get_radians(angle);

    vector<complex<double>> coordinate_list;
    coordinate_list.push_back(co1);
    coordinate_list.push_back(co2);
    coordinate_list.push_back(co3);
    coordinate_list.push_back(co4);

    // Origin point
    complex<double> origin(0,0);

    for (int i = 0; i < coordinate_list.size(); ++i)
    {
        complex<double> current = coordinate_list[i];
        double x = current.real();
        double y = current.imag();

        // Assuming all rectangles origins are at (0,0)
        float temp_x = origin.real() - x;
        float temp_y = origin.imag() - y;

        x = round(temp_x * cos(angle) - temp_y * sin(angle));
        y = round(temp_x * sin(angle) + temp_y * cos(angle));

        complex<double> rotated(x,y);
        coordinate_list[i] = rotated;
    }

    co1 = coordinate_list[0];
    co2 = coordinate_list[1];
    co3 = coordinate_list[2];
    co4 = coordinate_list[3];
    }

I'm looking for a way to avoid the part after the loop. 我正在寻找一种避免循环后出现的零件的方法。 I have the co1-4 values already and this method can be called at any point to rotate coordinates. 我已经有co1-4值了,可以在任意点调用此方法来旋转坐标。 I'd rather access these values directly instead of sticking them in a list, changing them, then assigning them back. 我宁愿直接访问这些值,而不是将它们粘贴在列表中,进行更改,然后将其分配回来。

Is there a way to do this? 有没有办法做到这一点?

Use pointers and refernces: 使用指针和引用:

vector<complex<double> *> coordinate_list;
coordinate_list.push_back(&co1);
coordinate_list.push_back(&co2);
coordinate_list.push_back(&co3);
coordinate_list.push_back(&co4);

// Origin point
complex<double> origin(0,0);

for (int i = 0; i < coordinate_list.size(); ++i)
{
    complex<double> &current = *coordinate_list[i];
    ...
    complex<double> rotated(x,y);
    current = rotated;
}

How about using a separate function instead of the for loop: 如何使用单独的函数代替for循环:

void rotate(complex<double> &co)
{
    // rotate it in place
}

// then just do something like this
rotate(co1);
rotate(co2);
rotate(co3);
rotate(co4);

Change your vector<complex<double> > to a vector<reference_wrapper<complex<double> > > and then you won't need the part after the loop. 将您的vector <complex <double>>更改为vector <reference_wrapper <complex <double>>>,然后在循环后就不需要该部分了。 The rest of your code will stay the same. 您的其余代码将保持不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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