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]
2 Comments
Instead of “copy” it’s better to use vector::assign.
Instead of ensuring the size of the destincaiton container you can use back_inserter()
list lis;
copy(vec.begin(),vec.end(),back_inserter(lis));