【问题标题】:The elements in an array seems to be changing, array's first half sorted and second half is randomized数组中的元素似乎在变化,数组的前半部分已排序,后半部分是随机的
【发布时间】:2020-10-12 15:14:02
【问题描述】:

该程序旨在根据用户输入的数组大小给出随机数。 rand() 正在工作并根据用户提供输出元素。

问题在于,当涉及到排序的部分时,数组的元素似乎从不同的值发生变化。

#include <iostream>
#include <ctime>
using namespace std;

int SizeArray = 0;
int setArray[] = { NULL };
int  tempA, half;

int main() {
  cout << "Enter number of elements: ";
  cin >> SizeArray;

  srand(time(0));
  for (int i = 0; i < SizeArray; i++) {
    setArray[i] = 51 + rand() % (100 - 51);
  }
    
  cout << "\n\n\nraw input  " << endl;
  for (int i = 0; i < SizeArray; i++) {
    cout << setArray[i] << "\t";
  }

  half = SizeArray / 2;
  cout << "\n\n\nfirst half  " << endl;
  for (int j = 0; j < half; j++){
    for (int i = 0; i < half; i++){
      if (setArray[i] > setArray[i + 1]){
        tempA = setArray[i];
        setArray[i] = setArray[i + 1];
        setArray[i + 1] = tempA;
      }
    }
  }
            
  for (int i = 0; i < half; i++){ //to print the sorted array
    cout << setArray[i] << "\t";
  }

  cout << "\n\n\nsecond half  " << endl;
  for (int i = half; i < SizeArray; i++){ //to print the second half 
    cout << setArray[i] << "\t";
  }

  cout << "\n\n\nmerge " << endl;
  for (int i = 0; i < SizeArray; i++) { //to print all elements of the array
    cout << setArray[i] << "\t";
  }
}

example of error there should be no "4" there

我希望知道为什么元素会发生变化以及有哪些可能的解决方案。

【问题讨论】:

  • VTC 是一个错字,因为您根本没有分配索引到的数组元素

标签: c++ arrays algorithm sorting


【解决方案1】:

int setArray[] = { NULL }; 创建一个包含 one 元素的数组。如果您尝试访问除setArray[0] 之外的任何内容,您的行为未定义,这就是您所看到的。

由于在编译时不知道元素的数量,请改用std::vector&lt;int&gt;

#include <vector>

// ...

std::vector<int> setArray;

然后,当用户输入应该有多少元素时,执行:

setArray.resize(SizeArray);

一个不相关的事情是你实际上并没有从用户那里得到任何输入。在你的 input 循环中,你打印已经存在的值:

cout << "\n\n\nraw input  " << endl;
for (int i = 0; i < SizeArray; i++) {
  cout << setArray[i] << "\t";         // cin >> setArray[i]   ???
}

【讨论】:

  • 感谢您回答,关于“原始输入”是一个错误,我的意思是显示从 rand() 生成的数字/元素没有任何更改。
  • @DeWard 不客气!关于原始输入:啊哈,是的,我明白你的意思了。
【解决方案2】:

您的程序有未定义的行为。

线

int setArray[] = { NULL };

创建一个包含一个元素的数组。从它访问任何索引大于 0 的元素会导致未定义的行为。

您需要创建一个动态分配的数组。我的建议是使用std::vector&lt;int&gt;

// Move themm inside main.
// int SizeArray = 0;
// int setArray[] = { NULL };
// int  tempA, half;

int main()
{
    int SizeArray = 0;
    int  tempA, half;

    cout << "Enter number of elements: ";
    cin >> SizeArray;

    // Construct a vector with size SizeArray.
    std::vctor<int> setArray(SizeArray);

    // Rest of your program.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-09
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 2013-01-04
    • 1970-01-01
    • 2019-04-05
    相关资源
    最近更新 更多