今天在写 leetcode 的时候, 出现了这么一个报错:
源代码
class Solution {
public:
static unordered_map<int, int> m;
static bool compare(int a, int b) {
if (m[a] < m[b]) {
return true;
} else if (m[a] == m[b]) {
return a > b;
}
return false;
}
vector<int> frequencySort(vector<int> &nums) {
m.clear();
for (auto i : nums) {
m.find(i) == m.end() ? m[i] = 1 : ++m[i];
}
sort(nums.begin(), nums.end(), compare);
return nums;
}
};
报错
执行结果:
编译出错
ld.lld: error: undefined symbol: Solution::m
>>> referenced by prog_joined.cpp
>>> /tmp/prog_joined-c167f6.o:(Solution::frequencySort(std::vector<int, std::allocator<int> >&))
>>> referenced by prog_joined.cpp
>>> /tmp/prog_joined-c167f6.o:(Solution::frequencySort(std::vector<int, std::allocator<int> >&))
>>> referenced by prog_joined.cpp
>>> /tmp/prog_joined-c167f6.o:(Solution::frequencySort(std::vector<int, std::allocator<int> >&))
>>> referenced 7 more times
clang-11: error: linker command failed with exit code 1 (use -v to see invocation)
原因分析
我感觉写的没毛病啊, 后来发现, 类的静态成员变量需要在类外面初始化:
unordered_map<int, int> Solution::m;
这样就行了
文章评论