插入排序起始
Insertion Sort Initiation
本文关键字:插入排序 更新时间:2023-10-16
我是第一个遇到堆栈溢出的人,所以感谢大家耐心地帮助我解决这个问题。我正在用c++编写一个程序,通过对.txt文件中的数字进行排序来实现插入排序。它接受一个文件,显示其中的内容,然后询问用户是否要对数字进行排序。当我键入"y"时,它应该在我的代码中启动插入排序算法。但是现在它所做的就是完成编译。任何建议都非常感谢。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//Read file input and display contents
ifstream& readfile(ifstream& file)
{
string line;
if (getline(file, line))
{
cout << line;
}
return file;
}
int main()
{
string fileName, line, r;
int n, i, j, k, temp;
int a[n];
ifstream fs;
cout << "enter file: ";
cin >> fileName;
ifstream file(fileName);
if (file.is_open())
{
while (readfile(file))
{
}
}
cout << endl << endl << "Sort File? y or n? ";
cin >> r;
if (r == "y")
{
for (i = 0; i < n; i++)
{
cin >> a[i];
}
for (i = 1; i < n; i++)
{
for (j = i; j >= 1; j--)
{
if (a[j] < a[j - 1])
{
temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
}
else
{
break;
}
}
}
for (k = 0; k < n; k++)
{
cout << a[k] << endl;
}
}
else
{
cout << endl << "error" << endl;
}
cin.get();
return 0;
}
n未初始化。
for (i=0;i<n;i++)
{
cin >> a[i];
}
这里什么都没有发生,因为(如果你幸运的话…)n=0。如果只需要5个条目,则将n初始化为5。
或
- 使用STL容器,如std::vector,例如,你在这里使用类似C的语言…
- 当用户初始化插入时,更改循环中的结束条件
例如,如果用户插入"stop"字:
std::vector<int> vIntegers;
std::string input;
int n = 0;
while ( input != "stop")
{
std::cin >> input;
// test if integer here
{
vIntegers.push_back(n);
}
}
在这里测试一个字符串是否是整数如何检查c++字符串是否为int类型?
相关文章:
- 这是插入排序的正确实现吗?
- 使用列表 STL 递归进行插入排序
- 列表 iter 不取消引用 使用列表进行插入排序
- 如何使插入排序更快?
- 插入排序的最小交换
- 双链表C++上的插入排序
- 如何在插入排序中使用 replace() 使语句变得不必要
- C++插入排序错误功能不起作用
- 如何在不通过插入排序更改原始矢量的情况下对 2D 矢量进行排序
- 插入排序打印错误的输出
- 从矢量末尾开始的插入排序
- 插入排序:我做错了什么?
- 插入排序的向量<unique_ptr<对时避免堆分配<>>>
- 获取有趣的输出以进行插入排序
- 插入排序算法在放入函数时的行为不同
- 插入排序的Valgrind Invalid读取尺寸8的尺寸
- 插入排序与插入/擦除?(所以我需要对一个向量进行排序,而不是手工做事,而是使用插入和擦除
- 堆排序和插入排序
- 计数Heapsort和插入排序中的复制和比较数
- 使用第二个数组C 插入排序算法