C++:<= 已签名和未签名之间的冲突

C++: <= conflict between signed and unsigned

本文关键字:之间 冲突 lt C++      更新时间:2023-10-16

我已经在.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"");
}

它可以正常工作,但是编译器给我警告"&lt; =签名和未签名之间的冲突"。

有人可以告诉我如何正确执行吗?

非常感谢!

您应该使用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)