Effective STL 学习笔记: 多用 vector & string
2024-08-28 09:43:44
Effective STL 学习笔记: 多用 vector & string
如果可能的话, 尽量避免自己去写动态分配的数组,转而使用 vector 和 string 。
原书作者唯一想到的一个不用 string 的可能的理由,就是 string 所使用的引用计数 (reference counting) 在多线程下可能会因为并发控制反而导致性能下降。我们可以通过查看文档或者 STL 源面的方法来看 String 是否引入了引用计数,如果 string 在多线程下真的因为引用计数而导致了性能下降,我们可以通过下面的方法来避免:
- 看是否可以通过某些方法来禁用引用计数,例如条件编译
该方法可移植性不佳,但最简单。 - 看是否有 string 的非引用计数替代品。
- 用 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
(使用许可:署名-非商业性使用-相同方式共享 3.0 中国大陆许可协议 。)
最新文章
- OpenCASCADE Rational Bezier Curves
- c# 不同窗体之间传值和调用
- LockSupport
- 神逸之作:国产快速启动软件神品ALTRun
- backup archivelog all
- you need to be root to perform this command linux
- 小A项目为什么加班
- 【HDU 4451 Dressing】水题,组合数
- 用QFileSystemWatcher来监视文件和目录的改变(内部还是使用了timer)
- jQuery Validate插入 reomte使用详细的说明
- awk学习总结(两) How awk works and awk CMD in a file
- 接口调用 GET方式
- 【设计模式】module(模块)模式
- 关于Could not resolve dependencies for project
- day 13 模块
- HDU 5372 Segment Game (树状数组)
- UVa 10377 - Maze Traversal
- 【AtCoder】AGC011 E - Increasing Numbers
- 转发:微信小程序-template模板使用
- maven Web项目中POM的配置信息