C++ 常用代码

  • vector 迭代器遍历
int main() {
  std::vector obj = {1, 2, 3, 4};
  std::vector::iterator it;
  for (it = obj.begin(); it != obj.end(); it++) {
    std::cout << *it << std::endl;
  }
  return 0;
}
  • C++ 函数模板
#include 

template  void swap(T &a, T &b) {
  T tmp = a;
  a = b;
  b = tmp;
}
int main(int argc, char *argv[]) {
  int a = 2;
  int b = 3;
  swap(a, b);
  std::cout << "a=" << a << ", b=" << b << std::endl;

  double c = 1.1;
  double d = 2.2;
  swap(c, d);
  std::cout << "c=" << c << ", d=" << d << std::endl;
  return 0;
}
  • 冒泡排序
#include 

void BubbleSort(int arr[], int len) {
  int i, j;
  for (i = 0; i < len - 1; i++)
    for (j = 0; j < len - 1 - i; j++)
      if (arr[j] > arr[j + 1])
        std::swap(arr[j], arr[j + 1]);
}

int main() {
  int arr[] = {61, 17, 29, 22, 34, 60, 72, 21, 50, 1, 62};
  int len = (int)sizeof(arr) / sizeof(*arr);
  BubbleSort(arr, len);
  for (int i = 0; i < len; i++)
    std::cout << arr[i] << ' ';
  std::cout << std::endl;
  return 0;
}
  • 快速排序
#include 

int Paritition(int A[], int low, int high) {
  int pivot = A[low];
  while (low < high) {
    while (low < high && A[high] >= pivot) {
      --high;
    }
    A[low] = A[high];
    while (low < high && A[low] <= pivot) {
      ++low;
    }
    A[high] = A[low];
  }
  A[low] = pivot;
  return low;
}

void QuickSort(int A[], int low, int high)
{
  if (low < high) {
    int pivot = Paritition(A, low, high);
    QuickSort(A, low, pivot - 1);
    QuickSort(A, pivot + 1, high);
  }
}

int main() {
  int arr[] = {61, 17, 29, 22, 34, 60, 72, 21, 50, 1, 62};
  int len = (int)sizeof(arr) / sizeof(*arr);
  QuickSort(arr, 0, len - 1);
  for (int i = 0; i < len; i++)
    std::cout << arr[i] << ' ';
  std::cout << std::endl;
  return 0;
}

你可能感兴趣的:(C++ 常用代码)