更好的方法来使用指针?

LF4*_*LF4 0 c++ pointers

我正在尝试创建一个程序,显示条形图,*最大数量*可以是40.我有一切正常,但对代码有疑问.是否有更好的方法,因为你可以看到我必须使用以下两次回到原始地址:

    p_bar_length = p_bar_length - size;
Run Code Online (Sandbox Code Playgroud)

有一个更好的方法吗?

#include <iostream>

using namespace std;

const int MAX_SPLATS = 40;

void bar_chart(double values[], int size)
{
    double largest = values[0]; //assign first element to be the largest

    //Find the largest value
    for (int i = 1; i < size; i++)
    {
        if (largest < values[i]) // check to see if there is something larger
        {
            largest = values[i];
        }
    }

    // Find the number of spalts to use
    // with the precent based on the largest value
    int* p_bar_length = new (nothrow) int[size];
    for (int i = 0; i < size; i++)
    {
        *p_bar_length = (values[i] / largest) * MAX_SPLATS;
        p_bar_length++; // Go to next memory address
    }

    // Go back to the orignal memory address
    p_bar_length = p_bar_length - size;

    // Pritnt the correct number of splats
    for (int i = 0; i < size; i++)
    {
        for (int j = 0; j < *p_bar_length; j++)
        {
            cout << "*";
        }
        p_bar_length++;
        cout << endl;
    }

    // Go back to the orignal memory address
    p_bar_length = p_bar_length - size;

    delete[] p_bar_length;
}

int main()
{
    double values[6] = { 22, 40, 28, 26, 14, 46};
    int val_size = 6;

    bar_chart(values, val_size);

    system("pause");

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Kon*_*lph 8

由于这是C++,最好的方法是使用指针; 相反,使用一个std::vector.

也就是说,您也可以始终将指针视为数组,只访问p_bar_length[i]给定位置0 <= i < length而不是递增指针.


Bri*_*ach 6

而不是递增指针,使用数组索引:

p_bar_length[i] = (values[i] / largest) * MAX_SPLATS;
Run Code Online (Sandbox Code Playgroud)

或使用指针算术:

*(p_bar_length + i) = (values[i] / largest) * MAX_SPLATS;
Run Code Online (Sandbox Code Playgroud)