加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – std :: find成员查找对象

发布时间:2020-12-16 09:44:44 所属栏目:百科 来源:网络整理
导读:脚本 我在使用STL的时候碰到了一个速度突发,看似正常的情况,在这里简化: class Person { string Name; int Age;};vectorPerson people;AddPeople(people);string s("Bob");find(people.begin(),people.end(),s); 问题 不幸的是,想要比较整个班级. 题 是否有
脚本

我在使用STL的时候碰到了一个速度突发,看似正常的情况,在这里简化:

class Person {
  string Name;
  int    Age;
};

vector<Person> people;
AddPeople(people);

string s("Bob");
find(people.begin(),people.end(),s);

问题
不幸的是,想要比较整个班级.


是否有更好或更合适的方式来实现“STL方式”?建议的问题没有帮助,但我设法找到了几个related questions,但没有直接的解决方案.

变通/测试

有一些潜在的解决方法:

>完全放弃找到(混乱,但可以重构):

bool bBob = false;
for (UINT i = 0; i < people.size(); i++) {
  if (people[i].Name == s)
  bBob = true;
  break;
}

>提供转换运算符(隐式转换不起作用;显式不能在find中使用):

class Person {
  string Name;
  int    Age;
  operator string() {return Name;}
};

Person b ("Bob",99);
string s ("Bob");
       b  == s;     //doesn’t work
string(b) == s;     //works,but no good for find()

>定义一个独立的相等运算符(简单,有效,但全局公开):

BOOL operator==(Person l,string r) {
  return l.Name == r;
}

>定义成员相等运算符(使比较顺序依赖;对象必须是第一个):

class Person {
  string Name;
  int    Age;
  bool operator==(string s) {return Name == s;}
};

Person b ("Bob",99);
string s ("Bob");
b==s;               //works
s==b;               //doesn’t work,but not a problem for find()

看起来#4是最好的候选人,但似乎没有理想或感觉“STL”,有些人有问题.

解决方法

Is there a better or more appropriate way to do this the “STL way”?

你可以使用std::find_if(由C 11 lambdas驱动):

std::string name = "Bob";
// ...
std::find_if(std::begin(people),std::end(people),[&] (Person const& p) { return p.Name == name; }

请注意,称其为“STL方式”是不合适的.这是C标准库,而不是STL(“标准模板库”). STL是C标准库的容器和算法库的强大灵感,但两者并不相同.有关详细信息,请参见this Q&A on StackOverflow.

编辑:

由于您使用的是不支持lambda的编译器,因此您可以定义自己的仿函数谓词:

struct person_has_name
{
    person_has_name(std::string const& n) : name(n) { }  
    bool operator () (Person const& p) { return p.Name == name; }
private:
    std::string name;
};

并以这种方式将它与std :: find_if一起使用:

std::string name = "Bob";
// ...
std::find_if(people.begin(),person_has_name(name));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读