美文网首页
C++基础知识

C++基础知识

作者: 好之者不如乐之者 | 来源:发表于2017-11-17 22:31 被阅读0次

#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为结尾的。

相关文章

网友评论

      本文标题:C++基础知识

      本文链接:https://www.haomeiwen.com/subject/rutdvxtx.html