pie*_*fou 4 c++ search stl vector
在Ruby中我可以做到:
[1,2,3,4].include?(4) #=>True
Run Code Online (Sandbox Code Playgroud)
在Haskell我能做到:
4 `elem` [1,2,3,4] #=> True
Run Code Online (Sandbox Code Playgroud)
我该怎么做C++?
Bur*_*ard 20
这里使用find的例子:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> Num(4);
//insert values
Num[0]=1;
Num[1]=2;
Num[2]=3;
Num[3]=4;
std::vector<int>::iterator p = find(Num.begin(), Num.end(), 4);
if (p == Num.end())
std::cout << "Could not find 4 in the vector" << std::endl;
else
std::cout << "Have found 4 in the vector" << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
没有内置函数正是这样做的.有std::find接近,但由于它不返回bool它使用它有点尴尬.
您可以随时滚动自己,获得类似于JIa3ep建议的语法,但不使用count(总是遍历整个序列):
template <typename iter_t>
bool contains(iter_t first, iter_t last, typename iter_t::value_type val){
return find(first, last, val) != last;
}
Run Code Online (Sandbox Code Playgroud)
然后你可以简单地这样做来使用它:
std::vector<int> x;
if (contains(x.begin(), x.end(), 4)) {...}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
467 次 |
| 最近记录: |