21xrx.com
2025-06-30 03:23:33 Monday
登录
文章检索 我的文章 写文章
C++实用代码大全
2023-06-27 09:43:36 深夜i     9     0
C++ 实用 代码 大全 编程技巧

C++是一门极其灵活的编程语言,具有强大的计算能力和广泛的应用领域。对于有经验的C++程序员来说,编写可扩展的C++代码是一种轻松的任务。但对于初学者而言,编写复杂的代码可能会极大地耗费时间和精力。

因此,我们为你准备了一份C++实用代码大全,帮助你轻松应对常见的开发任务。以下是代码示例:

1.反转字符串

在C++中反转字符串的代码十分简单:

#include <iostream>
#include <string>
using namespace std;
int main()
{
  string str = "Hello, world!";
  reverse(str.begin(), str.end());
  cout << str << endl;
  return 0;
}

2.添加元素到向量(vector)中

向向量中添加元素的代码十分简单:

#include <iostream>
#include <vector>
using namespace std;
int main()
{
  vector<int> vec 2;
  vec.push_back(5);
  for (auto i : vec)
    cout << i << " ";
  
  return 0;
}

3.检查指定文件是否存在

检查指定文件是否存在的代码如下:

#include <fstream>
#include <iostream>
using namespace std;
int main()
{
  string filename = "example.txt";
  ifstream file(filename.c_str());
  if (file.good())
    cout << "File exists!" << endl;
  
  else
    cout << "File does not exist!" << endl;
  
  return 0;
}

4.查找字符串中的子字符串

查找字符串中的子字符串代码如下:

#include <iostream>
#include <string>
using namespace std;
int main()
{
  string str = "Hello, world!";
  string sub = "world";
  size_t pos = str.find(sub);
  if (pos != string::npos)
    cout << "Substring found at position " << pos << endl;
  
  else
    cout << "Substring not found" << endl;
  
  return 0;
}

5.生成一个随机数

生成随机数的代码如下:

#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
  srand(time(NULL));
  int rand_num = rand() % 100;
  cout << "Random number: " << rand_num << endl;
  return 0;
}

以上是一些常用的C++代码示例,当然这只是冰山一角,C++语言功能极为强大,有着很多高级用法和重要的设计模式。 如何学好C++需要广泛的阅读书籍和编程实践。

  
  

评论区