【问题标题】:How do i search a list of object pointers? C++如何搜索对象指针列表? C++
【发布时间】:2015-03-06 05:59:33
【问题描述】:

首先,这是一个带有人为限制的作业。 作业要求我使用 STL、继承和多态性。我还必须使用迭代器根据对象 ID 从列表中查找、打印和删除项目。

我正在使用指向对象的指针列表。这些对象派生自一个抽象基类 Sequence,并被动态分配并存储在列表中。

我的抽象基类

class Sequence{
public:
    virtual void print() = 0;
    virtual int getId() = 0;


protected:
    std::string m_label;
    int m_id;
    std::string m_sequence;
    int m_length;

};

print()getId() 函数在派生类中被覆盖。正在从文件中读取数据并通过每行上的命令进行解析。

SequenceDatabase::SequenceDatabase(){

    std::list<Sequence*> myList;
}

// function reads in the filename creates a data stream and performs the requested actions
void SequenceDatabase::importEntries(std::string inputFile){
    std::ifstream dnaFile(inputFile);
    char command;
    std::string label, sequence, type;
    int id, length, index, orf; 
    while(dnaFile >> command){
        Sequence* s;
        // if the command = D this allocates memory for a dna object and pushes the object onto the list
        if(command == 'D'){
            dnaFile >> label >> id >> sequence >> length >> index;
            std::cout << "Adding " << id << " ...\n\n";
            s = new DNA(label, id, sequence, length, index);
            myList.push_back(s);
        }
        // if the command = R this allocates memory for a RNA object and pushes the object onto the list
        if(command == 'R'){
            dnaFile >> label >> id >> sequence >> length >> type;
            std::cout << "Adding " << id << " ...\n\n";
            s = new RNA(label, id, sequence, length, type);
            myList.push_back(s);
        }
        // if the command = A this allocates memory for an AA object and pushes the object onto the list
        if(command == 'A'){
            dnaFile >> label >> id >> sequence >> length >> orf;
            std::cout << "Adding " << id << " ...\n\n";
            s = new AA(label, id, sequence, length, orf);
            myList.push_back(s);
        }
        // if the command = O this searches the list for the id and either outputs that the object doesn't exist or it deletes it
        if(command == 'O'){
            dnaFile >> id;
            std::cout << "Obliterating " << id << " ...\n\n";
            // problem
        }
        // if the command = P this searches the lists for the id and either outputs that the object doesn't exist or it prints out the info of the object 
        if(command == 'P'){
            dnaFile >> id;
            std::cout << "Printing " << id << " ...\n";
            // problem  
        }
        // if the command = S this outputs the number of entries in the list
        if(command == 'S')
            std::cout << "Entries: " << myList.size() << " total\n";
    }
    dnaFile.close();
}

列表正在正确构建。尝试在列表中搜索具有特定 ID 的对象时出现了我的问题。我创建了 findId() 函数,因为我知道我必须将它与读入的 id 进行比较。

我不确定在处理对象指针时如何使用std::findstd::find_if 函数。我已经尝试了几个小时,但我尝试的每件事都无法编译。

感谢任何帮助。谢谢!

【问题讨论】:

    标签: c++ list pointers stl


    【解决方案1】:

    如果您可以使用 C++11 编译器,则可以使用:

    auto iter = std::find_if(myList.begin(),
                             myList.end(),
                             [](Sequence* s) -> bool { return (s->getId() == id); });
    if ( iter != myList.end() )
    {
       return *iter;
    }
    else
    {
       return nullptr;
    }
    

    std::find_if 搜索谓词返回true 的元素。更多信息请访问http://en.cppreference.com/w/cpp/algorithm/find

    在这种情况下,谓词是一个 lambda 函数,如果给定 ID 与 Sequence* 对象之一的 ID 匹配,则返回 true

    如果列表不包含匹配的Sequence*find_if 返回myList.end()

    【讨论】:

    • 你能解释一下这有什么作用吗?编译器抱怨预期的;如果之前。还有什么需要包含在捕获列表中吗?
    • @kemotoe,是的,我错过了find_if 语句末尾的;。现在已经修好了。
    • 感谢您的解释。我从来没有被介绍过 lambda 函数。效果很好。
    【解决方案2】:

    你可以使用类似的东西

      for (Sequence* p : myList)
        if (p->getId()>50) dosomething(p);
    

    顺便说一句,您可能想要使用智能指针列表(例如std::shared_ptr)所以

    std::list<std::shared_ptr<Sequence>> myList;
    

    【讨论】:

      【解决方案3】:

      如果您无法访问 C++11 编译器或者您不想使用 lambda 函数,您可以定义一个比较器

      struct Comparator {
          id_type find_id;
      
          Comparator(id_type id) : find_id(id) {}
      
          inline bool operator ()(const Sequence * obj) {
              return find_id == obj->getId();
          }
      }
      
      . . .
      
      typename std::list<Sequence *>::iterator it;
      it = std::find_if(List.begin(), List.end(), Comparator(id));
      return it != List.end();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-12
        • 2013-06-25
        • 1970-01-01
        • 1970-01-01
        • 2020-07-01
        相关资源
        最近更新 更多