gpt4 book ai didi

c++ - 左值在使用 std::make_pair 时指定 const 对象

转载 作者:行者123 更新时间:2023-11-30 00:48:03 25 4
gpt4 key购买 nike

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 specified 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() 将尝试分配 到目标容器的现有元素。映射的键是常量,不能分配给它,这就是为什么您会遇到编译器错误的原因。但即使它们是,你也会在运行时在这里得到未定义的行为,因为目标容器是空的,并且 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);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

这是一个live example .

此外,在 MapInserter 的调用运算符中通过可变左值引用获取 value 字符串不是一个好主意:您不希望修改参数,所以你应该通过 const& 获取它,或者——我的建议——通过值获取它,然后将它移到返回的对中,如下所示:

std::pair<int, std::string> operator()(std::string value)
{
return {count++, std::move(value)};
}

由于 std::pair 的构造函数不是显式,您甚至不需要调用 std::make_pair()在这种情况下。

关于c++ - 左值在使用 std::make_pair 时指定 const 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33039281/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com