jeudi 29 avril 2021

How does the C++ algorithm library check the range of the output and not create segfaults when it is smaller than the range of the input?

I was just curious how some of the C++ algorithms check the range of the result/output container when you only provide the range of the input? For example, for the following code

#include <iostream>
#include <algorithm>

int main()
{
  std::vector<int> a = {4, 2, 1, 7};
  std::vector<int> b = {1, 2};
  
  std::copy(a.begin(), a.end(), b.begin());
  for(auto val : b)
    std::cout << val << std::endl;
}

with the output:

4
2

I don't understand how the algorithm knows that the capacity of the output container b is 2. I would have expected it assumes just the same range as the input container and therefore generates some kind of segmentation fault.

Aucun commentaire:

Enregistrer un commentaire