21xrx.com
2024-11-24 17:13:49 Sunday
登录
文章检索 我的文章 写文章
「C++代码分享」10个有趣且可复制的代码实例
2023-07-04 23:50:05 深夜i     --     --
C++ 代码分享 代码实例 可复制 有趣

C++作为一种高效的编程语言,被广泛应用于各种领域,特别是在计算机科学和软件工程方面。如果你正在学习或者使用C++,下面为你分享10个有趣且可复制的代码实例。

1. 反转字符串

这个代码可以将字符串反转,可以用于加密等领域。


#include <iostream>

#include <string>

#include <algorithm>

using namespace std;

int main()

{

  string str;

  cout << "Enter a string: ";

  cin >> str;

  reverse(str.begin(), str.end());

  cout << "Reverse string: " << str << endl;

  return 0;

}

2. 猜数字游戏

这是一个简单的猜数字游戏,可以让你体验到C++的基本逻辑和语法。


#include <iostream>

#include <cstdlib>

#include <ctime>

using namespace std;

int main()

{

  srand(time(0));

  int number = rand() % 100 + 1;

  int guess;

  int count = 0;

  cout << "Guess my number between 1 and 100." << endl;

  do

  {

    cin >> guess;

    count++;

    if (guess > number)

      cout << "Too high" << endl;

    else if (guess < number)

      cout << "Too low" << endl;

    else

      cout << "You got it!" << endl;

  } while (guess != number);

  cout << "You took " << count << " guesses." << endl;

  return 0;

}

3. 计算圆的面积

这个程序可以计算圆的面积,可以让你学会如何声明变量和使用常量。


#include <iostream>

using namespace std;

const double PI = 3.14159265;

int main()

{

  double radius;

  cout << "Enter the radius of a circle: ";

  cin >> radius;

  double area = PI * radius * radius;

  cout << "The area of the circle is: " << area << endl;

  return 0;

}

4. 实现阶乘

这个程序可以计算一个数的阶乘,可以让你学会如何使用循环和递归。


#include <iostream>

using namespace std;

int factorialIterative(int n)

{

  int result = 1;

  for (int i = 1; i <= n; i++)

  {

    result *= i;

  }

  return result;

}

int factorialRecursive(int n)

{

  if (n <= 1)

  

    return 1;

  

  else

  {

    return n * factorialRecursive(n - 1);

  }

}

int main()

{

  int n;

  cout << "Enter a number: ";

  cin >> n;

  cout << "Iterative factorial: " << factorialIterative(n) << endl;

  cout << "Recursive factorial: " << factorialRecursive(n) << endl;

  return 0;

}

5. 实现排序算法

这个程序可以实现常用的排序算法,可以让你学会如何实现算法和优化算法。


#include <iostream>

#include <algorithm>

#include <vector>

using namespace std;

void bubbleSort(vector<int> &arr)

{

  for (int i = 0; i < arr.size() - 1; i++)

  {

    for (int j = 0; j < arr.size() - i - 1; j++)

    {

      if (arr[j] > arr[j + 1])

      {

        swap(arr[j], arr[j + 1]);

      }

    }

  }

}

void selectionSort(vector<int> &arr)

{

  for (int i = 0; i < arr.size() - 1; i++)

  {

    int minIndex = i;

    for (int j = i + 1; j < arr.size(); j++)

    {

      if (arr[j] < arr[minIndex])

      

        minIndex = j;

      

    }

    swap(arr[i], arr[minIndex]);

  }

}

void insertionSort(vector<int> &arr)

{

  for (int i = 1; i < arr.size(); i++)

  {

    int key = arr[i];

    int j = i - 1;

    while (j >= 0 && arr[j] > key)

    {

      arr[j + 1] = arr[j];

      j--;

    }

    arr[j + 1] = key;

  }

}

int main()

{

  vector<int> arr = 9;

  bubbleSort(arr);

  cout << "Bubble Sort: ";

  for (auto i : arr)

  

    cout << i << " ";

  

  cout << endl;

  arr = 5;

  selectionSort(arr);

  cout << "Selection Sort: ";

  for (auto i : arr)

  

    cout << i << " ";

  

  cout << endl;

  arr = 1;

  insertionSort(arr);

  cout << "Insertion Sort: ";

  for (auto i : arr)

  

    cout << i << " ";

  

  cout << endl;

  return 0;

}

6. 实现二叉堆

这个程序可以实现一个二叉堆,可以让你学会如何实现数据结构和优化数据结构。


