Search code examples
c++arraysconditional-statementsevaluation

c++ array evaluation


Is there a way to "bulk evaluate" the contents of an array in C++? For example, let int numbers[10]={23,42,12,42,53,10,0,0,0,0}. Is there a way to loop through each element in the array and check whether the element meets a specified condition?

In short, I'd like to be able to do something like:

if(every element in the array meets arbitrary condition)
do this

or

if(array element from m to array element n==something)
do this

For small arrays, I know I could use something like: if(numbers[0]==blabla) && if(numbers[n]==blabla), then do this, but obviously this is not a realistic solution when it comes to evaluating very large arrays.


Solution

  • " if(every element in the array meets arbitrary condition) do this " with STL:

    bool IsOdd (int i) 
    {
      return ((i%2)==1);
    }
      //...
    {
      vector<int> myvector;
      vector<int>::iterator it;
    
      myvector.push_back(2);
      myvector.push_back(4);
      myvector.push_back(6);
      myvector.push_back(8);
    
      it = find_if (myvector.begin(), myvector.end(), IsOdd);
      if (it == myvector.end())
        cout<< "No Odd numbers";
      }
    

    " if(every element in the array meets arbitrary condition) do this " without STL

    numbers[10]={2,4,6,8,10,12,14,16,18,20}
    bool oddExist=false;
    for (int i =0;i<10;++i)
      {
         if ( numbers[i]%2 )
         {                      //added
           oddExist=true;     
           break;               //added  for efficiency, was not in 
         }                      //        first post. 
      }
          if (!oddExist)
            cout<< "No Odd numbers";
    

    "if(array element from m to array element n==something) do this" with STL

    void printNumber (int i) 
    {
      cout  << i;
    }
    
      // ... 
    
      vector<int> myvector;
      myvector.push_back(10);
      myvector.push_back(20);
      myvector.push_back(30);
      myvector.push_back(40);
    
      for_each (myvector.begin(), myvector.end(), printNumber);
    

    "if(array element from m to array element n==something) do this" without STL

    numbers[10]={2,4,6,8,10,12,14,16,18,20}
    
    for (int i =0;i<10;++i)
       cout << numbers[i];