【问题标题】:Using a vector of shared pointers and sorting the pointees by sort function problem使用共享指针向量并通过排序函数问题对指针进行排序
【发布时间】:2019-06-20 23:00:58
【问题描述】:

我有一个名为 Contacts 的类,它的唯一属性是 vector<shared_ptr<Worker>>

其中 Worker 是另一个类。

班工具有三个属性,分别代表工人的姓名、地址和电话号码。

现在,当我尝试使用 std::sort 对指针向量进行排序时,我遇到了问题。我想我不知道如何将智能指针作为函数的参数传递。这是我的代码

    #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();




    }

这没有 main 函数,因为我的程序甚至无法编译。

我在 CodeBlocks 中收到的错误消息是 ``...\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}')|

我该怎么办?

【问题讨论】:

    标签: c++


    【解决方案1】:

    SortContacts 被声明为 const,但尝试修改成员 workers

    删除了const,并修复了几个明显的拼写错误,your code compiles 给我。

    【讨论】:

      猜你喜欢
      • 2016-07-06
      • 1970-01-01
      • 2012-02-25
      • 2012-11-19
      • 2014-03-11
      • 1970-01-01
      • 2014-05-16
      相关资源
      最近更新 更多