警告隐性转换失去整数精度

Warning Implicit conversion loses integer precision

本文关键字:整数 精度 失去 转换 警告      更新时间:2023-10-16

我有此代码:

//getIndividualWords(..) basically splits a sentence based on a specified delimiter: here delimiter is SPACE
vector<string> getIndividualWords(string line, string delimiter)
{
    int startingPosition = 0, endingPosition = 0, delimiterLength = delimiter.length();
    string words;
    vector<string> wordList; //stores all the words received by splitting the sentence
    while ((endingPosition = line.find (delimiter, startingPosition)) != string::npos) //the loop continues till it finds SPACES in the sentence
    {
        words = line.substr (startingPosition, endingPosition - startingPosition);
        startingPosition = endingPosition + delimiterLength;
        wordList.push_back (words);
    }
    wordList.push_back (line.substr (startingPosition)); //inserts the words into a vector container
    return wordList;
}

我得到了此警告:

隐式转换失去整数精度

所有std::string方法都在std::string::size_type值(而不是int值)上操作大小和索引。size_type通常是std::size_t,即 unsigned 整数。将未签名的整数转换为签名整数可能会失去精度。

因此,需要将startingPositionendingPositiondelimiterLength称为std::string::size_type,以匹配std::string实际使用的内容。

尝试以下操作:

vector<string> getIndividualWords(const string &line, const string &delimiter)
{
    string::size_type startingPosition = 0, endingPosition, delimiterLength = delimiter.length();
    string words;
    vector<string> wordList;
    while ((endingPosition = line.find (delimiter, startingPosition)) != string::npos)
    {
        words = line.substr (startingPosition, endingPosition - startingPosition);
        startingPosition = endingPosition + delimiterLength;
        wordList.push_back (words);
    }
    if (startingPosition < line.length())
        wordList.push_back (line.substr (startingPosition));
    return wordList;
}