为什么不能为类型的函数参数设置默认值<map>?
Why can't I set a default value for a function parameter of <map> type?
下面是我的示例程序,它不会编译。我想创建一个函数,该函数将映射作为可能的参数,但如果没有提供映射,则提供默认的空映射。很直接,只是不确定为什么它不起作用。
#include <map>
#include <iostream>
using std::cout; using std::endl; using std::map;
int func(map<int, int>& = map<int, int>());
int main() {
map<int, int> m;
m[2] = 4;
cout << "func() = " << func() << endl; // "func() = 0"
cout << "func(m) = " << func(m) << endl; // "func(m) = 1"
}
int func(map<int, int>& m) { return m.size(); }
我得到的编译器错误是:
test.cc:6:42: error: default argument for 'std::map<int, int>& <anonymous>' has type 'std::map<int, int>'
请解释一下,这对我来说没有意义。
您可以使用常量引用绑定临时对象。因此,该函数可能被声明为
int func( const map<int, int>& = map<int, int>());
相关文章:
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 使用一个考虑到std::map中键值的滚动或换行的键
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 允许从 std::map 的密钥窃取资源?
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- 有没有办法对std::unordered_set、std::unrdered_map、std::set、std::map
- 将重物插入std::map
- 使用通用值初始化 std::map,不重复
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- C++:当所有条目都保证是唯一时,替代 std::map
- 使用模板化的键类型定义 std::map,该键类型基于作为参数接收的函数
- 如果 KEY 是 std::list 或 std::vector 而不是值,那么 std::map 的默认行为是什么?
- 使用字符数组作为 Map 中的键
- 为什么STD :: MAP需要操作员&lt;以及我如何写一个
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- 使用map<>来自STL