【发布时间】:2020-10-15 21:31:13
【问题描述】:
我很困惑为什么 range-for 在我的示例中使用 ref?
#include <vector>
#include <unordered_map>
using namespace std;
int main()
{
const unordered_map<char, string> d2c_map= { {'1', "abc"} };
const string digits{"1"};
vector<string> R;
for(const auto c : d2c_map.at(digits[0])) {
R.push_back(c); // <-------------------------???
}
return 0;
}
错误表示c的类型是const char&:
error: no matching function for call to 'std::vector<std::__cxx11::basic_string<char> >::push_back(const char&)'
【问题讨论】:
-
R.emplace_back(1, c); -
这段代码还有一些其他问题。首先,字符
'1'有一个不是1的整数值。你需要解决这个问题;也许你想映射{'1', "abc"}或者你想说d2c_map.at(digits[0] - '0')。其次,基于范围的 for 循环会在您遍历地图时复制地图的每个元素,但您不需要副本。而不是for (const auto c : ...),写for (const auto& c : ...) -
@Justin 感谢您指出错误。但是问题仍然存在“为什么 'c' 是 const char &??? 这是我的问题。
-
auto不会推断为引用类型,因此const auto c在您的示例中不会推断为const char &c,而是推断为const char c。for循环将使用const auto c = *iterator;,其中iterator是std::string::iterator,它在取消引用时返回char&,但这不会使c推断为char&,而只是char。您的示例中只有两个push_back()可用:R.push_back(const string&)和R.push_back(string&&),两者都不能使用单个char作为输入来调用,因此会出现错误。额外的&来自哪里,谁知道呢,编译器细节。 -
您显然对内部结构感兴趣:您是否真的检查过
c的类型,例如使用类型特征和静态断言?我相信编译器只是输出“错误”错误消息,因为他试图首先(或最后)将c作为 const 左值引用传递。这并不重要,因为 oerload 解析失败,因此打印的消息是模棱两可的。
标签: c++