samedi 2 octobre 2021

How to terminate my cpp program after 3 attempts of asking for pin?

My program should terminate after 3 wrong attempts but mine would still proceed to the menu even if the attempts were wrong. I've tried using return 0, but I didn't know why it still not worked. Is there any way to fix my program?

#include <iostream>
#include <string>

using namespace std;

int main ()
{
string pin;
int attemptCount = 0;

while ( attemptCount < 3 )
{
cout << "Enter pin: " << endl;
cin >> pin;

if ( pin != "1234")
{
    cout << "Pin is incorrect." << "\n" <<
    endl;

    attemptCount++;

}
else if ( attemptCount = 0 )
{
    cout << "3 pins were unsuccessful.";
    return 0;
}

else
{
    cout << "Access granted." << endl;
    break;
 
}

}



    int a, b, c;
    char choice;
   cout<<"\n\n---Area of a polygon---\n[A] Triangle\n[B] Square\n[C] Rectangle\n[D] Exit \n";
   cout<<"Enter choice: \n";
   cin>>choice;
   
    switch(choice){
        
        case 'a':
        case 'A':
            int square_area, square_side;
            float base, height, area1;

          cout << "\nEnter length of base and height of Triangle: ";
        cin >> base >> height;
    
         area1 = (base * height) / 2;
         cout << "Area of Triangle: " << area1 << endl;
            break;
            
        case 'b':
        case 'B':
            cout<<"\nEnter the side of the square: ";
            cin >> square_side;
            square_area = square_side * square_side;
            cout << "Area of Square: " << square_area << endl;
            break;
            
        case 'c':
        case 'C':
             int length, width, area;
                cout << "\nEnter the Length of Rectangle : ";
   cin>>length;

   cout << "\nEnter the Width of Rectangle : ";
   cin>>width;

   area = length * width;
   cout << "\nArea of Rectangle : " << area;
   break;
   
        case 'd':
        case 'D':
            break;
;
            
        
        
}
   return 0;
}

My program should terminate after 3 wrong attempts but mine would still proceed to the menu even if the attempts were wrong. I've tried using return 0, but I didn't know why it still not worked. Is there any way to fix my program?

vendredi 1 octobre 2021

How to print graph structure (which uses vector of pointers to implement)? [duplicate]

I want to print the following graph structure. It is using vector to implement but not vector<vector>.

struct DirectedGraphNode {
  int label;
  vector<DirectedGraphNode*> neighbors;
  DirectedGraphNode(int x) : label(x) {};
};

int main() {
  DirectedGraphNode* n1 = new DirectedGraphNode(1);//create 1st node
  DirectedGraphNode* n2 = new DirectedGraphNode(2);//create 2nd node
  n1 -> neighbors = {n2};//link the 1st to 2nd
  vector<DirectedGraphNode*> graph = {n1, n2};//create graph

  /*********** start print ************/
  //print vertex node
  vector<DirectedGraphNode*>::iterator iter_pt;
  for (iter_pt=graph.begin(); iter_pt<graph.end(); iter_pt++) {
    cout << iter_pt -> label << ":";
    
    //print the neighbor nodes of each vertex
    vector<DirectedGraphNode*>::iterator iter_neighbor_pt;
    for (iter_neighbor_pt = (iter_pt -> neighbors).begin(); 
         iter_neighbor_pt < (iter_pt -> neighbors).end(); 
         iter_neighbor_pt++) {
         cout << iter_neighbor_pt -> label;
    }
    cout << "\n";
  }
}

I simplify the graph instance using only two nodes: 1 -> 2. So the expected output should be:

1: 2

2:

When I compiled using c++11, However, I got the error at those spots iter_pt -> label, iter_pt -> neighbors, and iter_neighbor_pt -> label:

error: member reference base type 'DirectedGraphNode *' is not a structure or union.

Could anyone explain why it's wrong and how to correctly print the graph structure above?

C++ shared_from_this() is not letting obj get destructed

I have a following piece of code, which is creating a simple object of Name and inside that it is creating another object Name, with a shared_from_this() reference. As I am reading from here https://en.cppreference.com/w/cpp/memory/enable_shared_from_this/shared_from_this

