用C++对数组进行排序
Sort an array in C++
问题是我从用户那里获得了5个名称,并按字母顺序显示它们。这是我的密码。调试时,问题似乎出现在排序函数中。它应该告诉我数组何时完全排序。有人能告诉我我的问题在哪里吗?谢谢
#include<iostream>
#include<string>
using namespace std;
void swap(string,string);
bool sorted (string [3]);
void main ()
{
string firstname[3];
string sortfirstname[3];
int orginialindex[3];
string lastname[3];
float gpa[3];
int id[3];
for (int i=0;i<3;i++)
{
cout<<"Enter firstname"<<endl;
cin>>firstname[i];
}
for (int i=0;i<3;i++)
{
sortfirstname[i]=firstname[i];
}
while (!(sorted(sortfirstname)))
{
for (int i=0;i<3;i++) //3-2-1
{
if (sortfirstname[i]>sortfirstname[i+1])
{
swap(sortfirstname[i],sortfirstname[i+1]);
}
}
}
cout<<sortfirstname[0]<<sortfirstname[1]<<sortfirstname[2];
}
void swap (string a, string b)
{
string temp = b;
b = a;
a = temp;
}
bool sorted (string sortfirstname[3])
{
bool sort;
for (int i=0;i<3;i++)
{
if (sortfirstname[i]<sortfirstname[i+1])
sort = true;
else
sort = false;
}
return sort;
}
您的交换错误。
void swap (string a, string b)
{
string temp = b;
b = a;
a = temp;
}
这不会有任何作用!!您需要使用引用参数,即将函数签名转换为:
void swap (string& a, string& b)
此外,bool sorted (string sortfirstname[3])
有错误,请尝试:
bool sorted (string sortfirstname[3]) {
bool sort = true;
for (int i=0;i<3-1;i++)
{
if (sortfirstname[i]>sortfirstname[i+1])
sort = false;
}
return sort;
}
这纠正了两件事。(a) 你之前已经跑过了终点,(b)你决定了它们是否只在上次测试中排序。
for
循环退出条件应该是i<3-1
,因为稍后您将访问第(i+1)个元素。
相关文章:
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 显示错误输出的简单数组排序程序
- 为什么我的排序算法会更改数组值
- 为什么我需要C++中不同的排序格式来对这个USACO代码上的数组和优先级队列进行排序
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 合并排序不排序自创建数组类 c++
- 带有枚举方向/类型的气泡排序结构数组
- 为什么指针在对二维数组进行排序时无法正常工作?
- 排序并行数组
- 如何在数组 c++ 中对字符串进行排序
- 为什么在此排序算法实现中,向量明显比数组慢?
- 如何对不在数组中的变量进行排序?
- C++数组与向量排序(在我的情况下,向量比数组慢~2.5倍(无优化))
- 按字母顺序对结构内数组变量中的名称进行排序
- 使用排序函数 c++ 对字符数组进行排序
- 使用 std::sort 对二维 c 数组进行排序
- 使用STL对用户输入数组进行排序的错误有什么解决方案吗?
- 使用 std::sort 对 C 样式的 2D 数组进行部分排序
- 数组为此合并排序函数提供了正确的输出,但向量给出了不正确的输出.出了什么问题?
- 对 0 、1 和 2 的数组进行排序