【问题标题】:Unordered_map has indrection requires pointer operandUnordered_map 哈希间接需要指针操作数
【发布时间】:2014-06-30 14:52:03
【问题描述】:

我有这个代码:

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.insert(A[i],i); //error here
  }

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

似乎无法弄清楚它为什么抱怨。错误如下所示:

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

在函数模板特化的实例化中 'std::__1::unordered_map, std::__1::equal_to, std::__1::allocator >>::insert' 在这里请求 map.insert(A[i],i);

谁能解释一下这是怎么回事?

同样用这个编译:clang++ -stdlib=libc++ -std=gnu++11 workingpairs.cpp

【问题讨论】:

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


    【解决方案1】:

    std::unordered_map::insert 需要一对:

    map.insert ( std::pair<int,int>(A[i],i) );
    

    两个参数的版本需要一个迭代器,在这里你不需要它。

    【讨论】:

      【解决方案2】:

      std::unordered_map::insert 的两个参数形式需要一对迭代器(插入一个范围)或一个迭代器(作为插入元素的提示)和一个元素。

      您应该使用std::pair 插入一个带有特定键的值:

      map.insert(std::make_pair(A[i],i));
      

      【讨论】:

        【解决方案3】:

        您在map.insert(A[i],i) 上的错误是因为它希望您插入容器的value_typekey/value 对)。您正在使用两个参数调用 insert(),并且在这种情况下,唯一匹配的重载不是您想要的。

        你可以说:

        map[A[i]] = i;
        

        map.insert(std::make_pair(A[i], i));
        

        map.emplace(A[i], i);
        

        【讨论】:

          猜你喜欢
          • 2014-10-31
          • 2015-06-02
          • 1970-01-01
          • 1970-01-01
          • 2011-11-05
          • 1970-01-01
          • 2020-07-23
          • 1970-01-01
          • 2014-05-22
          相关资源
          最近更新 更多