【问题标题】:How do I check in c++, if a vector of strings contains char 'p'如果字符串向量包含 char 'p',我如何检查 c++
【发布时间】:2019-09-12 11:37:23
【问题描述】:

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

2) 我有一个空向量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

【问题讨论】:

  • 最重要的是:韦斯莱!
  • w.get_subjects() 是按引用返回还是按值返回?提交minimal reproducible example
  • 没有看到Wizard的定义,无法准确回答。不过,我自己也是个巫师,我的占卜技巧告诉我get_subjects 按值返回一个容器。这是真的吗?
  • @kawillzocken 实际上首先比较两个迭代器是 UB。但我和 Angew 都没有解释是有原因的:(a) 我们不希望奖励发布不完整的问题,并且 (b) 我们不知道问题尚未解决,并且 (c) 答案不在 cmets 部分。
  • 它仍然不是minimal reproducible example。我们确实有足够的信息来回答这个问题(事实上,正如您所见,我们之前已经猜到了足够多),但您确实应该为您的问题提供minimal reproducible example

标签: c++ algorithm iterator copy c++-standard-library


【解决方案1】:

你在任何地方都使用,包括get_subjects()的返回类型。

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

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

指的是向量的完全独立的、不相关的副本

将迭代器与两个不相关的向量进行比较具有未定义的行为,这永远不会起作用。

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

【讨论】:

    【解决方案2】:

    首先声明函数get_subjectslike

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

    否则在此算法调用中

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

    beginend 返回不同范围(向量)的迭代器。

    【讨论】:

      猜你喜欢
      • 2012-02-11
      • 1970-01-01
      • 2011-12-19
      • 2014-05-25
      • 2012-02-11
      • 2015-12-29
      • 1970-01-01
      • 1970-01-01
      • 2017-09-23
      相关资源
      最近更新 更多