由于. std::string_view_ std::remove_if()但是,我不能直接std::remove_if()在 a 上使用,std::basic_string_view::iterator因為那確實是 astd::basic_string_view::const_iterator并且std::remove_if()不能將不可移動的迭代器作為引數。
我想到的唯一解決方法是將 a 轉換std::string_view為 astd::string然后使用迭代器。這是一個例子:
#include <string>
#include <string_view>
#include <algorithm>
#include <locale>
int main() {
std::string_view foo{"Whitepace...\nThe Final Frontier"};
const auto is_space{
[](const auto& character) {
return std::isspace(character, std::locale{});
}
};
// Doesn't compile
//auto without_conversion{
// std::remove_if(foo.begin(), foo.end(), is_space)
//};
// Works, for the most part.
auto with_conversion{
std::remove_if(std::string{foo}.begin(), std::string{foo}.end(), is_space)
};
但這有點違背了 using 的全部意義std::string_view,因為string_view從這個迭代器構造的 a 不會查看原始字串。
是否有一些(最好是優雅的)方法可以做到這一點,同時保持原始字串的視圖?也許某種方法可以使string_view迭代器非常量?
uj5u.com熱心網友回復:
如果您的目標是修剪 astring_view空格并將結果存盤在 a 中std::string,那么您應該選擇允許const迭代器的適當演算法。
一種這樣的演算法是std::copy_if:
#include <iostream>
#include <string_view>
#include <algorithm>
#include <iterator>
#include <cctype>
int main()
{
std::string_view foo{"Whitepace...\nThe Final Frontier"};
std::string result;
std::copy_if(foo.begin(), foo.end(), std::back_inserter(result), [](char ch)
{ return !std::isspace(static_cast<unsigned char>(ch)); });
std::cout << result;
}
輸出:
Whitepace...TheFinalFrontier
uj5u.com熱心網友回復:
std::string_view 是字串序列的常量視圖。
例如,begin回傳一個const_iterator.
https://en.cppreference.com/w/cpp/string/basic_string_view/begin
也許你會有更好的運氣std::span,但是考慮到程式中的文字總是不可變的。無論如何,您必須先制作副本。
此外,您的最后一行并沒有按照您的想法執行,因為您正在迭代不同的臨時物件,即使它可以編譯。
正確的代碼是,例如:
std::string FOO = foo;
auto with_conversion{
std::remove_if(FOO.begin(), FOO.end(), is_space)
};
換句話說,您的程式的整個想法(您可以修改“程式”字串)首先是有缺陷的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/417713.html
標籤:
上一篇:STL向量實作標頭大小
下一篇:創建灰度值增加的影像網格
