0

Inconsistance happens!

This piece of code goes well

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int> num_freq_map;
        for(const auto &ele : nums) {
            ++num_freq_map[ele];
        }
    }
};

but when I changed from unordered_map<int, int> num_freq_map; to unordered_map<int, int> num_freq_map(); , appending a pair of brackets.

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int> num_freq_map();
        for(const auto &ele : nums) {
            ++num_freq_map[ele];
        }
    }
};

I got an error: Line 6: lvalue required as increment operand

Why? What happend to my variable num_freq_map when initializing?

How should I learn this sort of things. Read the Standard Template Library source code, right?

Shihao Xu
  • 1,160
  • 2
  • 10
  • 23

2 Answers2

1

The

unordered_map<int, int> num_freq_map();

defines num_freq_map as a pointer to a function that does not take any parameters and returns unordered_map<int, int>. But don't worry, as

unordered_map<int, int> num_freq_map;

already calls the correct default constructor for you. If you want to make the call explicit to the reader, in C++11 you can use brace-initialization:

unordered_map<int, int> num_freq_map{};

majk
  • 827
  • 5
  • 12
1
unordered_map<int, int> num_freq_map();

is interpreted as following:

num_freq_map is a function without parameters which returns unordered_map<int, int> .

To learn this sort of things, read the C++ FAQ by Marshall Cline.

There is no such thing as "the STL source code". STL has many different implementations. I also doubt that reading a STL source code is useful, unless you have some very specific problem.

user31264
  • 6,557
  • 3
  • 26
  • 40