| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 2098 人关注过本帖
标题:求助findmax函数
只看楼主 加入收藏
七月与安生鉴
Rank: 1
等 级:新手上路
帖 子:6
专家分:0
注 册:2021-5-23
结帖率:100%
收藏
已结贴  问题点数:20 回复次数:3 
求助findmax函数
下面的程序中,调用了findmax()函数,该函数寻找数组中的最大元素,将该元素的下标通过参数返回,并返回其地址值。要求:1)编程实现findmax()函数。2)画出程序的内存结构图;

#include<iostream>

using namespace std;

int *findmax(int *array, int size, int *index);

void main(){

    inta[10] = { 33, 91, 54, 67, 82, 37, 85, 63, 19, 68 };

    int *maxaddr;

    int idx;

    maxaddr = findmax(a,sizeof(a) / sizeof(*a),&idx);

    cout<<"the indox of maximum element is"<<idx<<endl

           <<"the address of it is"<<maxaddr<<endl

            <<"the value of it is"<< a[idx] <<endl;

}
搜索更多相关主题的帖子: sizeof int 函数 返回 the 
2021-05-23 11:03
apull
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
来 自:三体星系
等 级:版主
威 望:216
帖 子:1479
专家分:9035
注 册:2010-3-16
收藏
得分:15 
程序代码:
int* findmax(int* array, int size, int* index)
{
    int max = *array;
    *index = 0;
    for (int i=1; i < size; ++i)
    {
        if (max < *(array + i))
        {
            max = *(array + i);
            *index = i;
        }
    }
    return array + *index;
}
2021-05-23 11:53
rjsp
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:528
帖 子:9007
专家分:53942
注 册:2011-1-18
收藏
得分:5 
int *findmax(int *array, int size, int *index);
这函数定义得不好。
既然不修改 array,那么就应该加 const;
数组长度的类型不应该是int size,而是 size_t size;
数组下标的类型不应该是int *index,而是 size_t* index;
既然用 int* 返回了元素地址,又何必用 int* index 返回下标?多此一举。

参考一下,C++ STL 的实现
程序代码:
template<class ForwardIt>
ForwardIt max_element(ForwardIt first, ForwardIt last)
{
    if (first == last) {
        return last;
    }
    ForwardIt largest = first;
    ++first;
    for (; first != last; ++first) {
        if (*largest < *first) {
            largest = first;
        }
    }
    return largest;
}


程序代码:
#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;

int main( void )
{
    int a[] = { 33, 91, 54, 67, 82, 37, 85, 63, 19, 68 };
    auto p = max_element( begin(a), end(a) );
    cout << "最大值元素的下标是 " << distance(begin(a),p) << endl;
    cout << "最大值元素的地址是 " << &*p << endl;
    cout << "最大值元素的数值是 " << *p << endl;
}

2021-05-24 09:02
七月与安生鉴
Rank: 1
等 级:新手上路
帖 子:6
专家分:0
注 册:2021-5-23
收藏
得分:0 
回复 2楼 apull
如果findmax改为int *findmax(int *array,int size,int&index)变为使用引用类型怎么做呀
2021-05-26 21:52
快速回复:求助findmax函数
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.015710 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved