Tuesday, March 27, 2018

STL's Linked List

#include <list>
#include <iostream>

std::list<int> myList = {3, 4};

int main() {
  for (int x = 7; x < 10; x++) {
    myList.push_back(x);
  }
  
  std::list<int>::iterator it = myList.begin();
  while(it != myList.end()) {
    std::cout << (*it) << " ";
    it++;
  }
  std::cout << std::endl;
}
$ g++ -std=c++1z -o stl01 stl01.cpp
$ ./stl01
3 4 7 8 9
$

Saturday, March 24, 2018

Initializer Examples

#include <iostream>

class Widget {
  private:
    int w;
  public: 
    Widget(int i) {
      w = i;
    }
    Widget(long x) {
      w = 2 * x;
    }
    int getW() {
      return w;
    }
};

int main() {
  int m{7 + 8};
  auto n{9};
  Widget w0{2};
  Widget w1(3);
  Widget w2{(long)10};
  std::cout << w0.getW() << ":" << w1.getW() << ":" << w2.getW() << ":" << m << ":" << n << std::endl;
}
$ g++ -std=c++1z -o widget widget.cpp
$ ./widget
2:3:20:15:9

Monday, February 26, 2018

Quantum Computing with Microsoft & Mac

$ dotnet new -i "Microsoft.Quantum.ProjectTemplates::0.2-*"

Templates                                         Short Name       Language              Tags               
------------------------------------------------------------------------------------------------------------
Console Application                               console          [C#], F#, Q#, VB      Common/Console     
Class library                                     classlib         [C#], F#, Q#, VB      Common/Library     
Unit Test Project                                 mstest           [C#], F#, VB          Test/MSTest        
xUnit Test Project                                xunit            [C#], F#, Q#, VB      Test/xUnit         
ASP.NET Core Empty                                web              [C#], F#              Web/Empty          
ASP.NET Core Web App (Model-View-Controller)      mvc              [C#], F#              Web/MVC            
ASP.NET Core Web App                              razor            [C#]                  Web/MVC/Razor Pages
ASP.NET Core with Angular                         angular          [C#]                  Web/MVC/SPA        
ASP.NET Core with React.js                        react            [C#]                  Web/MVC/SPA        
ASP.NET Core with React.js and Redux              reactredux       [C#]                  Web/MVC/SPA        
ASP.NET Core Web API                              webapi           [C#], F#              Web/WebAPI         
global.json file                                  globaljson                             Config             
NuGet Config                                      nugetconfig                            Config             
Web Config                                        webconfig                              Config             
Solution File                                     sln                                    Solution           
Razor Page                                        page                                   Web/ASP.NET        
MVC ViewImports                                   viewimports                            Web/ASP.NET        
MVC ViewStart                                     viewstart                              Web/ASP.NET        

Examples:
    dotnet new mvc --auth Individual
    dotnet new classlib --framework netcoreapp2.0
    dotnet new --help


$ dotnet new console -lang Q# --output Bell
The template "Console Application" was created successfully.

$ cd Bell
$ code .
$ dotnet run
Init:Zero 0s=1000 1s=0   
Init:One  0s=0    1s=1000
Press any key to continue...

$ dotnet run
Init:Zero 0s=0    1s=1000
Init:One  0s=1000 1s=0   
Press any key to continue...

$ dotnet run
Init:Zero 0s=481  1s=519 
Init:One  0s=518  1s=482 
Press any key to continue...


Tuesday, December 19, 2017

Destructor and Scope in C++

Java's finalize method (ie, not the same thing as Java's finally) is said to be similar to the destructor in C++ with the caveat that there is no guarantee that the finalize method will run. I wondered if the same was true for C++ destructors.

The following code shows the destructor in C++ classes does run. Also in this example, I used parentheses to create a scope in the second function and show how the scope effects the time at which the destructors are executed. Note the difference between func1 and func2.
#include <iostream>
using namespace std;

int n = 1;

class A
{
  private:
    int age;
  public :
    A()
    {
      cout << "   A constructor" << endl;
    }
    ~A()
    {
      cout << "   A *destructor*" << endl;
    }
};

class B
{
  private:
    A *bsa;
  public:
    B(A *a)
    {
      cout << "   B constructor" << endl;
      bsa = a;
    }
    ~B()
    {
      cout << "   B *destructor*" << endl;
    }
};

void func1() {
  A a;
  B b(&a);
  cout << n++ << ". objects created in f1" << endl;
  cout << n++ << ". end of f1" << endl;
}

void func2() {
  {
    A a;
    B b(&a);
    cout << n++ << ". objects created in f2" << endl;
  }
  cout << n++ << ". end of f2" << endl;
}

int main() {
  cout << n++ << ". calling function 1" << endl;
  func1();
  n = 1;
  cout << n++ << ". calling function 2" << endl;
  func2();
  cout << n++ << ". end of program" << endl;
}

Commands to compile, link and run followed by program output
$ g++ -std=c++14 -c -o blocked_scope.o blocked_scope.cpp
$ g++ -o blocked_scope blocked_scope.o
$ ./blocked_scope
1. calling function 1
   A constructor
   B constructor
2. objects created in f1
3. end of f1
   B *destructor*
   A *destructor*
1. calling function 2
   A constructor
   B constructor
2. objects created in f2
   B *destructor*
   A *destructor*
3. end of f2
4. end of program

Monday, December 18, 2017

Initializers

In C++, classes and sructs have few differences. Structs have public access as the default (just like in C) and classes have private access as default. Both allow for curly braces initialization. Curly braces are preferred except where the auto keyword is used as the type.
#include <iostream>
using namespace std;

struct S {
  int x, y;
  string mystr {"hello world"};   // curly brace initializer
  S(int j, int k)                 // "normal" constructor
  {
    x=j;
    y=k;
  }
  S():x(0),y(0){}                 // constructor with initializer
};

class C : public S {              // class C inherits from struct S
  public:
    int z{9};
    C(int a, int b, int c):S(a,b) // subclass & super class constructors
    {
      z = c;
    };
    C(int j):S(3, 4)              // super class constructor passed 3 and 4
    {
      z=j;
    };
    C():S(){};                    // super class constructor will be initialized with zeros
};

int main() {
  C c;
  // printf may cause problems but I wanted to investigate how it can be used
  printf("x=%i, y=%i, z=%i, str=%s\n", c.x, c.y, c.z, c.mystr.c_str());

  C c2(11);
  printf("x=%i, y=%i, z=%i, str=%s\n", c2.x, c2.y, c2.z, c2.mystr.c_str());

  C c3(-1, -2, -3);
  printf("x=%i, y=%i, z=%i, str=%s\n", c3.x, c3.y, c3.z, c3.mystr.c_str());
}
$ g++ -std=c++14 -c -o class_struct.o class_struct.cpp
$ g++ -o class_struct class_struct.o
$ ./class_struct
x=0, y=0, z=9, str=hello world
x=3, y=4, z=11, str=hello world
x=-1, y=-2, z=-3, str=hello world

Sunday, December 17, 2017

Using Abstract Superclass

In this code, Mammal and Fish will inherit from the abstract super class Animal and we add instances of Mammmals and Fish to a vector of Animals. This necessitates a couple of small changes to the syntax; (1.) the vector will now have to be defined as a vector of pointers to the Mammals and Fish and (2.) the call to the respire() method will need to use the arrow to dereference off the pointer rather than the dot.

After creating the vector, the Animal and Fish references will be accessed and the respire() method executed on each instance using the new for loop and then the STL for_each method.
#include <iostream>
#include <vector>
using namespace std;

class Animal {
  public:
    virtual string respire() = 0;
};

class Mammal:public Animal {
  public:
    string respire() {
      return "huff, puff";
    }
};

class Fish: public Animal {
  public:
    string respire() {
      return "bubbles";
    }
};

int main() {
  Mammal dog, cat;
  Fish goldfish;
  vector<Animal *> animals = {&cat, &dog, &goldfish};
  for (auto a : animals) {
    cout << a->respire() << endl;
  }

  for_each(
    animals.begin(), 
    animals.end(), 
    [](Animal* x){cout << x->respire() << endl;});
}
$ g++ -std=c++14 -c -o Animals.o Animals.cpp
$ g++ -o Animals Animals.o
$ ./Animals
huff, puff
huff, puff
bubbles
huff, puff
huff, puff
bubbles
$ 

Saturday, December 16, 2017

C++ Constructor Initializer List with Inheritance

This code has Penguin and Bluejay inheriting from Bird and each displaying specialized functionality particular to their species; in this code, Bluejay can fly and Penguin can swim but not vice-versa.
#include <iostream>
using namespace std;

class Bird {
  private:
    bool can_fly, can_walk, can_swim;
  public:
    // constructor definition using "initializer list"
    Bird(bool flyer, bool walker, bool swimmer): 
      can_fly(flyer), can_walk(walker), can_swim(swimmer) {} 

    string walk(int steps) {
      if (can_walk) return go(steps, "hop");
      return "";
    }
    string fly(int flaps) {
      if (can_fly) return go(flaps, "flap");
      return "";
    }
    string swim(int kicks) {
      if (can_swim) return go(kicks, "kick");
      return "";
    }
    string go(int steps, string flap) {
      string comma = "";
      string going = "";
      for (int x = 0; x < steps; x++) {
        going += (comma + flap);
        comma = ", ";
      }
      return going;
    }
};

class Penguin : public Bird {
  public:
    // Penguin initialized with super class as the "initializer list"
    Penguin():Bird(false, true, true){}; 
};

class Bluejay : public Bird {
  public:
    // Bluejay initialized with super class as the "initializer list"
    Bluejay():Bird(true, true, false){}
};

int main() {
  Penguin p;
  cout << "Penguin swim 5 " << p.swim(5) << endl; 
  cout << "Penguin fly 3 "  << p.fly(3)  << endl; 
  cout << "Penguin walk 4 " << p.walk(4) << endl;
  Bluejay b;
  cout << "Bluejay walk 2 " << b.walk(2) << endl; 
  cout << "Bluejay swim 4 " << b.swim(4) << endl; 
  cout << "Bluejay fly 3 "  << b.fly(3)  << endl;
}

Commands to compile, link and run the code followed by the program output
$ g++ -std=c++14 -c -o Bird.o Bird.cpp
$ g++ -o Bird Bird.o
$ ./Bird
Penguin swim 5 kick, kick, kick, kick, kick
Penguin fly 3 
Penguin walk 4 hop, hop, hop, hop
Bluejay walk 2 hop, hop
Bluejay swim 4 
Bluejay fly 3 flap, flap, flap