2

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

3 Answers 3

4

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);
Sign up to request clarification or add additional context in comments.

Comments

-1

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.

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.