【发布时间】:2014-03-24 03:28:15
【问题描述】:
我在一个面试问题上遇到了这个问题。我想看看 StackOverflow 是如何做到的。
Bjarne Stroustrop 会如何看待我的方式?这有点罗嗦,但不幸的是,我不知道如何使它变得更好。我知道你们会嘲笑我的愚蠢。
template <class T>
T mode(T* arr, size_t n)
// If there's a tie, return an arbitrary element tied for 1st
// If the array size is 0, throw an error
{
if (n == 0)
{
throw("Mode of array of size 0 is undefined, bro.");
}
else if (n == 1)
{
return arr[0];
}
else
{
std::pair<T, int> highest(arr[0], 1);
std::map<T, int> S;
S.insert(highest);
for (T* thisPtr(arr + 1), lastPtr(arr+n); thisPtr != lastPtr; ++thisPtr)
{
if (S.count(*thisPtr) == 0)
{
S.insert(std::pair<T, int> (*thisPtr, 1);
}
else
{
++S[*thisPtr];
if (S[*thisPtr] > highest.second)
{
highest = std::pair<T, int> (*thisPtr, S[*thisPtr]);
}
}
}
}
}
【问题讨论】:
-
您可以将
for循环的内容替换为if ( ++S[*thisPtr] > highest.second ) highest = ...
标签: c++