如何推断for_each的模板参数功能

How to deduce template parameter funct for for_each

本文关键字:参数 功能 each 何推断 for      更新时间:2023-10-16

我正在尝试从unordered_map中删除条目。vector保存需要从unordered_map中删除的密钥。我正在尝试使用for_each遍历向量并在unordered_map上调用erase

#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);
}

我收到错误:

note: couldn't deduce template parameter '_Funct' std::for_each(keys_to_delete.begin(), keys_to_delete.end(), &sample_map.erase);

如何正确绑定sample_map的擦除功能?

您缺少向量key_to_delete的模板参数。

无论如何,如果您手动编写循环遍历每个键并调用函数 erase 的代码,则此问题可能会更简单。

但是,如果您想使用 std::for_each,则可以将其绑定到要调用的正确函数。在这种情况下,必须static_cast才能获得正确的功能,因为擦除具有多个重载。

#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));
}

做你想做的方法是像这样使用lambda:

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

>std::for_each不太适合那里。使用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);
}

使用for_each代码将很难理解。 std::unordered_map::erase具有重载,因此不能直接使用,则必须创建一个函数对象来调用合适的重载方法,或使用 lambda。