1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
|
// Example program
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
using std::cout;
// returns index of the second-to-last instance of the given number_to_find
// returns -1 if there are not at least two instances of the number_to_find
int index_of_second_to_last(const std::vector<int>& numbers, int number_to_find)
{
auto first_it = std::find(numbers.rbegin(), numbers.rend(), number_to_find);
auto second_it = std::find(std::next(first_it), numbers.rend(), number_to_find); // WARNING: bug. See later post in thread.
// this is a reverse iterator, so it's the distance from the last element
int distance = second_it - numbers.rbegin();
if (distance == 0)
{
return -1;
}
else
{
return (int)numbers.size() - distance - 1;
}
}
void test_equals(int actual_value, int expected_value)
{
if (actual_value == expected_value)
{
cout << "Passed\n";
}
else
{
cout << "Failed\n";
}
}
int main()
{
// Tests
{
std::vector<int> numbers { 1, 1, 1, 4, 4, 1, 4 };
test_equals(index_of_second_to_last(numbers, 4), 4);
}
{
std::vector<int> numbers { 4, 4, 1, 1, 0, 0, 1, 0 };
test_equals(index_of_second_to_last(numbers, 4), 0);
}
{
std::vector<int> numbers { 1, 1, 1, 4, 4, 1, 4, 1 };
test_equals(index_of_second_to_last(numbers, 4), 4);
}
{
std::vector<int> numbers { };
test_equals(index_of_second_to_last(numbers, 4), -1);
}
{
std::vector<int> numbers { 42 };
test_equals(index_of_second_to_last(numbers, 42), -1);
}
{
std::vector<int> numbers { 1, 2, 3, 4 };
test_equals(index_of_second_to_last(numbers, 4), -1);
}
{
std::vector<int> numbers { 4, 4 };
test_equals(index_of_second_to_last(numbers, 4), 0);
}
}
|