I've been trying to sort a vector of Employee's with a string data member called last name. I've tried several different ways, using the sort method of vector, trying to convert my vectors to list and using its sorting, I even tried using string compare and > operators as shown below:
vector<Employee>sortE(vector<Employee>record)
{
for (unsigned int i = 0; i < record.size() - 1; i++)
if (record[i].getLastName() > record[i+1].getLastName())
swap(record[i], record[i + 1]);
return record;
}
I thought if I used the above method with the swap function, it would work. But maybe since swap is a string method and I'm doing it with Employees it won't swap properly? But I've also tried it with my own "swap" like below:
vector<Employee>sortE(vector<Employee>record)
{
Employee temp;
for (unsigned int i = 0; i < record.size() - 1; i++)
if (record[i].getLastName() > record[i + 1].getLastName())
{
temp = record[i];
record[i] = record[i + 1];
record[i + 1] = temp;
}
return record;
}
Either way I can't seem to get it to work properly, any insight or help would be appreciated.
You could try using a lambda if using C++11 or newer (also, I don't know what your Employee class looks like, so I made a trivial one). Also, check here for online execution: http://cpp.sh/6574i
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
class Employee
{
public:
Employee( const std::string& firstName, const std::string& lastName ) :
_firstName( firstName ),
_lastName( lastName )
{}
~Employee()
{}
std::string FirstName() const
{
return _firstName;
}
std::string LastName() const
{
return _lastName;
}
std::string FullName() const
{
return _firstName + " " + _lastName;
}
private:
std::string _firstName;
std::string _lastName;
};
int main()
{
Employee e1( "Suresh", "Joshi" );
Employee e2( "Mats", "Sundin" );
Employee e3( "Steve", "Nash" );
std::vector< Employee > employees { e1, e2, e3 };
std::sort(employees.begin(), employees.end(),
[](const Employee& lhs, const Employee& rhs) -> bool
{
return rhs.LastName() > lhs.LastName();
});
for ( auto employee : employees )
{
std::cout << employee.FullName() << std::endl;
}
}
You can provide a lambda to std::sort
:
std::vector<Employee> ve;
using std::begin;
using std::end;
std::sort(begin(ve), end(ve),
[](const Employee& lhs, const Employee& rhs)
{
return lhs.getLastName() < rhs.getLastName();
});
That said, in real life last names are not necessarily unique, and when they compare equal it's a good idea to fall back on first name, and if that's also equal some other field like an employee id:
return lhs.getLastName() < rhs.getLastName() ||
lhs.getLastName() == rhs.getLastName() &&
(lhs.getFirstName() < rhs.getFirstName() ||
lhs.getFirstName() == rhs.getFirstName() &&
lhs.getId() == rhs.getId());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.