当使用std::make_pair时,L-value指定const对象
l-value specifies const object when using std::make_pair
struct MapInserter
{
private:
int count;
public:
explicit MapInserter()
: count(0)
{
}
std::pair<int, std::string> operator()(std::string& value)
{
return std::make_pair(count++, value);
}
};
vector<std::string> words = { "one", "two", "three","four","five" };
std::map<int, std::string> map;
MapInserter inserter;
transform(words.begin(), words.end(), map.begin(), inserter);
for (auto it = map.begin(), end = map.end(); it != end; ++it)
cout << it->first << " : " << it->second << endl;
return 0;
就是代码。VS返回关于l-value specifies const object
的编译错误。
单击错误将移动到名为utility
的文件中的以下代码template<class _Other1,
class _Other2>
_Myt& operator=(pair<_Other1, _Other2>&& _Right)
{ // assign from moved compatible pair
first = _STD forward<_Other1>(_Right.first);
second = _STD forward<_Other2>(_Right.second);
return (*this);
}
一开始,我让operator()
取const std::string&
,所以我去掉了const,因为它显然是在谈论make_pair函数。但它仍然没有消失。有人能告诉我这个错误是怎么回事吗?
问题是std::transform()
将尝试将分配给目标容器的现有元素。map的键是常量,不能赋值,这就是为什么会出现编译错误。但是,即使它们是,在运行时也会得到未定义的行为,因为目标容器是空的,并且std::transform()
会期望它包含与输入范围一样多的元素。
应该使用std::inserter()
创建插入迭代器,如下所示:
vector<std::string> words = { "one", "two", "three","four","five" };
std::map<int, std::string> map;
MapInserter inserter;
transform(words.begin(), words.end(), std::inserter(map, map.begin()), inserter);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
下面是一个的实例。
此外,在MapInserter
的调用操作符中通过可变左值引用获取value
字符串并不是一个好主意:您不希望修改参数,因此您应该通过const&
获取它,或者-我的建议-通过值获取它,然后将其移动到返回对中,如下所示:
std::pair<int, std::string> operator()(std::string value)
{
return {count++, std::move(value)};
}
由于std::pair
的构造函数不是explicit
,因此在本例中甚至不需要调用std::make_pair()
。
相关文章:
- C++,系统无法执行指定的程序
- 将值指定给向量(2D)的向量中的某个位置
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 在派生函数中指定void*参数
- 瓦尔格林德:数学函数"Conditional jump or move depends on uninitialised value(s)"
- 在循环C++中指定字符串之后,不会打印该字符串
- 如何指定我希望我的LIB链接到的DLL文件?-Visual Studio 2019
- C++在变量给定的指定时间内关闭电脑
- 如何在ArangoDb AQL查询中指定数据库
- 带有指定长度字符* 参数的 std::regex_search 在 VS2017 中不起作用?
- 在C++中传递给函数时,为什么要指定数组大小作为参数
- 如何创建长度由常量参数指定的数组
- 如何计算具有指定类型的表达式的相对精度和绝对精度
- 为什么static_assert错误:即使我传递常量"expression must have a constant value"?
- 从具有默认值的部分指定模板类继承时发生SWIG错误,具有不带默认值的正向声明
- 将所有模板类型传递给运算符,而不指定所有类型
- 如何从通用函数符号计算或指定COFF符号表的"value"?
- 当使用std::make_pair时,L-value指定const对象
- L-value在使用std::map时指定const对象