C++: 生成100万随机数, 排序后保存到文件中

简介

这大概是大二数据结构课上老师布置的一个作业, 当年忙着打DOTA所以直接抄同学的, 今天补上。。。

代码

#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>

using namespace std;

class Solution
{
public:
	void generate_nums()
	{
		srand(time(NULL));
		for (auto &r : nums_)
			r = rand();
	}

	void save_nums(string file_name)
	{
		ofstream ofs(file_name);

		for (auto &r : nums_)
			ofs << &r << '\n';
		
		ofs.close();
	}

	void sort_nums()
	{
		sort(nums_.begin(), nums_.end());
	}
private:
	vector<int> nums_ = vector<int>(1000000);
};

int main()
{
	Solution s;

	s.generate_nums();		//generate 1 million nums
	s.save_nums("nums");	//save to file "nums"
	s.sort_nums();			//sort
	s.save_nums("nums2");	//save to file "nums2"

	return 0;
}

参考

http://blog.csdn.net/hackbuteer1/article/details/6574908

本文章迁移自http://blog.csdn.net/timberwolf_2012/article/details/39398505

/** * RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS. * LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/ /* var disqus_config = function () { this.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable }; */ (function() { // DON'T EDIT BELOW THIS LINE var d = document, s = d.createElement('script'); s.src = 'https://chenzz.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })();