【问题标题】:Error in using find() function in map<string, int> [closed]在 map<string, int> 中使用 find() 函数时出错 [关闭]
【发布时间】:2020-08-21 03:57:58
【问题描述】:

以下是更正后的我的代码。 错误已解决。

unordered_map<string, int> map;
int m = B.size();
int n=A.size();
for(int i=0; i<m; i++) map[B[i]]++;
for(int end=0; end<n; end=end+1)
{

  if(map.find(A.substr(end, 3))!=map.end() && map[A.substr(end, 3)]>0)
  {     
             something here;
  }

}

我在使用 find() 运算符或“!=”作为键为字符串、值为 int 的映射时发现错误。

*solution.cpp: In member function 'std::vector<int> Solution::findSubstring(std::string, const std::vector<std::__cxx11::basic_string<char> >&)':
solution.cpp:16:36: error: no match for 'operator!=' (operand types are 'std::unordered_map<std::__cxx11::basic_string<char>, int>::iterator' {aka 'std::__detail::_Node_iterator<std::pair<const std::__cxx11::basic_string<char>, int>, false, true>'} and 'bool')
   20 |       if(map.find(A.substr(end, 3))!=A.empty() && map[A.substr(end, 3)]>0)
      |          ~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~
      |                  |                          |
      |                  |                          bool
      |                  std::unordered_map<std::__cxx11::basic_string<char>, int>::iterator {aka std::__detail::_Node_iterator<std::pair<const std::__cxx11::basic_string<char>, int>, false, true>}
In file included from /usr/include/c++/9.2.0/iosfwd:40,
                 from /usr/include/c++/9.2.0/ios:38,
                 from /usr/include/c++/9.2.0/ostream:38,
                 from /usr/include/c++/9.2.0/iostream:39,
                 from solution.h:7,
                 from solution.cpp:-3:
/usr/include/c++/9.2.0/bits/postypes.h:227:5: note: candidate: 'template<class _StateT> bool std::operator!=(const std::fpos<_StateT>&, const std::fpos<_StateT>&)'
  227 |     operator!=(const fpos<_StateT>& __lhs, const fpos<_StateT>& __rhs)
      |     ^~~~~~~~

【问题讨论】:

  • map.find(A.substr(end, 3))!=A.empty() -> map.find(A.substr(end, 3))!=map.end()
  • 您希望map.find(...) != A.empty() 做什么?不要将using namespace std; 与名为map 的变量结合使用
  • 请在问题中以文本形式包含错误消息
  • 错误消息告诉您,您尝试将迭代器与没有意义的 bool 进行比较....
  • 我认为 empty() 而不是 end() 是一个错字(如上面的评论中所述)。投票结束。

标签: c++ c++11 hash stl unordered-map


【解决方案1】:

问题在于find 将返回满足条件的迭代器或结束迭代器。所以你可以使用 map.end() 而不是 A.empty()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-07
    • 1970-01-01
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    • 1970-01-01
    • 2013-01-28
    • 1970-01-01
    相关资源
    最近更新 更多