work8

使用裸指针:

#include <iostream>
#include <memory>
#include <stdio.h>
#include <cstring>
#include <string>
using namespace std;
int test(int n)
{
char * p(new char[13]);
n = 12-n;
strcpy(p,"hello world!");
string s(p+n);
*(p+n) = '\0';
string t(p);
cout<<s<<t<<endl;
return 0;
}//没有delete操作,观察执行100000次的结果
int main()
{
for (int i=0;i<100000;i++)
{
test(1);
}
return 0;
}

使用智能指针:

#include <iostream>
#include <memory>
#include <stdio.h>
#include <cstring>
#include <string>
using namespace std;
int test(int n)
{
shared_ptr<char> p(new char[13]);
n = 12-n;
strcpy(p.get(),"hello world!");
string s(p.get()+n);
*(p.get()+n) = '\0';
string t(p.get());
cout<<s<<t<<endl;
return 0;
}//没有delete操作,观察执行100000次的结果
int main()
{
for (int i=0;i<100000;i++)
{
test(1);
}
return 0;
}

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string s("hello world!");
string::iterator idx;
int suml=0,sume=0;
for_each (s.begin(),s.end(),[&suml,&sume](char x)
{
suml+=x=='l'?1:0;
sume+=x=='e'?1:0;
});
cout<<suml<<endl;
cout<<sume<<endl;
return 0;
}

posted on 2013-11-24 15:45  Yuzuka  阅读(201)  评论(0编辑  收藏  举报

导航