Containers: assignment, construction from

Anjul anjul@cyberspace.org
Fri Feb 18 07:50:00 GMT 2000


Is there a better list to post this question to?

Hi,

Thanks for the email. My question is different.

I want to construct a vector of ints from a list of ints. I.e. if the list
contains the integers: 1,2,3,4,5, I want a vector of 5 ints and I want it to
contain 1,2,3,4,5.

One way to do this is:

    list<int> mylist;
    mylist.push_back(1);
    mylist.push_back(2);
    mylist.push_back(3);
    mylist.push_back(4);
    mylist.push_back(5);
    vector<int> myvec(mylist.size());
    copy(mylist.begin(),mylist.end(),myvec.begin());

What I would like to do is:

    list<int> mylist;
    mylist.push_back(1);
    mylist.push_back(2);
    mylist.push_back(3);
    mylist.push_back(4);
    mylist.push_back(5);
    vector<int> myvec(mylist); // construct vector from list

The reason I prefer this is to avoid needless construction of blank elements in
the first case. Yes, I could create a vector of size 0 and use a back_inserter
as an argument to the copy command, but then, I may run into repeated "reallocs"
(extensions), some of which may necessiate copying the entire vector. Since I
know the number of elements I need, and since I have the elements available, I
want to avoid "reallocs" as also construction of blank elements.

Is there an efficient way of constructing a container from another? I guess what
I am asking for is reasonable. Say, I had a list of 1000,000 elements. I would
not want the vector to be initialized with 1000,000 blank elements first only to
have the 1000,000 elements from the list copied over them. Also, I would not
want the vector to be extended upto 800,000 only to run out of contiguous space,
and have the 800,000 elements copied to a new location by the reallocation.

By the way, the reason I need to copy from one container into a vector is to
sort. In my real-life problem, I have a map that I want sorted on the 'value'.
The only way I can think of doing it is to copy the map elements into a vector,
and then sort the vector. Is there a better way?

Thanks,
Anjul.

"Morrow, Mal" wrote:

> Hi Anjul -
>
> Personal email, because it's a code-based answer, nothing to do with gcc!
>
> If you're trying to create a vector of lists of int and assign to it, you
> need
> *
>
> vector < list < int> > v(10);   // 10 being a magic number dimensioning the
> vector
> v[0] = m;
> // .. and assign v[1] thru v[9] in the same manner
>
> *
> If you're trying to create a vector of the size of the entry in the list of
> int, you need
> *
>
> vector < list < int > > v(*m.rbegin());
> // ... now you can assign lists of int to the vector in the above manner.
> //  Note you have only 3 elements in vector v.
>
> *
> gcc works just fiiiiine!
>
> Mal Malachy Morrow



More information about the Gcc mailing list