任何方法都可以在C++中比较数据结构中的许多方法



例如我有结构体

struct A {
std::string Id;
std::string Name;
Std::string Year;
};
I defined data type look like
std::map<A, int> MyMap;

我把一些项目放到我的地图上。我想找到满足以下条件之一的商品

- MyMap.find(it1); //that return iter if match Id
- MyMap.find(it2); //that return iter if match both Id and Name
- MyMap.find(it3); //that return iter if match all Id, Name,Year

我知道我必须在结构 A 中定义运算符

std::map只能有一个谓词来将键与值相关联。

您可以对标准算法使用不同的谓词来实现此目的std::find_if,但它执行的是线性搜索,而不是高效的地图查找。

如果需要多个谓词来有效地查找元素,则需要一个多索引容器。标准库没有这样的东西,但您可以通过在内部使用多个映射来实现一个,或者您可以使用 Boost 中的通用解决方案。

如果你的研究顺序仍然相同,你可以使用如下内容:

struct A {
std::string Id;
std::string Name;
Std::string Year;
};
bool operator < (const A& lhs, const A& rhs) {
return std::tie(lhs.Id, lhs.Name, lhs.Year) < std::tie(rhs.Id, rhs.Name, rhs.Year);
}

auto findById(const std::map<A, int>&m, const std::string& id)
{
auto it = m.lower_bound(A{id, "", ""});
if (it != m.end() && it->first.Id == id) {
return it;
}
return m.end();
}
auto findByIdName(const std::map<A, int>&m, const std::string& id, const std::string& name)
{
auto it = m.lower_bound(A{id, name, ""});
if (it != m.end() && it->first.Id == id && it->first.Name == name) {
return it;
}
return m.end();
}
auto findByIdNameYear(const std::map<A, int>&m,
const std::string& id,
const std::string& name,
const std::string& year)
{
return m.find(A{id, name, year});
}

如果您更喜欢使用std::vector,您可以使用这样的std::find_if

std::vector<A> as = /*...*/;
auto it = std::find_if(as.begin(), as.end(),
[&](const A& a){ return a.Id = id && a.Name = name;} );
if (it == as.end()) {
// Not found
} else {
// use *it as matching A.
}

最新更新