Search code examples
c++11stdarray

How to get the index of an item in std::array without using a loop?


How can I get the index an item in a std::array without running any loops?

#include <iostream>
#include <array>

std::array<int, 10> some_array = { 89, 56, 78, 96, 4, 34, 77, 2, 48, 3};

unsigned int GetIndexOfValue(unsigned int some_value) {
    // How get the index of some_value here without running a loop?
}

int main() {
    unsigned int some_value = 34;
    std::cout << "The index of value passed is " << GetIndexOfValue(some_value) << std::endl;
}

Is it possible to do it using std::find?


Solution

  • You can use the functionality from the <algorithm> header, so you can avoid writing a raw loop, like this:

    unsigned int GetIndexOfValue(unsigned int some_value) {
        return std::distance(std::begin(some_array),
                 std::find(std::begin(some_array), std::end(some_array), some_value));
    }
    

    Here's a demo.