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).

[sourcecode language='cpp']
#include
#include

#include
#include

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;
}
[/sourcecode]

This entry was posted in Uncategorized. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. Posted June 18, 2009 at 11:01 am | Permalink

    Instead of “copy” it’s better to use vector::assign.

  2. kobiwan
    Posted June 20, 2009 at 8:01 am | Permalink

    Instead of ensuring the size of the destincaiton container you can use back_inserter()

    list lis;
    copy(vec.begin(),vec.end(),back_inserter(lis));

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>