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

时间:2018-03-20 01:15:33

标签: c++ foreach c++17

我正在尝试从unordered_map中删除条目。 vector包含需要从unordered_map中删除的密钥。我正在尝试使用for_each来迭代向量并在erase上调用unordered_map

#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的擦除功能?

3 个答案:

答案 0 :(得分:3)

您错过了矢量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));
}

答案 1 :(得分:2)

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。

答案 2 :(得分:2)

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

ffmpeg -rtsp_flags listen -i rtsp://ownaddress/live.sdp -codec copy -map 0 -f segment -segment_time 900 -segment_atclocktime 1 out%03d.mp4