|
One can make the case a flat data structure should be declared with all elements already sorted so run-time checks for elements being contained within the list can be optimized. C++20 has isSorted as a constexpr which therefore can be used with static_asserts possibly failing compilation. This is a betterment to writing a comment above the data structure and hoping for the best as non-sorted lists with silently degrade performance or require extra run-time checks or complicated constructs. Here is a proposal for a possible polyfill:
template <typename It>
|
constexpr bool constexprIsSorted(It b, It e) {
|
#if __cpp_lib_constexpr_algorithms >= 201806L
|
return std::is_sorted(b, e);
|
#else
|
if (b == e)
|
return true;
|
auto p = b++;
|
while (b != e) {
|
if (!(*p < *b))
|
return false;
|
p = b++;
|
}
|
return true;
|
#endif
|
}
|
And here's an example on how to use it:
// Keep this sorted.
|
constexpr std::array roCmds{
|
"collStats"_sd,
|
"count"_sd,
|
"dataSize"_sd,
|
"dbStats"_sd,
|
"distinct"_sd,
|
"filemd5"_sd,
|
"find"_sd,
|
"listCollections"_sd,
|
"listIndexes"_sd,
|
"planCacheListFilters"_sd,
|
};
|
|
static_assert(constexprIsSorted(roCmds.begin(), roCmds.end()));
|
|
bool isReadOnlyCommand(StringData cmd) {
|
return std::binary_search(roCmds.begin(), roCmds.end(), cmd);
|
}
|
|