21xrx.com
2024-09-20 00:09:30 Friday
登录
文章检索 我的文章 写文章
C++常用代码大全
2023-06-29 06:29:17 深夜i     --     --
C++ 代码 常用 大全 程序设计

C++是一种高性能的编程语言,灵活性和可移植性使它被广泛应用于各种领域。在C++编程中,常用的代码模板可以帮助程序员快速实现各种算法和操作。本篇文章介绍C++常用代码大全,以帮助C++程序员更加方便地开发应用程序。

一、输入输出

1.输入整数

int n;

cin >> n;

2.输入字符串

string s;

cin >> s;

3.输出整数

int n = 100;

cout << n << endl;

4.输出字符串

string s = "hello world";

cout << s << endl;

二、循环控制

1.while循环

int i = 0;

while (i < 10) {

  cout << i << endl;

  i++;

}

2.for循环

for (int i = 0; i < 10; i++)

  cout << i << endl;

3.do-while循环

int i = 0;

do {

  cout << i << endl;

  i++;

} while (i < 10);

三、条件控制

1.if语句

int n = 10;

if (n < 20)

  cout << "n is less than 20" << endl;

2.if-else语句

int n = 10;

if (n < 20)

  cout << "n is less than 20" << endl;

else

  cout << "n is greater than or equal to 20" << endl;

3.switch语句

int n = 3;

switch (n)

  case 1:

    cout << "n is 1" << endl;

    break;

  case 2:

    cout << "n is 2" << endl;

    break;

  case 3:

    cout << "n is 3" << endl;

    break;

  default:

    cout << "n is not 1

四、数组

1.声明并初始化一维数组

int a[5] = 5;

2.声明并初始化二维数组

int a[2][3] = { 3, 4};

3.遍历一维数组

for (int i = 0; i < 5; i++) {

  cout << a[i] << endl;

}

4.遍历二维数组

for (int i = 0; i < 2; i++) {

  for (int j = 0; j < 3; j++) {

    cout << a[i][j] << " ";

  }

  cout << endl;

}

五、函数

1.无参函数

void hello()

  cout << "hello" << endl;

2.带参函数

int add(int a, int b) {

  return a + b;

}

3.递归函数

int fib(int n) {

  if (n < 2)

    return n;

   else {

    return fib(n-1) + fib(n-2);

  }

}

六、指针

1.定义指针

int *p;

2.取指针所指向的值

int n = 10;

int *p = &n;

cout << *p << endl;

3.修改指针所指向的值

int n = 10;

int *p = &n;

*p = 20;

cout << n << endl;

七、类

1.定义类

class Person {

public:

  string name;

  int age;

  void say_hello()

    cout << "Hello

};

2.创建对象

Person p;

p.name = "Tom";

p.age = 20;

3.调用对象的成员函数

p.say_hello();

总结:以上是C++常用代码大全,这些代码模板是C++程序员编写高效程序的必备工具。程序员可以根据实际需求和代码框架来结合使用这些代码模板,以更加方便快捷地实现各种算法和功能。同时,也可以通过阅读其他C++开源项目的源代码来学习优秀的编码习惯和实践经验,不断提升自己的编程技能。

  
  
下一篇: C++绘图库

评论区

{{item['qq_nickname']}}
()
回复
回复