I want to write a function that find an element present in an array by its index and returns a bool value. I have tried the below code :
enum NUMBERS
{
NUMBERS_ZERO,
NUMBERS_ONE,
NUMBERS_TWO,
NUMBERS_TOTAL,
};
std::array<std::string, NUMBERS_TOTAL> arrayList{ "abc", "pqr", "xyz" };
bool IsNumberAvailable(NUMBERS num)
{
if (num >= NUMBERS_TOTAL) // better approach
return false;
std::string name = arrayList[num];
// do something for name...
return true;
}
int main()
{
std::cout << "NUMBERS_ZERO : " << IsNumberAvailable(NUMBERS_ZERO) << "\n";
return 0;
}
I know in general, we find the element by value which can be solved by linear search or using STL std::find
, std::find_if
. But can anyone suggest to me how to achieve above scenario with a better approach i.e. finding the element by its index provided by the enum?
Aucun commentaire:
Enregistrer un commentaire