Have I overspent my time on this once-asked question?
The umbrella question — write a utility function to iterate any container and print out every Other element backwards?
Good coding practice! I think this is all about iterator syntax knowledge (my weakness) not algorithm (my strength)!
Note this is really about knowledge not coding abilities. QQ not ZZ.
Iterator declaration is a can of worm 😦 I might need to give up on this.
#include <iostream>
#include <vector>
#include <list>
#include <set>
using namespace std;
template<class _InIt> void printAlternateItem2itr(_InIt _First, _InIt _Last){
bool flag = true;
// if the iterator is from rbegin, then ++ would reverse it!
for (_InIt it = _First; it != _Last; ++it, flag=!flag) {
if (flag) cout << *it << ' ';
}
cout << endl;
}
template <typename CONT> void printAlternateItemBackward(CONT const & cont) {
printAlternateItem2itr(cont.rbegin(), cont.rend());
}
int main() {
//vector<int> cont = { 11,2,3,4,5,6,7,18 };
//list<int> cont = { 11,2,3,4,5,6,7,18 };
string cont = "0123456789a";
set<int> cont2 = { 11,2,33,44,55,66,77,88,99 };
printAlternateItemBackward(cont);
printAlternateItemBackward(cont2);
int arr[] = { 11,2,3,4,5,6,7,18,9 };
int size = sizeof(arr) / sizeof(arr[0]);
printAlternateItem2itr(arr, arr + size); //forward only
}
—-
Q: is comparison defined on all iterators?
A: now I think linked list doesn’t. Now I think only random access itr does.
%%Q: what’s the signature of STL find()? I will use those declarations of iterators in my function. (Actually the map and set containers have member functions find() outperforming std::find)
%%Q: from a const container, can u get a non-const iterator?
Q: why don’t you take a container as input? Why must you take iterators?
%%A: it’s more common to take iterator, but in this case container will do. All containers provide rbegin() or begin() including string. Raw array doesn’t but the iterator increment won’t work for raw arrays anyway.
—
Separate question
Q: OO design — how would you represent Order state transition graph in an OMS?