#include <iostream>

#include <vector>

using namespace std;

class MaxHeap

{

private:

  vector<int> heap;

  int parent(int i)

  {

    return (i - 1) / 2;

  }

  int leftChild(int i)

  {

    return 2 * i + 1;

  }

  int rightChild(int i)

  {

    return 2 * i + 2;

  }

  void siftUp(int i)

  {

    while (i > 0 && heap[parent(i)] < heap[i])

    {

      swap(heap[parent(i)], heap[i]);

      i = parent(i);

    }

  }

  void siftDown(int i)

  {

    int maxIndex = i;

    int l = leftChild(i);

    if (l < heap.size() && heap[l] > heap[maxIndex])

      maxIndex = l;

    int r = rightChild(i);

    if (r < heap.size() && heap[r] > heap[maxIndex])

      maxIndex = r;

    if (i != maxIndex)

    {

      swap(heap[i], heap[maxIndex]);

      siftDown(maxIndex);

    }

  }

public:

  void insert(int p)

  {

    heap.push_back(p);

    siftUp(heap.size() - 1);

  }

  int extractMax()

  {

    int result = heap[0];

    swap(heap[0], heap[heap.size() - 1]);

    heap.pop_back();

    siftDown(0);

    return result;

  }

  void printHeap()

  {

    for (int i = 0; i < heap.size(); i++)

    {

      cout << heap[i] << " ";

    }

    cout << endl;

  }

};

int main()

{

  MaxHeap h;

  h.insert(3);

  h.insert(2);

  h.insert(1);

  h.printHeap();

  cout << h.extractMax() << endl;

  h.printHeap();

  return 0;

}

7. 实现图

这个程序可以实现一个图,可以让你学会如何实现图和优化图。


#include <iostream>

#include <vector>

#include <list>

#include <iterator>

using namespace std;

class Graph

{

private:

  int V;

  list<int> *adj;

public:

  Graph(int V)

  {

    this->V = V;

    adj = new list<int>[V];

  }

  void addEdge(int v, int w)

  {

    adj[v].push_back(w);

    adj[w].push_back(v);

  }

  void printGraph()

  {

    for (int v = 0; v < V; ++v)

    {

      cout << "Adjacency list of vertex " << v << endl;

      cout << "head";

      for (auto x : adj[v])

        cout << "-> " << x;

      cout << endl;

    }

  }

};

int main()

{

  Graph g(5);

  g.addEdge(0, 1);

  g.addEdge(0, 4);

  g.addEdge(1, 2);

  g.addEdge(1, 3);

  g.addEdge(1, 4);

  g.addEdge(2, 3);

  g.addEdge(3, 4);

  g.printGraph();

  return 0;

}

8. 实现随机森林

这个程序可以实现随机森林,可以让你学会如何实现机器学习算法和优化机器学习算法。


#include <iostream>

#include <vector>

#include <cstdlib>

#include <ctime>

using namespace std;

const int MAX_FEATURES = 2;

const int N_ESTIMATORS = 5;

const int N_SAMPLES = 10;

const int N_TREES = 10;

class DecisionTree

{

private:

  struct TreeNode

  {

    int feature;

    int threshold;

    int value;

    TreeNode* left;

    TreeNode* right;

  };

  int getClass(vector<int> sample)

  {

    int sum = 0;

    for (int i = 0; i < sample.size(); i++)

    {

      sum += sample[i];

    }

    if (sum > sample.size() / 2)

    

      return 1;

    

    else

    

      return 0;

    

  }

public:

  TreeNode* buildTree(vector<vector<int>> &X, vector<int> &y)