"Effectively executes std::shared_ptr(weak_this), where weak_this is the private mutable std::weak_ptr member of enable_shared_from_this."

Which I am understanding as shared_from_this() is only creating a weak pointer to shared obj. But I don't see this is the case in runtime. There is effectively a circular reference getting created.

At the end of the I was expecting the Name obj should be destructed, but it is not because the reference counter is 2.

Can someone help me understand how should I use enable_shared_from_this(), that can effectively cleanup the Name obj, once it goes out of reference.

#include <iostream>
#include <memory>
#include <string>
#include <chrono>
#include <thread>

using namespace std;

struct Another;
struct Name : public std::enable_shared_from_this<Name> {
    std::string t;
    int m, n, p;
    shared_ptr<Another> ann;
    Name() {
        std::cout << "constructor\n";
    }
    void MakeSomething() {
        ann = std::make_shared<Another>(shared_from_this());
    }
    ~Name() {
        std::cout << "destructor\n";
    }
};

struct Another {
    shared_ptr<Name> nn;
    Another(shared_ptr<Name> n) : nn(n) {
        std::cout << "from another constructor " << nn.use_count() << "\n";
    }
    ~Another() {
        std::cout << "from another destructor\n";
    }
};

int main()
{
    {
        auto n = std::make_shared<Name>();
        std::cout << "Name ref count so far: " << n.use_count() << "\n";

        auto p = n.get();
        //delete p;
        std::cout << "Name ref count so far: " << n.use_count() << "\n";

        n->MakeSomething();
        std::cout << "Name ref count so far: " << n.use_count() << "\n";
        {
            shared_ptr<Name> m = n;
            std::cout << "Name ref count so far: " << n.use_count() << "\n";
        }

        std::cout << "Name ref count so far: " << n.use_count() << "\n";
    }
    // problem: at this point Name obj, should go out of reference and destructor to be called, which is NOT happening

    return 0;
}

And here is the runtime output (compiler used msvc)

constructor
Name ref count so far: 1
Name ref count so far: 1
from another constructor 3
Name ref count so far: 2
Name ref count so far: 3
Name ref count so far: 2

Simple Neural Network -- learning machine learning by brute force [closed]

I am making my first steps in machine learning and today I have taken a code from this blog post, compiled it and ran, here is the repository. I have fed it csv MNIST from here. Seems like it is doing something.

I do not get what is going on here even at 10% level though.

  1. Class "NeuralNetwork" has been defined in .hpp as an object with two dependancies but in main.cpp it, for some reason, is ok with taking just a topology vector in.
  2. topology vector seems to be valid only if first layer has 2 neurons and last layer - 1. Why?
  3. Function "traning" has some print statements. The counter in the loop is constrained by the size of "input_data". This size for some reason 1000. SHouldn't it be 60,000 (MNIST data set size)?

Thanks=)

Run time polymorphism to create a dynamic object with changing methods in it [closed]

This is a design suggestion question. Came up with something that uses bridge pattern. This will separate the type of accounts and the various operations on it. Below is the code for CAccounts class and it's derived ones.

class CAccounts
{
public:
    virtual void create() = 0;
    virtual void activate() = 0;
    virtual void process() = 0;
    virtual void close() = 0;
};

class CPersonal : public CAccounts {
    shared_ptr< CAccountImplementation> implPtr;

public:
    CPersonal(shared_ptr< CAccountImplementation> impl) : implPtr(impl) {}
    virtual ~CPersonal();

    void create() {
        implPtr->create();
    }

    void activate() {
        implPtr->activate();
    }

    void process() {
        implPtr->process();
    }

    void close() {
        implPtr->close();
    }
};

class CBusiness : public CAccounts {
    shared_ptr< CAccountImplementation> implPtr;

public:
    CBusiness(shared_ptr< CAccountImplementation> impl) : implPtr(impl) {}
    virtual ~CBusiness();

    void create() {
        implPtr->create();
    }

    void activate() {
        implPtr->activate();
    }

    void process() {
        implPtr->process();
    }

    void close() {
        implPtr->close();
    }
};

