gpt4 book ai didi

c++ - 为什么当我输入 12 位数字时,以下代码会崩溃?

转载 作者:搜寻专家 更新时间:2023-10-31 00:53:39 25 4
gpt4 key购买 nike

<分区>

我一直在学习 Coursera 上的算法类(class),并尝试将所学知识转化为代码。这应该是一个“分而治之”的算法,我希望这部分没问题。我遇到了一个问题,只是把它弄乱了:一切正常,直到我在程序中输入一个 12 位数字。当我这样做时,它只是结束 cin 并输出所有先前排序的数字(如果之前没有数字则为空格)。如果可以的话,如果你发现错误,请告诉我哪里出了问题。这是我的代码:

#include "stdafx.h"
#include <iostream>
#include <vector>

using namespace std;

// setup global variable for the number of inversions needed
int inversions = 0;

// function to merge 2 sublists into 1 sorted list
vector<int> Merge_and_Count(vector<int>& split_lo, vector<int>& split_hi) {
// setup output variable -> merged, sorted list of the 2 input sublists
vector<int> out;
int l = 0;
int m = 0;

// loop through all the elements of the 2 sublists
for (size_t k = 0; k < split_lo.size() + split_hi.size(); k++) {
// check if we reached the end of the first sublist
if (l < split_lo.size()) {
// check if we reached the end of the second sublist
if (m < split_hi.size()) {
// check which element is smaller and sort accordingly
if (split_lo[l] < split_hi[m]) {
out.push_back(split_lo[l]);
l++;
}
else if (split_hi[m] < split_lo[l]) {
out.push_back(split_hi[m]);
m++;
inversions++;
}
}
else {
out.push_back(split_lo[l]);
l++;
inversions++;
}
}
else {
out.push_back(split_hi[m]);
m++;
}
}

return out;
}

// function that loops itself to split input into halves until it reaches the base case (1 element array)
vector<int> MergeSort_and_CountInversions(vector<int>& V) {
// if we reached the base case, terminate the loop and feed the output to the previous loop to be processed
if (V.size() == 1) return V;
// if we didn't reach the base case
else {
// continue halving the sublists
size_t const half_size = V.size() / 2;
vector<int> split_lo(V.begin(), V.begin() + half_size);
vector<int> split_hi(V.begin() + half_size, V.end());

// feed them back into the loop
return Merge_and_Count(MergeSort_and_CountInversions(split_lo), MergeSort_and_CountInversions(split_hi));
}
}

// main function of the app, runs everything
int main()
{
// setup main variables
int input;
vector<int> V;

// get input
cout << "Enter your numbers to be sorted (enter Y when you wish to proceed to the sorting)." << endl;
cout << "Note: do NOT use duplicates (for example, do not input 1 and 1 again)!" << endl;
while (cin >> input)
V.push_back(input);

cout << "\nThe numbers you chose were: " << endl;
for (size_t i = 0; i < V.size(); i++)
cout << V[i] << " ";

// get sorted output
vector<int> sorted = MergeSort_and_CountInversions(V);
cout << "\n\nHere are your numbers sorted: " << endl;
for (size_t j = 0; j < sorted.size(); j++)
cout << sorted[j] << " ";

// show number of inversions that were needed
cout << "\n\nThe number of inversions needed were: " << inversions << endl;

return 0;
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com