在结构数组中寻找最大值

时间:2012-02-06 20:25:58

标签: c++ struct

我只是学习阶段的初学者。

我应该安排pointxyz)的结构,以便结构p[n]具有最大的x {1}}存储在其中。我的方法是否正确?如果没有,有没有简单的方法来做到这一点?

struct point 
{
    float x;
    float y;
} p[1000];

void sortptx(struct point *t, int ctr);  

int main()
{
    int n = 100;  
    sortptx(&p, n);  
    return 0;  
}  

void sortptx(struct point *t, int ctr)  
{
    float temp;  
    int i;  
    for(i = 0; i < ctr-1; i++)  
    {
        if (t[ctr]->x < t[i]->x)  
        {
            temp = t[ctr]->x;  
            t[ctr]->x = t[i]->x;  
            t[i]->x = temp;  
        }
    }
}

2 个答案:

答案 0 :(得分:0)

这里至少有一些错误:

  1. 如评论中所述,struct point *t是指向单个struct point的指针或点数组。 不是指向struct point指针数组的指针。因此t[i]->x应为t[i].x

  2. 如果ctr是一个点数组的长度,t[ctr]将在数组的末尾运行,并且可以访问未初始化的内存。在这种情况下,t[ctr-1]将是数组的最后一个元素。

  3. 不是交换整个点,而是交换x坐标。

答案 1 :(得分:0)

根据我的理解,您不希望对其进行排序,但查找最大point的{​​{1}}并确保其存储在x

p[n-1]

这就是它的样子:

struct point 
{
    float x;
    float y;
} p[1000];

此函数将void max(struct point *t, int ctr) { struct point temp; int i; for(i = 0; i < (ctr - 1); i++) { if (t[ctr - 1].x < t[i].x) { temp = t[ctr - 1]; t[ctr - 1] = t[i]; t[i] = temp; } } } 作为参数,这是指向struct point *t的第一个point的指针。 p t[i]位于索引struct point(不是i的指针),因此您在访问其成员时使用struct point而不是.。并且由于您从零开始索引,因此大小为->的数组的最后一个元素具有索引n,这是存储具有最高n-1的{​​{1}}的位置。

示例:

struct point

输出:x

相关问题