Effective STL 读书笔记 7

来源:互联网 发布:上虞网络干部培训 编辑:程序博客网 时间:2024/05/18 03:48
Item 35:使用 mismatch 或者 lexicographical_compare 实现简单的忽略大小写的字符串比较函数。
  • mismatch 实现:
int ci_compare (const string &s1, const string &s2) {
    if (s1.size() <= s2.size())
       return ci_compare_impl(s1, s2);
    else
       return -ci_compare_impl(s2, s1);
}

int ci_compare_impl (const string &s1, const string &s2) {
    typedef pair<string::const_iterator,
                 string::const_iterator> citer_pair;
    citer_pair p = mismatch(s1.begin(), s1.end(),
                            s2.begin(),
                            not2(ptr_fun(ci_char_compare)));
    if (p.first == s1.end()) {
       if (p.second == s2.end()) return 0;
       else return -1;
    }
    return ci_char_compare(*p.first, *p.second);
}
  • lexicographical_compare 实现:
bool ci_equal (const string &s1, const string &s2) {
    return lexicographical_compare(s1.begin(), s1.end(),
                                   s2.begin(), s2.end(),
                                   ci_char_less);

}
  • 利用非标准C库实现:
int ci_compare (const string &s1, const string &s2) {
    return stricmp(s1.c_str(), s2.c_str()); // or strcmpi
}


Item 36:了解 copy_if 的适当实现。
  • 标准库里没有 copy_if 算法。
  • 下面的实现必须传入一个函数对象,而不是函数指针。(因为 not1 不能接受函数指针,见 Item 41)
template< typename InputIter,
          typename OutputIter,
          typename Predicate>
OutputIter copy_if (InputIter begin,
                    InputIter end,
                    OutputIter destBegin,
                    Predicate p)
{
    return remove_copy_if(begin, end, destBegin, not1(p));
}
  • 最简单的方法:用循环自己实现。

Item 37:使用 accumulate 或者 for_each 计算总计。
  • 先介绍四个算法:count, count_if, min_element, and max_element
  • 算法 accumulate 并没有被包含在头文件 <algorithm> 而是在 <numeric> 中,虽然此算法并非仅限于对 numeric 操作。与它同在一个文件下的算法还包括:inner_product, adjacent_difference, and partial_sum
  • 需要注意的是 accumulate 的第三个参数(初始值)的类型指定了算法的运算类型和返回类型。例如,如果要对 list<double> 排序,则必须按如下调用:
double sum = accumulate(ld.begin(), ld.end(), 0.0); // must be 0.0
  • accumulate 的谓词定义:
template< ValueT, ElementT >
class Predicate : public binary_function<ValueT, ElementT
, ValueT> {
public:
    const ValueT operator() (const ValueT &avgSoFar, const ElementT &p);
};
  • 按照标准的定义 accumulate 的谓词必须是无状态的(不能有成员)。作者认为并不有此限制。
  • 为遵照标准可以用 for_each 代替,for_each 的谓词没有限制。但是必须自定义函数用来获得运算结果。
原创粉丝点击