C++ STL extras - random_sample_n

转自: http://antonym.org/2003/09/c-plus-plus-stl-extras-random-sample-n.html


Working on some code for my research tonight, I wasted a lot of time looking for some information on a particlar STL function. Since I couldn’t find the answers elsewhere, I am posting a quick explanation/solution here, to hopefully save someone else the trouble.

I am writing a C++ application, and use the STL in various places. I have been consulting the SGI Standard Template Library Programmer’s Guide. It is quite poorly named; it is really a reference, with not much guidance at all. And unfortunately I have yet to find a decent book on the STL (I have one but it sucks).

(Note that the below applies to the g++ compiler version 3.3; I don’t know about other compilers or libraries.)

Anyway, I found just the function I was after: random_sample_n. So I added the include for algorithm, and couldn’t get the sucker to compile. It turns out that since it is an extension to the STL, it is located in theext/algorithm header, and under the namespace __gnu_cxx:: instead of std::. This stuff I found the hard way, slugging through header files.

Another thing: I didn’t find any decent examples (the one in the SGI docs is trivial) so here is some real code:

#include <ext/algorithm>
#include <vector>
#include <iostream>

int main()
{
	srand(time(NULL));

	// fill up vec with useful stuff
	std::vector<int> vec{ 13213,4325,634,234,2,432,56346,6 };

    // Take N random models
	const int N = 4;
	std::vector<int> rs_model;
    __gnu_cxx::random_sample_n( vec.begin(), vec.end(), std::back_inserter(rs_model) , N );

	for(int i = 0 ; i< (int)rs_model.size() ; i++)
	{
		std::cout << rs_model[i] << std::endl;
	}
}

2013 Update

Nowdays, there is the most excellent http://www.cppreference.com/ which has a comprehensive reference for all the STL and standard C++ library classes, methods and functions.

And the new C++11 standard features e whole module for generating random numbers.



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值