gpt4 book ai didi

c++ - 使用 static_cast 忽略迭代器作为返回值是否正确?

转载 作者:行者123 更新时间:2023-12-03 06:58:38 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How can I intentionally discard a [[nodiscard]] return value?

(6 个回答)


1年前关闭。




我必须处理来自 std::remove 的 [[nodiscard]] 警告;

static_cast<void>(std::remove(stringVar.begin(), stringVar.end(), ' '));
我想要正确的方法来做到这一点。可以通过以下代码停止警告:
auto temp = std::remove(stringVar.begin(), stringVar.end(), ' ');
我不想使用 std::remove 的返回值.
void main()
{
std::string stringVar { "Operation : In , Value : 3884 ," };

size_t from = 0, to = 0, pos = 0;
std::string delFrom{ ":" }, delTo{ "," };

static_cast<void>(std::remove(stringVar.begin(), stringVar.end(), ' '));

from = stringVar.find(delFrom, pos);
to = stringVar.find(delTo, pos);
std::cout<< stringVar.substr(from + 1, to - from - 1);
}
输出:
In
这是一个对 SO 上已经搜索过的问题不感兴趣的特定问题。
更新:数据一致且可读的格式。

最佳答案

这里的问题是,如果你不使用 temp您没有正确删除字符串中的空格。
正确的代码是

auto temp = std::remove(stringVar.begin(), stringVar.end(), ' ')
stringVar.erase(temp, stringVar.end());
你看 std::remove不会从任何东西中删除任何东西(当它只有两个迭代器时它怎么可能?)。它所做的只是重新排列字符串,以便字符串末尾的项目是应该删除的字符串部分(您可以将其视为将所有空格移动到字符串末尾,但实际上它比那)。
要真正删除,您需要调用 string::erase ,使用 std::remove 返回的迭代器如上面的代码所示。

关于c++ - 使用 static_cast<void> 忽略迭代器作为返回值是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64763654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com