I want to start out by saying that I am really new to C and have not been able to find an answer to this question yet. It is for a school project and my teacher has not been very helpful.
I wanted to know how to use a switch statement with a multidimensional array. For example, say we have this array:
int arr[3][5] = {{1, 3, 1, 1, 2}, {1, 2, 4, 5, 6}, {6, 3, 4, 3, 5}};
How would I use a switch statement in order to locate the individual rows and check for certain criteria within them?
Edit: I think it is best if I clarify a bit. I want to check the conditions of the elements in each row, not just the individual elements themselves.
So I may check if there are 1's in the first subarray, check for 3's in the second subarray, and check for 4's in the last subarray.
CodePudding user response:
Short answer; you wouldn't. swtich is not the right tool for the job. You are searching for some criteria right? In the absence of a specific criteria, lets say that you are interested in if the sub array contains a 1.
We can formulate this with a function:
bool contains_a_1(int arr[5]) {
return std::any_of( // This is an algorithm that will check if any of them
// match the predicate below
std::begin(arr), std::end(arr), // This is the range to check over
[](int v) { return v == 1; } // This is a simple lambda function that tells the
// algorithm what we are looking for.
);
Now we have a function that checks our condition. So now we need to check it, but how? If we want to check if any of the arrays in our array meet this condition, we have already seen a thing that can help us with this, std::any_of:
int arr[3][5] = {{1, 3, 1, 1, 2}, {1, 2, 4, 5, 6}, {6, 3, 4, 3, 5}};
bool there_is_a_one_somewhere = std::any_of(std::begin(arr), std::end(arr), contains_a_1);
Or maybe you want this bool for each value in the array:
std::array<bool, 3> contains_1;
std::transform(std::begin(arr), std::end(arr), std::begin(contains_1), contains_a_1);
Or maybe you want to do something else? Well, there is probably an algorithm for that! You just need to find the right one here in <algorithm>.
CodePudding user response:
So I may check if there are 1's in the first subarray, check for 3's in the second subarray, and check for 4's in the last subarray.
You can use for loops to iterate over the rows and std::find to check whether the subarray contains a particular element or not as shown below:
#include <iostream>
#include <algorithm>
int main()
{
int arr[3][5] = {{1, 3, 1, 1, 2}, {1, 2, 4, 5, 6}, {6, 3, 4, 3, 5}};
//iterate over rows
for(auto &row: arr)
{
bool exists = std::find(std::begin(row), std::end(row), 1) != std::end(row); //check if 1 is present in the current row
std::cout<<"element "<<(exists?"is present":"not present")<<std::endl;
}
}
In the above code, we have checked whether 1 is present in the subarray or not. Similarly you can check for other values like 3 or 4.
