How to create a list from vector?

The following sample demonstrates, how to convert a vector to list(in other words, how to create a list from vector).

The simplest way is to iterate through all elements of container and add it to the destination container. the following snippet make use of std::copy function to copy contents from source to destination container. The destination and source iterator will be automatically incremented inside on each iteration. Before using this function you will have to ensure the destination container has enough room to hold the source elements. For that it may necessary to resize the container. See the snippet below. Note that you can use this technique with anu containers which supports iterator(actually that’s the purpose of std::copy function).

#include <iostream>
#include
	<list>
#include <vector>
#include <algorithm>

using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
	vector vec;
	// prepare the vector
	for (int i = 0; i < 10; i++ )
	{
		vec.push_back( i+1 );
	}

	// construct list with the size of vector
	list lis(vec.size());

	// iterate and copy the content to list
	copy( vec.begin(), vec.end(), lis.begin());

	// output the content to console
	copy( lis.begin(), lis.end(), ostream_iterator(cout, "\t" ) );

	return 0;
}

View CommentsHow to create a list from vector?

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

blog comments powered by Disqus