【问题标题】:Swapping all smallest and largest number in an array/vector交换数组/向量中的所有最小和最大数字
【发布时间】:2020-11-12 09:26:02
【问题描述】:

我正在尝试编写一个程序来交换数组或向量中的所有最大和最小数字。我想出了一个程序,但由于某种原因我无法调试它来解决问题。它没有打印矢量,我也不知道问题是什么。谁能帮帮我。

Desired Input and Output

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main()
{
    int n;
    cin>>n; //size input
    vector<int> arr;
    for(int i=0;i<n;i++) //filling up the vector
    {
        int input;
        cin>>input;
        arr.push_back(input);
    }
    vector<int> arr1=arr; //copying the vector
    sort(arr1.begin(), arr1.end()); //sorting the new vector
    int i=0,j=n-1,i1=0,j1=n-1; //i and j are for the vector arr & i1 and j1 are for vector arr1
    while(i1<j1)
    {
        if(arr1[i1]==arr[i] && arr1[j1]==arr[j]) //if the first and last number of the sorted vector is found in arr the swap
        {
            int temp=arr[i];
            arr[i]=arr[j];
            arr[j]=temp;
            i1++;
            j1--;
            i=0; // i and j are set to initial value so that it is checked from the start
            j=n-1;;
        }
        else if(arr1[i1]<arr[i] && arr1[j1]==arr[j]) //if only the biggest place element is found the increase i 
        {
            i++;
        }
        else if(arr1[i1]==arr[i] && arr1[j1]>arr[j]) //if only the smallest place element is found the decrease j
        {
            j--;
        }
        else if(arr1[i1]!=arr[i] && arr1[j1]!=arr[j]) //if none of them are found then increase i and decrease j
        {
            i++;
            j--;
        }
    }
    for(int f=0;f<n;f++) //print the vector
        cout<<arr[f]<<" ";
    return 0;
}

/*
Sample input 1
6
12 34 87 56 38 98

Sample output 1
98 87 34 38 56 12

Sample input 2
6
8 7 9 2 4 6

Sample output 2
4 6 2 9 8 7

*/ 

我们将不胜感激。

【问题讨论】:

  • 如果arr1包含arr中项目的索引可能会简单得多
  • 对问题的描述完全不清楚。 “交换所有最小和最大的数字”是什么意思?
  • 将输入和所需输出包含为 text,而不是链接图像(也不是代码底部的内容)。 -1.
  • 在打印出数组后,尝试在末尾输出换行符。
  • 您的程序似乎完全按照您希望的方式运行

标签: c++ arrays sorting vector


【解决方案1】:

一种更简单的方法是创建一个索引向量,而不是对向量进行排序并尝试在原始向量中查找值。例如:

#include <iostream>
#include <algorithm>
#include <vector>

int main()
{
    int n;
    std::cin >> n;
    std::vector<int> arr;
    std::vector<int> indexes;
    for (int i = 0; i < n; i++)
    {
        int input;
        std::cin >> input;
        arr.push_back(input);
        indexes.push_back(i);
    }
    std::sort(indexes.begin(), indexes.end(), [&](int a, int b) {return arr[a] < arr[b]; });
    for (int i = 0, j = n - 1; i < n / 2; i++, j--)
    {
        std::swap(arr[indexes[i]], arr[indexes[j]]);
    }
    for (int f = 0; f < n; f++)
    {
        std::cout << arr[f] << " ";
    }
    return 0;
}

【讨论】:

  • 谢谢,它确实有效,但我不明白排序函数中的“[&](int a, int b) {return arr[a]
  • 它是lamda
猜你喜欢
  • 2021-01-08
  • 1970-01-01
  • 1970-01-01
  • 2013-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-23
相关资源
最近更新 更多