如何在单个函数中切换数组中的元素? [英] How to switch elements in an array in a single function ?

查看:69
本文介绍了如何在单个函数中切换数组中的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨.我是C ++的新手,我一直在研究大学的程序,但遇到了一些问题.问题是,我需要在一个函数中的单个数组中输入7个元素,而我确实这样做了.现在,我必须在数组中找到最小和最大的元素,并在另一个函数中切换它们的位置.我怎么做 ? (这不是家庭作业,这是我的个人锻炼)该功能应如下所示:

void switch(float array [],int v)//v是数组的const int大小


帮助将不胜感激. :)

Hi. I''m a bit of a newbie in C++, and I''v been working on a program from college and I got a little problem. The thing is, i need to enter 7 elements in a single array in one function, which I did. Now I have to find the smallest and the biggest element in the array and switch their places in another function. How do I do that ? (It is NO homework, it''s my personal exercising) The function should look like this:

void switching(float array[], int v) //v is the const int size of the array


Help would be appreciated. :)

推荐答案

看起来像这样:

Would look something like this:

// method to switch two elements in an array
void switching(float[] array, int positionX, int positionY)
{
    float temp = array[positionX];
    array[positionX]  = array[positionY];
    array[positionY] = temp;
}



那里有一个方法可以切换数组中的两个元素.
您可以从其他函数中调用该函数,例如:



There you have a method that switches two elements in an array.
You''d call that from you other function like this:

...
switching(array, idxOfBiggest, idxOfSmallest);
...



其中idxOfBiggest和idxOfSmallest是最大和最小数组元素的索引.

干杯!



where idxOfBiggest and idxOfSmallest are the indices of the biggest and the smallest array element.

Cheers!


选项一:
  1. 选择排序算法,实现它.
  2. 使用编码算法find max& min(例如v[max]v[min]).

  3. 用通常的
  1. Choose the sort algorithm, implement it.
  2. Using the coded algo find max & min (say v[max], v[min]).

  3. Swap v[max] and v[min] with the usual
float tmp = v[max]; v[max] = v[min]; v[min] = tmp



您可以将点(1)替换为:
使用现有的排序方法,例如STL sort [



You may replace point (1) with:
Use an existing sorting method, like, for instance STL sort[^].


这篇关于如何在单个函数中切换数组中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