C++ 如何推导每个_的模板参数funct

C++ 如何推导每个_的模板参数funct,c++,foreach,c++17,C++,Foreach,C++17,我正在尝试从无序映射中删除条目。一个向量包含需要从无序映射中删除的键。我正在尝试使用for_each遍历向量,并在无序地图上调用擦除 #include <unordered_map> #include <vector> #include<algorithm> int main() { std::unordered_map<int, bool> sample_map = { {0, false}, {1, true}, {2,false}}

我正在尝试从无序映射中删除条目。一个
向量
包含需要从
无序映射
中删除的键。我正在尝试使用
for_each
遍历向量,并在
无序地图上调用
擦除

#include <unordered_map>
#include <vector>
#include<algorithm>

int main()
{
    std::unordered_map<int, bool> sample_map = { {0, false}, {1, true}, {2,false}};
    std::vector keys_to_delete = { 0, 2};
    std::for_each(keys_to_delete.begin(), keys_to_delete.end(), &sample_map.erase);
}

如何正确绑定示例地图的擦除功能

std::for_每个
在那里都不太合适。对于
,代码将更干净

#include <unordered_map>
#include <vector>
#include<algorithm>

int main()
{
    std::unordered_map<int, bool> sample_map = { {0, false}, {1, true}, {2,false}};
    std::vector<int> keys_to_delete = { 0, 2};
    for (auto key : keys_to_delete)
        sample_map.erase(key);
}
#包括
#包括
#包括
int main()
{
无序映射样本映射={{0,false},{1,true},{2,false};
std::向量键_to _delete={0,2};
用于(自动关键点:关键点到删除)
样本映射擦除(键);
}

使用
for_每个
时,代码将很难理解
std::unordered_map::erase具有重载,因此无法直接使用它,您必须创建调用适当重载方法的函数对象,或使用lambda。

实现此目的的方法是使用lambda,如下所示:

std::for_each(keys_to_delete.begin(), keys_to_delete.end(), [&](const auto& key) { sample_map.erase(key); });

您缺少向量键要删除的模板参数

无论如何,如果手动编写循环通过每个键并调用函数erase的代码,这个问题可能会更简单

但是,如果您想使用std::for_each,那么可以将其绑定到要调用的正确函数。在这种情况下,必须
static\u cast
才能获得正确的函数,因为erase有多个重载

#include <unordered_map>
#include <vector>
#include<algorithm>
#include <functional>
#include <iostream>

int main()
{
    std::unordered_map<int, bool> sample_map = { { 0, false },{ 1, true },{ 2,false } };
    std::vector<int> keys_to_delete = { 0, 2 };
    using type = std::unordered_map<int, bool>;
    std::for_each(keys_to_delete.begin(), keys_to_delete.end(), std::bind(static_cast<std::size_t(type::*)(const int&)>(&type::erase), &sample_map, std::placeholders::_1));
}
#包括
#包括
#包括
#包括
#包括
int main()
{
无序映射样本映射={{0,false},{1,true},{2,false};
std::向量键_to _delete={0,2};
使用type=std::无序映射;
std::for_each(键到_delete.begin()、键到_delete.end()、std::bind(静态_cast(&type::erase)、&sample_映射、std::占位符::_1));
}

为什么每个都不合适?我在答案中添加了更多信息。看看其他答案,比较哪一个更清楚。
#include <unordered_map>
#include <vector>
#include<algorithm>
#include <functional>
#include <iostream>

int main()
{
    std::unordered_map<int, bool> sample_map = { { 0, false },{ 1, true },{ 2,false } };
    std::vector<int> keys_to_delete = { 0, 2 };
    using type = std::unordered_map<int, bool>;
    std::for_each(keys_to_delete.begin(), keys_to_delete.end(), std::bind(static_cast<std::size_t(type::*)(const int&)>(&type::erase), &sample_map, std::placeholders::_1));
}