user3178285
user3178285

Reputation: 151

error: base operand of '->' has non-pointer type 'std::pair<int, int>'

This is my horrible attempt at a function that returns the mode (most common element) of an int array.

The error mentioned in the title is commented out in the code.

My understanding was that a map was made up of pairs, so I don't what the problem is.

#include <iostream>
#include <map>

int mode(int* arrPtr, int size) { 
   assert (size > 0);
   std::map<int,int> M; 
   for (int k = 0; k < size; ++k) 
      M[*(arrPtr + k)]++;
   std::pair<int,int> maxpair(M.begin()->first, M.begin()->second);
   for (std::map<int,int>::iterator it = M.begin() + 1; it < M.end(); ++it) 
        if (it->second > maxpair->second) maxpair = *it; // ERROR HERE
   return maxpair->second;
} 


int main() { 

    int myArray[] = {1, 4, 5, 59, 1, -1, 4, 9, 1, 1, 9, -40};

    return 0;

} 

Also, there's gotta be a better way to do this. How would a C++ guru do it?

Upvotes: 2

Views: 6347

Answers (2)

CrazyCasta
CrazyCasta

Reputation: 28302

The iterator acts basically like a pointer which is why you use -> on it. Your std::pair however is a value, so you should use . instead of ->.

Try:

if (it->second > maxpair.second) maxpair = *it;

P.S. The maxpair = *it assignment can be slow because of the overhead involved in copying an object. If you're going for speed it would probably be better to store the value and count as simple integers instead of as a pair object.

P.P.S. If you're trying to find the mode, don't you actually want the value that has the largest count, rather then the count?

Upvotes: 2

Shoe
Shoe

Reputation: 76240

Replace:

if (it->second > maxpair->second)

with:

if (it->second > maxpair.second)

If you take a look at your program, maxpair is of type std::pair<int, int> which does not have the operator-> overloaded.

What you are trying to access, instead, is the member object second, therefore you should use maxpair.second.

Upvotes: 4

Related Questions