[英]C++: <= conflict between signed and unsigned
我圍繞.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
。 因此使用它會更加一致。
您需要unsigned
參數,例如:
wstring MidEx(wstring u, unsigned long uStartBased1, unsigned long uLenBased1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.