Alcott
Alcott

Reputation: 18585

arithmetic operation on list::iterator?

I got a list like this:

list<float> l;

And I know there are 10 elements in l, I want to take first 7 elements from l and assign them to a vector, so I tried to do it like this:

vector<float> v(l.begin(), l.begin()+7);

The code above can't compile, later I found out that, list doesn't support random access while vector does, so list::iterator doesn't support arithmetic operation?

If so, How could I finish the job mentioned above?

Upvotes: 1

Views: 573

Answers (1)

Zang MingJie
Zang MingJie

Reputation: 5275

Use copy_n:

v.resize(7);
copy_n(l.begin(), 7, v.begin());

Upvotes: 4

Related Questions