使用C++标准库来提高编程效率
使用C++标准库来提高编程效率
在C语言中几乎所有的数据结构都需要自己去实现甚至最常用的链表,队列等。。。,在中国很多程序员都是在Windows下成长起来的,很多程序员都习惯于使用非语言标准的集合类,入MFC中的CArray, CList, CStringArray … 如下图
在现代的C++编程理念中很强调使用类库, B.J多次强调不应增加太多的语言特性来解决问题(C++语言特性已经够多了够复杂了,要不然现在很多人都又回到C的怀抱啦),而是需要提供更好的类库来解决。
我们应该养成使用C++标准库的习惯,这也是人类从工程学科积累下来的经验,这些经过了千锤百炼的类库无论是性能和跨平台都做了最好的权衡。为每一个应用造一个*不仅效率地下,而且在短的时间内你造的*不一定好用(bug…)我们不要做“不要重复发明*”的“英雄”。纵观其他行业,如计算机硬件,武器工业等。。。都体现了这一思想。如:很多国家,都通过某一优良的坦克或汽车底盘。派生出很多类别的作战车辆。有侦察型。防空型。维修型。这也体现了重用的思想。战舰也是这样的,战舰的船体(包括动力系统,操控系统…)。以这一种成熟的船体来模块化的组合在上层的不同的武器系统便可以承担不同的作战任务。有防空型,反潜行。反舰型。。。我们也要有这种思想。也不多扯淡了下面演示使用C++ 标准库给我们带来的好处,这里只举一个使用STL和传统方式的对比来体现使用 STL 方便之处。更多的STL使用方式可以参考《C++标准库手册》。
简单的例子:
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#ifndef _countof
#define _countof(array) (sizeof(array)/sizeof(array[0]))
#endif
using namespace std;
void demonstrate_traditionary()
{
string strs1[] = {
"Hello",
"Long",
"Time",
"No",
"See",
};
string strs2[_countof(strs1)];
//Copy strs1 to strs2
for (int i=0; i<_countof(strs1); i++) {
strs2[i] = strs1[i];
}
//Compares strs1 and strs2
bool isEqual = false;
for (int i=0; i<_countof(strs1); i++) {
if (strs1[i] == strs2[i]) {
isEqual = true;
break;
}
}
if (isEqual) {
cout << "strs1 == strs2" << endl;
} else {
cout << "strs1 != strs2" << endl;
}
for (int i=0; i<_countof(strs2); i++) {
string::size_type len = strs2[i].length();
for (string::size_type n=0; n<len; n++) {
strs2[i][n] = toupper(strs2[i][n]);
}
}
for (int i=0; i<_countof(strs2); i++) {
cout << strs2[i] << "\t";
}
cout << endl;
}
void demonstrate_modern()
{
vector<string> strs1;
strs1.push_back("Hello");
strs1.push_back("Long");
strs1.push_back("Time");
strs1.push_back("No");
strs1.push_back("See");
vector<string> strs2;
//Copy strs1 to strs2
strs2.resize(strs1.size());
copy(strs1.begin(), strs1.end(), strs2.begin());
//Compares strs1 and strs2
if (equal(strs1.begin(), strs1.end(), strs2.begin())) {
cout << "strs1 == strs2" << endl;
} else {
cout << "strs1 != strs2" << endl;
}
struct StringToUpper {
void operator() (string& str) { transform(str.begin(), str.end(), str.begin(), toupper); }
};
for_each(strs2.begin(), strs2.end(), StringToUpper());
copy(strs2.begin(), strs2.end(), ostream_iterator<string>(cout, "\t"));
cout << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
demonstrate_traditionary();
demonstrate_modern();
return 0;
}
运行结果: