我是靠谱客的博主 沉默咖啡,这篇文章主要介绍C++ string,现在分享给大家,希望可以做个参考。

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

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main()
{
string str1 = "hello world"; string str2 = str1; printf("Sharing the memory:n"); printf("tstr1's address:%xn", str1.c_str()); // str1's address:501028 printf("tstr2's address:%xn", str2.c_str()); // str2's address:501028 str1[1] = 'w'; printf("After Copy_On_Write:n"); printf("tstr1's address:%xn", str1.c_str()); // str1's address:501058 printf("tstr2's address:%xn", 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包含的字符。

复制代码
1
2
3
4
5
6
7
8
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)。

复制代码
1
2
3
4
5
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

最后

以上就是沉默咖啡最近收集整理的关于C++ string的全部内容,更多相关C++内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(65)

评论列表共有 0 条评论

立即
投稿
返回
顶部