2012MS IV:func2back-scan any container n print every Other item

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 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 };
	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 ans 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?

tryGet, tryAdd … on maps – c#, STL etc

* in dotnet the plain lookup operation will throw exception if non-existent. I hit this frequently in my projects…
*** STL map silently adds an empty entry! For the justifications (crazy interviewers?), see http://stackoverflow.com/questions/4382656/why-is-stdmapoperator-so-counter-intuitive
*** java returns null http://stackoverflow.com/questions/5220619/return-from-hashmapstring-string-when-no-key
* basic Dictionary offers TryGet…()

TryAdd? Concurrent dict only, not the basic Dictionary.
* in dotnet, the plain Add() will throw exception if clash
*** STL map will silently ignore the insert() attempt, but operator[] can be used to insert or overwrite ???

TryRemove? No such thing. Using the plain Remove to remove a non-existent is no-throw.

range-check in c++ vector^raw array

[[safe c++]] points out that static array or dynamic array are both (unfortunately) silent about access beyond their limits. Vector has operator[] and at() —

[[]] says c++ new array type supports .size()…

#include <iostream>
#include <vector>
using namespace std;

int main(){
    vector<int> v;
    size_t sz = v.size();
        cout<<v[0]<<" "<<v[sz]<<" <- operator[]: out-of-range treated as non-error!"<<endl;
        cout<<v.at(sz)<<" <- at(): throws:)"<<endl;
    }catch(exception & ex){
        cerr<<"Must catch by ref (what() virtual) " << ex.what()<<endl;

std::array+alternatives #RAII dtor

features wish list: RAII; fixed size; bound check

https://stackoverflow.com/questions/16711697/is-there-any-use-for-unique-ptr-with-array compares vector ^ unique_ptr ^ std::array. Conclusion — Vector is more powerful, more versatile, more widely useful, less restrictive. std::array is

All alternatives to std::array:

  • vector and raw array
  • std::unique_ptr<T[]>
  • boost::scoped_array and boost::shared_array — least quizzed.

The dtor in each data structure is a key feature if you want RAII:

  1. std::array — dtor probably destroys each element one by one. No q(delete) called since the elements could be on stack
  2. scoped_array — dtor calls delete[], which is a key difference from scoped_ptr, according to my book [[beyond the c++ standard lib]]
  3. vector — dtor uses its allocator, which very likely calls delete[] since vector uses heap for the underlying growable array.
  4. unique_ptr<T[]> — yes as expected. This valgrind experiment shows the array-specialization uses delete[], whereas the vanilla instance uses regular q(delete).

container of ptr – master list of references

Item 20 [[effSTL]] has a set
[[c++ coding standards]] advised against container of raw ptr

[[STL Tutorial Reference]] has a container of polymorphic objects by pointer

java generic Container<? extends Number>use case

Jargon warning — it’s rather abstract to talk about “super-types .. sub-types”, so I will use Number (a real super-type), Integer etc in this post.


ArrayList<Number> liNum = new …;
ArrayList<Integer> liInt = new ..;

Rule 0 —- The method myCollection.add() is tolerant, lenient and easy. Wildcard never needed for add().

liNum.add(100); // fine
liNum.add(0.0001); //fine

Rule 1 —- cast/assignment/param-passing is stricter than add()
Rule 1a —- A List-of-subtype can’t be cast to List-of-SUPERtype.
Rule 1b —- A List-of-SUPERtype can’t be cast to List-of-subtype.

As a result, a method parameter declared as type A will not accept an argument of the type B, and vice-versa. Parameter passing is assignment.

There’s no “subsumption” between types A and B. See P16[[java generics]] for the (simple) reasons. STL has similar restrictions[4]

ArrayList<Integr> tmp5 = liNum; // wont’ compile
ArrayList<Number> tmp3 = liInt; // won’t compile

[4] See P662 [[Programming]] by Stroustrup. Given a vector of ptr2shapes, producer can insert ptr2square but consumer may expect a ptr2Circle!

Now, what if my method wants to accept any list of number, or list of int, or list of float etc?  (In other words, i want to accept a List-of-SUPERtype or a List-of-any-subtype?)

Rule 2 —- use wildcard to accept list-of-Number-OR-list-of-Integer

In other words, ArrayList<? extends Number> is a SUPERtype of ArrayList<Integer>. P18 [[java generics]].

ArrayList liWild6 = liNum; //ok
ArrayList liWild1 = liInt; //ok

I feel this is about the only common usage of wildcard.