0
votes

I have a class named Contacts whose only attribute is a vector<shared_ptr<Worker>>

where Worker is another class.

Class worker has three attributes which represent the name, the address and the phone number of the worker.

Now, when I try to sort the vector of pointers by using std::sort, I get a problem. I think I do not know how to pass smart pointers as parameters of functions. Here's my code

    #include <iostream>
    #include <vector>
    #include <memory>
    #include <string>
    #include <algorithm>


    class Worker
{
    string name, address;
    int phone;

public:

    Worker(string name, string aaddress, int phone): name(name), address(aaddress), phone(phone) {}

    string GiveName() const { return name;}
    string GiveAddress() const { return address;}
    int &GivePhone()  { return phone;}
};



class Contacts
{


    vector<shared_ptr<Worker>> workers{} ;


   static bool SortFoo( shared_ptr<Worker> r1,  shared_ptr<Worker> r2) {

    return r1->GiveName() > r2->GiveName();

}
     public: 

     Contacts() {
  workers.resize(0);
  }

  Contacts(int n) { workers.resize(n); }


   void AddWorker(const Worker & r)
    {
        workers.push_back(make_shared<Worker> (r));

    }



   void PrintContacts() const
    {




        for(int i = 0; i < workers.size(); i++)
        {
           cout <<  workers[i]->GiveName() << std::endl
               std::endl;
        }
    }



   // here comes the part that doesnt work

     void SortContacts() const {


    sort(workers.begin(), workers.end(), SortFoo);

      PrintContacts();




    }

This is without the main function, as my program wont even compile.

The error message I get in CodeBlocks is ``...\stl_algo.h|1847|error: no match for 'operator=' (operand types are 'const std::shared_ptr' and 'std::remove_reference&>::type {aka std::shared_ptr}')|

What do I do?

1

1 Answers

3
votes

SortContacts is declared const, but attempts to modify the member workers.

With that const removed, and a couple obvious typos fixed, your code compiles for me.