  {

    if (X.size() == 0)

    {

      TreeNode* node = new TreeNode;

      node->value = 0;

      return node;

    }

    if (y.empty() || (y.size() != X.size()))

    {

      cerr << "Error: Incorrect usage" << endl;

      TreeNode* node = new TreeNode;

      node->value = 0;

      return node;

    }

    int class0 = 0;

    int class1 = 0;

    for (int i = 0; i < y.size(); i++)

    {

      if (y[i] == 0)

      {

        class0++;

      }

      else if (y[i] == 1)

      {

        class1++;

      }

    }

    if (class0 == 0)

    {

      TreeNode* node = new TreeNode;

      node->value = 1;

      return node;

    }

    if (class1 == 0)

    {

      TreeNode* node = new TreeNode;

      node->value = 0;

      return node;

    }

    int feature;

    int threshold;

    while (true)

    {

      feature = rand() % MAX_FEATURES;

      threshold = rand() % X.size();

      int left0 = 0;

      int left1 = 0;

      int right0 = 0;

      int right1 = 0;

      for (int i = 0; i < X.size(); i++)

      {

        if (X[i][feature] < X[threshold][feature])

        {

          if (y[i] == 0)

          {

            left0++;

          }

          else

          {

            left1++;

          }

        }

        else

        {

          if (y[i] == 0)

          {

            right0++;

          }

          else

          {

            right1++;

          }

        }

      }

      if ((left0 > 0) && (left1 > 0) && (right0 > 0) && (right1 > 0))

      

        break;

      

    }

    vector<vector<int>> leftX;

    vector<int> lefty;

    vector<vector<int>> rightX;

    vector<int> righty;

    for (int i = 0; i < X.size(); i++)

    {

      if (X[i][feature] < X[threshold][feature])

      {

        leftX.push_back(X[i]);

        lefty.push_back(y[i]);

      }

      else

      {

        rightX.push_back(X[i]);

        righty.push_back(y[i]);

      }

    }

    TreeNode* node = new TreeNode;

    node->feature = feature;

    node->threshold = threshold;

    node->left = buildTree(leftX, lefty);

    node->right = buildTree(rightX, righty);

    return node;

  }

  int predict(TreeNode* node, vector<int> sample)

  {

    if (node != nullptr)

    {

      int feature = node->feature;

      if (sample[feature] < node->threshold)

      {

        return predict(node->left, sample);

      }

      else

      {

        return predict(node->right, sample);

      }

    }

    else

    

      return 0;

    

  }

};

class RandomForest

{

private:

  vector<DecisionTree> trees;

public:

  void fit(vector<vector<int>> X, vector<int> y)

  {

    srand(time(0));

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

    {

      vector<vector<int>> sampleX;

      vector<int> sampley;

      for (int j = 0; j < N_SAMPLES; j++)

      {

        int index = rand() % X.size();

        sampleX.push_back(X[index]);

        sampley.push_back(y[index]);

      }

      DecisionTree tree;

      trees.push_back(tree);

      trees.back().buildTree(sampleX, sampley);

    }

  }

  int predict(vector<int> sample)

  {

    int sum = 0;

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

    {

      sum += trees[i].predict(trees[i].getRoot(), sample);

    }

    if (sum > N_ESTIMATORS / 2)

    

      return 1;

    

    else

    

      return 0;

    

  }

};

int main()

{

  RandomForest rf;

  vector<vector<int>> X = {1, 2, 3, 4, 5, 5, 3, 4, 5, 10};

  vector<int> y = 1;

  rf.fit(X, y);

  int result = rf.predict( 3);

  cout << result << endl;

  return 0;

}

9. 解决八皇后问题

这个程序可以解决八皇后问题,可以让你学会如何解决深度优先搜索和回溯问题。


#include <iostream>

using namespace std;

const int N = 8;

int ans[N];

bool column[N];

bool diagonal1[N * 2 - 1];

bool diagonal2[N * 2 - 1];

void dfs(int row)

{

  if (row == N)

  {

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

    {

      for (int j = 0; j < N; j++)

      {

        if (ans[i] == j)

        

          cout << "Q";

        

        else

        

          cout << ".";

        

      }

      cout << endl;

    }

    cout << endl;

    return;

  }

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

  {

    if (column[i] || diagonal1[row + i] || diagonal2[row - i + N - 1])

    

      continue;

    

    ans[row] = i;

    column[i] = true;

    diagonal1[row + i] = true;

    diagonal2[row - i + N - 1] = true;

    dfs(row + 1);

    column[i] = false;

    diagonal1[row + i] = false;

    diagonal2[row - i + N - 1] = false;

  }

}

int main()

{

  dfs(0);

  return 0;

}

10. 实现暴力破解密码

这个程序可以暴力破解密码,可以让你学会如何暴力破解加密。


#include <iostream>

#include <string>

using namespace std;

int main()

{

  string password = "password";

  string guess;

  int count = 0;

  do

  {

    cout << "Guess the password: ";

    cin >> guess;

    count++;

  } while (guess != password);

  cout << "You took " << count << " guesses." << endl;

  return 0;

}

这些代码实例可以让你学到很多C++的基础知识和进阶知识,同时也可以给你提供很多编程思路和灵感。希望这些代码能够帮助你学习和掌握C++编程。

  
  

评论区

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