Skip to the content of the web site.

Primitive arrays

So far, we have always discussed iterators, because that is what is used with most containers in the standard library. It is also how you can extend your classes so that they, too, can be worked on by these algorithms. However, this seems to leave more primitive arrays behind. Fortunately, this is not the case.

You may recall that we can walk through an array as follows:

    double data[10]{ 0.3, 0.6, 1.7, 0.3, 0.9, 0.2, 1.9, 1.3, 0.4, 0.2 };

    for ( double *ptr{ data }; ptr < data + 10; ++ptr ) {
        std::cout << *ptr << " " << std::endl;
    }

The local array data occupies 40 bytes, and the value of data is the address of the first byte of that range.

The loop variable ptr is a pointer to a double, and it is initialized with the address of data.

The address data + 10 is the address of data[10], so (data + 10) == &data[10]. You will note that data is the first entry, so similar to begin(); and data + 10 is one beyond the last entry, so similar to end().

Consequently, there is no reason we should not be able to sort an array as follows:

    // This was declared above...
    // double data[10]{ 0.3, 0.6, 1.7, 0.3, 0.9, 0.2, 1.9, 1.3, 0.4, 0.2 };

    std::sort( data, data + 10 );

    for ( double *ptr{ data }; ptr < data + 10; ++ptr ) {
        std::cout << *ptr << " " << std::endl;
    }

Similarly, you could perform a binary search on a subarray of the full array:

    // Search from data[2] to data[6] inclusive
    //   - 1.3 is not found...
    auto item{ std::lower_bound( data + 2, data + 7, 1.3 ) };

    if ( item == (data + 7) ) {
	std::cout << "1.3 was not found on the given range" << std::endl;
    } else {
	std::cout << "1.3 was found at" << (item - data) << std::endl;
    }

    // Search from data[2] to data[8] inclusive
    //   - 1.3 is found...
    item = std::lower_bound( data + 2, data + 9, 1.3 );

    if ( item == (data + 9) ) {
	std::cout << "1.3 was not found on the given range" << std::endl;
    } else {
	std::cout << "1.3 was found at " << (item - data) << std::endl;
    }

    return 0;
}