我已经围绕 .substr 函数创建了一个包装器:
wstring MidEx(wstring u, long uStartBased1, long uLenBased1)
{
//Extracts a substring. It is fail-safe. In case we read beyond the string, it will just read as much as it has
// For example when we read from the word HELLO , and we read from position 4, len 5000, it will just return LO
if (uStartBased1 > 0)
{
if (uStartBased1 <= u.size())
{
return u.substr(uStartBased1-1, uLenBased1);
}
}
return wstring(L"");
}
它工作正常,但是编译器给我警告“<= 有符号和无符号之间的冲突”。
谁能告诉我如何正确地做到这一点?
非常感谢!
最佳答案
您应该使用wstring::size_type
(或size_t
)而不是long
:
wstring MidEx(wstring u, wstring::size_type uStartBased1, wstring::size_type uLenBased1)
{
//Extracts a substring. It is fail-safe. In case we read beyond the string, it will just read as much as it has
// For example when we read from the word HELLO , and we read from position 4, len 5000, it will just return LO
if (uStartBased1 > 0)
{
if (uStartBased1 <= u.size())
{
return u.substr(uStartBased1-1, uLenBased1);
}
}
return wstring(L"");
}
这是 u.size()
的确切返回类型。这样,您可以确保比较给出预期的结果。
如果您正在使用 std::wstring
或其他标准库容器(如 std::vector
等),则 x::size_type
将被定义为 size_t
。所以使用它会更加一致。
关于C++:<=有符号和无符号之间的冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21350214/