Effective STL 学习笔记: 多用 vector & string

如果可能的话, 尽量避免自己去写动态分配的数组,转而使用 vector 和 string 。

原书作者唯一想到的一个不用 string 的可能的理由,就是 string 所使用的引用计数 (reference counting) 在多线程下可能会因为并发控制反而导致性能下降。我们可以通过查看文档或者 STL 源面的方法来看 String 是否引入了引用计数,如果 string 在多线程下真的因为引用计数而导致了性能下降,我们可以通过下面的方法来避免:

  1. 看是否可以通过某些方法来禁用引用计数,例如条件编译
    该方法可移植性不佳,但最简单。
  2. 看是否有 string 的非引用计数替代品。
  3. vector<char> 来替代 string
    虽然这样可能会导致很多 string 专属的成员函数不能用,但大多的函数都可以通过
    STL 算法来替代。
#include <vector>
#include <stdio.h>
using namespace std; int main(int argc, char *argv[])
{
vector<char> ss;
char c = 'a';
while (c < 'z') {
ss.push_back(c);
c++;
} char* p = ss.data();
fprintf(stderr, "p = %s\n",p);
return 0;
}

Output:

~/tmp $ g++ test.cpp -o test
~/tmp $ ./test
p = abcdefghijklmnopqrstuvwxy

最新文章

  1. OpenCASCADE Rational Bezier Curves
  2. c# 不同窗体之间传值和调用
  3. LockSupport
  4. 神逸之作:国产快速启动软件神品ALTRun
  5. backup archivelog all
  6. you need to be root to perform this command linux
  7. 小A项目为什么加班
  8. 【HDU 4451 Dressing】水题,组合数
  9. 用QFileSystemWatcher来监视文件和目录的改变(内部还是使用了timer)
  10. jQuery Validate插入 reomte使用详细的说明
  11. awk学习总结(两) How awk works and awk CMD in a file
  12. 接口调用 GET方式
  13. 【设计模式】module(模块)模式
  14. 关于Could not resolve dependencies for project
  15. day 13 模块
  16. HDU 5372 Segment Game (树状数组)
  17. UVa 10377 - Maze Traversal
  18. 【AtCoder】AGC011 E - Increasing Numbers
  19. 转发:微信小程序-template模板使用
  20. maven Web项目中POM的配置信息

热门文章

  1. 多项式 Wannafly挑战赛22
  2. ICMP类型和代号对照表
  3. poj 2774 后缀数组 两个字符串的最长公共子串
  4. poj 1284 Primitive Roots (原根)
  5. Intellij IDEA设置及快捷键使用总结
  6. SpringCloud(六) Hystrix入门
  7. 20155213 2016-2017-2 《Java程序设计》第七周学习总结
  8. STL-set and multiset
  9. 差分约束系统 + spfa(A - Layout POJ - 3169)
  10. imperva 非交互式导入导出配置