I'm learning C++, so I feel like this should be a very simple answer - but I can't seem to find it. So I apologize in advance if it's naive.
I have a std::vector<int>
of of values, and I am trying to find the indices of the odd values.
I am following the code from here:
(repeated below):
// find_if example
#include <iostream> // std::cout
#include <algorithm> // std::find_if
#include <vector> // std::vector
bool IsOdd (int i) {
return ((i%2)==1);
}
int main () {
std::vector<int> myvector;
myvector.push_back(10);
myvector.push_back(25);
myvector.push_back(40);
myvector.push_back(55);
std::vector<int>::iterator it = std::find_if (myvector.begin(), myvector.end(), IsOdd);
std::cout << "The first odd value is " << *it << '\n';
return 0;
}
This example prints the first odd value. How could I extend this to give me the index values for each of the odd values in myvector
? Is this the correct approach?
// find_if example
#include <iostream> // std::cout
#include <algorithm> // std::find_if
#include <vector> // std::vector
bool IsOdd (int i) {
return ((i%2)==1);
}
int main () {
std::vector<int> myvector;
myvector.push_back(10);
myvector.push_back(25);
myvector.push_back(40);
myvector.push_back(55);
std::vector<int>::iterator it = std::find_if (myvector.begin(), myvector.end(), IsOdd);
std::cout << "ODD values are: " << std::endl;
while(it != myvector.end() ){
std::cout << *it << " in position " << (it - myvector.begin()) << '\n';
it = std::find_if (++it, myvector.end(), IsOdd);
}
return 0;
}
EDIT: Changed it+1
to ++it
see @David Rodríguez - dribeas comment below.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With