How to find out if an item is present in a std::vector?
You can use std::find
from <algorithm>
:
#include <algorithm>
#include <vector>
vector<int> vec;
//can have other data types instead of int but must same datatype as item
std::find(vec.begin(), vec.end(), item) != vec.end()
This returns an iterator to the first element found. If not present, it returns an iterator to one-past-the-end. With your example:
#include <algorithm>
#include <vector>
if ( std::find(vec.begin(), vec.end(), item) != vec.end() )
do_this();
else
do_that();
check if a std::vector contains a certain object? [duplicate]
Checking if v
contains the element x
:
#include <algorithm>
if(std::find(v.begin(), v.end(), x) != v.end()) {
/* v contains x */
} else {
/* v does not contain x */
}
Checking if v
contains elements (is non-empty):
if(!v.empty()){
/* v is non-empty */
} else {
/* v is empty */
}
In C++ check if std::vectorstring contains a certain value [duplicate]
You can use std::find
as follows:
if (std::find(v.begin(), v.end(), "abc") != v.end())
{
// Element in vector.
}
To be able to use std::find
: include <algorithm>
.
How to check if **any** element exists in an `std::vector` at a given index
You cannot do it if you don't do some work on your data-structure, for every element in vector is initialized.
The simplist and quickest way I think, is to store a std::vector<bool>
of the same size to store whether a element is not only initialized, but "modified" later as well.
If you worry that you may forget to set the other vector, bind them together:
std::vector<std::pair<std::pair<int, int>, bool>> a;
If you still think this is too ugly, you may have to implement your own simple optional
How to check if a c++ vector already contains and element with a specific value (in this case a struct)?
Two things are wrong here (there may be others but these are the relevant ones).
First, there is no equality operator in your structure that would allow find
to compare items. This can be added with something like:
struct position {
int column;
int row;
bool operator==(const position &other) const {
return column == other.column && row == other.row;
}
};
Second, the sense of your comparison is wrong. The find
will return end
if the item is not found, so your if
section should be:
if (std::find(positions.begin(), positions.end(), pos) == positions.end()) {
positions.push_back(pos);
} else {
std::cout << "Value is already present" << std::endl;
}
For completeness, here's a full program that shows what happens when you try to add a non-existant element three times:
#include <iostream>
#include <vector>
#include <algorithm>
struct position {
int column;
int row;
bool operator==(const position &other) const {
return column == other.column && row == other.row;
}
};
int main () {
std::vector<position> vec = {};
position pos = {2,1};
for (int i = 0; i < 3; ++i) {
if (std::find(vec.begin(), vec.end(), pos) == vec.end()) {
std::cout << "Adding value" << std::endl;
vec.push_back(pos);
} else {
std::cout << "Value is already present" << std::endl;
}
}
return 0;
}
From the ouput, you can see only the first one actually inserts:
Adding value
Value is already present
Value is already present
Checking if an item is already in a vector
You are assigning instead of comparing for equality here:
if(items = new_item) // assigns value of new_item to items
This kind of problem is easily avoided by using well tested standard library functions such as std::find
:
#include <algorithm> // for std::find
....
if (find(vector_.begin(), vector_.end(), newitem) == vector_.end())
vector_.push_back(newitem);
How do I check if a element is not present inside of a vector?
if (std::find(disliked.begin(), disliked.end(), words[i]) == disliked.end()) {
cout << words[i] << " ";
} else {
cout << "BLEEP" << " ";
}
If you replace std::vector<string> disliked(3);
with std::set<string> disliked;
it works faster.
std::set<string> disliked;
disliked.insert("Broccoli");
disliked.insert("Mushrooms");
disliked.insert("Fish");
//....
if (disliked.find(words[i]) == disliked.end()) {
cout << words[i] << " ";
} else {
cout << "BLEEP" << " ";
}
How to check the element is in the vector using std::lower_bound?
The !(*i < w)
is clearly wrong (or, at the very least, redundant) because, if the std::lower_bound()
search does not return vw.end()
, then the result of that test must be true. From cppreference:
Returns an iterator pointing to the first element in the range [first,
last) that is not less than (i.e. greater or equal to) value, or last
if no such element is found.
Here's a trivial test that shows it does not correctly determine whether or not a given value is in your vector:
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> vec = { 1,2,3,5,6,7,8,9,10 };
std::vector<int>::iterator i1 = std::lower_bound(vec.begin(), vec.end(), 3); // Present
if (i1 != vec.end() && !(*i1 < 3)) {
std::cout << "3 is present\n";
}
else {
std::cout << "3 is missing\n";
}
std::vector<int>::iterator i2 = std::lower_bound(vec.begin(), vec.end(), 4); // Missing
if (i2 != vec.end() && !(*i2 < 4)) {
std::cout << "4 is present\n";
}
else {
std::cout << "4 is missing\n";
}
return 0;
}
Output (clearly wrong):
3 is present
4 is present
However, changing the second test from the above !(*i < w)
form, to your !(w < *i)
works, as shown in the following modified code:
int main()
{
std::vector<int> vec = { 1,2,3,5,6,7,8,9,10 };
std::vector<int>::iterator i1 = std::lower_bound(vec.begin(), vec.end(), 3); // Present
if (i1 != vec.end() && !(3 < *i1)) {
std::cout << "3 is present\n";
}
else {
std::cout << "3 is missing\n";
}
std::vector<int>::iterator i2 = std::lower_bound(vec.begin(), vec.end(), 4); // Missing
if (i2 != vec.end() && !(4 < *i2)) {
std::cout << "4 is present\n";
}
else {
std::cout << "4 is missing\n";
}
return 0;
}
Output (correct):
3 is present
4 is missing
So, unless you have somehow inadvertently misrepresented the code from the book you quote (which I am not accusing you of doing), then its author should be contacted to point out their error.
c++ std::vector search for value
The C++ standard library has some abstract algorithms, which give C++ a kind of functional flavour, as I call it, which lets you concentrate more on the criteria of your search than on how you implement the search itself. This applies to a lot of other algorithms.
The algorithm you are looking for is std::find_if
, a simple linear search through an iterator range.
In C++11, you can use a lambda to express your criteria:
std::find_if(myObjList.begin(), myObjList.end(), [&](const myObj & o) {
return o.id == searchCriteria;
});
When not having C++11 available, you have to provide a predicate (function object (=functor) or function pointer) which returns true if the provided instance is the one you are looking for. Functors have the advantage that they can be parameterized, in your case you want to parameterize the functor with the ID you are looking for.
template<class TargetClass>
class HasId {
int _id;
public:
HasId(int id) : _id(id) {}
bool operator()(const TargetClass & o) const {
return o.id == _id;
}
}
std::find_if(myObjList.begin(), myObjList.end(), HasId<myObj>(searchCriteria));
This method returns an iterator pointing to the first element found which matches your criteria. If there is no such element, the end iterator is returned (which points past the end of the vector, not to the last element). So your function could look like this:
vector<myObj>::iterator it = std::find_if(...);
if(it == myObjList.end())
// handle error in any way
else
return *it;
Related Topics
What Platforms Have Something Other Than 8-Bit Char
What Do Single Quotes Do in C++ When Used on Multiple Characters
How to Convert a Std::String to Int
Exotic Architectures the Standards Committees Care About
How to Figure Out the Parameter Type and Return Type of a Lambda
How to Add "-L" (Ell) Compiler Flag in Cmake
Meaning of Acronym Sso in the Context of Std::String
C++ Convert Hex String to Signed Integer
What Is Ownership of Resources or Pointers
Why Is My Power Operator (^) Not Working
Best Practices For Circular Shift (Rotate) Operations in C++
Check If a Class Has a Member Function of a Given Signature
Multicharacter Literal in C and C++
How to Set Multiple Conditions for a Loop
Finding Current Executable'S Path Without /Proc/Self/Exe
How to Get Enum Item Name from Its Value
Cout ≪≪ With Char* Argument Prints String, Not Pointer Value