【发布时间】: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::find 或std::find_if 函数。我已经尝试了几个小时,但我尝试的每件事都无法编译。
感谢任何帮助。谢谢!
【问题讨论】: