簡體   English   中英

關於 output 的 C++ function 的 npos 和 -1 的問題

[英]Question about npos and -1 for the output of a C++ function

下面的代碼是對要點中所示問題的解決方案。 -1返回案例的處理方式有問題嗎?

  • 輸入字符串保證僅由小寫英文字母組成。
  • 如果字符串中沒有唯一字符(只出現一次的字符),則返回 -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;
}


這段代碼仍然存在將nposint64_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM