简体   繁体   English

我是否正确使用了指针和数组?

[英]Am I using pointers and array correctly?

My teacher for an assignment problems requires that we pass an array to a function that just finds the median of it. 对于分配问题,我的老师要求我们将数组传递给仅能找到其中位数的函数。 and if there's an even amount of numbers, it averages the two in the middle. 如果有偶数,则将中间的两个取平均值。 I quote from him "use pointers whenever possible". 我引用他的话“尽可能使用指针”。 The only one I could see using a pointer is the array itself? 使用指针我唯一能看到的就是数组本身?

I understand the concept of what needs to happen, I'm just not sure how to properly use pointers and Googling doesn't reveal too helpful results. 我了解需要发生的情况的概念,只是不确定如何正确使用指针,而Google搜索也不会揭示有用的结果。

int medianArray(int *pArray, int sizeArray)
{
    if(sizeArray % 2 == 1)
    {
        return (pArray[((int)(sizeArray/2)) -1 ] + pArray[((int)(sizeArray/2)) +1 ]) / 2;
    }
    else
        return pArray[(int) sizeArray/2];
}

You've got the right idea here, but you're computing your offsets wrong. 您在这里有个正确的主意,但您计算出的偏移量是错误的。

Here's an idea: 这是一个主意:

size_t median = sizeArray / 2;

return (pArray[median] + pArray[median+1]) / 2;

Don't forget this will fail if the values exceed int bounds, and additionally you should be using size_t to express sizes as that should never be negative. 不要忘记,如果值超过int界限,它将失败,此外,您应该使用size_t来表示尺寸,因为它永远不能为负数。

Additionally, there's no point in casting the result of an int calculation to int. 此外,将int计算的结果转换为int没有意义。

Regarding this C++ lesson, I think anything that bucks the principles laid out in the Standard Library better have a good reason for doing so. 关于本C ++课程,我认为任何与标准库中列出的原理背道而驰的方法都有很好的理由。 While an academic exploration of the benefits of pointers vs. iterators vs. references is always encouraged, advocating pointers "whenever possible" is a bad plan and comes from a C mindset. 虽然总是鼓励人们对指针,迭代器和引用的好处进行学术探索,但“尽可能”提倡指针是一个糟糕的计划,并且源于C语言。

In a modern C++ course this assignment would revolve around computing the median of an unsorted Standard Library container of an arbitrary type by defining a template function. 在现代C ++课程中,此任务将围绕通过定义模板函数来计算任意类型的未排序标准库容器的中位数。

just so you can get a concrete feel regarding what people were talking about when they said 'modern c++ doesnt use pointer' etc. 只是这样,您可以对人们所说的“现代c ++不使用指针”等有个具体的了解。

One alternative is to use std::vector 一种替代方法是使用std :: vector

int medianArray(const std::vector<int> &vec)
{
    int sizeArray = vec.size();
    if(sizeArray % 2 == 1)
    {
        return (vec[((int)(sizeArray/2)) -1 ] + vec[((int)(sizeArray/2)) +1 ]) / 2;
    }
    else
        return vec[(int) sizeArray/2];
}

note that vector knows how big it is. 请注意,向量知道它有多大。 It also wont run off either end if you use vec.at(index) 如果您使用vec.at(index)它也不会在两端运行

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

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