inline bool FoundInVector(std::vector<int> * p, int num){
int len = (*p).size();
for (int i=0; i < len; i++)
if (num == (*p)[i]) return true;
return false;
}
it compiles but i wonder if (*p) is correct.
inline bool FoundInVector(std::vector<int> * p, int num){
int len = (*p).size();
for (int i=0; i < len; i++)
if (num == (*p)[i]) return true;
return false;
}
it compiles but i wonder if (*p) is correct.
Yep, that's correct.
However, I'd write that function like this:
template<typename Element> //Templated for flexibility.
bool Exists(std::vector<Type> &container, const Type &valueToFind) //Pass the container by reference, not by pointer, unless the parameter is optional.
{
for(const Element &element : container) //Range-for for speed and safety.
{
if(element == valueToFind)
return true;
}
return false;
}
@Servant:
I think you also want to replace "Element" by "Type" (Type is now undefined), and pass the vector as a const as well. This then becomes
template<typename Type>
bool Exists(const std::vector<Type> &container, const Type &valueToFind)
{
for(const Type &element : container) //Range-for for speed and safety.
{
if(element == valueToFind) return true;
}
return false;
}
@WiredCat
"int *p" is a pointer to integer, so "std::vector<int> * p" is a pointer to a vector (changing the base type has no influence on the meaning of "*").
If "p" is a pointer to a vector, then "*p" is the vector itself. You can add parentheses for clarity, giving "(*p)". You can index a vector. Since "(*p)" is a vector, you can index "(*p)", leading to "(*p)" like you wrote.
Perhaps it looks weird to you , since you mostly see "p->something", but this is actually a simpler-to-write version of "(*p).something".
There is also an STL function "find" http://en.cppreference.com/w/cpp/algorithm/find but for this case, it is probably simpler to just write the implementation by hand.
If this isn't something you do often then you could just use std::find instead of writing a function:
#include <algorithm>
bool found = std::find(vec.begin(), vec.end(), val) != vec.end();
If this isn't something you do often then you could just use std::find instead of writing a function:
#include <algorithm> bool found = std::find(vec.begin(), vec.end(), val) != vec.end();
I think I prefer that approach (while holding onto the return value), it actually lets you do something if you find it without really doing more than necessary to check for it's existence.
@Servant:
I think you also want to replace "Element" by "Type" (Type is now undefined), and pass the vector as a const as well.
Oops, I switched from 'Type' to 'Element' (more descriptive) but missed one. Thanks for the catch!
'container' totally should be const. :ph34r: