Question

I have this code:

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;    
}

Can't seem to figure out why its complaining. The error look like this:

indirection requires pointer operand ('int' invalid) __table_.__insert_unique(*__first);

and

in instantiation of function template specialization 'std::__1::unordered_map, std::__1::equal_to, std::__1::allocator > >::insert' requested here map.insert(A[i],i);

Can anyone explain me whats going on?

Also using this to compile: clang++ -stdlib=libc++ -std=gnu++11 workingpairs.cpp

Was it helpful?

Solution

Your error on the map.insert(A[i],i) is because it wants you to insert the value_type of the container (a key/value pair). You are calling insert() with two parameters and the only matching overloads aren't the ones you want in this case.

You could instead say:

map[A[i]] = i;

or

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

or

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

OTHER TIPS

std::unordered_map::insert takes a pair:

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

The two-argument version takes an iterator, which you don't want here.

The two argument form of std::unordered_map::insert expects either a pair of iterators (to insert a range), or an iterator (that acts as a hint for where to insert the element) and an element.

You should use a std::pair to insert a value at with a particular key:

map.insert(std::make_pair(A[i],i));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top