Skip to content

Instantly share code, notes, and snippets.

@jdswinbank
Last active August 29, 2015 14:07
Show Gist options
  • Save jdswinbank/6cbca5ad676b9a52c5f2 to your computer and use it in GitHub Desktop.
Save jdswinbank/6cbca5ad676b9a52c5f2 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <vector>
// Returns a vector of indices in the range [st, end) which correspond to
// values for which pred is true.
template <typename Iterator, typename Func>
std::vector<std::size_t> find_indices(Iterator st, Iterator end, Func pred) {
std::vector<std::size_t> indices;
for (auto i=st; i<end; i++) {
if (pred(*i)) indices.push_back(std::distance(st, i));
}
return indices;
}
// Returns true if val >= 2, else false.
bool example_pred(int val) {
return val >= 2;
}
int main()
{
// We use a vector as input, but find_indices()
// should work for anything you can iterate over.
std::vector<int> data_array { 0, 1, 2, 3, 0, 3, 2, 1, 0 };
// This particular predicate checks for all values >= 2,
// but you could use whatever arbitrary logic you like.
//auto indices = find_indices(begin(data_array), end(data_array), [](int i){return i>=2;});
// If you like ugly things, you could use a function
// pointer instead of a lambda.
auto indices = find_indices(begin(data_array), end(data_array), example_pred);
for (auto &i: indices) {
std::cout << "Index: " << i << " Value: " << data_array[i] << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment