Tat*_*ili 1 c++ algorithm iterator copy c++-standard-library
1)假设我有一个v巫师向量(向导有一个名字,姓氏,字符串向量,其中包括他/她参加的主题以及他/她所属的房子)
2)我有一个空向量cpy,我想在其中复制那些参加主题的向导,其中带有字母“ p”。
就我而言,我只想复制劳拉,因为她参加运动,这是唯一包含“ p”的主题。
//wizard.cpp
Wizard::Wizard(string name, string lastname, Vector<string> subjects, Haus haus) :
name{name}, lastname{lastname}, subjects{subjects}, haus{haus}
{
if (name.empty() || lastname.empty() ){
throw runtime_error("name or lastname wrong");
}
}
string Wizard::get_name() const {
return name;
}
string Wizard::get_lastname() const {
return lastname;
}
Vector<string> Wizard::get_subjects() const {
return subjects;
}
Haus Wizard::get_haus() const {
return haus;
}
Vector<Wizard> v;
Wizard harry("Harry", "Potter", {"magic", "music"}, Haus::Gryffindor);
Wizard ron("Ron", "Weasley", {"magic", "dancing"}, Haus::Gryffindor);
Wizard hermione("Hermione", "Granger", {"magic", "defence"}, Haus::Gryffindor);
Wizard laura("Laura", "Someone", {"running", "sports"}, Haus::Slytherin);
v.push_back(harry);
v.push_back(ron);
v.push_back(hermione);
v.push_back(laura);
Vector<Wizard> cpy;
// v is the original vector of all wizards
copy_if(v.begin(), v.end(), back_inserter(cpy), [](const Wizard& w) {
return(any_of(w.get_subjects().begin(), w.get_subjects().end(), [](const string& s) {
return s.find('p') != string::npos;
}));
});
Run Code Online (Sandbox Code Playgroud)
我最终得到退出代码11
您到处都在使用值,包括返回类型get_subjects()。
因此,下面的两个迭代器:
w.get_subjects().begin(), w.get_subjects().end()
Run Code Online (Sandbox Code Playgroud)
指载体的完全独立的,不相关的副本。
将迭代器与两个不相关的向量进行比较具有不确定的行为,这永远无法工作。
相反,您的访问器应按(const)引用返回。
对于初学者声明函数get_subjects像
const Vector<string> & Wizzard::get_subjects() const {
return subjects;
}
Run Code Online (Sandbox Code Playgroud)
否则在算法调用中
any_of(w.get_subjects().begin(), w.get_subjects().end(),...);
Run Code Online (Sandbox Code Playgroud)
begin并end返回不同范围(向量)的迭代器。