所以这就是我想出来的: (注意,这个isnt线程安全,它的设计是安全的,调用generateSet不影响eachother(通过改变rand内部值的状态))
template< typename container_type,typename element_type> class RandElemGetter { const container_type& containter_ref; std :: uniform_int_distribution< size_t> distribution; std :: mt19937 engine; public: RandElemGetter(container_type& container):containster_ref(container),distribution(0,container.size 1) { } element_type get() { return containster_ref [distribution(engine)]; } };用法:
{ vector< int> v {1,2,3,1701,1729}; vector< int> result; RandElemGetter< vector< int& ,int> reg_v(v); for(size_t i = 0; i< nelements; ++ i) result.push_back(reg_v.get()); }我知道它不是线程安全的,这不是重点。我想知道是有更好的scoped的方式从随机访问容器获取随机元素。它可以修改可能与std :: advance为所有工作。
解决方案RandElemGetter(container_type container): containster_ref (0,container.size() - 1)
复制,并存储对该副本的引用。一旦构造函数完成,引用就无效。
您需要存储一个副本,或者通过引用传递参数。这是一个好主意,通过不断的引用传递复杂的对象,以避免不必要的复制。
recently I decided to try out new c++11 random lib, and one thing came to mind... to get rid of the [rand()%nelemennts] when picking random element from container. Reason is that i want repeatable generation, when using rand encapsulation is nonexistant because
auto set_a=generateSet(nelements1); //generateSet calls rand auto set_b=generateSet(nelements2); //so set_b is determined by the previous line :(So this is what I came up with: (note that this isnt thread safe, it is designed to be safe in a way that calls to generateSet dont affect eachother(through changing state of rand internal value))
template<typename container_type,typename element_type > class RandElemGetter { const container_type& containter_ref; std::uniform_int_distribution<size_t> distribution; std::mt19937 engine; public: RandElemGetter(container_type& container): containter_ref(container),distribution(0,container.size()-1) { } element_type get() { return containter_ref[distribution(engine)]; } };usage :
{ vector<int> v{1,2,3,1701,1729}; vector<int> result; RandElemGetter<vector<int>,int> reg_v(v); for(size_t i=0;i<nelements;++i) result.push_back(reg_v.get()); }So is this OK solution? I know it is not thread safe, that is not the point. Im wondering is there better "scoped" way of getting random element from random access container. It could be modified maybe with std::advance to work for all.
解决方案 RandElemGetter(container_type container): containter_ref(container),distribution(0,container.size()-1)This takes the container by value, creating a temporary copy, and stores a reference to that copy. The reference is invalid once the constructor has finished.
You need to either store a copy, or pass the argument by reference. It's a good idea to pass complex objects by constant reference anyway, to avoid unnecessary copying.
更多推荐
这是确定范围的方式从容器中获取随机元素吗?
发布评论