有没有内置的函数告诉我,我的向量包含一个特定的元素或没有 例如:。
std::vector<string> v; v.push_back("abc"); v.push_back("xyz"); if (v.contains("abc")) // I am looking for one such feature, is there any // such function or i need to loop through whole vector?
it's in <algorithm> and called std::find.
<algorithm>
std::find
std::find().
std::find()
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>.
include <algorithm>
If your container only contains unique values, consider using std::set instead. It allows querying of set membership with logarithmic complexity.
std::set
std::set<std::string> s; s.insert("abc"); s.insert("xyz"); if (s.find("abc") != s.end()) { ...
If your vector is kept sorted, use std::binary_search, it offers logarithmic complexity as well.
std::binary_search
If all else fails, fall back to std::find, which is a simple linear search.
In C++11, you can use std::any_of instead.
std::any_of
An example to find if there is any zero in the array:
std::array<int,3> foo = {0,1,-1}; if ( std::any_of(foo.begin(), foo.end(), [](int i){return i==0;}) ) std::cout << "zero found...";