设为首页 加入收藏

TOP

C++随机打乱数组
2014-11-24 14:06:07 来源: 作者: 【 】 浏览:1
Tags:随机 打乱

开始学习c++,看看服务器上有没有装g++ -v ,成功安装显示


如果没有安装或者不支持c++,那就要自己动手了,需要安装GNU make 和GNU binutils包,详细参照gcc.gnu.org/install网站


先搞个简单的算法实现下:


从0到9随机打乱数组,输出


shuffle.cpp


#include
#include
#include
#include
#include "utils.h"


using namespace std;
int main(){
vector v;
back_insert_iterator > p = back_inserter(v);
for(int i = 0; i < 10; ++i){
*p = i;
}
printContainer(v,true);
random_shuffle(v.begin(), v.end());
printContainer(v,true);
}




utils.h


#include
#include
#include
#include
#include


using namespace std;


template
void printRange(Fwd first,Fwd last,char delim=',',ostream& out=cout){
out << "{";
while (first != last){
out << * first;
if(++first != last)
out << delim << ' ';
}
out << "}" << endl;
}


template
void printContainer(const C& c, char delim = ',',ostream& out = cout){
printRange(c.begin(),c.end(),delim,out);
}




编译:


g++ -o shuffle shuffle.cpp


执行:


./shuffle


输出结果:


{0 1 2 3 4 5 6 7 8 9}
{4 3 7 8 0 5 2 1 6 9}




好了,先玩到这里,有空 再玩!


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C++ 使用正则表达式分割字符串 下一篇用Python和awk实现二分法查找

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: