I'm looking for some guidance here. I have a project and I'm looking to sort a char vector inside a struct.
I have the next struct and the main:
struct employee
{
long Id;
char name[20]
};
int main ()
{
employee data[5]
for(int i=0; i<5; i )
{
for(int x=i 1; x<5; x )
{
if(data[i].name[0]> data[x].name[0])
{
data[i].Id = data[x].Id;
data[i].name = data[x].name;
}
}
}
}
I'm stuck in this part. What I am trying to do is to basically sort the vector alphabetically by the name. For example: brayan
should be first and carlos
next.
It should look like this:
Employee #1
Id: 123
Name: brayan
Employee #2
Id: 121
Name: Carlos
I would appreciate any kind of help. The only requirement for this program is not to use std::string.
CodePudding user response:
You can use std::sort
with a custom comparison function, as commented.
The comparison function:
- receives two
employee
s, and - returns true if the first name is alphabetically "smaller" than the second (i.e.
strcmp
returned< 0
).
#include <algorithm> // sort
#include <cstring> // strcmp
#include <fmt/core.h>
struct employee {
long Id;
char name[20];
};
int main() {
employee data[5] {
{ 200, "Bryan"},
{ 100, "Charles"},
{ 300, "Anne"},
{ 500, "Will"},
{ 400, "John"}
};
std::sort(data, data std::size(data),
[](const auto& e1, const auto& e2) { return strcmp(e1.name, e2.name) < 0; }
);
for (auto i{0}; i < std::ssize(data); i) {
fmt::print("Employee #{}\nId: {}\nName: {}\n\n",
i 1, data[i].Id, data[i].name);
}
}
// Outputs:
//
// Employee #1
// Id: 300
// Name: Anne
//
// Employee #2
// Id: 200
// Name: Bryan
//
// Employee #3
// Id: 100
// Name: Charles
//
// Employee #4
// Id: 400
// Name: John
//
// Employee #5
// Id: 500
// Name: Will
CodePudding user response:
#include <string>
#include <vector>
#include <algorithm>
struct Test
{
int id;
std::string name;
};
int main()
{
std::vector<Test> tab(5);
std::sort(std::begin(tab), std::end(tab), []
(const Test& lhs, const Test& rhs)
{return lhs.name > rhs.name;});
}