C++基础知识

#include #include #include #include #include

最重要的还有using namespace std;
C++的优势 举两个例子:
交换函数 C语言写法:
#include void swap(int *a, int *b) { int p = *a; *a = *b; *b = p; }int main() { int a, b; swap(&a, &b); return 0; }

C++语言写法:
#include using namespace std; template void swap(T *a, T *b) { T p = *a; *a = *b; *b = p; }int main() { int a, b; cin >> a >> b; swap(&a, &b); return 0; }

【C++基础知识】而其中C++的程序体现出的好处就在于模板(即STL中的T), 所以不管a和b是什么类型的,只要把调用swap时的那个改一下即可,而相对来说,c语言的程序却要写很多函数(如long long, int, double, short等等), 比起来c++的明显要更加的方便。
vector库与 algorithm库 以上这两个库中有许多东西, 如algorithm中就有很多可以直接调用的算法,很方便,而c语言里就没有这种东西,每次都要自己定义一些基本算法或函数, 下面这个程序就体现出了这两个库的用处:
#include #include #include using namespace std; int main() { int i; vector data; while (cin >> i) data.push_back(i); cout << "random data." << endl; random_shuffle(data.begin(), data.end()); for (int j = 0; j < data.size(); j++) cout << j+1 << " : " << data[j] << endl; cout << "sorted." << endl; sort(data.begin(), data.end()); for (int j = 0; j < data.size(); j++) cout << j+1 << " : " << data[j] << endl; return 0; }

此外c++还有很多优势:如不用gcc编译,即不用把变量定义都写在最开始, 还有一点很重要:一定要写using namespace std; ,并且c++程序文件名是以cpp为结尾的。

    推荐阅读