开发者

which stl container I should choose If I need to random get an item from the container

Just As title . As least I know array might not be one I want . cus I need to generate a random index before I want to randomly pick up one item from the array . For your opinion.

I've change the title of my question to "which stl container I should choose If I need to random get an item from the container" . what I really find is a cotain , let's say C , and this Contain should have method , let's say, get_ramdom_member(), which开发者_如何学C will help me get an item randomly from the Container C without providing any key .

@binary: what I store in the container is actually socket fd . the other side of the socket is an "erlang node" . several erlang node togerther serves as a cluster . So I store all the socket fds towards that cluster into one container . Every time I need to talk to the cluster , I need choose one fd . For the purpose of load sharing, I need to randomly get one . I can't tell you guys exactly number of fd the Container need to maintain , but currently it is less than 10 at the moment. but who knows whether the number will be 1000 some day later on .


From the information you provided, which isn't much, the obvious answer is std::vector. That will give you random access to the elements. The nice thing about the standard containers is that you can change between them with relatively little effort, so if vector doesn't pan out you can probably change to another container without re-writing all your code.

If you simply want to randomise the contents of container, see std::random_shuffle.


We need more information really, but it looks like you just need a std::vector. This is a good choice for random access by index.


If you want a random element and make it easy on yourself. Load up a std::queue call std::random_shuffle and then pop off the elements till your hearts content.


You could always wrap an array in a class that checks bounds on assignment and grows to accommodate new elements transparently. Although, you mention wanting to pick a random index into the array - this assumes that you have filled the array already with something and at that point you are no longer talking about accessing an index that does not exist and std::vector would work just fine.

To fit all of your [stated] needs you could always use a std::map<int,Thing>. It allows you to do a find to look for elements and the [] operator acts as you would want with an array for items that exist.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