Selection-Sort Algorithm w/ Strings

EDIT: I figured out what I was doing wrong. I'll post a similar solution as a reference for anyone that might be having trouble with this in the future.

The assignment is to make a program read data from a file into a vector, and then use a sort algorithm to alphabetize the data. The data being read from the file comprises of an int (employee ID #'s) and a string (employee names).

The class is in the header.

#include <iostream>
#include <string>
#include <vector>
using namespace std;

class employee {

private:
int num;
string name;

public:

employee () {
num = 0;
name = "";
}

int getnum () {
return num;
}

string getname () {
return name;
}

employee(int a, string b) {
num = a;
name = b;
}
};

The MAIN, including the header:

#include <iostream>
#include <fstream>
#include "employee.h"
#include <string>
#include <vector>
using namespace std;

void read_file(string file_name, vector <employee> & order )
{
//reference variables
int num;
string name;
ifstream file;

//open file, pass data through vector
file.open(file_name);
while(!file.eof()){
file >> num >> name;
employee a(num,name);
order.push_back(a);
}
}

int main ()
{
vector <employee> order;
int k; //loop variable

//input file and read file as string
string file_name;

cout << "Please enter the name of a file: " << endl;
cin >> file_name;


int min, max; //range variables

read_file(file_name,order);
int length = order.size();

employee temp; //swap

for(int top = 0; top < length - 1; top++) {
//find smallest number in unsorted part of the list
min = top;
for(k = top + 1; k <= length - 1; k++) {
if ( order[k].getname() < order[min].getname() ) { min = k; }
}

//swap smallest (min) number into its final position in the sorted list
temp = order[top];
order[top] = order[min];
order[min] = temp;
}

//display
cout << endl << "Sorted List " << endl << endl;

for( k = 0; k < order.size(); k++ ) {
cout << order[k].getnum() << "\t" << order[k].getname() << endl;
}
return 0;
}
Last edited on
string a;
string b;

if(a > b)
cout <<a;
else if ( b > a)
cout << b;


I did an assignment similar to this and this is what my instructor replied to the same question i asked him:

"If you use C++ strings:

string a = "hello";
string b = "goodbye";

then you can compare them using relational operators (< > != ==)

a < b

The string library < function will do the character by character comparison.

`Tyson"
Last edited on
Topic archived. No new replies allowed.