简体   繁体   中英

How do I check in c++, if a vector of strings contains char 'p'

1 ) Let's say I have a vector v of Wizards (Wizard has a name, lastname, vector of strings which includes subjects that he/she attends, and a house where he/she belongs)

2) I have an empty vector cpy , where I want to copy those wizards, who attend a subject, that has a letter 'p' in it.

In my case, I would like to copy only Laura, because she attends sports, which is the only subject containing '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;
   }));
 });

I end up with exit code 11

You're using values everywhere, including in the return type of get_subjects() .

Because of that, the two iterators below:

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

refer to completely separate, unrelated copies of the vector.

Comparing iterators to two unrelated vectors has undefined behaviour and this can never work.

Instead, your accessors should return by (const) reference.

For starters declare the function get_subjects like

const Vector<string> & Wizzard::get_subjects() const {
  return subjects;
}

Otherwise in this call of the algorithm

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

begin and end return iterators of different ranges (vectors).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM