庫
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
最重要的還有using namespace std;
C++的優勢
舉兩個例子:
交換函數
C語言寫法:
#include <stdio.h>
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 <iostream>
using namespace std;
template<class T>
void swap(T *a, T *b)
{
T p = *a;
*a = *b;
*b = p;
}
int main()
{
int a, b;
cin >> a >> b;
swap<int>(&a, &b);
return 0;
}
而其中C++的程序體現出的好處就在于模板(即STL中的T), 所以不管a和b是什么類型的,只要把調用swap時的那個<int>改一下即可,而相對來說,c語言的程序卻要寫很多函數(如long long, int, double, short等等), 比起來c++的明顯要更加的方便。
vector庫與 algorithm庫
以上這兩個庫中有許多東西, 如algorithm中就有很多可以直接調用的算法,很方便,而c語言里就沒有這種東西,每次都要自己定義一些基本算法或函數, 下面這個程序就體現出了這兩個庫的用處:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int i;
vector<int> 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為結尾的。