【问题标题】:"auto" becoming the wrong type? [closed]“自动”成为错误的类型? [关闭]
【发布时间】:2014-08-27 18:11:38
【问题描述】:

基本上,我的代码如下所示:

vector<int> myVec; // defined elsewhere, and has stuff in it.
auto it = lower_bound(myVec.front(), myVec.back(), key);
myVec.insert(it, key); // <- compiler error!

编译器错误是error: no matching function for call to 'std::vector&lt;int&gt;::insert(int&amp;, int&amp;)',这是意外的,因为它应该是“something_something_iterator”。

为什么要这样做?

我在 Windows 7 上使用 MinGW-W64 进行编译。

【问题讨论】:

  • 完整的编译器错误是什么?为什么你认为编译器认为itint&amp;
  • std::vector::front/back 返回一个引用或 const_reference.. 你可能想使用 std::vector::begin/end
  • 您的编译器是否配置为使用 C++11 模式(-std=c++11,我想,在命令行上)?否则,它可能会将auto 解释为存储类说明符,并添加隐含的int
  • 完整的编译器错误是:error: no matching function for call to 'std::vector&lt;int&gt;::insert(int&amp;, int&amp;)'
  • 它赋予itmyVec.front() 相同的类型,即int。这样做是因为这是指定 lower_bound 的方式。它推导出第一个参数的类型,并将其作为返回类型。

标签: c++ c++11 vector auto


【解决方案1】:

应该是

auto it = std::lower_bound(myVec.begin(), myVec.end(), key);

【讨论】:

  • 一开始我完全错过了问题和答案中的begin/end 部分:/
  • 成功了,谢谢!
猜你喜欢
  • 2015-07-15
  • 2013-05-23
  • 2022-01-21
  • 2012-11-06
  • 2012-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-30
相关资源
最近更新 更多