我有此代码:
//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 整数。将未签名的整数转换为签名整数可能会失去精度。
因此,需要将startingPosition
,endingPosition
和delimiterLength
称为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;
}