如何推断for_each的模板参数功能
How to deduce template parameter funct for for_each
我正在尝试从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。
相关文章:
- 对可变参数使用声明.如何选择正确的功能
- 如何在C++中调用默认模板功能参数?
- 如何从其他功能C++访问参数?
- 如何定义可变参数类模板的成员模板功能
- C++ std::enable_if - 第二个参数的功能
- 对于非常量指针类型的参数,未调用具有常量指针模板类型参数的功能
- 具有C++迭代器参数的多功能函数
- "(void) cast"与功能有什么区别 "__attributes__"来沉默未使用的参数警告?
- C 函数调用包装器包含类成员功能作为模板参数
- 非拖动功能模板参数包的合法使用
- 组件X86转换为ARM功能呼叫,其中有不同数量的参数为ARM
- 公共功能以私人课程为参数
- 如何部分专业化功能以用元组元素作为参数调用功能
- 如何存储指针以功能模板,该模板将可呼叫对象作为其参数之一
- std ::功能作为默认参数的功能
- C 功能模板指定第二个模板参数类型
- 传递多个参数的功能,该函数将类包含到其他函数
- 别名一个模板函数,该功能没有参数可更简洁
- 如何推断for_each的模板参数功能
- 用户界面-GUI和文本模式C++设计,以消除冗余(可选参数?功能过载?)