假设我有一个向量A = {1 0 1 1 0 0 0 1 0}.现在我想将所有出现的0的索引作为另一个向量返回B.
template< class InputIt, class T>
std::vector<int> IndicesOf(InputIt first, InputIt last, const T& value) {
}
Run Code Online (Sandbox Code Playgroud)
这是一个开始:
std::vector<int>::iterator iter = std::find_if(A.begin(), A.end(), 0);
B = std::distance(A.begin(), iter);
Run Code Online (Sandbox Code Playgroud)
Som*_*ude 18
std::find_if再次调用,先前返回的迭代器(加一)作为开头.循环直到std::find_if返回A.end().
示例代码
#include <algorithm> //find_if
bool isZero(int x){
return x == 0;
}
std::vector<int>::iterator iter = A.begin();
while ((iter = std::find_if(iter, A.end(), isZero)) != A.end())
{
// Do something with iter
iter++;
}
Run Code Online (Sandbox Code Playgroud)