【问题标题】:Unordered_map iterator throwing errorUnordered_map 迭代器抛出错误
【发布时间】:2014-06-30 14:29:26
【问题描述】:

我有这个代码:

int solution(int K, const vector<int> &A) {
  int count=0,size,comp=0;
  unordered_map<long,long> map;

  size = A.size();
  if(size==0)
      return 0;

  for(int i=0;i<size;i++){
      map[A[i]] = i;
  }

  for(int i=0;i<size;i++){
      comp = K-A[i];
      unordered_map<long,long>::const_iterator index = map.find(comp); //error here
      if(index == map.end())
          continue;
      else{
          count++;
      }
  }
  cout << "final count: " << count << endl;
  return count;    
}

我收到无效操作数的错误,无法弄清楚我做错了什么。我试过切换迭代器,但它也可能是我的编译器。我正在使用它来编译:

clang++ -stdlib=libc++ -std=gnu++11 workingpairs.cpp

我的错误是:预期的';'在声明结束时 unordered_map::const_iterator index = map.find(comp);

间接需要指针操作数('int'无效) __table_.__insert_unique(*__first);

在函数模板特化的实例化中 'std::__1::unordered_map, std::__1::equal_to, std::__1::allocator >>::insert' 在这里请求

任何见解/帮助将不胜感激!

编辑:

我已经返回并修复了错误。

【问题讨论】:

  • 这将是使用auto index = map.find(comp);的好地方@
  • @Blastfurnace 而不是 const_interator?还是除此之外?
  • 我只会使用 auto 关键字。编译器已经知道表达式map.find(comp) 的类型,因此它将index 声明为该类型。那些繁琐的迭代器声明不再有错别字。

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


【解决方案1】:

您在下面的声明中错过了::

unordered_map<long,long>const_iterator

应该是:

unordered_map<long,long>::const_iterator

【讨论】:

  • 哇...谢谢!我还有另一个错误:在函数模板特化的实例化 'std::__1::unordered_map, std::__1::equal_to, std:: __1::allocator<:__1::pair long> > >::insert' 在这里请求 map.insert(A[i],i);。你知道那是什么吗?
  • 那是因为map.insert(A[i],i);,insert可以取pair,而不是直接取key/value
猜你喜欢
  • 2019-02-26
  • 2020-10-23
  • 1970-01-01
  • 2018-04-16
  • 1970-01-01
  • 1970-01-01
  • 2013-12-21
  • 2020-06-28
  • 2023-03-07
相关资源
最近更新 更多