C++编程

1、字符串转为int ,用库函数:
string s = "123";
int num = atoi(s.c_str());

2、int转为字符串:
int i = 234;
char str[10];
itoa(i,str,10);
cout<<str<<endl;

3、动态声明数组:
一维 a[n]:
int *a = new int [n];
delete []a;
二维a[m][n]:
int **a = new int *[m];
for(int i=0;i<m;i++)
a[i] = new int [n];

for(int i =0;i<m;i++)
delete []a[i];
delete []a;

4. 对数组元素排序,数组a[0,......n-1]
从小到大:sort(a,a+n); //该库函数在#include<algorithm>中,采用快排实现的,默认从小到大
从大到小:bool cmp(int x,int y)
{
return x>y;
}
sort(a,a+n,cmp);

5.哈希
例如:输出一个数组中的数字,重复的数字只输出一次
#include<iostream>
#include<vector>
using namespace std;
void remove(int *a,int n)
{
int hsize = 3*n+1;
vector<int> *vec = new vector<int>[hsize];
for(int i=0;i<n;i++)
{
int temp = a[i]%hsize;
bool find = false;
for(int j =0;j<vec[temp].size();j++)
if(vec[temp][j]==a[i])
{
find = true;
break;
}
if(!find)
{
vec[temp].push_back(a[i]);
cout<<a[i]<<" ";
}
}

}
int main()
{
int a[12] = {1,2,4,3,2,7,4,3,1,4,5,6};
remove(a,12);
}

6、
最大公约数:
int gcd(int a, int b)
{
int r;
while(b)
{
r = a%b;
a = b;
b = r;
}
return a;
}

最小公倍数 = a*b/最大公约数
在代码实现中 先除后乘 即:
a/gcd(a,b)*b;

7、已知memcpy的函数为: void* memcpy(void *dest , const void* src , size_t count)其中dest是目的指针,src是源指针。不调用c++/c的memcpy库函数,请编写memcpy。

  1. void* memcpy(void *dst, const void *src, size_tcount)
  2. {
  3. //安全检查
  4. assert( (dst != NULL) && (src != NULL) );
  5. //assert断言,是宏,assert的作用是现计算表达式 expression ,
  6. //如果其值为假(即为0),那么它先向stderr打印一条出错信息,然后通过调用 abort 来终止程序运行。
  7. unsigned char *pdst = (unsigned char *)dst;
  8. const unsigned char *psrc = (const unsigned char*)src;
    1. //如果不这样下面使用指针的时候会提示表达式必须是指向完整对象类型的指针

  9. //防止内存重复
  10. assert(!(psrc<=pdst && pdst<psrc+count));
  11. assert(!(pdst<=psrc && psrc<pdst+count));
  12. while(count--)
  13. {
  14. *pdst = *psrc;
  15. pdst++;
  16. psrc++;
  17. }
  18. return dst;
  19. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值