【问题标题】:equivalent of this in STL [closed]STL中的等效项[关闭]
【发布时间】:2016-11-02 21:10:50
【问题描述】:

给出以下代码

inline void inlineConvertPackFilename(char *name)
{
    while(*name)
    {
        if(*name == '\\')
        {
            *name = '/';
        }
        else
        {
            *name = (int) tolower(*name);
        }

        name++;
    }
}

问题很简单,是否存在 intro STL 这个函数的任何等价网络?

用法是:

static char filename[MAX_PATH + 1];
inlineConvertPackFilename(filename);

是的,我知道这是 C 代码,但我想要 c++ 中的等效代码。

【问题讨论】:

  • 为什么会有一种算法来做如此具体的事情?

标签: c++ stl


【解决方案1】:

这应该可行:

inline std::string inlineConvertPackFilename(std::string name)
{
    std::transform( name.begin(), name.end(), name.begin(), []( char c ) {
        if( c == '\\' ) return '/';
        return tolower(c);
    } );
    return name;
}

用法:

auto filename = inlineConvertPackFilename( tmpFilename );

【讨论】:

    【解决方案2】:

    你可以这样做:

    #include <algorithm>
    
    void convert(std::string &name)
    {
      std::replace(name.begin(), name.end(), '\\', '/');
    
      std::transform(name.begin(), name.end(), name.begin(), ::tolower);
    }
    

    问题在于 std::replace() 仅适用于 1:1 替换(例如,将一个字符替换为另一个字符)。你可以使用它,但是如果你需要做一个更通用的多字符子字符串替换,你必须自己使用 string::find() 和 string::replace()。

    【讨论】:

    • 另一个(次要)缺点是这种方法对输入字符串进行了两次传递,而原始代码只进行了一次。所以它稍微慢了一点。
    【解决方案3】:

    这使用了std::for_each(),因为您要求的是 STL:

    #include <string.h>
    #include <string>
    #include <algorithm>
    
    void inlineConvertPackFilename(std::string& name)
    {
        std::for_each(name.begin(), name.end(), [](auto& c) {
            if (c == '\\')
            {
                c = '/';
            }
            else
            {
                c = tolower(c);
            }
        });
    }
    
    
    int main()
    {
        static std::string filename("C:\\FOO\\bar\\Baz.txt");
        inlineConvertPackFilename(filename);
        return 0;
    }
    

    但这确实没有必要,因为您可以使用for 范围来代替:

    void inlineConvertPackFilename(std::string& name)
    {
        for (auto& c : name)
        {
            if (c == '\\')
            {
                c = '/';
            }
            else
            {
                c = tolower(c);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-09-03
      • 2012-01-10
      • 2011-10-14
      • 1970-01-01
      • 1970-01-01
      • 2014-11-19
      • 2010-12-04
      • 1970-01-01
      相关资源
      最近更新 更多