在C ++中选择结构类型

时间:2015-04-24 16:05:05

标签: c++ vector struct

我的任务是创建一个选择排序算法来存储数据。所以我使用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

1 个答案:

答案 0 :(得分:2)

我不确定您的问题是什么或您期望的是什么,但您只是在这里交换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;