【发布时间】:2017-01-24 03:53:14
【问题描述】:
我刚刚完成了一项任务,但最后一部分让我很生气。我做过研究,解决方案是我们在课堂上没有教过的概念,完全超出了我的想象。我需要冒泡排序和结构数组。但是我完全迷路了。任何帮助将不胜感激。
#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是一个引用数据类型,因此这种类型的变量(对象)没有原始的可比较值您可以用作排序的参数。您必须根据结构的成员变量的值来评估struct对象。在您的代码中,唯一的数值由int zipCode保存。你是如何被要求排序的?它应该按邮政编码值的升序/降序排列吗? -
抱歉说得这么含糊。我将使用冒泡排序按字母顺序对字段名称进行排序
标签: c++ bubble-sort