Sorting a vector of structs c++

Viewed 234

I have a struct where data is defined as:

typedef struct contacts 
{
    string name;
    string nickName;
    string phoneNumber;
    string carrier;
    string address;
    //callDetails callDetails;

} contactDetails;

vector <contactDetails> proContactFile;

I have like 10 -20 fields of information inside the vector. I need to bubble sort the name(Alphabetically),and display other respective data infront of name.(As an example after sorting a names i want to display the respective nickname , phone number ,carrier and address infront of that sorted name.) Is there a simple way to do it?

2 Answers

Learning about "custom comparators" will solve your problem. Here is one of the ways to achieve the desired result. I am using cmp as a custom comparator. Notice that it is passed while calling sort().

This way is useful if you need to sort on basis of something else tomorrow, say phoneNumber. The only change you would need is adding or updating a comparator function to return c1.phoneNumber < c2.phoneNumber;

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

typedef struct contacts
{
    string name;
    string nickName;
    string phoneNumber;
    string carrier;
    string address;
    //callDetails callDetails;
} contactDetails;

//sort based on name
bool cmp (const contacts& c1, const contacts& c2) {
    return c1.name < c2.name;
}

void print(vector <contactDetails> proContactFile) {
    for (auto s : proContactFile) {
        cout << s.name << " " << s.nickName << " " << s.phoneNumber << " " << s.carrier << " " << s.address << endl;
    }
}

int main()
{
    vector <contactDetails> proContactFile;

    proContactFile.push_back({"name1","nickName1","phone1","carrier1", "address1"});
    proContactFile.push_back({ "ame1","ickName1","hone1","arrier1", "ddress1" });
    proContactFile.push_back({ "me1","ckName1","one1","rrier1", "dress1" });
    proContactFile.push_back({ "e1","kName1","ne1","rier1", "ress1" });

    sort(proContactFile.begin(), proContactFile.end(), cmp);
    print(proContactFile);
}

Have you tried the standard template library?

#include <algorithm>
#include <functional>
#include <array>
#include <iostream>
 
int main()
{
    std::array<int, 10> s = {4, 7, 6, 3, 9, 2, 1, 0, 8, 3}; ; 
 
    // sort using the default operator<
    std::sort(s.begin(), s.end());
}

See: https://en.cppreference.com/w/cpp/algorithm/sort

You just need to define your compare operator '<' for your type.

Related