空的for循环只用于计数

Empty for loop only used for counting

本文关键字:只用于 循环 for 空的      更新时间:2023-10-16

我正在编写一个方法来读取字符串并丢弃所有字符,直到它找到空白字符。我想到了这个:

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::removestd::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可能有点冗长,而且它是值得用更合理的接口包装它一次,并系统地使用包装器。