C++ string

  1、写时复制(COW)。例子:

int main() 
{
string str1 = "hello world"; string str2 = str1; printf("Sharing the memory: "); printf(" str1's address:%x ", str1.c_str()); // str1's address:501028 printf(" str2's address:%x ", str2.c_str()); // str2's address:501028 str1[1] = 'w'; printf("After Copy_On_Write: "); printf(" str1's address:%x ", str1.c_str()); // str1's address:501058 printf(" str2's address:%x ", str2.c_str()); // str2's address:501028 return 0; }

  2、find系列的成员函数(可参照源码,如/usr/include/c++/4.1.2/bits/basic_string.tcc)。

  首先需要了解,该系列的函数都返回string::size_type(无符号)类型。特殊值string::npos是size_type类型的最大值

  它们的功能都类似:若能找到目标则返回其出现的位置,否则返回string::npos(因此不要直接拿这些函数的返回值去和0比较)。比如:

  s.find(ch|subs, pos); 对于s从下标为pos的位置开始查找字符ch或子串subs。

  s.find_first_of(ch|subs, pos); 从pos处向后遍历s,找到第一个能与ch匹配或被subs包含的字符。

  s.find_last_of(ch|subs, pos); 从pos处向前遍历s,找到第一个能与ch匹配或被subs包含的字符。

int main()
{
    string s = "hello world";

    cout << s.find_first_of("telh", 0) << endl;    // 结果为0
    cout << s.find_last_of("telo", s.length() - 1) << endl;    // 结果为9
}

  3、其他成员函数

  1)关于compare()和==(参考源码,如/usr/include/c++/4.8.2/bits/basic_string.h)。

template<typename _CharT, typename _Traits, typename _Alloc>
inline bool operator==(const basic_string<_CharT, _Traits, _Alloc>& __lhs,
                        const basic_string<_CharT, _Traits, _Alloc>& __rhs)
{ return __lhs.compare(__rhs) == 0; }

  可知==是通过调用compare()实现的。因此,compare()的性能总是不比==差,比如如果编译器没有执行内联优化,则==比compare()还要多一次函数调用的开销。

不断学习中。。。

原文地址:https://www.cnblogs.com/hanerfan/p/3361422.html