c++ - Remove_If 字符串不区分大小写

标签 c++ c++11

有人可以告诉我如何使用 Remove_If 进行一些不区分大小写的比较吗?

目前我是这样做的:

template<typename T>
struct is_literal
{
   enum{value = false};
};

template<>
struct is_literal<char>
{
   enum{value = true};
};

template<>
struct is_literal<char*>
{
   enum{value = true};
};

template<>
struct is_literal<const char*>
{
   enum{value = true};
};

template<typename Char, typename Traits, typename Alloc>
struct is_literal<std::basic_string<Char, Traits, Alloc>>
{
   enum{value = true};
};

template<typename T>
template<typename U>
CustomType<T>& CustomType<T>::Delete(U ValueToDelete, bool All, typename std::enable_if<is_literal<U>::value, bool>::type  CaseSensitive)
{
    for (std::size_t I = 0; I < TypeData.size(); ++I)
    {
        if (CaseSensitive ? std::string(TypeData[I]) == std::string(ValueToDelete) : std::string(ToLowerCase(TypeData[I])) == std::string(ToLowerCase(ValueToDelete)))
        {
            TypeData.erase(TypeData.begin() + I);
            if (!All)
                break;
            --I;
        }
    }
    return *this;
}

我想用 remove_if 来做这件事……或者至少是比这更好的方法……它看起来很难看,我决定优化代码,所以我想出了:

if (CaseSensitive)
{
    if (All)
    {
        TypeData.erase(std::remove(TypeData.begin(), TypeData.end(), ValueToDelete), TypeData.end());
    }
    else
    {
        TypeData.erase(std::find(TypeData.begin(), TypeData.end(), ValueToDelete));
    }
}
else
{
    //Do I have to forloop and lowercase everything like before then compare and remove? OR can I do it just like above using std::remove or std::find with some kind of predicate for doing it?
}

有什么想法吗?

最佳答案

好吧,由于 remove_if 采用谓词参数,使用 lambda 应该很容易:

std::remove_if(TypeData.begin(), TypeData.end(),
    [&ValueToDelete](U &val){ return ToLowerCase(val) == ToLowerCase(ValueToDelete); });

关于c++ - Remove_If 字符串不区分大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15329680/

相关文章:

c++ - NVCC 警告级别

c++11 - g++ 4.8.* std::chrono 未声明

c++ - 局部静态变量初始化是线程安全的

c++ - 自动循环和优化

c++ - 在 C++ 中静态初始化匿名 union

c++ - 构造函数泄漏

c++ - 好友方法错误

c++ - 使用类成员初始化数组时的奇怪行为

c++ - 编译器如何传递 `std::initializer_list` 值? (或 : how can I get around a universal overload with one? )

c++ - 宏是否保证没有开销?