gpt4 book ai didi

c++ - 如果字符串 vector 包含 char 'p',我如何检查 C++

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:10:33 24 4
gpt4 key购买 nike

1 ) 假设我有一个巫师 vector v (巫师有名字、姓氏、字符串 vector ,其中包括他/她参加的科目,以及他/她所属的房子)

2) 我有一个空 vector cpy,我想在其中复制那些参加主题的巫师,其中有一个字母“p”。

就我而言,我只想复制 Laura,因为她参加体育运动,这是唯一包含“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;
}));
});

我以退出代码 11 结束

最佳答案

您到处都在使用,包括在 get_subjects() 的返回类型中。

因此,下面的两个迭代器:

w.get_subjects().begin(), w.get_subjects().end()

指的是载体的完全独立的、不相关的拷贝

将迭代器与两个不相关的 vector 进行比较具有未定义的行为,这永远行不通。

相反,您的访问器应该通过(常量)引用返回。

关于c++ - 如果字符串 vector 包含 char 'p',我如何检查 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57905890/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com