[英]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.