【问题标题】:Transform range-based for normal loop基于变换范围的正常循环
【发布时间】:2020-02-10 09:42:16
【问题描述】:
for (const auto & rRec : m_map_handshake)
    {
        if (rRec.second->GetHostName() == inet_ntoa(c_rSockAddr.sin_addr))
        {
                return true;
        }
    }

我有这样的代码,但是基于范围的 for 循环在旧的 gcc 编译器上不起作用。

有什么办法可以解决这个问题吗?我不是 C++ 专家

【问题讨论】:

  • 我会建议std::find_if,但没有 lambda,就不太好...
  • 请向我们展示一个不适合您的最小可重现示例。
  • 实际上,基于范围的 for 循环在底层使用迭代器。 solution provided by @Wander3r 是您正在寻找的 ;)

标签: c++ c++03


【解决方案1】:

您可以使用普通的for 循环。看起来是std::map。使用迭代器遍历元素并匹配条件。

for(const <map-type>::iterator it = m_map_handshake.begin(); it != m_map_handshake.end();++it){
        if (it->second->GetHostName() == inet_ntoa(c_rSockAddr.sin_addr))
        {
                return true;
        }
}

这里&lt;map-type&gt; 将是m_map_handshake 的类型。

【讨论】:

  • 好的,但是为什么范围循环不起作用?这有什么不同?
  • @mfnx range based for loop 从 C++ 11 开始出现,正如 OP 提到的旧 gcc 编译器,它可能不支持 C++ 11。
  • 哦,好吧,对不起,打扰了
猜你喜欢
  • 2016-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-23
相关资源
最近更新 更多