在map<string, int> [关闭]中使用find()函数时出错。

问题描述 投票:-1回答:1

下面是我改正后的代码。这个错误已经解决了。

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()运算符或"!="时发现错误,因为map的key为string,value为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)
      |     ^~~~~~~~
c++ c++11 hash stl unordered-map
1个回答
1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.