class CFamily : public CAccounts {
    shared_ptr< CAccountImplementation> implPtr;

public:
    CFamily(shared_ptr< CAccountImplementation> impl) : implPtr(impl) {}
    virtual ~CFamily();

    void create() {
        implPtr->create();
    }

    void activate() {
        implPtr->activate();
    }

    void process() {
        implPtr->process();
    }

    void close() {
        implPtr->close();
    }
};

class CCombo : public CAccounts {
    shared_ptr< CAccountImplementation> implPtr;

public:
    CCombo(shared_ptr< CAccountImplementation> impl) : implPtr(impl) {}
    virtual ~CCombo();

    void create() {
        implPtr->create();
    }

    void activate() {
        implPtr->activate();
    }

    void process() {
        implPtr->process();
    }

    void close() {
        implPtr->close();
    }
};

CAccounts class is an interface class and bunch of other classes based on the account types are derived from it. Now the implementation of account activities are in another set of implementation classes as shown below.

class CAccountImplementation
{
public:
    virtual void create() = 0;
    virtual void activate() = 0;
    virtual void process() = 0;
    virtual void close() = 0;
};

class CStockImplementation : public CAccountImplementation {
public:
    void create() {
        //Do Something
        //.......
        //.......
    }

    void activate() {
        //Do Something
        //.......
        //.......
    }

    void process() {
        //Do Something
        //.......
        //.......
    }

    void close() {
        //Do Something
        //.......
        //.......
    }
};

class CSharesImplementation : public CAccountImplementation {
public:
    void create() {
        //Do Something
        //.......
        //.......
    }

    void activate() {
        //Do Something
        //.......
        //.......
    }

    void process() {
        //Do Something
        //.......
        //.......
    }

    void close() {
        //Do Something
        //.......
        //.......
    }
};

class CBondsImplementation : public CAccountImplementation {
public:
    void create() {
        //Do Something
        //.......
        //.......
    }

    void activate() {
        //Do Something
        //.......
        //.......
    }

    void process() {
        //Do Something
        //.......
        //.......
    }

    void close() {
        //Do Something
        //.......
        //.......
    }
};

Now in main() it can be called as below. This is for a stock implementation for personal account.

shared_ptr<CAccountImplementation> implPtr = static_pointer_cast<CAccountImplementation>(make_shared<CStockImplementation>());
    shared_ptr<CAccounts> acctPtr = static_pointer_cast<CAccounts>(make_shared<CPersonal>(implPtr));
    acctPtr->create();

This design works as long as any of the accounts class only need to use any of the one implementation class.

i.e., for e.g., CBusiness can use the CBondImplementation.

Now if an account like CCombo wants to use different combinations of implementation methods, then this design will not work.

i.e., for e.g., CCombo wants to use create() in CStockImplementation and then process() in CShareImplementation and close() in CBondImplementation, then this design has it's limitations. Can create separate objects of these other implementation classes and use it.

But need something different. i.e., one implementation class where it's possible to inject various different methods and then use that implementation pointer.

Ideally this should be happening in runtime. Something like below,

class CMotherOfAllImplementations {
       CMotherOfAllImplementations (/*pass varient number of APIs*/) 
       { /* Do Something to initialize those APIs*/}
};

How is it possible to create an implementation class during runtime with a bunch of methods? i.e., inject the class with a new set of methods.

Above is something that may or may not be possible. It'll be great to get some good design strategy and some sample code.

How can a constructor be called within a construtor in c++11?

I know that we could use MIL to call a constructor in a constructor like the following code. But I would also like to ask whether there are any other methods to call the constructor in a constructor without using MIL? How could I change the following code to call a constructor in a constructor without MIL? Thanks a lot.

#include <iostream>
using namespacestd;
class Food{

private:
        int a; 
        int b;
public:
        Food(){cout << "default constructor" << endl};
        Food(int x = 0, int y ) { a = x; b = y;}; 
        Food(const Food& z) : Food(z.b){cout << "using mil" << endl; };
};

int main( ){

    Food apple; // default constructor
    Food orange = apple; //copy constructor

    return 0;
}```

Is it possible to place a std::array at a fixed memory address?

For an embedded design I want to place a C++ std::array at a specific memory address, which points to a buffer shared by hardware and software. Is this possible?