Click here to Skip to main content
15,914,608 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello everyone. i have problem passing arrays as parameters to function. recently i have learned vectors and i tried to use vectors to solve this problem but it didnt work too.
the error is in third line from end when calling function.

What I have tried:

C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;


bool existsHigher(std::vector<int> arr, int n)
{
	for (int i = 0; i < arr.size(); i++)
	{
		if (arr[i] >= n)
		{
			return true;
		}
	}

	return false;
}

int main() {

existsHigher([2,3,4,5,6],3) ;

return 0;
}
Posted
Updated 12-Sep-19 1:23am
v2
Comments
jeron1 10-Sep-19 10:33am    
You are calling a method with [23456] as a parameter, that parameter is not a vector, your compiler is probably complaining on this line. You have to create the vector, then pass it to the method, usually passed by reference. something like;
int main()
{
std::vector<int> blah {2,3,4,5,6};

existsHigher(blah, 3);

return 0;
}

where the method looks something like this

bool existsHigher(std::vector<int>& arr, int n)
{
for (int i = 0; i < arr.size(); i++)
{
// do your stuff
}
}
Many people though, may use iterators to access the elements of the vector.

Your main problem is here:
C++
existsHigher([2,3,4,5,6],3);
The expression [2,3,4,5,6] does not define a vector<int>. If you want a temporary vector of int, you'd need to use
C++
existsHigher(vector<int>{2,3,4,5,6},3);
. That's C++11, though, so if your compiler is still using C++98, you have to construct the vector first. e.g:
C++
vector<int> myvect;
for(int i = 2; i <= 7; ++i)
    myvect.push_back(i);
 
Share this answer
 
There is an 'algorithm' (any_of) for that.
Try:
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
  std::vector<int> v{2,3,4,5,6};
  bool exist_higher =  std::any_of( v.begin(), v.end(), [] (int x) {return x>= 3;});
  std::cout << "exist_higher = " << std::boolalpha << exist_higher << std::endl;
}
 
Share this answer
 
Comments
Stefan_Lang 12-Sep-19 10:58am    
Interesting. Somehow I must have missed that function. I was a about to suggest a similar solution, using std::find_if, but this is clearly better.
C++
// create a vector type for ease of use
typedef std::vector<int> vectorInteger;
//work with reference to avoid creating copies (best for perfomance)
bool existsHigher(const vectorInteger &data, int maximum)
{
  // use iterator
 for(vectorInteger::iterator it = myvector.begin(); it != myvector.end(); ++it)
  {
    if( it > maximum)
      return true;
  }
  return false;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900