空的for循环只用于计数
Empty for loop only used for counting
我正在编写一个方法来读取字符串并丢弃所有字符,直到它找到空白字符。我想到了这个:
void Utility::TrimToWhiteSpace( std::string& str )
{
size_t i = 0;
for( ; i < str.size() && !std::isspace( str[i], "C" ); i++ ){}
str.erase( 0, i );
}
我只需要这个循环来计数,但是把它留空似乎很奇怪。例如,这会导致任何优化问题吗?
这样的"空"循环在查找时很常见;没有他们真正的问题是。尽管很多人,包括我自己,在这种情况下,你更喜欢while
,你写的for
这是完全可以接受的,应该不会造成任何问题。
当然,在习惯的c++中,您会使用std::remove
和std::find_if
,而不是手写的循环:
str.remove(
std::find_if( str.begin(), str.end(), []( char ch ) { return !std::isspace( ch, "C" ); } ),
str.end() );
我个人也会避免使用的两个参数形式std::isspace
,除非在孤立的实例中。在这种情况下,在下面的语句中:
static std::locale const cLocale( "C" ); // Define locale to ensure lifetime.
static std::ctype<char> const& cType( std::use_facet<std::codecvt<char>>( cLocale ) );
str.remove(
std::find_if( str.begin(), str.end(), [&]( char ch) { return !cType.is( std::ctype_base::space, ch ); } ),
str.end() );
或者如果你正在进行大量的文本处理:
template <std::ctype_base::mask mask>
class Is
{
std::locale myCopyToEnsureLifetime;
std::ctype<char> const* myCType;
public:
Is( std::locale const& locale = std::locale() )
: myCopyToEnsureLifetime( locale )
, myCType( &std::use_facet<std::codecvt<char>>( myCopyToEnsureLifetime )
{
}
bool operator()( char ch ) const
{
return myCType->is( mask, ch );
}
};
template <std::ctype_base::mask mask>
class IsNot
{
std::locale myCopyToEnsureLifetime;
std::ctype<char> const* myCType;
public:
Is( std::locale const& locale = std::locale() )
: myCopyToEnsureLifetime( locale )
, myCType( &std::use_facet<std::codecvt<char>>( myCopyToEnsureLifetime )
{
}
bool operator()( char ch ) const
{
return !myCType->is( mask, ch );
}
};
typedef Is<std::ctype_base::space> IsSpace;
typedef IsNot<std::ctype_base::space> IsNotSpace;
// And so on...
直接使用std::locale
可能有点冗长,而且它是值得用更合理的接口包装它一次,并系统地使用包装器。
相关文章:
- std::任何只用于移动的模板,其中副本ctor内的static_assert等于编译错误,但为什么
- 相同的 for 循环适用于其他项目,但不适用于此项目。为什么?
- 将函数应用于特征矩阵中的所有元素,而无需循环
- C++参数类型以接受适用于基于范围的 for 循环的所有序列
- 为什么 OpenCL 嵌套循环仅适用于某些元素
- Openmp-嵌套用于循环
- 有类似于循环(圆形)迭代器的东西吗?
- 我是否必须求助于循环,以比较C 中的两个2D阵列
- 对于作用于整数向量的循环行为异常
- 我可以告诉 nvcc 将 #pragma 展开应用于函数中的所有循环吗?
- 在现代C++中,有没有类似于python中基于范围的“enumerate”循环
- 此循环仅适用于第一次迭代
- "继续"使用标志作用于哪个循环?
- 嵌套用于数字沿列向下的循环
- 嵌套用于未产生所需结果的循环
- C++嵌套用于循环
- C++嵌套用于循环-内积-marix乘法
- 无限循环的"for(;;)"习语是否正确归因于 PDP-11 C 编译器?
- 空的for循环只用于计数
- 为什么for循环中定义的变量只存在于循环内部