mis*_*ter 6 c++ iterator vector
我有一个函数,如果找到一个对象,它返回一个迭代器.
现在我有一个问题.我如何解决通知调用此函数的对象未找到该对象的问题?
vector<obj>::iterator Find(int id, int test)
{
vector<obj>::iterator it;
aClass class;
for(it = class.vecCont.begin(); it != class.vecCont.end(); ++it)
{
if(found object) //currently in psuedo code
return it;
}
return ???? // <<< if not found what to insert here?
}
Run Code Online (Sandbox Code Playgroud)
我需要改变我的数据结构吗?
提前致谢!:)
返回vector::end(),抛出异常,或返回除普通迭代器之外的其他内容
更好的是,不要实现自己的Find功能.这就是<algorithm>图书馆的用途.基于你的psudocode,你可以使用std::find或std::find_if. find_if在平等并不一定意味着的情况下特别有用operator==.在这些情况下,您可以使用[C++ 11] lambda,或者如果您无法使用C++ 11,那么可以使用仿函数类.
由于函子是最低的共同点,我将从那开始:
#include <cstdlib>
#include <string>
#include <algorithm>
#include <vector>
#include <functional>
using namespace std;
class Person
{
public:
Person(const string& name, unsigned age) : name_(name), age_(age) {};
string name_;
unsigned age_;
};
class match_name : public unary_function <bool, string>
{
public:
match_name(const string& rhs) : name_(rhs) {};
bool operator()(const Person& rhs) const
{
return rhs.name_ == name_;
}
private:
string name_;
};
#include <iostream>
int main()
{
vector<Person> people;
people.push_back(Person("Hellen Keller", 99));
people.push_back(Person("John Doe", 42));
/** C++03 **/
vector<Person>::const_iterator found_person = std::find_if( people.begin(), people.end(), match_name("John Doe"));
if( found_person == people.end() )
cout << "Not FOund";
else
cout << found_person->name_ << " is " << found_person->age_;
}
Run Code Online (Sandbox Code Playgroud)
found_person现在指向名字为"John Doe"的人,或指向people_.end()是否找不到该人.
C++ 11 lambda是一种新的语言语法,它使得这个声明/定义仿函数和使用的过程在许多情况下更简单一些.它是这样完成的:
string target = "John Doe";
vector<Person>::const_iterator found_person = std::find_if(people.begin(), people.end(), [&target](const Person& test) { return it->name_ == target; });
Run Code Online (Sandbox Code Playgroud)
不要将迭代器返回到隐藏容器。仅返回您想要的内容,即访问对象(如果存在)的方法。在此示例中,我通过指针将对象存储在容器中。如果您的对象只是暂时存在,那么新建一个并复制该对象!
class AClass;
//...some time later
std::vector<AClass*> vecCont; //notice, store pointers in this example!
//..some time later
AClass * findAClass(int id, int test)
{
vector<AClass*>::iterator it;
for(it = class.vecCont.begin(); it != class.vecCont.end(); ++it)
{
if(found object) //currently in psuedo code
return it;
}
return NULL;
}
//later still..
AClass *foundVal = findAClass(1, 0);
if(foundVal)
{
//we found it!
}
else
{
//we didn't find it
}
Run Code Online (Sandbox Code Playgroud)
编辑:明智的做法是为您的班级编写一个比较器,并使用 std 算法排序并为您找到它们。不过,做你想做的事吧。
| 归档时间: |
|
| 查看次数: |
7882 次 |
| 最近记录: |