冒泡排序一个结构数组
Bubble Sort an Array of Structs
我马上就要完成作业了,但是最后这部分太难了。我做了研究,解决方案是我们在课堂上没有教过的概念,完全超出了我的理解。我需要冒泡排序和数组的结构。然而,我完全迷路了。如有任何帮助,我将不胜感激。
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
struct billingInfo;
void bubbleSort(billingInfo list[], int length);
using namespace std;
int main()
{
// create struct with a field for zip codes and name of recepients that are being imported from text document
struct billingInfo {
int zipCode;
string name;
};
// create array of billingInfo struct
billingInfo recipients[20];
// open text file and test if file opened
ifstream dataFile("NameZip.txt");
if (dataFile.fail())
cout << "Can't open file." << endl;
else cout << "File opened." << endl;
int numElements = 0;
while (dataFile.peek() != EOF) {
dataFile >> recipients[numElements].zipCode;
getline(dataFile, recipients[numElements].name);
cout << recipients[numElements].zipCode << endl;
cout << recipients[numElements].name << endl;
numElements++;
}
system("pause");
return 0;
}
void bubbleSort(billingInfo list[], int length) {
billingInfo temp;
int itterator;
int index;
for (itterator = 1; itterator < length - itterator - length; itterator++) {
for (index = 0; index < length - itterator; index++) {
temp = list[index];
list[index] = list[index + 1];
list[index + 1] = temp;
}
}
enter code here
}
struct billingInfo
{
int key; // Can be any key
};
typedef struct billingInfo billingInfo;
// Overload the > operator
bool operator> (const billingInfo& first,const billingInfo& second)
{
return first.key > second.key;
}
// Make a custom Swap function for your struct
void swap (billingInfo& first,billingInfo& second)
{
int temp;
temp = first.key;
first.key = second.key;
second.key = temp;
}
// Not a single line of change in Bubble Sort Code.
// I hope the below code is bubble sort :p
void bubble_sort (billingInfo *list,int length)
{
for (int i=0;i<length-1;i++)
for (int j=0;j<length-i-1;j++)
if (list[j] > list[j+1]) // will work since we overloaded
swap (list[j],list[j+1]); // Our custom function
}
相关文章:
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么将一个结构的引用设置为等于另一个结构只会更改一个数据成员?
- 如何将一个结构的字符数组复制到结构的另一个字符数组中?
- 如何将数据从一个结构链接到另一个结构
- 是否可以使用智能指针成员设置具有另一个结构的结构?
- std::transform 将一个结构数组复制到另一个结构数组
- 输入 ctrl + x 后如何再次 cin (cin<<x) 循环(cin 一个结构)
- 如何在级别上打印树,给定一个结构,该结构保存节点的值及其父节点的值,对于树中的每个节点
- 创建一个结构的关联数组,以创建一个缓冲区,供键快速访问
- 如何在另一个结构中初始化结构数组?
- 在另一个结构中声明内部结构会导致错误:结构使用无效
- 我想重置一个C++结构统计,我可以以某种方式使用 stat() 语法吗?
- C++可以输出一个结构的内存地址吗
- 通过 C++ 中的另一个结构成员访问结构
- C++ push_back() 一个结构体到一个向量中
- 难以从另一个结构中的函数返回结构
- 如何将向量添加到结构中以创建一个库存系统,在该系统中,我可以仅使用一个结构向系统添加多种不同的葡萄酒
- 如何制作一个结构程序,在其中可以存储无限量的数据,以便每次您想要时都可以将另一个产品添加到列表中?
- 将一个结构的值复制到另一个结构
- 是否可以在同一未创建的结构内创建一个结构