Iterate over the first N elements of C ++ 11 std :: array

I am using std :: array (C ++ 11). I prefer to use std :: array because I want the size to be fixed at compile time (as opposed to runtime). In any case, I can iterate over the first N elements ONLY. eg:

std::array<int,6> myArray = {0,0,0,0,0,0};
std::find_if(myArray.begin(), myArray.begin() + 4, [](int x){return (x%2==1);});

This is not a good example because find_if returns an iterator labeled FIRST with an odd number, but you get the idea (I just want to consider the first N, in this case N = 4, elements of my std :: array).

Note. There are questions similar to this, but the answer always involves using a different container (a vector or valarray, which I don't want). As I said, I want the size of the container to be fixed at compile time).

Thanks in advance!

+4
source share
2 answers

From the way you presented your question, I assume that you say "iteration", but actually means "work with the algorithm."

The behavior does not apply to the container, but to the type of container iterator.

std::array::iterator_typesatisfies RandomAccessIterator , are the same as std::vectorand std::deque.

This means that given

std::array<int,6> myArray = {0,0,0,0,0,0};

and

auto end = myArray.begin() // ...

you can add a number to it n...

auto end = myArray.begin() + 4;

... causes the iterator to move one element after the nth element in the array. Since this is the very definition for an iterator endfor a sequence,

std::find_if(myArray.begin(), myArray.begin() + 4, ... )

works just fine. A slightly more intuitive example:

#include <algorithm>
#include <array>
#include <iostream>

#define N 4

int main()
{
    std::array<char, 6> myArray = { 'a', 'b', 'c', 'd', 'e', 'f' };
    auto end = myArray.begin() + N;
    if ( std::find( myArray.begin(), end, 'd' ) != end )
    {
        std::cout << "Found.\n";
    }
    return 0;
}

This finds the 4th element in the array and prints "Found."

#define N 4 #define N 3, .

, , n. , N <= myArray.size() myArray.end(), .


:

+1

N a std::array, - :

#include <iostream>
#include <array>

int main() {
    constexpr const int N = 4;
    std::array<int, 6> arr{ 0, 1, 2, 3, 4, 5 };
    for (auto it = std::begin(arr); it != std::begin(arr) + N && it != std::end(arr); ++it)
        std::cout << *it << std::endl;
}
0

All Articles