By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,127 Members | 1,211 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,127 IT Pros & Developers. It's quick & easy.

conversion from one container object to another

P: n/a
How do I convert, for example, from vector to queue?
Say,

vector<int> a;
queue<int> b = queue(a);

This gives type error because there's no queue constructor that takes
vector. Is there any other way besides looping through the entire set
of elements?

Thanks.

Aug 3 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
seung wrote:
How do I convert, for example, from vector to queue?
Say,

vector<int> a;
queue<int> b = queue(a);

This gives type error because there's no queue constructor that takes
vector. Is there any other way besides looping through the entire set
of elements?

Thanks.


Try:

vector<int> a;
queue<int, vector<int> > b(a);
Aug 3 '05 #2

P: n/a
Could you elaborate how this works? Also, this seems like a solution
only applicable to conversion to queue; is there any more generic
solution?

Thanks

Aug 3 '05 #3

P: n/a
seung wrote:
Could you elaborate how this works? Also, this seems like a solution
only applicable to conversion to queue; is there any more generic
solution?

Thanks


If you look at std::queue<>, you'll see that the container type to use
is a template parameter, defaulting to std::deque<T>. There is a
constructor for queue<T, Container> that takes a const Container& as a
parameter. I'm not sure it's particularly generic.

For the generic STL containers:

try:

vector<int> a;
deque<int> b(a.begin(), a.end());
note: replace deque with whatever the standard container is.

For adapters (stack, queue, priority_queue), try:

vector<int> a;
queue<int> b(queue<int>::container_type(a.begin(), a.end());

or a generic:

// disclaimer -- typed off the top of my head!
template<typename Container>
queue<typename cont::value_type>
make_queue(const Container& cont)
{
typedef typename queue<typedef typename cont::value_type> ct;
return queue<value_type>(ct(cont.begin(), cont.end()));
}

You can probably adapt it to stacks and priority_queues as well.
Aug 3 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.