[英]Selection sort of struct in C++
我的任务是创建一个选择排序算法来存储数据。 所以我使用struct来存储数据,并且已经实现了选择排序,但是我对结果确实感到困惑。 我感谢您的帮助。
#include <iostream>
#include <vector>
#include <cstdlib>
#include <vector>
#include <string>
using namespace std;
struct employee
{
string name;
int salary;
};
void swap(int& x, int& y)
{
int temp = x;
x = y;
y = temp;
}
int min_position(vector<employee>& a, int from, int to)
{
int min_pos = from;
int i;
for (i = from + 1; i <= to; i++)
if (a[i].salary < a[min_pos].salary)
min_pos = i;
return min_pos;
}
void selection_sort(vector<employee>& a)
{
int next; // the next position to be set to the minimum
for (next = 0; next < a.size() - 1; next++)
{ // find the position of the minimum
int min_pos = min_position(a, next, a.size() - 1);
if (min_pos != next)
swap(a[min_pos].salary, a[next].salary);
}
}
void print(vector<employee>& a)
{
for (int i = 0; i < a.size(); i++)
cout << a[i].name << ", " << a[i].salary;
cout << "\n";
}
int main()
{
int empl;
cout << "enter the number of employees:\n";
cin >> empl;
vector<employee> v(empl);
for (int i = 0; i < empl; i++)
{
cout << "Enter the employee and the salary: " << endl;
employee e; // create an employee
cin >> e.name; // get name from user
cin >> e.salary; // get salary from user
v.push_back(e); // put employee into vector
}
print(v);
selection_sort(v);
cout << "_________________________" << endl;
print(v);
return 0;
}
这是输出:
Enter the number of employees:
2
Enter the employee and the salary:
John
60
Enter the employee and the salary:
Ron
20
, 0, 0John, 60Ron, 20
_________________________
, 0, 0John, 20Ron, 60
我不确定您的问题是什么或期望什么,但是您只是在这里交换salary
:
swap(a[min_pos].salary, a[next].salary);
您想交换整个employee
:
swap(a[min_pos], a[next]);
编辑:现在,您编辑了问题所在,这是您看到的问题:
vector<employee> v(empl);
for (int i = 0; i < empl; i++)
{
cout << "Enter the employee and the salary: " << endl;
employee e; // create an employee
cin >> e.name; // get name from user
cin >> e.salary; // get salary from user
v.push_back(e); // put employee into vector
}
在此循环之前,您将矢量初始化为员工人数,然后添加您所读的员工。 因此,您最终得到的雇员数量是您期望的2倍,其中一半是垃圾。 要解决此问题,请声明向量不同:
vector<employee> v;
还是不要push_back
:
v[i] = e;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.