庫(kù)
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
最重要的還有using namespace std;
C++的優(yōu)勢(shì)
舉兩個(gè)例子:
交換函數(shù)
C語(yǔ)言寫(xiě)法:
#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++語(yǔ)言寫(xiě)法:
#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++的程序體現(xiàn)出的好處就在于模板(即STL中的T), 所以不管a和b是什么類型的,只要把調(diào)用swap時(shí)的那個(gè)<int>改一下即可玄组,而相對(duì)來(lái)說(shuō)无牵,c語(yǔ)言的程序卻要寫(xiě)很多函數(shù)(如long long, int, double, short等等)蓖议, 比起來(lái)c++的明顯要更加的方便矢棚。
vector庫(kù)與 algorithm庫(kù)
以上這兩個(gè)庫(kù)中有許多東西肝匆, 如algorithm中就有很多可以直接調(diào)用的算法味悄,很方便刻获,而c語(yǔ)言里就沒(méi)有這種東西,每次都要自己定義一些基本算法或函數(shù), 下面這個(gè)程序就體現(xiàn)出了這兩個(gè)庫(kù)的用處:
#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++還有很多優(yōu)勢(shì):如不用gcc編譯只祠,即不用把變量定義都寫(xiě)在最開(kāi)始兜蠕, 還有一點(diǎn)很重要:一定要寫(xiě)using namespace std;
,并且c++程序文件名是以cpp為結(jié)尾的抛寝。