mardi 31 mai 2016

Standard library function to create array of indices whose corresponding value is a given number

I've got a C-style array called board that contains some char's. I'm trying to create a std::array or std::vector (either would be fine, although std::array would be preferable) to store all the indices of board that are a certain value (in my case, 0).
This code I wrote is functional and works well:

std::vector<int> zeroes;
zeroes.reserve(16); //board has 16 elements, so zeroes.size() will never be larger than 16.
for (int i = 0; i < 16; ++i)
{
    if (board[i] == 0)
    {
        zeroes.push_back(i);
    }
}

However, from past experience, whenever a std function exists that could replace part of my code, it is turser and hence stylistically preferred and also faster. My function seems like a fairly basic operation - I know there is a standard function* to access the index of an array that contains a value when that value only occurs once** in the array. So, is there a standard function to create an array of the indices that contain a value, assuming that more than one such index exists?
Thanks a lot!


* Technically, two nested function calls: int x = std::distance(board, std::find(board, board + 16, 0));. See the accepted answer here.
** Well, it still works if more than one index with the desired value is present, but it returns only the first such index, which isn't very useful in my context.

Aucun commentaire:

Enregistrer un commentaire