The following sample shows how to define and use a checked array iterator.
If the destination is not large enough to hold all the elements being copied, such as would be the case if you changed the line:
copy(a, a + 5, checked_array_iterator<int*>(b, 5));
to
copy(a, a + 5, checked_array_iterator<int*>(b, 4));
A runtime error will occur.
// checked_array_iterator_overview.cpp
// compile with: /EHsc
#include <algorithm>
#include <iostream>
using namespace std;
using namespace stdext;
int main() {
int a[]={0, 1, 2, 3, 4};
int b[5];
copy(a, a + 5, checked_array_iterator<int*>(b, 5));
cout << "(";
for (int i = 0 ; i < 5 ; i++)
cout << " " << b[i];
cout << " )" << endl;
// constructor example
checked_array_iterator<int*> checked_out_iter(b, 5);
copy(a, a + 5, checked_out_iter);
cout << "(";
for (int i = 0 ; i < 5 ; i++)
cout << " " << b[i];
cout << " )" << endl;
} Output
( 0 1 2 3 4 )
( 0 1 2 3 4 )
To avoid the need for the checked_array_iterator class when using Standard C++ Library algorithms, consider using a vector instead of a dynamically allocated array. The following example demonstrates how to do this.
// checked_array_iterator_2.cpp
// compile with: /EHsc
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
std::vector<int> v(10);
int *arr = new int[10];
for (int i = 0; i < 10; ++i)
{
v[i] = i;
arr[i] = i;
}
// std::copy(v.begin(), v.end(), arr); will result in
// warning C4996. To avoid this warning while using int *,
// use the Microsoft extension checked_array_iterator.
std::copy(v.begin(), v.end(),
stdext::checked_array_iterator<int *>(arr, 10));
// Instead of using stdext::checked_array_iterator and int *,
// consider using std::vector to encapsulate the array. This will
// result in no warnings, and the code will be portable.
std::vector<int> arr2(10); // Similar to int *arr = new int[10];
std::copy(v.begin(), v.end(), arr2.begin());
for (int j = 0; j < arr2.size(); ++j)
{
cout << " " << arr2[j];
}
cout << endl;
return 0;
} Output
0 1 2 3 4 5 6 7 8 9