【问题标题】:failed to determine the correct return type无法确定正确的返回类型
【发布时间】:2025-12-02 16:35:01
【问题描述】:

我有以下简化的文件和类:

Stat.h:

class Stat
{
  auto getMinMaxValue(std::unordered_map< int, int >&);
};

Stat.cpp:

auto Stat::getMinMaxValue(std::unordered_map< int, int >&m)
{
  return std::minmax_element(m.begin(), m.end(), [](const pair<int, int>& p1, const pair<int, int>& p2) { return p1.second < p2.second; });
}

StatCount.h:

class StatCount : public Stat
{   
  void setWeight(std::vector<D> const&, const std::string);
};

StatCount.cpp:

void StatCount::setWeight(vector<D> const& ref, const string type)
{
    auto a = Stat::getMinMaxValue(m_value);
    cout << "MIN: " << a.first->second << endl;
    cout << "MAX: " << a.second->second << endl;
}

由于我在基类 Stat 中声明了函数“getMinMaxValue”,如果我使用自动返回类型,我得到了一个错误:

function 'getMinMaxValue' with deduced return type cannot be used before it is defined

但我未能删除自动返回类型并找到正确的语法来指定方法“getMinMaxValue”的返回类型

如果我阅读了关于 cppreference 的文档,我发现它一定是一对迭代器,但如何?

【问题讨论】:

  • 这可能对你有帮助*.com/questions/18559452/…
  • 可能与*.com/q/40694607/10077重复
  • @FredLarson:它不是重复的,我没有搜索保留“自动”的解决方案,我想找到方法 minmax_element 的返回类型的正确声明
  • @BoPersson,我认为您没有完全阅读我的问题,我不明白您为什么说它是重复的,我没有搜索保留“自动”的解决方案,我想找到正确的声明方法 minmax_element 的返回类型...
  • 好的,我触发了错误消息,没有注意到您继续研究。对不起。重新打开。

标签: c++ class inheritance auto


【解决方案1】:

我自己回复一下,看来我找到了解决办法:

Stat.h:

std::pair<std::unordered_map< int, int >::iterator, std::unordered_map< int, int >::iterator> getMinMaxValue(std::unordered_map< int, int >&); 

【讨论】: