declare variable ] loop header #c^java

Small trick to show off in your coding test…

Background — In short code snippet, I want to minimize variable declarations. The loop control variable declaration is something I always want to avoid. shows java WHILE-loop header allows assignment:

List<Object> processables;
while ((processables = retrieveProcessableItems(..)).size() > 0) {/*/}

But only (I’m 99% sure) c++ WHILe-loop header allows variable declaration.

The solution — both java/c++ FOR-loop headers allow variable declarations.


demo: static method declare/define separately n inherited

Low complexity in this demo, but if you lack a firm grip on the important details here, they will add to the complexity in a bigger code base.

  • When subclass is compiled, compiler complains about undefined sf() since it sees only the declaration. You need “g++ der.cpp base.cpp”.
  • Note the static method is inherited automatically, so you could call der::sf().
#include <iostream>
struct base{
  static void sf();
///////// end of header /////////
#include "base.h"
using namespace std;
void base::sf(){ // no "static" please
///////// end of base class /////////
#include "base.h"
using namespace std;
struct der: public base{};
int main(){
///////// end of sub class /////////

STL vector-of-containers: better use pointers

Typical example: If you heavily use a vector of map, it’s more convenient to use a vector of pointers to maps. The java way.

If you drop the “pointers to”, then when you retrieve the map from the vector, you often get a copy, unless you do this:

map<int, int> * mapPtr = &v1[i];

By the way, here’s an initializer for std::map:

vec.push_back(map<int, int>{{32,1}} );