Home > Blockchain >  Understanding vector::assign example on cplusplus
Understanding vector::assign example on cplusplus

Time:10-30

I am confused about the following code and what it does:

first.assign (7,100);             // 7 ints with a value of 100

std::vector<int>::iterator it;
it=first.begin() 1;

second.assign (it,first.end()-1); // the 5 central values of first

I don't understand the second.assign statement. I would assume it assigns 100 elements in second with a value of 100. Why is the size of second 5?

CodePudding user response:

In the example code

it = vec.begin() 1 meaning 2nd element

And

second.assign (it,first.end()-1);
                       ^^^^^^^^^^

One past the last element. it has skipped the first and last elements and hence you have 7-2=5 elements in the last assignment.

CodePudding user response:

There are 2 overloads of assign (3 in C 11).

  • First assign uses the new contents are n elements, each initialized to a copy of val.
  • 2nd assign uses the new contents are elements constructed from each of the elements in the range between first and last, in the same order.

Therefore the 2nd assign copies first from the 2nd element to the penultimate element.

  • Related