std::vector has no contains member. Search it with std::ranges::find and compare the result with end(): std::ranges::find(v, x) != v.end() is true when x is in v. Before C++20 write std::find(v.begin(), v.end(), x) != v.end(). For a condition, use std::ranges::any_of with a lambda.
Every container answer in C++ goes through an iterator: find returns one pointing at the first match, or end() when there is none, and you compare against end() to get a bool. That search walks the vector element by element, which is right for a one-off check and wrong for thousands of them. The sections below cover find for plain values and strings, structs matched by a member or any condition, binary_search on a sorted vector, a set for repeated lookups, and the two cases where == gives the wrong answer, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1std::ranges::find and std::findRecommended
std::ranges::find(v, x) (C++20, in <algorithm>) takes the whole vector; the older std::find takes a begin and an end iterator. Both compare each element with == from the front and return an iterator to the first match, so the same call answers "is it there?" and "where is it?": std::distance(v.begin(), it) is the index. A four-line contains template wraps the comparison with end() once, for any container.
#include <algorithm> #include <iostream> #include <iterator> #include <string> #include <vector> // A reusable contains() for any container: true if value is in range template <typename Range, typename T> bool contains(const Range& range, const T& value) { return std::ranges::find(range, value) != std::ranges::end(range); } int main() { std::vector<int> ids = {7, 42, 13, 42, 99}; std::cout << std::boolalpha; // std::ranges::find returns an iterator to the first match, or end() auto it = std::ranges::find(ids, 42); if (it != ids.end()) { // The index is the distance from begin() to the match std::cout << "42 found at index " << std::distance(ids.begin(), it) << '\n'; } // Not found: the iterator equals end(), which must never be dereferenced if (std::ranges::find(ids, 5) == ids.end()) { std::cout << "5 not found\n"; } // The pre-C++20 spelling takes two iterators; same answer bool has13 = std::find(ids.begin(), ids.end(), 13) != ids.end(); std::cout << "has 13: " << has13 << '\n'; // count() answers "how many", but it always scans the whole vector std::cout << "42 appears " << std::ranges::count(ids, 42) << " times\n"; // Strings: a literal is compared with each std::string by content std::vector<std::string> langs = {"go", "rust", "zig"}; std::cout << "has rust: " << contains(langs, "rust") << '\n'; std::cout << "has Rust: " << contains(langs, "Rust") << '\n'; }
Output
42 appears twice, and find stops at the first one: 42 found at index 1. A missing value gives end(), hence 5 not found; dereferencing that iterator is undefined behaviour, so always compare before you use it. std::ranges::count reports 42 appears 2 times, but it reads every element even when the first one matches, so count(...) > 0 is a slower contains. A string literal compares with each std::string by content, and case-sensitively: has rust: true, has Rust: false. C++23 adds std::ranges::contains(v, x), which returns the bool directly; this page compiles as C++20, hence the helper.
2Structs: operator==, projections, find_if and any_of
find on a vector of your own type needs an operator== for it, and without one the call does not compile. In C++20 one defaulted line writes it for you. Usually, though, you want to match one field, not a whole object: give std::ranges::find a projection, a pointer to the member to compare, or use find_if with a lambda for any condition. When you only need yes or no, any_of and none_of say it directly.
#include <algorithm> #include <iostream> #include <string> #include <vector> struct Person { std::string name; int age; // C++20: the compiler writes == for you, comparing every member in order bool operator==(const Person&) const = default; }; int main() { std::vector<Person> people = {{"Ada", 36}, {"Linus", 54}, {"Grace", 85}}; std::cout << std::boolalpha; // A whole object: std::ranges::find uses Person's operator== bool hasLinus = std::ranges::find(people, Person{"Linus", 54}) != people.end(); std::cout << "Linus, 54: " << hasLinus << '\n'; bool hasLinus30 = std::ranges::find(people, Person{"Linus", 30}) != people.end(); std::cout << "Linus, 30: " << hasLinus30 << '\n'; // One member: the projection &Person::name compares p.name with "Grace" auto it = std::ranges::find(people, "Grace", &Person::name); if (it != people.end()) { std::cout << "Grace is " << it->age << '\n'; } // Any condition: find_if with a lambda gives you the first match auto first = std::ranges::find_if(people, [](const Person& p) { return p.age > 50; }); std::cout << "first over 50: " << first->name << '\n'; // Just yes or no: any_of / none_of stop at the first match too auto isTeen = [](const Person& p) { return p.age < 20; }; std::cout << "any teen: " << std::ranges::any_of(people, isTeen) << '\n'; std::cout << "no teens: " << std::ranges::none_of(people, isTeen) << '\n'; }
Output
The defaulted == compares name and then age, so Linus, 54: true but Linus, 30: false. The projection &Person::name compares only the name and hands back the whole element, which is how it prints Grace is 85. find_if returns the first element the lambda accepts, first over 50: Linus, and it was safe to use first->name only because a match is known to exist here; check against end() in real code. any_of and none_of give any teen: false and no teens: true. The same lambda approach handles a case-insensitive search: compare lowercased copies, as in converting a string to lowercase.
3Sorted vectors: binary_search and lower_bound
find is a linear scan: a miss reads every element. If the vector is sorted, std::ranges::binary_search halves the range at each step instead. It only returns a bool; lower_bound runs the same search and returns an iterator to the first element not less than the value, which is the match when there is one and the right insertion point when there isn't. Both require sorted input: on an unsorted vector the answer is simply unreliable, with no error.
#include <algorithm> #include <iostream> #include <numeric> #include <vector> int main() { std::vector<int> v = {42, 7, 99, 13, 58}; std::cout << std::boolalpha; // Binary search needs sorted input: sort once, then search many times std::ranges::sort(v); std::cout << "has 58: " << std::ranges::binary_search(v, 58) << '\n'; std::cout << "has 50: " << std::ranges::binary_search(v, 50) << '\n'; // binary_search only says yes or no; lower_bound also gives the position auto it = std::ranges::lower_bound(v, 58); if (it != v.end() && *it == 58) { std::cout << "58 at index " << (it - v.begin()) << '\n'; } // Missing? lower_bound is where it belongs, so insert keeps v sorted auto pos = std::ranges::lower_bound(v, 50); if (pos == v.end() || *pos != 50) { v.insert(pos, 50); } for (std::size_t i = 0; i < v.size(); ++i) { std::cout << (i ? ", " : "") << v[i]; } std::cout << '\n'; // The cost, counted: look for the last of a million sorted numbers std::vector<int> big(1'000'000); std::iota(big.begin(), big.end(), 0); long linear = 0, binary = 0; std::ranges::find_if(big, [&](int x) { ++linear; return x == 999'999; }); std::ranges::binary_search(big, 999'999, [&](int a, int b) { ++binary; return a < b; }); std::cout << "find: " << linear << " comparisons\n"; std::cout << "binary_search: " << binary << " comparisons\n"; }
Output
After sorting, has 58: true and has 50: false, and lower_bound locates 58 at index 3. For the missing 50 it points at 58, so insert there keeps the vector sorted: 7, 13, 42, 50, 58, 99. The counted search shows the difference in work: finding the last of a million numbers took find: 1000000 comparisons against binary_search: 21 comparisons. Sorting costs more than one linear search, so this pays off when you sort once and search many times.
4Many lookups: copy into a set
When membership checks are the main thing you do with the data, a vector is the wrong container. Build a std::unordered_set from it once (a hash table, roughly constant time per lookup) or a std::set (sorted, logarithmic), and ask contains, a real member function on sets and maps since C++20. A set also drops duplicates, which is often what you wanted anyway.
#include <iostream> #include <set> #include <string> #include <unordered_set> #include <vector> int main() { std::vector<std::string> banned = {"spam", "scam", "phish", "spam"}; std::cout << std::boolalpha; // Build the set once from the vector; duplicates collapse std::unordered_set<std::string> lookup(banned.begin(), banned.end()); std::cout << banned.size() << " in the vector, " << lookup.size() << " in the set\n"; // Then every check is a hash lookup, not a scan (contains is C++20) for (const char* word : {"hello", "scam", "phish", "Spam"}) { std::cout << word << ": " << lookup.contains(word) << '\n'; } // std::set keeps the values sorted, so it also answers range questions std::set<int> seen = {42, 7, 99, 13}; std::cout << "seen 13: " << seen.contains(13) << '\n'; std::cout << "smallest >= 50: " << *seen.lower_bound(50) << '\n'; // Before C++20, use count(): a set holds each value at most once std::cout << "count(7): " << seen.count(7) << '\n'; }
Output
The duplicate "spam" collapses: 4 in the vector, 3 in the set. Each check after that is a hash lookup, and it is as case-sensitive as ==: scam: true but Spam: false. std::set keeps its values ordered, so besides seen 13: true it can answer smallest >= 50: 99. On older compilers count(7) does the same job, since a set holds a value at most once: count(7): 1. Building the set costs about as much as one pass over the vector, so for one or two checks, find is still the simpler choice.
5When == gives the wrong answer: doubles and const char*
find is exactly as good as the element type's ==, and two common element types have a misleading one. A double computed by arithmetic is rarely bit-for-bit equal to the literal you search for. And a std::vector<const char*> holds pointers, so == asks "is this the same array?", not "is this the same text?". Both compile and run without a warning.
#include <algorithm> #include <cmath> #include <iostream> #include <string_view> #include <vector> int main() { std::cout << std::boolalpha; // 1. Doubles: 0.1 + 0.2 is not exactly 0.3, so == finds nothing std::vector<double> totals = {0.1 + 0.2, 1.5}; bool exact = std::ranges::find(totals, 0.3) != totals.end(); std::cout << "exact 0.3: " << exact << '\n'; // Compare with a tolerance instead auto near = [](double target) { return [target](double x) { return std::abs(x - target) < 1e-9; }; }; bool close = std::ranges::any_of(totals, near(0.3)); std::cout << "near 0.3: " << close << '\n'; // 2. A vector of const char* compares pointers, not text std::vector<const char*> names = {"go", "rust"}; char typed[] = "rust"; // same text, different array bool byPointer = std::ranges::find(names, typed) != names.end(); std::cout << "by pointer: " << byPointer << '\n'; // Compare the characters: wrap each side in a std::string_view bool byText = std::ranges::any_of(names, [&](const char* n) { return std::string_view(n) == typed; }); std::cout << "by text: " << byText << '\n'; }
Output
0.1 + 0.2 is stored as a value a hair above 0.3, so the exact search prints exact 0.3: false; any_of with a tolerance gives near 0.3: true. Pick a tolerance that suits the size of your numbers; see comparing floating-point numbers. The pointer search prints by pointer: false although both spell rust, because typed is a separate array; comparing through std::string_view compares the characters and gives by text: true. Storing std::string instead of const char* avoids the problem entirely.
6Which should you use?
| Method | Cost per check | Gives | Best for |
|---|---|---|---|
| std::ranges::find(v, x) | Linear | Iterator (index) | A value in an unsorted vector, one-off checks |
| std::find(begin, end, x) | Linear | Iterator (index) | The same, before C++20 |
| find(v, x, &T::member) | Linear | Iterator (element) | Structs matched by one field |
| find_if / any_of | Linear | Iterator / bool | Any condition, tolerances, custom compares |
| std::ranges::count(v, x) | Always full scan | Number of matches | Counting, not membership |
| binary_search / lower_bound | Logarithmic | bool / iterator | Sorted vectors searched many times |
| unordered_set::contains | About constant | bool | Many membership checks |
Frequently asked questions
Does std::vector have a contains method?
No. std::set, std::unordered_set and the maps got a contains member in C++20, but std::vector did not. C++23 adds the free function std::ranges::contains(v, x), which returns a bool; on C++20 and earlier write std::ranges::find(v, x) != v.end() or std::find(v.begin(), v.end(), x) != v.end(), or wrap that in a small contains template.
How do I get the index of an element in a vector?
Find it, check it, then measure the distance from the start: auto it = std::ranges::find(v, x); if (it != v.end()) { auto i = std::distance(v.begin(), it); }. For a vector, it - v.begin() gives the same number. Never compute the index before checking against end(): a missing value would give v.size(), which is not a valid index.
Why does std::find not compile for my struct?
std::find compares elements with ==, and a struct has no operator== unless you write one. In C++20 add bool operator==(const Person&) const = default; to compare every member. If you only want to match one field, skip == and use a projection, std::ranges::find(people, "Grace", &Person::name), or std::find_if with a lambda.
Is std::find or std::count faster for checking if a vector contains a value?
std::find. It stops at the first match, while std::count always reads the whole vector to count every match. When the value is missing both read everything. If you check the same vector many times, sort it and use std::ranges::binary_search, or copy it into a std::unordered_set and call contains.
How do I check if a vector contains all elements of another vector?
For a few elements, test each one: std::ranges::all_of(needles, [&](int x) { return std::ranges::find(hay, x) != hay.end(); }). For larger vectors, sort both and call std::ranges::includes(hay, needles), which walks them once, or put hay into a std::unordered_set and check each needle with contains.
Can I use std::binary_search on an unsorted vector?
No. std::binary_search and std::lower_bound require the range to be sorted by the same ordering you search with. On unsorted data they do not report an error, they just return an unreliable answer. Sort first with std::ranges::sort(v), or use std::ranges::find, which works on any order.