[英]Question about npos and -1 for the output of a C++ function
下面的代碼是對要點中所示問題的解決方案。 -1返回案例的處理方式有問題嗎?
int64_t FirstUniqueCharInString(const std::string& s)
{
std::array<bool, 26U> seen{};
std::array<std::string::size_type, 26U> pos{};
pos.fill(std::string::npos);
for (auto i = static_cast<std::size_t>(0); i < s.size(); ++i)
{
auto array_index_for_current_char = static_cast<std::size_t>(s[i] - 'a');
pos.at(array_index_for_current_char) = seen.at(array_index_for_current_char) ?
std::string::npos : i;
seen.at(array_index_for_current_char) = true;
}
// static casting result and std::string::npos to int64_t to match return type of function which
// is int64_t to allow for negative values (we have to be able to return -1 when there are no unique chars).
int64_t result = static_cast<int64_t>(*std::min_element(pos.begin(), pos.end()));
return result == static_cast<int64_t>(std::string::npos) ? -1 : result;
}
這段代碼仍然存在將npos
為int64_t
的問題,不能保證返回-1
。
最后兩行可以改正:
auto element = *std::min_element(pos.begin(), pos.end());
if ( element == std::string::npos )
return -1;
return element;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.