C++学习归纳与总结

PS:本文作为个人学习C++的笔记,不能保证内容的准确性。如被网友检索到,答案仅供参考。


//《Introduction to Pragramming with C++ 》第7章:指针和C字符串

Error 7.1:数组使用前未初始化

int * count(const char * const s)
{
 int *countNumber = new int[10];
 for (int i = 0; i < strlen(s); i++) { if (isdigit(s[i])) { ++countNumber[s[i] - '0']; } }  //Wrong: 使用new动态创建数组countNumber,使用前并未初始化。

 return countNumber;
}

Error 7.2:数组下标越界访问

void count(const char * const s, int * counts, int size)
{
 for (int i = 0; i < size; i++) { counts[i] = 0; }
 for (int i = 0; i < strlen(s); i++) { if (isalnum(s[i])) { ++counts[s[i] - '0']; } }  //Wrong: 当字符为字母时,数组countNumber下标越界访问。
}


//《Introduction to Pragramming with C++ 》第8章:递归

GoodExercise 8.17 : 用递归打印字符串的所有排列

#include <iostream>
using namespace std;

void displayPermutation(const char * const s);  // 构造辅助递归函数
void displayPermutation(const char * const str1, const char * const str2);  // 递归函数

int main()
{
 char testStr[] = "ABC";
 displayPermutation(testStr);

 return 0;
}

void displayPermutation(const char * const s)
{
 displayPermutation("", s);
}

void displayPermutation(const char * const str1, const char * const str2)
{
 if (strlen(str2) == 0)
  cout << str1 << " ";
 else
 {
  for (int i = 0; i < strlen(str2); i++)
  {
   char *newStr1 = new char[strlen(str1) + 1];
   strcpy(newStr1, str1);
   newStr1[strlen(str1)] = str2[i];
   newStr1[strlen(str1) + 1] = '\0';

   char *newStr2 = new char[strlen(str2) - 1];
   int k = 0;
   for (int j = 0; j < strlen(str2); j++)
   {
    if (j != i) newStr2[k++] = str2[j];
   }
   newStr2[k] = '\0';
   
   displayPermutation(newStr1, newStr2);
  }
 }
}

OUTPUT : ABC ACB BAC BCA CAB CBA



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值