如何在类中对数组值排序
How to sort array values inside a class
我想按升序对输入进行排序。但它似乎只排序整数…我的排序方法基于冒泡排序。抱歉,如果我的帖子太乱了…我在这里的第一篇文章:
using namespace std;
struct movies_t{
string title;
int year;
}films[3];
void printmovie (movies_t movie);
int main ()
{
string mystr;
int n,t;
string d;
for(n=0;n<3;n++)
{
cout <<"Enter title:";
getline(cin,films[n].title);
cout <<"Enter year:";
getline(cin,mystr);
stringstream (mystr)>> films[n].year;
}
for(n=0;n<3;n++)
{
for(int y=0; y<3; y++)
{
if(films[n].year < films[y].year)
{
t = films[n].year;
films[n].year = films[y].year;
films[y].year = t;
}
if(films[n].title < films[y].title)
{
d = films[n].title;
films[n].title = films[y].title;
films[y].title = d;
}
}
}
cout <<"n You have entered these movies:n";
for(n=0;n<3;n++)
printmovie (films[n]);
return (0);
}
void printmovie(movies_t movie)
{
cout <<movie.title;
cout <<"("<<movie.year<<")n";
}
的输出 Enter title:a
Enter year:2001
Enter title:d
Enter year:2011
Enter title:f
Enter year:2005
You have entered these movies:
a(2001)
d(2005)
f(2011)
我希望输出是:
You have entered these movies:
a(2001)
f(2005)
d(2011)
你应该比较电影的年份,但要替换整个元素,而不仅仅是它们的标题,像这样:
d = films[n];
films[n] = films[y];
films[y]= d;
对数组进行排序的更有效或更简洁的方法可能是添加运算符<到该结构,然后使用std::sort进行排序。这也可以解决你的排序功能的问题。>
struct movies_t{
string title;
int year;
bool operator<(const movies_t& rhs) const
{
if (year < rhs.year)
return true;
if (year > rhs.year)
return false;
return title < rhs.title;
}
}films[3];
用:
替换排序代码#include <algorithm>
std::sort(films, films + n);
相关文章:
- 显示错误输出的简单数组排序程序
- C 使用单个函数对具有多种值类型的数组排序
- 2D数组排序,空格打乱顺序
- C 2D数组排序
- C++数组排序 - 将"bbba"和"0001"视为不正确排序的问题
- 数组排序功能
- CString 数组排序
- 简单的数组排序/检查 划分和征服版本
- C++ 中的多维数组排序
- 选择在++中对并行数组排序
- C++:二维指针数组排序:选择排序不适用于某些实例
- C++字符串数组排序
- C++中的指针数组排序算法
- 在VC++6中使用向量进行数组排序时出错,而在VC++2012中没有错误
- 将索引数组排序为主数组
- 数组排序、数组输入、数组输出
- C++数组排序,内存错误
- 在嵌入式系统上将数组排序功能从c++移植到c
- 基于其他int数组排序
- 多维数组排序c++奇怪行为