【问题标题】:Why does ranged for loop converts value to ref implicitly?为什么 ranged for 循环将 value 隐式转换为 ref?
【发布时间】: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&amp;

error: no matching function for call to 'std::vector<std::__cxx11::basic_string<char> >::push_back(const char&)'

Demo

【问题讨论】:

  • R.emplace_back(1, c);
  • 这段代码还有一些其他问题。首先,字符'1' 有一个不是1 的整数值。你需要解决这个问题;也许你想映射{'1', "abc"} 或者你想说d2c_map.at(digits[0] - '0')。其次,基于范围的 for 循环会在您遍历地图时复制地图的每个元素,但您不需要副本。而不是for (const auto c : ...),写for (const auto&amp; c : ...)
  • @Justin 感谢您指出错误。但是问题仍然存在“为什么 'c' 是 const char &??? 这是我的问题。
  • auto 不会推断为引用类型,因此const auto c 在您的示例中不会推断为const char &amp;c,而是推断为const char cfor 循环将使用const auto c = *iterator;,其中iteratorstd::string::iterator,它在取消引用时返回char&amp;,但这不会使c 推断为char&amp;,而只是char。您的示例中只有两个 push_back() 可用:R.push_back(const string&amp;)R.push_back(string&amp;&amp;),两者都不能使用单个 char 作为输入来调用,因此会出现错误。额外的&amp; 来自哪里,谁知道呢,编译器细节。
  • 您显然对内部结构感兴趣:您是否真的检查过c 的类型,例如使用类型特征和静态断言?我相信编译器只是输出“错误”错误消息,因为他试图首先(或最后)将c 作为 const 左值引用传递。这并不重要,因为 oerload 解析失败,因此打印的消息是模棱两可的。

标签: c++


【解决方案1】:

如何将字符串的每个字符推入字符串向量中?

此行正在尝试将char 添加到vector&lt;string&gt;

R.push_back(c);

如果你想添加一个由char构造的字符串,你可以这样做:

R.push_back({c});

【讨论】:

  • 或改为vector
猜你喜欢
  • 2023-02-05
  • 2012-03-05
  • 2012-10-13
  • 2015-12-03
  • 2021-03-12
  • 2018-02-22
  • 2017-04-26
  • 2018-08-19
  • 1970-01-01
相关资源
最近更新 更多