dimanche 30 septembre 2018

type deduction with auto &

Today I wrote some code dealing with binary tree. Later I noticed a bug in the code:

void find(TreeNode* root, int target) {
    stack<int> myStack;
    while(!myStack.empty()){
        auto& top = myStack.top(); // here I used auto& by mistake
        ...
    }
}

However, I am confused with auto& top = myStack.top();. After the type deduction, what is the type for top? Is it TreeNode & or TreeNode* &?

How about if I used auto* top = myStack.top()?

Issue with getting values from polymorphic objects

The function that needs to be fixed is int getCValue(A *pa).

Right now the output I'm getting is * * 5 16 when it should be * * 5 7.

What is causing this to be incorrect? I need to return the value of the c-object if C or D are not NULL. I think that this may be because multiple objects are being initialized thus changing the value that the C-object holds but I don't know how to prevent this.

#include <iostream>
#include <stdexcept>
using namespace std;
struct A {
  A(int n) : _value(n) {}
  virtual ~A(void) {}
  virtual int value(void) { return _value; }
private:
  int _value;
};


struct B : A {
  B(int m, int n) : A(m), _value(n) {}
  ~B(void) override {}
  int value(void) override { return A::value() + _value; }
private:
  int _value;
};


struct C : A {
  C(int n) : A(n) {}
  ~C(void) override {}
  int value(void) override { return A::value() + 2; }
};


struct D : B, C {
  D(int m, int n) : B(m, n), C(n) {}
  ~D(void) override {}
  int value(void) override { return B::value() + C::value(); }
};

/////////////////////////////////////////////////////////////////
A *createD(int m, int n)
{
  D* newD = new D(m, n);
  C* newC = newD;
  A* newA = newC;
  return newA;
}

int getCValue(A *pa)
{
  C* c = dynamic_cast<C*>(pa);
  D* d = dynamic_cast<D*>(pa);

  if (c != NULL || d != NULL)
  {
    int check = c->value();
    return check;
  }
  else
  {
    throw std::runtime_error("whoa");
  }
}
/////////////////////////////////////////////////////////////////
int main(void) {

  A *pa = createD(2, 3);
  int value = pa->value();
  cout << "expected: 10" << endl;
  cout << "     got: " << value << endl;
  delete pa;
  cout << endl;

  A *array[] = { new A(0), new B(1,2), new C(3), createD(4,5) };
  cout << "expected: * * 5 7" << endl;
  cout << "     got: ";
  for (A *pa : array) {
    try {
      cout << getCValue(pa) << ' ';
    }
    catch (exception &e) {
      cout << '*' << ' ';
    }
  }
  for (A *pa : array)
    delete pa;
  cout << endl;

  return 0;
}

error expected initializer before 'namespace', c++

"vectortest.h" is a class representing a vector with its methods. So, the question is why the error " expected initializer before 'namespace' " occurs?

#ifndef LISTTEST_INCLUDED
#define LISTTEST_INCLUDED   1

#include <list> 
#include <string> 
#include <fstream>
#include <iostream>
#include "vectortest.h"
namespace listtest
{

   std::list<std::string> readfile( std::istream& input );


   std::list<std::string> randomstrings( size_t nr, size_t s );
      // Return nr random strings of length s.

   void sort_assign( std::list< std::string > & v );

   void sort_move( std::list< std::string > & v );
}

std::list<std::string> convToList(std::vector<std::string> &v);

std::ostream& 
operator << ( std::ostream& , const std::list< std::string > & );

#endif

Remove duplicate string elements C++

The problem consists of finding all permutations using k out of n digits. I'm able to find all the permutations, but I'm struggling trying to erase duplicates. I can successfully compare and find the duplicates, but erasing them is what I'm struggling to do. I have a feeling I'm missing something simple but I don't know what it is.

Any help would be greatly appreciated. I've been staring at this for a week.

Here is the code that I've got right now.

void getPermutations(int n, int k){
    string str = "";
    for(int i = 0; i < n; i++){//fill string with numbers <= n
        str += to_string(i);//convert numbers to string
    }
    string tempStr = "";
    string outputStr = "";
    do{
        tempStr = str.substr(0, k);
        int compareResult = tempStr.compare(0, k, outputStr, 0, k);
        if(compareResult == 0){
            cout << "| same | ";
            outputStr.erase(k,k);

        }
        outputStr = tempStr;
        cout << outputStr << " ";
    }while(next_permutation(str.begin(), str.end()));
}

Delete first column of 2d vector matrix read in using sstream

I have a 2d vector where the rows are unequal. I have been trying to delete the first column but have no luck look at previous stackoverflow posts.

example data:

1 2 4 5 6 6
1 2 3 4 6 6 8

Code to read in data:

myfile.open("test.txt");
if(myfile.is_open())
{
    while(getline(myfile, line)){
        //cout << "This line: ";
        istringstream is(line);
        sortVec.push_back(std::vector<int>( std::istream_iterator<int>(is),
                                                std::istream_iterator<int>() ) );
    }
}
else
{
    cout << "Myfile is not open" << endl;
}

    myfile.close();

When I try to erase the first column using std:vector:

int columnIndex = 0;
    for(auto& row:sortVec){
        row.erase(next(row.begin(), columnIndex));
    }

I get a segmentation fault.

I have tried the following stackoverflow posts as well. How to delete column in 2d vector, c++

Additionally when I create a vector manually everything works perfect so I am lost at the moment.

Desired output:

2 4 5 6 6
2 3 4 6 6 8

+ Operator Not Overloaded

I'm writing a program that adds two imaginary numbers. The problem i'm facing is when i output the program the numbers doesn't get added and i get gibberish result.. I've wasted my whole day trying to find the solution but invain. I have an exam tomorrow and i really really would appreciate if anyone can help.

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


 class ComplexNo{
    int real, img;
    public:
    ComplexNo operator+(ComplexNo c){

        ComplexNo temp;
        temp.real = real + c.real;
        temp.img = img + c.img;
        return temp;

    }//have to give something
    friend istream& operator>>(istream& in, ComplexNo& m);
    friend ostream& operator<<(ostream& out,ComplexNo m);

 };

 istream& operator>>(istream& in, ComplexNo&m){

     int i,j;
     cout << "Enter the real number =";
     in >> m.real;
     cout << "Enter the imaginary number =";
     in >> m.img;

     return in;
 }

 ostream& operator<<(ostream&  out,ComplexNo m){

       out<<m.real<<((m.img<0)?"":"+")<<m.img<<"i" ;
       return out;
 }



class MatrixOfComplex{
    ComplexNo **data;
    int row, col;
    public:
    MatrixOfComplex& operator+(MatrixOfComplex &m)//Have to give
    {
        int i,j;
        MatrixOfComplex temp;

        if(row == m.row && col == m.col)
        {
            temp.row = row;
            temp.col = col;
            temp.data = new ComplexNo*[row];

            for(i=0;i<row;i++)
            {
                temp.data[i] = new ComplexNo[col];
                for(j=0;j<col;j++)
                {
                    temp.data[i][j] = data[i][j] + m.data[i][j];
                }
            }

        }
        else{
            cout << "The matrices cannot be added = ";
        }



    }

    void populateMatrix(int row, int col)
    {
        int i,j;
        cout << endl;
        cout << "Enter no of rows =";
        cin >> row;
        cout << "Enter no of cols = ";
        cin >> col;

        data = new ComplexNo*[row];

        if(data == NULL)
        {
            cout << "Matrix is yet to be populated";
        }
        else{
        for(i=0;i<row;i++)
        {
            data[i] = new ComplexNo[col];
            for(j=0;j<col;j++)
            {
                cin >> data[i][j];
            }
        }
    }
    }

   /// MatrixOfComplex operator[](int x){



    //show all ComplexNo objects of x-th row of the client using cout<<
    //and return the complex no of that row with highest real value.

    friend istream& operator>>(istream& in, MatrixOfComplex& m);
    friend ostream& operator<<(ostream& out, MatrixOfComplex m);
};

    ostream& operator<<(ostream& out, MatrixOfComplex m){

        int i,j;

        for(i=0;i<m.row;i++)
        {
            for(j=0;j<m.col;j++)
            {
                out << m.data[i][j] << " ";
            }
                out << endl;
        }
            return out;

    }


    istream& operator>>(istream& in,MatrixOfComplex &m){

        int i,j;
        cout << endl;
        cout << "Enter no of rows =";
        in >> m.row;
        cout << "Enter no of cols = ";
        in >> m.col;

        m.data = new ComplexNo*[m.row];

        if(m.data == NULL)
        {
            cout << "Matrix is yet to be populated";
        }
        else{
        for(i=0;i<m.row;i++)
        {
            m.data[i] = new ComplexNo[m.col];
            for(j=0;j<m.col;j++)
            {
                in >> m.data[i][j];
            }
        }
        }
        return in;
    }

int main(){
    MatrixOfComplex m1, m2, m3;
    cout <<"Enter the first matrix= " << endl;
    cin>>m1;
    //should ask no of rows, cols and
    //then populate rows*cols ComplexNo objects
    cout << m1;

   /// populateMatrix(row,col);
    cout << "Enter the 2nd matrix =" << endl;
     m2.populateMatrix(4,4);
    cout << endl;
    //set no of rows, cols with parameters and
    //then populate rows*cols ComplexNo objects with random real & img values
    cout << m2;

    m3 = m1 + m2;
    cout << m3;

//    ComplexNo temp = m1[0];
   // cout<<temp;
    return 0;
}

Move constructor never gets called

I have written the below piece of code:

#define LOG cout << __PRETTY_FUNCTION__ << endl;

class MyClass
{
private:
    int* ptr;

public:
    MyClass()
        : ptr(new int(10))
    {
        LOG
    }

    ~MyClass()
    {
        LOG

        if (ptr)
        {
            delete ptr;
            ptr = nullptr;
        }
    }

    MyClass(const MyClass& a)
        : ptr(nullptr)
    {
        LOG
        ptr = new int;
        *ptr = *(a.ptr);
    }

    MyClass& operator=(const MyClass& a)
    {
        LOG
        if (this == &a)
        {
            return *this;
        }

        delete ptr;
        ptr = new int;
        *ptr = *(a.ptr);

        return *this;
    }

    MyClass(MyClass&& a)
        : ptr(nullptr)
    {
        LOG

        ptr = a.ptr;
        a.ptr = nullptr;
    }

    MyClass& operator=(MyClass&& a)
    {
        LOG

        if (this == &a)
        {
            return *this;
        }

        delete ptr;
        ptr = a.ptr;
        a.ptr = nullptr;

        return *this;
    }

    void deleteMe()
    {
        LOG
        delete this;
    }

    void printClass()
    {
        LOG;
    }
};

MyClass function()
{
    MyClass m;
    return m;
}

int main()
{
    MyClass m = function();
    return 0;
}

Output of the program:

MyClass::MyClass()
MyClass::~MyClass()

This does not call the move constructor. Is there something is wrong?

I was expecting the below output:

MyClass::MyClass()
MyClass::MyClass(MyClass&&)
MyClass::~MyClass()
MyClass::MyClass(MyClass&&)
MyClass::~MyClass()
MyClass::~MyClass()

It might look like the compiler is doing some optimisation. If this the case then why we need move constructor or move assignment operator for our case.

samedi 29 septembre 2018

Passing an int function to a while loop in java

I am implementing the three Missionary and Canniball problem.When implementing it works fine in c++ and python but gives an error in the while loop when implemented in java. The code in c++ is as follows:

/* Variables are as follows: * im and ic = initial missionaries and cannibal respectfully * fm and fc = final missionaries and cannibal respectfully * status = indicates what side we are on * select = used in solution() method to determine the boat grouping * flag = used to determine boat's current location * i = loop counter */

int im = 3, ic = 3, i, fm = 0, fc = 0, status = 0, flag = 0, select = 0;

void display(char bpass1, char bpass2)

{

cout << "\n\n\n";
for (int i = 0; i < fm; i++) 
    cout << " M "; 
for (int i = 0; i < fc; i++)
    cout << " C "; 

if (flag == 0)
    cout << "     ~~~~~WATER~~~~~<B0(" << bpass1 << "," << bpass2 << ")AT>  ";
else
    cout << "     <BO(" << bpass1 << "," << bpass2 << ")AT>~~~~~WATER~~~~~  ";
for (int i = 0; i < im; i++)
    cout << " M ";
for (int i = 0; i < ic; i++)
    cout << " C ";

}

int win()

{

return (fc == 3 && fm == 3) ? 0 : 1;

}

/** Basic algorithm is as follows: * 1 - Get boat's current location * 2 - Determine passenger grouping * 3 - Make trip * 4 - Determine if we won * 5 - Repeat until we won */

void solution()

{

while (win()) //In java gives me error here in my IDE. 

{

    if (!flag)
    {
        switch (select)
        {
            case 1: display('C', ' ');
                    ic++;
                    break;
            case 2: display('C', 'M');
                    ic++; im++;    
                    break;   
        }

        if (((im - 2) >= ic && (fm + 2) >= fc) || (im - 2) == 0)
        {
            im = im - 2;
            select = 1;
            display('M', 'M');
            flag = 1;
        }
        else if ((ic - 2) < im && (fm == 0 || (fc + 2) <= fm) || im == 0)
        {
            ic = ic - 2;
            select = 2;
            display('C', 'C');
            flag = 1;
        }

        else if ((ic--) <= (im--) && (fm++) >= (fc++))
        {
            ic = ic - 1;
            im = im - 1;
            select = 3;
            display('M', 'C');
            flag = 1;
        }
    }

    else
    {
        switch (select)
        {
            case 1: display('M', 'M');
                    fm = fm + 2;
                    break;

            case 2: display('C', 'C');
                    fc = fc + 2;
                    break;   

            case 3: display('M', 'C');
                    fc = fc + 1;
                    fm = fm + 1;
                    break;
        }

        if (win())
        {
            if (((fc > 1 && fm == 0) || im == 0))
            {
                fc--;
                select = 1;
                display('C', ' ');
                flag = 0;
            }

            else if ((ic + 2) > im)
            {
                fc--; fm--;
                select = 2;
                display('C', 'M');
                flag = 0;
            }
        }
    }
}

}

int main()

{

cout << "MISSIONARIES AND CANNIBAL SOLUTION";
display(' ', ' ');
solution();
display(' ', ' ');
return 0;

}

I don't know where am i going wrong.Any replacement of the code with same output(in java) or correction is appreciated.Thanks!!

How to write a procedure that takes integer to string map and produces string to set of integers map

It is supposed to take an integer and string as a map and return string and set of integers as a map. Say the input is (205 -> "ORD" 309 -> "ORD"); it returns ("ORD" -> {205,309}). Something like that.

map(int,string)myMap;

map(int,set)setMap;

Strange behavior when modifying string passed by reference

I have a function passing a string by reference and swapping two characters in it, but after the function call completes, the value of that string is different. At POINT A the value of s is "care", but at POINT B the value of s is "are". Can someone please explain why this is the case?

void func1() {
    string s = "acre";
    func2(s);
    //POINT B
}

void func2(string& s, string t) {
    int i = stoi(t.substr(2, 1));
    char c = s[i];
    s[i] = s[i + 1];
    s[i + 1] = c;
    //POINT A
}

Can a non-copyable member be used as alternative to make an object non-copyable?

A class with non-copyable member is said to be also non-copyable. From SO, to make a class non-copyable these are the options:

  1. Use boost::noncopyable
  2. Declare constructor and assignment operator as private.

    class foo 
    {
        private:
          std::mutex _dummy;
    };
    
    

Question: Will inclusion of a dummy non-copyable member be used for similar purpose and for simplicity? What are the down-sides?

Why first code work and the second doesn't?

Why this line work: auto it = objects.insert(objects.end(), {move(object), 0, 0});

In function:

    Id Add(T object) {
    auto it = objects.insert(objects.end(), {move(object), 0, 0});

    int id = objects.size();
    arr.insert({&(*it).pri, id - 1});

    return id - 1;
}

But this line doesn't (can't compile): auto iter = objects.insert(objects.end(), {*it, 0, 0}); At this function:

    template <typename ObjInputIt, typename IdOutputIt>
void Add(ObjInputIt range_begin, ObjInputIt range_end,
       IdOutputIt ids_begin) {
    auto begin = objects.size();

    for (auto it = range_begin; it != range_end; it++) {
        auto iter = objects.insert(objects.end(), {*it, 0, 0});
        int id = objects.size();
        arr.insert({&(*iter).pri, id - 1});
    }

    auto end = objects.size();

    ids_begin = {begin, end - 1};
}

Why does `std::allocator_traits` need `construct` while placement new is enough?

According to cppreference, std::allocator_traits::construct just calls placement new by default. I cannot imagine any practical reason to use the former rather than the latter.

My questions are:

  1. Why does std::allocator_traits need construct while placement new is enough?
  2. Is there any use case showing the former has obvious advantages over the latter?

How std::min / std::max works?

I have problem understand why this works correctly?

//#include <algorithm>

template<class T> 
const T& min(const T& a, const T& b){
    return (b < a) ? b : a;
}

int main(){
    int x = /*std*/ min(5 - 1, 5 + 1);

    return x;
}

If we get const reference in a, how it survive "returning" const reference?

Is this because function is inlined?

Why is not possible to declare an array with a constant expression?

I have a two dimensional std::array

std::array<std::array<String, nHieght>, nWidth> dataTable;

nHieght and nWidth are constant variables, which I don't know their values for diferent dataTables, and the only possible way to get their values is using a function call.

const size_t nHieght = dcmImage->getHeight();
const size_t nWidth = dcmImage->getWidth();

but that is not possible, and this is what I get as an Error:

error: the value of ‘nHieght’ is not usable in a constant expression
 ‘nHieght’ was not initialized with a constant expression

the same is for nWidth of course.

C++ http program returns 505 HTTP Version Not Supported error

I'm trying to get public ip address of my sysetm using windows C++ api. But, I got following response:

HTTP/1.1 505 HTTP Version Not Supported
Connection: close
Server: Cowboy
Date: Sat, 29 Sep 2018 08:46:51 GMT
Content-Length: 0

My Code:

std::stringstream request2;
std::string hostName = "api.ipify.org";
std::string path = "/?format=text";

request2 << "GET " << path <<" HTTP/1.1" << std::endl;
request2 << "Host: " << hostName << std::endl;

request2 << std::endl;
std::string request1 = request2.str();

//init winsock
if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0)
{
    exit(1);
}

//open socket
if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
{
    exit(1);
}

struct hostent  *he;
memset(&serveraddr, 0, sizeof(serveraddr));

const char *hostname = hostName.c_str();
if ((he = gethostbyname(hostname)) == NULL)
{
    WriteLogFile("Host not found");
    exit(1);
}

/* copy the network address to sockaddr_in structure */
memcpy(&serveraddr.sin_addr, he->h_addr_list[0], he->h_length);
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(PORT);

if ((connect(sock, (struct sockaddr *) &serveraddr, sizeof(serveraddr))) < 0)
{
    exit(1);
}

//send request
if (send(sock, request1.c_str(), request1.length(), 0) != request1.length())
{
    exit(1);
}

//get response
response = "";
resLen = BUFFERSIZE;
while (resLen == BUFFERSIZE)
{
    resLen = recv(sock, (char*)&buffer, BUFFERSIZE, 0);
    if (resLen>0) {
        response += std::string(buffer).substr(0, resLen);
    }
}

IpAddress = response;

//disconnect
closesocket(sock);

//cleanup
WSACleanup();

Please help me. Thanks in advance.

Note: My request link:

https://api.ipify.org/?format=text

towers of hanoi recursion not working correctly

I am trying to do towers of hanoi with 7 disks using recursion for a school project, I'm not sure what the problem is but the output is completely wrong. I assume it has something to do with the moveDisk() function but I'm unable to find the issue. The number of moves is correct. Any help would be much appreciated. Here is my code and please leave a comment if you have any questions:

//#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <cassert>

using namespace std;

struct Peg
{
    vector<int> peg;
    string name;
};

void loadDisk(int diskNum, vector<int> &startPeg)
{
assert(startPeg.size() == 0);
for (int i = diskNum; i > 0; i--)
{
    startPeg.push_back(i);
}
}

void printPeg(int diskNum, vector<int> peg, string name)
{
cout << name << endl;
assert(peg.size() >= 0);
if (peg.size() > 0)
{
    for (unsigned int i = 0; i < peg.size(); i++)
    {
        cout << peg[i];
    }
}
cout << endl << endl;
}

void moveDisk(vector<int> &startPeg, vector<int> &goalPeg)
{
if (goalPeg.size() == 0)
{
    int temp = startPeg.back();
    startPeg.pop_back();
    goalPeg.push_back(temp);
}
}

int hanoi(int diskNum, vector<int> &startPeg, vector<int> &goalPeg, vector<int> &tempPeg)
{
int count = 0;
if (diskNum == 0)
{
    moveDisk(startPeg, goalPeg);
}
else
{
    count = hanoi(diskNum - 1, startPeg, tempPeg, goalPeg);
    moveDisk(startPeg, goalPeg); 
    count++;
    count += hanoi(diskNum - 1, tempPeg, goalPeg, startPeg);
}
return count;
}



int main()
{
Peg startPeg, tempPeg, goalPeg;
startPeg.name = "Start";
tempPeg.name = "Temp";
goalPeg.name = "Goal";
int diskNum = 7;

loadDisk(diskNum, startPeg.peg);

cout << "Starting Conditions with three pegs: " << endl;

printPeg(diskNum, startPeg.peg, startPeg.name);
printPeg(diskNum, tempPeg.peg, tempPeg.name);
printPeg(diskNum, goalPeg.peg, goalPeg.name);

int moveCount = hanoi(diskNum, startPeg.peg, tempPeg.peg, goalPeg.peg);

cout << "End Conditions with three pegs: " << endl;

printPeg(diskNum, startPeg.peg, startPeg.name);
printPeg(diskNum, tempPeg.peg, tempPeg.name);
printPeg(diskNum, goalPeg.peg, goalPeg.name);

cout << moveCount << " total moves were taken." << endl;

system("pause");
return 0;
}

and the current output is : Starting Conditions with three pegs: Start 7654321

Temp

Goal

End Conditions with three pegs: Start 76543

Temp 2

Goal 1

127 total moves were taken.

vendredi 28 septembre 2018

Is there a better way to print vector elements using iterator and reverse_iterator

I have a program that creates a vector and adds the given values to it using push_back(). The expected output is to print the vector values in default order and reverse order using an iterator and reverse iterator. The output is absolutely correct but I was just wondering if there's a better way to dthis: :-

    #include <iostream>
    #include <vector>
    using namespace std;
    vector<int> myvector;
    int i;
    int main()
    {
        int n;
        cin>>n;
        int input;
        for (i = 0; i < n; i++) 
        {
            cin >> input;
            myvector.push_back(input);
        }
        for (int i = 0; i < n; i++) 
        {
            cout<<" "<<myvector[i]; //prints user vector input
        }
      cout<<endl;
      typedef vector<int>::iterator iter_type;                                      
      iter_type from (myvector.begin());                                   
      iter_type until (myvector.end());                      
      reverse_iterator<iter_type> rev_until (from);                                               
      reverse_iterator<iter_type> rev_from (until);   
      while (rev_from != rev_until)
      cout << ' ' << *rev_from++;  //prints reversed vector
      return 0;
    }

Implementing an AVL Tree using smart pointers Part 2

I made a similar post on here but I did not get any useful feedback. I thus tried to re-do my code a bit to see if that would lead to any decent results. So far my code compiles but yet does not print anything and I am not sure why.

I have an example in int main() that should give me a tree that looks like:

/* The constructed AVL Tree would be
        9
       /  \
      1    10
    /  \     \
   0    5     11
  /    /  \
 -1   2    6
*/

Here is my code:

#include <algorithm>
#include <iostream>
#include <memory>
#include <utility>
#include <stack>
#include <queue>

struct Node {
    int data;
    int height;
    std::unique_ptr<Node> left = nullptr;
    std::unique_ptr<Node> right = nullptr;

    Node(const int& x, const int& y, std::unique_ptr<Node>&& p = nullptr, std::unique_ptr<Node>&& q = nullptr) :
        data(x),
        height(y),
        left(std::move(p)),
        right(std::move(q)) {}

    Node(const int& data) : data(data) {}

};
std::unique_ptr<Node> root = nullptr;

int height(std::unique_ptr<Node>& root) {
    if (!root) return 0;
    return root->height;
}

void fixHeight(std::unique_ptr<Node>& root) {
    auto h1 = height(root->left);
    auto h2 = height(root->right);
    root->height = (h1 > h2 ? h1 : h2) + 1;
}

void rightRotate(std::unique_ptr<Node>& p) {
    std::unique_ptr<Node> q = std::move(p->left);
    p->left = std::move(q->right);
    q->right = std::move(p);
    fixHeight(p);
    fixHeight(q);
}

void leftRotate(std::unique_ptr<Node>& q) {
    std::unique_ptr<Node> p = std::move(q->left);
    q->right = std::move(p->left);
    p->left = std::move(q);
    fixHeight(q);
    fixHeight(p);
}

int heightDiff(std::unique_ptr<Node>& root) {
    if (!root) return 0;

    return height(root->left) - height(root->right);
}

void balance(std::unique_ptr<Node>& root) {
    fixHeight(root);
    if (heightDiff(root) == 2) {
        if (heightDiff(root->right) < 0)
            rightRotate(root->right);
        leftRotate(root);
    }

    if (heightDiff(root) == -2) {
        if (heightDiff(root->left) > 0)
            leftRotate(root->left);
        rightRotate(root);
    }
}

void insert(std::unique_ptr<Node>& root, const int& theData) {
    if (!root) return;
    if (theData < root->data)
        insert(root->left, theData);
    else
        insert(root->right, theData);
    balance(root);
}

auto findMin(std::unique_ptr<Node>& root) {
    while (root->left != nullptr) root = std::move(root->left);
    return root.get();
}

void deleteNode(std::unique_ptr<Node>& root, const int& theData) {
    // Step 1: Perform regular deletion for BST
    if (!root) return;
    else if (theData < root->data) deleteNode(root->left, theData);
    else if (theData > root->data) deleteNode(root->right, theData);

    else {
        // Case 1: No child
        if (root->left == nullptr && root->right == nullptr) {
            root = nullptr;
        }

        // Case 2: One child
        else if (root->left == nullptr) {
            root = std::move(root->left);
        }

        else if (root->right == nullptr) {
            root = std::move(root->right);
        }

        // Case 3: Two children
        else {
            auto temp = findMin(root->right);
            temp->data = root->data;
            deleteNode(root->right, temp->data);
        }
    }

    if (!root) return;

    // Step 2: Update height of the current node
    root->height = 1 + std::max(height(root->left), height(root->right));

    // Step 3: Get the balalce factor of the this node (to 
    // check whether this node became unbalanced)
    int balance = heightDiff(root);

    // If this node becomes unbalanced, then there are 4 cases

    // Left Left Case
    if (balance > 1 && heightDiff(root->left) >= 0)
        rightRotate(root);

    // Left Right Case
    if (balance > 1 && heightDiff(root->left) < 0) {
        leftRotate(root->left);
        rightRotate(root);
    }

    // Right Right Case
    if (balance < -1 && heightDiff(root->right) <= 0)
        leftRotate(root);

    // Right Left Case
    if (balance < -1 && heightDiff(root->right) > 0) {
        rightRotate(root->right);
        leftRotate(root);
    }
}

void inorderTraversal(std::unique_ptr<Node>& root) {
    if (!root) {
        inorderTraversal(root->left);
        std::cout << root->data << " ";
        inorderTraversal(root->right);
    }
}

void preorderTraversal(std::unique_ptr<Node>& root) {
    if (root != nullptr) {
        std::cout << root->data << " ";
        preorderTraversal(root->left);
        preorderTraversal(root->right);
    }
}

void postorderTraversal(std::unique_ptr<Node>& root) {
    if (root != nullptr) {
        postorderTraversal(root->left);
        postorderTraversal(root->right);
        std::cout << root->data << " ";
    }
}

void DFS(std::unique_ptr<Node>& root) {
    if (!root) return;

    std::stack<Node const *> s;
    s.push(root.get());

    while (!s.empty()) {
        auto p = s.top();
        s.pop();

        if (p->right != nullptr) s.push(p->right.get());
        if (p->left != nullptr) s.push(p->left.get());

        std::cout << p->data << " ";
    }
}

void BFS(std::unique_ptr<Node>& root) {
    if (!root) return;

    std::queue<Node const *> q;
    q.push(root.get());

    while (!q.empty()) {
        auto p = q.front();
        q.pop();

        if (p->left != nullptr) q.push(p->left.get());
        if (p->right != nullptr) q.push(p->right.get());

        std::cout << p->data << " ";
    }
}

bool exists(int d) {
    auto temp = root.get();
    while (temp != nullptr) {
        if (temp->data == d) {
            return true;
        }
        else {
            if (d > temp->data) {
                temp = temp->right.get();
            }
            else {
                temp = temp->left.get();
            }
        }
    }
    return false;
}

int main() {

    //        8
    //      /    \
    //    4       10
    //   / \     /  \
    //  2   6   9    12

    //insert(root, 8);
    //insert(root, 10);
    //insert(root, 4);
    //insert(root, 2);
    //insert(root, 6);
    //insert(root, 12);
    //insert(root, 9);


  /* Constructing tree given in the above figure */
    insert(root, 9);
    insert(root, 5);
    insert(root, 10);
    insert(root, 0);
    insert(root, 6);
    insert(root, 11);
    insert(root, -1);
    insert(root, 1);
    insert(root, 2);

    /* The constructed AVL Tree would be
            9
           /  \
          1    10
        /  \     \
       0    5     11
      /    /  \
     -1   2    6
    */

    printf("Preorder traversal of the constructed AVL "
        "tree is \n");
    preorderTraversal(root);

    //deleteNode(root, 10);

    /* The AVL Tree after deletion of 10
            1
           /  \
          0    9
        /     /  \
       -1    5     11
           /  \
          2    6
    */

    //printf("\nPreorder traversal after deletion of 10 \n");
    //preorderTraversal(root);

    /*inorderTraversal(root);
    std::cout << "\n";

    preorderTraversal(root);
    std::cout << "\n";

    postorderTraversal(root);
    std::cout << "\n";

    DFS(root);
    std::cout << "\n";

    BFS(root);
    std::cout << "\n";

    exists(4) ? std::cout << "Yes" << std::endl : std::cout << "No" << std::endl;*/


    std::cin.get();
}

Why can't I use a lambda in a std::map constructor?

I am currently working on a program for which I must create a map to store data using a specific key. Although a strict weak ordering is possible for that key, the ordering has no meaning relative to the meaning of the key. As such, I decided to give my map a comparator lambda instead of overriding operator< on my key type. When I do this, however, I get a plethora of compile errors that seem to boil down to the idea that a lambda can not be converted into the type that the compiler requires. Why is this?

Minimum complete verifiable example:

#include <iostream>

#include <map>

struct CustomClass{
    unsigned a;
};

int main(){
    std::map<CustomClass, int> bad_map([](const CustomClass &a, const CustomClass &b){ return a.a < b.a; });
}

Clang 6.0.1 errors on Linux:

$ clang++ bug.cpp -o bug
bug11.cpp:9:29: error: no matching constructor for initialization of 'std::map<CustomClass, int>'
        std::map<CustomClass, int> bad_map([](const CustomClass &a, const CustomClass &b){ return a.a < b.a; });
                                   ^       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/8.2.1/../../../../include/c++/8.2.1/bits/stl_map.h:192:7: note: candidate constructor not viable: no known conversion from '(lambda at bug11.cpp:9:37)' to
      'const std::less<CustomClass>' for 1st argument
      map(const _Compare& __comp,
      ^
/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/8.2.1/../../../../include/c++/8.2.1/bits/stl_map.h:205:7: note: candidate constructor not viable: no known conversion from '(lambda at bug11.cpp:9:37)' to 'const
      std::map<CustomClass, int, std::less<CustomClass>, std::allocator<std::pair<const CustomClass, int> > >' for 1st argument
      map(const map&) = default;
      ^
/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/8.2.1/../../../../include/c++/8.2.1/bits/stl_map.h:213:7: note: candidate constructor not viable: no known conversion from '(lambda at bug11.cpp:9:37)' to
      'std::map<CustomClass, int, std::less<CustomClass>, std::allocator<std::pair<const CustomClass, int> > >' for 1st argument
      map(map&&) = default;
      ^
/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/8.2.1/../../../../include/c++/8.2.1/bits/stl_map.h:226:7: note: candidate constructor not viable: no known conversion from '(lambda at bug11.cpp:9:37)' to
      'initializer_list<std::map<CustomClass, int, std::less<CustomClass>, std::allocator<std::pair<const CustomClass, int> > >::value_type>' (aka 'initializer_list<pair<const CustomClass, int> >') for
      1st argument
      map(initializer_list<value_type> __l,
      ^
/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/8.2.1/../../../../include/c++/8.2.1/bits/stl_map.h:234:7: note: candidate constructor not viable: no known conversion from '(lambda at bug11.cpp:9:37)' to 'const
      std::map<CustomClass, int, std::less<CustomClass>, std::allocator<std::pair<const CustomClass, int> > >::allocator_type' (aka 'const std::allocator<std::pair<const CustomClass, int> >') for 1st
      argument
      map(const allocator_type& __a)
      ^
/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/8.2.1/../../../../include/c++/8.2.1/bits/stl_map.h:254:2: note: candidate constructor template not viable: requires 3 arguments, but 1 was provided
        map(_InputIterator __first, _InputIterator __last,
        ^
/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/8.2.1/../../../../include/c++/8.2.1/bits/stl_map.h:271:2: note: candidate constructor template not viable: requires 2 arguments, but 1 was provided
        map(_InputIterator __first, _InputIterator __last)
        ^
/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/8.2.1/../../../../include/c++/8.2.1/bits/stl_map.h:288:2: note: candidate constructor template not viable: requires at least 3 arguments, but 1 was provided
        map(_InputIterator __first, _InputIterator __last,
        ^
/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/8.2.1/../../../../include/c++/8.2.1/bits/stl_map.h:183:7: note: candidate constructor not viable: requires 0 arguments, but 1 was provided
      map() = default;
      ^
/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/8.2.1/../../../../include/c++/8.2.1/bits/stl_map.h:238:7: note: candidate constructor not viable: requires 2 arguments, but 1 was provided
      map(const map& __m, const allocator_type& __a)
      ^
/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/8.2.1/../../../../include/c++/8.2.1/bits/stl_map.h:242:7: note: candidate constructor not viable: requires 2 arguments, but 1 was provided
      map(map&& __m, const allocator_type& __a)
      ^
/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/8.2.1/../../../../include/c++/8.2.1/bits/stl_map.h:248:7: note: candidate constructor not viable: requires 2 arguments, but 1 was provided
      map(initializer_list<value_type> __l, const allocator_type& __a)
      ^
1 error generated.

vector

I am writing a program right now where I have to have only alpha characters, and one is only integers.

I have made a header file for the alpha character vectors and one for the int vectors.

I have vector<vector<char>> and vector<vector<int>>

Is it possible for c++11 to figure out what type of 2d vector I want with something like

vector<vector<auto>>

or does this not exist in c++

Implementing an AVL Tree

I am trying to implement an AVL Tree following the guidelines from here. I been having some issues getting this to work. Currently I am getting this error in the "Right Right Case" of insert. Specifically at this line:

// Right Right Case
if (balance < -1 && theData > root->right->data)
    leftRotate(root);

The error I get is:

Exception thrown: read access violation.
root._Mypair._Myval2->right._Mypair._Myval2 was nullptr.

I would really appreciate if someone could help me fix this.

Here is my code:

#include <algorithm>
#include <iostream>
#include <memory>
#include <utility>
#include <stack>
#include <queue>

struct Node {
    int data;
    int height;
    std::unique_ptr<Node> left = nullptr;
    std::unique_ptr<Node> right = nullptr;

    Node(const int& x, const int& y, std::unique_ptr<Node>&& p = nullptr, std::unique_ptr<Node>&& q = nullptr) :
        data(x),
        height(y),
        left(std::move(p)),
        right(std::move(q)) {}

    Node(const int& data) : data(data) {}

};
std::unique_ptr<Node> root = nullptr;

int height(std::unique_ptr<Node>& root) {
    if (!root) return 0;
    return root->height;
}

void rightRotate(std::unique_ptr<Node>& y) {
    std::unique_ptr<Node> x = std::move(y->left);
    std::unique_ptr<Node> T2 = std::move(x->right);

    // Perform rotation
    x->right = std::move(y);
    y->left = std::move(T2);

    // Update heights
    y->height = std::max(height(y->left), height(y->right)) + 1;
    x->height = std::max(height(x->left), height(x->right)) + 1;

}

void leftRotate(std::unique_ptr<Node>& x) {
    std::unique_ptr<Node> y = std::move(x->right);
    std::unique_ptr<Node> T2 = std::move(y->left);

    // Perform rotation
    y->left = std::move(x);
    x->right = std::move(T2);

    // Update heights
    x->height = std::max(height(x->left), height(x->right)) + 1;
    y->height = std::max(height(y->left), height(y->right)) + 1;

}

int heightDiff(std::unique_ptr<Node>& root) {
    if (!root) return 0;

    return height(root->left) - height(root->right);
}

void insert(std::unique_ptr<Node>& root, const int& theData) {
    std::unique_ptr<Node> newNode = std::make_unique<Node>(theData);
    // Perform normal BST insertion
    if (root == nullptr) {
        root = std::move(newNode);
        return;
    }

    else if (theData < root->data) {
        insert(root->left, theData);
    }

    else {
        insert(root->right, theData);
    }

    // Update height of this ancestor node
    root->height = 1 + std::max(height(root->left), height(root->right));

    // Get the balance factor of this ancestor node to check whether this node became unbalanced
    int balance = heightDiff(root);

    // If this node become unbalaced, then we have 4 cases

    // Left Left Case
    if (balance > 1 && theData < root->left->data)
        rightRotate(root);

    // Right Right Case
    if (balance < -1 && theData > root->right->data)
        leftRotate(root);

    // Left Right Case
    if (balance > 1 && theData > root->left->data) {
        leftRotate(root->left);
        rightRotate(root);
    }

    // Right Left Case
    if (balance < -1 && theData < root->right->data) {
        rightRotate(root->right);
        leftRotate(root);
    }
}

auto findMin(std::unique_ptr<Node>& root) {
    while (root->left != nullptr) root = std::move(root->left);
    return root.get();
}

void deleteNode(std::unique_ptr<Node>& root, const int& theData) {
    // Step 1: Perform regular deletion for BST
    if (!root) return;
    else if (theData < root->data) deleteNode(root->left, theData);
    else if (theData > root->data) deleteNode(root->right, theData);

    else {
        // Case 1: No child
        if (root->left == nullptr && root->right == nullptr) {
            root = nullptr;
        }

        // Case 2: One child
        else if (root->left == nullptr) {
            root = std::move(root->left);
        }

        else if (root->right == nullptr) {
            root = std::move(root->right);
        }

        // Case 3: Two children
        else {
            auto temp = findMin(root->right);
            temp->data = root->data;
            deleteNode(root->right, temp->data);
        }
    }

    if (!root) return;

    // Step 2: Update height of the current node
    root->height = 1 + std::max(height(root->left), height(root->right));

    // Step 3: Get the balalce factor of the this node (to 
    // check whether this node became unbalanced)
    int balance = heightDiff(root);

    // If this node becomes unbalanced, then there are 4 cases

    // Left Left Case
    if (balance > 1 && heightDiff(root->left) >= 0)
        rightRotate(root);

    // Left Right Case
    if (balance > 1 && heightDiff(root->left) < 0) {
        leftRotate(root->left);
        rightRotate(root);
    }

    // Right Right Case
    if (balance < -1 && heightDiff(root->right) <= 0)
        leftRotate(root);

    // Right Left Case
    if (balance < -1 && heightDiff(root->right) > 0) {
        rightRotate(root->right);
        leftRotate(root);
    }
}

void inorderTraversal(std::unique_ptr<Node>& root) {
    if (!root) {
        inorderTraversal(root->left);
        std::cout << root->data << " ";
        inorderTraversal(root->right);
    }
}

void preorderTraversal(std::unique_ptr<Node>& root) {
    if (root != nullptr) {
        std::cout << root->data << " ";
        preorderTraversal(root->left);
        preorderTraversal(root->right);
    }
}

void postorderTraversal(std::unique_ptr<Node>& root) {
    if (root != nullptr) {
        postorderTraversal(root->left);
        postorderTraversal(root->right);
        std::cout << root->data << " ";
    }
}

void DFS(std::unique_ptr<Node>& root) {
    if (!root) return;

    std::stack<Node const *> s;
    s.push(root.get());

    while (!s.empty()) {
        auto p = s.top();
        s.pop();

        if (p->right != nullptr) s.push(p->right.get());
        if (p->left != nullptr) s.push(p->left.get());

        std::cout << p->data << " ";
    }
}

void BFS(std::unique_ptr<Node>& root) {
    if (!root) return;

    std::queue<Node const *> q;
    q.push(root.get());

    while (!q.empty()) {
        auto p = q.front();
        q.pop();

        if (p->left != nullptr) q.push(p->left.get());
        if (p->right != nullptr) q.push(p->right.get());

        std::cout << p->data << " ";
    }
}

bool exists(int d) {
    auto temp = root.get();
    while (temp != nullptr) {
        if (temp->data == d) {
            return true;
        }
        else {
            if (d > temp->data) {
                temp = temp->right.get();
            }
            else {
                temp = temp->left.get();
            }
        }
    }
    return false;
}

int main() {

    //        8
    //      /    \
    //    4       10
    //   / \     /  \
    //  2   6   9    12

    //insert(root, 8);
    //insert(root, 10);
    //insert(root, 4);
    //insert(root, 2);
    //insert(root, 6);
    //insert(root, 12);
    //insert(root, 9);


  /* Constructing tree given in the above figure */
    insert(root, 9);
    insert(root, 5);
    insert(root, 10);
    insert(root, 0);
    insert(root, 6);
    insert(root, 11);
    insert(root, -1);
    insert(root, 1);
    insert(root, 2);

    /* The constructed AVL Tree would be
            9
           /  \
          1    10
        /  \     \
       0    5     11
      /    /  \
     -1   2    6
    */

    printf("Preorder traversal of the constructed AVL "
        "tree is \n");
    preorderTraversal(root);

    deleteNode(root, 10);

    /* The AVL Tree after deletion of 10
            1
           /  \
          0    9
        /     /  \
       -1    5     11
           /  \
          2    6
    */

    printf("\nPreorder traversal after deletion of 10 \n");
    preorderTraversal(root);

    /*inorderTraversal(root);
    std::cout << "\n";

    preorderTraversal(root);
    std::cout << "\n";

    postorderTraversal(root);
    std::cout << "\n";

    DFS(root);
    std::cout << "\n";

    BFS(root);
    std::cout << "\n";

    exists(4) ? std::cout << "Yes" << std::endl : std::cout << "No" << std::endl;*/


    std::cin.get();
}

unpacking variadic template arguments to define new template arguments

I am new to template programming and I have two questions...Hopefully someone can help me. I am trying to use variadic templates to generate a new input to another variadic template. In other words, I have a class

template <std::size_t N, std::size_t... M>
class Class1 {

}

I want to use the integer values represented by N,M to generate a new set of std::bitset type inputs to another templated class

template <typename T, typename... Ts>
class Class2 {

}

So for example if I use Class1<10,20,25> I want inside the body of Class1 to create a Class2<std::bitset<10>, std::bitset<20>, std::bitset<25>> variable. Is there a simple way to do this using C++11?

My second question then is how can I abstract this even more so that the unpacking is not specific to the std::bitset class? Is there a way to modify the Class1 template definition so that I can expand some arbitrary templated class that I develop instead of std::bitset?

howto use find_if with non-container such as linked list?

I am trying to algorithm support for a static list of objects. I have tried to do this various ways but the only way I can get it to work is to write a traditional C for loop.

Example:

class ListNode
{
public:
    ListNode(int id);
    virtual ~ListNode() {}

    // Container support functions
    ListNode* operator++() {return m_nextNode;}
    static ListNode* findNode(int p_id);
    static ListNode* m_nodeList{nullptr};

private:
    int m_id;
    ListNode *m_nextNode;

protected:
    static void addNewNode(ListNode* p_node);

    friend ListNode* begin(void);
};

inline ListNode* begin(void) {return ListNode::m_nodeList;}
inline ListNode* end(void) {return nullptr;}

// Declare the list head
ListNode* ListNode::m_nodeList = nullptr;

// Constructor
ListNode::ListNode (int id): m_id{id}
{
    ListNode::addNewNode(this);
}

// Add node to front of list
void ListNode::addNewNode(ListNode* p_node)
{
    p_node->m_nextService = m_nodeList;
    m_nodeList = p_node;
}

//
// The following are all the find implementation attempts
//

ListNode* ListNode::failedFind1(int id) {
   return std::find_if(ListNode::m_nodeList, 
      static_cast<ListNode*>(nullptr),
      [p_serviceNumber](const ListNode& s) {
         return id==s.m_id;
      }
);

I also tried this using the begin() and end() functions defined. The only thing that works is the following:

for (auto *s = m_nodeList; s != nullptr; s = s->m_nextNode)
{
    if (s->m_id == id)
        return s;
}
return nullptr;

What am I missing?

Thanks

Is a condition variable's .wait_for() an efficient way to perform a background task at a specific interval?

I need to run an activity every so often while my program is running. In production code this is configurable with a default of 30 minutes, but in the example below I've used 5 seconds. Previously I had a std::thread that would loop once per second checking to see if it was time to run the activity OR if the program was closed. This allowed me to close the program at any time without having the .join() on the activity's thread block my application's exit waiting for its next iteration. At any moment it was less than a second away from checking to see if it should close or perform the activity.

I do not like the idea of wasting time checking every second for an activity that may only occur every 30 minutes while the program is running, so I attempted to switch it to a condition variable. I've included a small example of my implementation below. I want to be sure I'm using the right tools to do this. The issue I see with my code is unnecessary calls of the lambda expression which I'll explain below.

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

bool asking_thread_to_quit;
std::mutex cv_mutex;
std::condition_variable cv;

void RunThread()
{
    asking_thread_to_quit = false;

    std::cout << "Started RunThread." << std::endl;
    while(true)
    {
        std::unique_lock<std::mutex> lock(cv_mutex);
        std::chrono::seconds delay(5);
        if(cv.wait_for(lock, delay, [] { std::cout << "WAKEUP" << std::endl; return asking_thread_to_quit; })) // timed out
        {
            std::cout << "Breaking RunThread Loop." << std::endl;
            break;
        }
        else
            std::cout << "TIMER CODE!" << std::endl;
    }
}

int main(int argc, char *argv[])
{
    std::cout << "Program Started" << std::endl;
    std::thread run_thread(RunThread);

    // This is where the rest of the program would be implemented, but for the sake of this example, simply wait for user input to allow the thread to run in the background:
    char test;
    std::cin >> test;

    asking_thread_to_quit = true;
    cv.notify_all();

    std::cout << "Joining RunThread..." << std::endl;
    run_thread.join();
    std::cout << "RunThread Joined." << std::endl;

    return 0;
}

If you execute the program and allow for one 5-second iteration to pass, it gives the following output:

Program Started
Started RunThread.
WAKEUP
WAKEUP
TIMER CODE!
WAKEUP
q    <-- I typed this to quit.
Joining RunThread...
WAKEUP
Breaking RunThread Loop.
RunThread Joined.

You can see that it does the following:

  1. (WAKEUP) Performs the check prior to waiting

  2. Wait for five seconds

  3. (WAKEUP) Performs the check

  4. (TIMER CODE!) Executes the activity
  5. (WAKEUP) Performs the check again before going back to waiting

Step 5 seems unnecessary as I just performed it a split second ago, but I believe it is necessary as .wait_for() doesn't know I'm using it inside of a while(true) loop. Is this something I'm stuck with, or is there a way to remove the initial check in the .wait_for() call? I'm guessing there is not as it would allow for the system to .wait_for() something that it doesn't need to wait for. This is what leads me to wonder if I'm using the right language features to begin with. Is there a better way?

using EnumWindows in namespaced class

All, I'm trying to implement EnumWindows behavior in order to close a running executable. I have created a standard class (h/cpp) and only have a couple simple functions in there. The callback function i have defined is causing compilation errors, which clear up as soon as i remove the class namespacing. See code below.

class ProcessLauncher()
{
public:
    ProcessLauncher() {}
    ~ProcessLauncher() {}

    bool CloseApplicationByTitle(const std::string& title)
    {
        //error says: argument of type "BOOL (__stdcall ProcessLauncher::*)(HWND hwnd, LPARAM lParam)" is incompatible with parameter of type "WNDENUMPROC"
        EnumWindows(DoActionByTitle, (LPARAM)WM_CLOSE);
    }

private:
    BOOL CALLBACK DoActionByTitle(HWND hwnd, LPARAM lParam)
    {
        //do stuff
    }
};

SO what in the world am i doing wrong here?

C++ template: add const to type if template arg is const

I have a class:

struct Foo {
  vector<float> data;
};

and I have a templated function that takes a Foo&:

template<typename T>
void f(T& arg) {
  using ftype = float *;    // <-- would like this to be const float * if T is const
  ftype ptr = &arg.data[0];
  // ... do stuff with ptr ...
}

How can I make ptr be const float * iff T is const? I know about add_const and is_const but don't see how to use them here. (My real struct is more complicated and I don't have direct access to its internals; it's actually an OpenCV cv::Mat.) I can use recent (C++14/C++17) features if needed.

I'll use it like this:

Foo foo1 = Foo();
f(foo1); // modifiable in f
const Foo cfoo = Foo();
f(cfoo); // const, should not be modifiable in f

std::vector move instead of swap to clear

Do I understand right, that with introduction of move semantics in C++11, move can be used instead of swap-to-clear idiom?

std::vector<T>().swap( v );
// VS
v = std::move( std::vector<T>() );

Is the second approach guaranteed to clear storage?

Why does not my code do input validation upon a string getting entered?

I have been trying to get a bug fixed. which is based on upon when a user inputs a number instead of a string as a name for the user. the program loops, i have been trying to implement Cin.reset and cin.ignore(numeric_limits::max(),’\n’);. But it does not work, i did this in a while loop, but all forsaken.

Down below is my code:

#include "stdafx.h"
#include "pch.h"
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <ctime>
#include <string>
#include <stdlib.h>

using namespace std;

int main() {
    string Yes;
    int bet;
    int color;
    string name;
    string answer;
    //string choice;
    int age;
    char choice, colour;
    int yes;
    int no;
    int konto = 1000;
    int number;
    int rand_number;

    cout << "Hello and welcome to Roulette House" << endl;


    cout << "What is Your name:" << endl;
    cin >> name;
    cout << "Your name is: \t" << name << endl;
    while (!(cin >> name)) {
        cin.reset();
        cin.ignore(numeric_limits<streamsize>::max(), ’\n’);
        cout << "please write only characters" << endl;
        cin >> name;

    }
    cout << "Do you want to start the game?" << endl;''

    cout << "please write yes or no?" << endl;
    cin >> answer;

    if (answer != "yes") {
        cout << "ok thanks for stepping by" << "!!!!!" << endl;
        return 0;
    }

    cout << "welcome" << endl;
    cout << "This is the rules of the game: You must be 18 or over to play this game!" << endl;
    cout << "As a bonus you will start the game with 1000kr" << endl;

    cout << "you have" << konto << "kr in your account" << endl;

    cout << "How old are you?";
    cin >> age;

    if (age >= 18)
    {
        cout << "you are allowed to play" << endl;
    }
    else
    {
        cout << "sorry your are to young to play" << endl;
        return (0);
    }


    while (true)
    {
        cout << "Place your bet. Remember you can only bet 100kr,300kr and 500kr" << endl;
        cin >> bet;

        while (bet != 100 && bet != 300 && bet != 500) {
            cout << "please choose between 100 or 300 or 500" << endl;
            cin >> bet;
        }

        while (true)
        {
            cout << "You can choose one of the options, c (color)  or n (number)?" << endl;
            cin >> choice;

            if (choice != 'c' && choice != 'C' && choice != 'n' && choice != 'N') {
                break;
            }
        }

        if (toupper(choice) == 'N') {

            cout << "choose a number between 1 and 36" << endl;
            cin >> number;

            while (number < 1 || number > 36) {
                cout << "Enter a number between 1 and 36" << endl;
                cin >> number;
            }


            srand(time(0));
            rand_number = rand() % 36 + 1;

            cout << "the winning number is" << rand_number << "." << endl;

            if (choice == 'N' && number != rand_number)

                cout << "You lost $" << 1*bet << endl;
            }
            else {

                cout << "You win!" << endl;
            }
        }
        else if (choice == 'c' || choice == 'C')
        {
            colour = ' ';

            while (colour != 'b' && colour != 'r')
            {
                cout << "color b (black) or r (red)" << endl;
                cin >> colour;

                if (colour == 'b') {
                    cout << "you choosed black" << endl;
                }
                else if (colour == 'r') {
                    cout << "you choosed red" << endl;
                }
            }
            char colors[2] = { 'b', 'r' };
            int rand_index = rand() % 2;
            if (colors[rand_index] == colour) {
                cout << "You won!" << endl;
            }
            else {
                cout << "You lost!" << endl;
            }
        }

        cout << "Bet again yes or no?" << endl;
        cin >> answer;

        if (answer != "yes") {
            cout << "ok thanks for stepping by" << "!!!!!" << endl;
            return 0;
        }
    }
    return 0;
}

Thank you for youre time and i will appreciate all feedback given.

initialising array of vectors in constructor

I have a class named Graph. There this vertices member of the class. I have initialized vertices in the constructor. Also, There is a member array of vectors. I want the number of vectors to be equal to vertices. for example if vertices = 5 then my array of vectors should look like this. vector v[5]; How can I do this in the constructor as I will only know the value of vertices in the constructor?

class Graph
{

private:
    int vertices;
    std::vector<int> adj[];
public:
    Graph(int v); //constructor
    // add an edge
    void addEdge(int u, int v);
    //print bfs traversal of graph
    void bfs(int s); // s is a source from where bfs traversal should 
                     //start

};

Graph :: Graph(int v)
{
   vertices = v;
}

Why overriding both the global new operator and the class spefic operator is not ambigous behaviour?

Consider the following code:

class Foo 
{
public:
    //class specific
    Foo operator+(Foo& rhs)
    {
       return Foo(); //Just return a temporary
    }

    void* operator new(size_t sd)
    {
        return malloc(sd);
    }
};

//global
Foo operator+(Foo& lhs, Foo& rhs)
{
    return Foo();
}

void* operator new(size_t sd)
{
    return malloc(sd);
}

This code will not compile, stating the call is ambigous because it matches two operators:

Foo a, b;
a + b;

But this one with the new operator compiles just fine, and will call the class-specific one.

Foo* a = new Foo();

Why doesn't it result in a compile error? Does the compiler treat the new operator differently? (Any citation to the standard would be appreciated)

Initialize initializer_list from template parameters

I need to set up a large number of std::vector in a lookup library. The all have the structure:

{N, N, ..., -N, -N}

I can do that with a number of templated functions:

template<int N>
static constexpr std::initializer_list<int> H2 = {N, -N};
template<int N>
static constexpr std::initializer_list<int> H4 = {N, N, -N -N};
...

from which I can simply do:

std::vector<int> v22 = H2<3>    
std::vector<int> v35 = H3<5>
etc.

But would there be a way to include also the numbers 2, 4 etc. as a template parameter?

MSVC's (seem not perfect) support for constexpr

I am making the naive wheel of type traits's is_base_of. And Here's a minimal demo about my implementation(didn't consider robustness, is_class...).

#include <type_traits>
#include <cstdint>
struct A
{

};
struct B : A
{

};
template
<typename T, typename U>
struct IsBaseOf {
    constexpr static bool Test(T* t)
    {
        return true;
    }

    constexpr static bool Test(...)
    {
        return false;
    }

    constexpr static bool value = IsBaseOf<T,U>::Test(static_cast<U*>(nullptr));
};
int main()
{
    static_assert(IsBaseOf<A, B>::value, "Pass");
}

This demo can be compiled by gcc/clang but cannot be compiled by MSVC. http://rextester.com/ATOC6638 http://rextester.com/IWU81465

When i type it on my laptop's Visual Studio 2015(with update patch 3). It cannot be compiled either, the IDE reminds me that "expression must have constant value" before compiling.

So I wonder how's MSVC support for constexpr, or is my code wrong?

How to add label to a bounding box in dlib c++

I have several face shapes and their corresponding labels. I wanna print the labels along side of the face bounding boxes. So far what I have found is the following:

            win.clear_overlay();
            win.set_image(cimg);
            for (size_t i = 0; i < input_face_descriptors.size(); ++i)
            { 
                win.add_overlay(face_position[i], rgb_pixel(255, 0, 0));
                label::draw(face_position[i]);
                const rectangle r;
                win.add_overlay(image_window::overlay_rect(r, rgb_pixel(255, 0, 0), labels[i]));
            }

But this adds the text to the right hand corner of the frame and the labels are displayed one over the other.

Reference to non-static member function must be called when processing callbacks inside a class

I have the following API code provided by PiGPIO library. Basically it allows you to set a callback function when the state of a pin was changed.

Normally the API looks like this:

typedef void (*gpio_callback_t)(int, int, uint32_t);
int gpioSetAlertFunc(int, gpio_callback_t)

And it can be called like this:

void callback_func(int pin, int NewLevel, uint32_t CurrentTicks)
{
    // Callback process
}

int main()
{
    // Setting up callback function
    gpioSetAlertFunc(10, callback_func)

    // Do stuff while callback will be called independently  
}

Now the code above works perfectly!


The big problem comes when I try to wrap this code in a C++ class. The class shall look like the following:

class Pin
{
public:
    Pin()
    {
        gpioSetAlertFunc(10, this->internal_gpio_callback) );
    }

    void internal_callback_func(int pin, int level, uint32_t tick)
    {
        cout << "New level: " << pin << " " << level;
    }
}

The problem is that the reference to that function is not allowed as it is not a static function. For things to be more complicated, I can't just make the callback function static. That callback function will interact a lot with the rest of the class methods and it's internal variables.

Do you know a workaround for this? Or maybe a dirty hack using pointers or something?

jeudi 27 septembre 2018

Time complexity of std::vector::erase on the beginning element of a vector

After taking a look at how vector.erase works I am unsure if the run time complexity of std::vector::erase on the first element of a vector. Would it be constant time?

AVL Tree implementation, error with left and right rotate

I am rewritting some data structures and I have not done this one before so I am pretty new with AVL trees. Following the link here I tried to implement the insert function.

Although, I get an error for the left and right rotate function. For example in the right rotate function the line where I perform the rotation, my compiler flags this line: y->left = std::move(T2); with an error:

    binary '=': no operator found which takes a right-hand operand of type '_Ty 
*' (or there is no acceptable conversion)

I am not sure how to fix this issue. Here is my code:

#include <algorithm>
#include <iostream>
#include <memory>
#include <utility>


struct Node {
    int key;
    int height;
    std::unique_ptr<Node> left = nullptr;
    std::unique_ptr<Node> right = nullptr;

    Node(const int& x, const int& y, std::unique_ptr<Node>&& p = nullptr, std::unique_ptr<Node>&& q = nullptr) :
        key(x),
        height(y),
        left(std::move(p)),
        right(std::move(q)) {}
};
std::unique_ptr<Node> root = nullptr;

int getDepth(std::unique_ptr<Node>& root) {
    if (!root) return 0;
    else {
        int l = getDepth(root->left);
        int r = getDepth(root->right);
        return std::max(l, r) + 1;
    }
}

void rightRotate(std::unique_ptr<Node>& y) {
    auto x = y->left.get();
    auto T2 = x->right.get();

    // Perform rotation
    x->right = std::move(y);
    y->left = std::move(T2);

    // Update heights
    y->height = std::max(getDepth(y->left), getDepth(y->right));
    x->height = std::max(getDepth(x->left), getDepth(x->right));
}

void leftRotate(std::unique_ptr<Node>& x) {
    auto y = x->right.get();
    auto T2 = y->left.get();

    // Perform rotation
    y->left = std::move(x);
    x->right = std::move(T2);

    // Update heights
    x->height = std::max(getDepth(x->left), getDepth(x->right));
    y->height = std::max(getDepth(y->left), getDepth(y->right));
}

int getBalance(std::unique_ptr<Node>& root) {
    if (!root) return 0;

    return getDepth(root->left) - getDepth(root->right);
}

void insert(std::unique_ptr<Node>& root, int key) {
    std::unique_ptr<Node> newNode = std::make_unique<Node>(key);
    // Perform normal BST insertion
    if (root == nullptr) {
        root = std::move(newNode);
        return;
    }
    else if (key < root->key) {
        insert(root->left, key);
    }
    else {
        insert(root->right, key);
    }

    // Update height of this ancestor node
    root->height = std::max(getDepth(root->left), getDepth(root->right));

    // Get the balance factor of this ancestor node to check whether this node became unbalanced
    int balance = getBalance(root);

    // If this node become unbalaced, then we have 4 cases

    // Left Left Case
    if (balance > 1 && key < root->left->key)
        rightRotate(root);

    // Right Right Case
    if (balance < -1 && key > root->right->key)
        leftRotate(root);

    // Left Right Case
    if (balance > 1 && key > root->left->key) {
        leftRotate(root->left);
        rightRotate(root);
    }

    // Right Left Case
    if (balance < -1 && key < root->right->key) {
        rightRotate(root->right);
        leftRotate(root);
    }


}

void preorderTraversal(std::unique_ptr<Node>& root) {
    if (root != nullptr) {
        std::cout << root->key << " ";
        preorderTraversal(root->left);
        preorderTraversal(root->right);
    }
}

int main() {

/* The constructed AVL Tree would be
        30
        /  \
    20   40
    /  \     \
    10  25    50
*/

    insert(root, 10);
    insert(root, 20);
    insert(root, 30);
    insert(root, 40);
    insert(root, 50);
    insert(root, 25);

    preorderTraversal(root);

}

C++ comparator passing argument problem of complex situation

I have class A, in which there is a member variable of class B. And in B, there is a member variable of priority_queue "q" and I want to define a customized comparator class C for it. But for the comparator, the comparison needs a member variable "f_val" from A.

Since the original code is long, the basic idea is as follows:

class C
{
  map<Point,double> f_val;
  C(double f_val1)
  {
    f_val=f_val1;
  }
  bool operator () (const Point &pt1, const Point &pt2)
  {
    return f_val[pt1] > f_val[pt2];
  }

};



class A
{
    B b;
    map<Point,double> f_val;
}

class B
{
    B(map<Point,double> f_val1){f_val=f_val1;}
    priority_queue<Point,vector<Point>,C(f_val)> q;
    map<Point,double> f_val;
}

invalid initialization of reference of type âstd::pair

#include <iostream>
#include <utility>
#include <vector>
#include <sys/types.h>
#include <algorithm>
#include <sys/wait.h>
#include <unistd.h>
 using namespace std;
void childFunction(pair<int, pair<int, int>>b);
void parentFunction(pair<int, pair<int, int>>b);
bool priority_sort(pair<int, int> &a, pair<int, int> &b);
int main() {
 pid_t PID;
 int pid = 0;
 int count = 0;
 int quantum, exec, pr;
 vector<pair<int, int>> a;
 vector<int> pid2;
 vector<int>::iterator check;
 pair<int, pair<int, int>>b;
 while (cin >> quantum) {
     while (cin >> exec >> pr) {
        a.push_back(make_pair(exec, pr));
    }
}
 for (int i = 0; i < a.size(); i++) {
     pid2.push_back(pid);
     pid++;
}
 sort(a.begin(), a.end(), priority_sort);
 cout << "Scheduling queue: ";
 for (int i = 0; i < a.size(); i++) {
     if (a[i].first > quantum) {
         a.insert(a.begin() + i + 2, make_pair(a[i].first - quantum, 
   a[i].second)); //SPLIT IF GREATER THEN QUANTUM;
         pid2.insert(pid2.begin() + i + 2, pid2[i]);
        a[i].first = a[i].first - (a[i].first - quantum);
    }
     b = make_pair(pid2[i], a[i]);
     parentFunction(b);
}
 cout << endl;
 pid = 0;
 int endtime = a.size();
 for (int i = 0; i < a.size(); i++) {
    b = make_pair(pid2[i], a[i]);
    pid++;
    if (PID = fork() == 0) {
    childFunction(b);
    exit(0);
    }
    else
    wait(&endtime);

}

}
 void childFunction(pair<int, pair<int, int>>b) {
 cout << "Process " << b.first << ": " << "exec time = " << b.second.first 
 << 
 "," << "priorty = "
    << b.second.second << endl;
 sleep(b.second.first);
 cout << "Process " << b.first << "ends." << endl;
}
  void parentFunction(pair<int, pair<int, int>>b) {
    cout << "(" << b.first << "," << b.second.first << "," <<
    b.second.second << ")" << " ";
}
 bool priority_sort(pair<int, int> &a, pair<int, int> &b)
{
 return (a.second < b.second);
}

The program is to output the childFunction everytime I fork, which works in atom on ubuntu server, and worked on visual studio without fork, but a carbon copy, however inputting it in a ssh server, I get this error:

/usr/include/c++/4.8.2/bits/stl_algo.h:2263:35: error: invalid initialization of reference of type âstd::pair&â from expression of type âconst std::pairâ while (__comp(*__first, __pivot)) ^

/usr/include/c++/4.8.2/bits/stl_algo.h:2266:34: error: invalid initialization of reference of type âstd::pair&â from expression of type âconst std::pairâ while (__comp(__pivot, *__last))

I am unable to get past this intilazation as debugging the code and reading over const haven't lead me to any proper solution. USING NAMESPACE AS IT IS REQUIRED FOR THIS PROJECT

Detect rvalues in forwarding references

I'm trying to write a type-safe, forwarding reference enabled version of list append.

#include <list>
using namespace std;

// Both l1, l2 are mutable, l2 will be copied if lvalue
template<typename L1, typename L2,
         typename T = typename std::remove_reference_t<L1>::value_type,
         typename = std::enable_if_t<is_same_kind_v<L1, list<T>>>,
         typename = std::enable_if_t<is_same_kind_v<L2, list<T>>>>
inline static list<T> app(L1&& l1, L2&& l2) noexcept {
    if constexpr (std::is_rvalue_reference_v<L2>) {
        l1.splice(l1.end(), l2);
        std::cout << "Is RVALUE" << std::endl;
    } else {
        l1.insert(l1.end(), FWD(l2.begin()), FWD(l2.end()));
        std::cout << "Is LVALUE" << std::endl;
    }
    return l1;
}

I'm trying to save as many list copies as possible. I only want one function definition (instead of three for list<T>&, const list<T>&, list<T>&&). The idea is that lvalues should not be modified (insert does not change l2) while rvalues are temporary and can thus be modified (splice moves from l2 to l1).

However when I call my app function like this (my own print function for std::list<T>).

 print(app(lval, list<int>{1,3,5}));

Is LVALUE!!!

[2, 4, 6, 8, 1, 3, 5]

C++: split a string and get all non-empty elements

Now I have a C++ string like this

string str = "         1     30716         5         5         2         2         6";

I need to split the string and get all non-empty elements1,30716,5,5,2,2,2and6. How can I do this?
By the way, someone just told me that C# can do this easily by using string.Split(separator,StringSplitOptions.RemoveEmptyEntries).Can I do the same thing in C++?

C++ string index can be negative?

I have a working code in Ideone here that does not return a failure and my expectation was that an index of -1 in std string should crash the program. Is this a valid access index ?

https://ideone.com/gg7P6M

#include <iostream>
using namespace std;

int main() {
    string h = "hiu";
    std::cout << h[h.size()] << ":" << h[-1] << std::endl; 
    return 0;
}

universal reference within lambda capture [duplicate]

This question already has an answer here:

I have a function with universal reference:

template<typename T>
void Func(T&& foo) {
  // within this function, I have a lambda function
  auto someFunc = [&foo] {                    <---- is this the right way to do it?
      callIntoAnotherFunction(std::forward<T>(foo));
  }
}

Wondering if the way to use reference in the lambda is correct or not. Also what does it mean? Do I always pass into the lambda by reference? What if foo is a r-val reference then?

Lost in a world of pointers

Please help me, i'm not being able to understand how this code is working. I just can't seem to visualize it in my head. An elaborative explanation could save me the trouble of being a failure in life in the future.Thank you.

int **data = new int*[row];

    for(i=0;i<row;i++)
        data[i] = new int[col];

    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            data[i][j] = rand() % u;
        }
    }

Deprecated implicitely-declared copy constructor

I am trying to wrap my head around a weird characteristic of implicitely-declared copy constructors. Take the following example. Once the user implements a custom destructor, the copy-constructor isn't trivial anymore, but is still generated.

#include <type_traits>
#include <cstdio>

struct test {
    test() = default;
    ~test() {
    }
    test(const test&) = default;
    int i{42};
};
static_assert(std::is_copy_constructible_v<test>, "werks"); // OK
static_assert(std::is_trivially_copy_constructible_v<test>, "sad"); // FAILS

int main() {
    test t;
    test t2(t);
    printf("%d\n", t2.i);
    return 0;
}

Online version : https://godbolt.org/z/t-8_W3

My understanding of trivial constructors is they are generated by the compiler. However, cppreference states :

The generation of the implicitly-defined copy constructor is deprecated if T has a user-defined destructor or user-defined copy assignment operator.

So, it seems there is one more state an implicitly-declared constructor can be in, which is "deprecated". It is not "trivial" and not user implemented, but still generated by your compiler... Is that correct? Does someone know a type trait or workaround to verify if a constructor is "deprecated"?

Is it a bad coding practice to include "using namespace std" inside unnamed namespaces?

I understand that it is a bad practice to have "using namespace std" in general as it pollutes the global namespace. But if I consider a case where I'm writing a command line utility, which has core logic inside an unnamed namespace within the same file.

For example,

namespace myapp{
    // Define generic application wide APIs here.
    namespace {
        using namespace std;
        int f(...){
        // cli logic
        } 
    }
}
int main(int argc, char** argv){
    // parse args
    myapp::f(arg1, arg2, ...);
    return 0;
}

The namespace myapp is project specific namespace and many API are enclosed under this namespace. The unnamed namespace will restrict the scope of symbols declared inside it to the current file, so it won't pollute the namespace myapp. Would it still be considered a bad practice?

Declaring Arbitrary Number of Data Members with Variadic Templates

I have a class name that is defined under different specifications, and the class attributes and their corresponding data types change between the specifications. For example, the same class may have new attributes added to it or subtracted from it. In addition, types of these data members also change.

Now, what I want to do is to design a variadic template, so that I can pass these modified class data members from different specifications to one skeleton template class. For example,

template <typename ... T>
class X { .... };
// Now intended use:

X <Type1, Type2, Type3> first_spec (value1, value2, value3);
X <Type5, Type6, Type7, Type8, Type9> second_spec(value5, value6, value7, value8, value9);

The specs share the same member functions but number of data members and their corresponding data types change between specifications.

No sound output in WASAPI shared event driven mode

I have been hammering away at this for the last 24 hours, but no matter what I do, I can't get any sound output through WASAPI (Tried all 3 IAudioClient interfaces, and in the end, I decided to stick with the most recent one). I'm not getting any errors, and everything looks normal on the debugger. Heh, I guess that's what happens when you are just reading docs left and right and hacking code together without having the slightest clue what you are doing.

For the most part, I think my decoder code is correct, unless I misunderstood something. According to the libFLAC docs the "buffer parameter" of the write_callback is an array of signed samples of length frame->header.blocksize. Which matches up with what the Microsoft docs had to say about it

Anyhow, here's my (extremely hacky) code:

This is what my header file looks like:

#pragma once
#include <iostream>
#define NOMINMAX
#include <Mmdeviceapi.h>
#include <Audioclient.h>
#include <limits>

#include <FLAC++/decoder.h>

class WASAPIBackend
{
public:
    WASAPIBackend();
    ~WASAPIBackend();
private:
    HRESULT hr;
    IMMDeviceEnumerator* pEnumerator;
    IMMDevice* pDevice;
    IAudioClient3* pAudioClient;
    IAudioRenderClient* pAudioRenderClient;
    WAVEFORMATEX* pMixFormat;
    uint32_t defaultPeriodInFrames, fundamentalPeriodInFrames, minPeriodInFrames, maxPeriodInFrames;
};

And this is what my cpp file looks like:

#include "WASAPIBackend.h"

// TODO: Fix this mess.
BYTE* m_audioBuf = nullptr;
int32_t* m_audioFrame = nullptr;
size_t currentFrame = 0;

class FLACDecoder : public FLAC::Decoder::File {
    virtual ::FLAC__StreamDecoderWriteStatus write_callback(const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
    virtual void metadata_callback(const ::FLAC__StreamMetadata *metadata);
    virtual void error_callback(::FLAC__StreamDecoderErrorStatus status);

};

::FLAC__StreamDecoderWriteStatus FLACDecoder::write_callback(const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[]) {
    // Audio frame: size of an audio frame is the sample size multiplied by the number of channels in the stream.

    //memmove(m_audioFrame, buffer[0], frame->header.blocksize);
    // printf("Uniplemented - %llu\n", frame->header.channels * frame->header.blocksize);
    m_audioFrame = new int32_t[frame->header.blocksize * frame->header.channels * sizeof(int16_t*)];
    /*memcpy(m_audioFrame, buffer, frame->header.blocksize * frame->header.channels);

    return FLAC__StreamDecoderWriteStatus::FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;*/ 

    // Code below inspired by SDL_Mixer. (Remember to give proper credit later if I decide to stick with it!!!)

    int16_t *data; // TODO:: Switch to smart pointers once everything works.
    unsigned int i, j, channels;
    int shift_amount = 0;

    if (!is_valid()) {
        return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
    }

    switch (get_bits_per_sample()) {
    case 16:
        shift_amount = 0;
        break;
    case 20:
        shift_amount = 4;
        break;
    case 24:
        shift_amount = 8;
        break;
    default:
        fprintf(stderr, "FLAC decoder doesn't support %d bits_per_sample", get_bits_per_sample());
        return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
    }

    if (get_channels() == 3) {
        /* We'll just drop the center channel for now */
        channels = 2;
    }
    else {
        channels = get_channels();
    }

    data = new int16_t[frame->header.blocksize * channels];
    if (!data) {
        fprintf(stderr, "Couldn't allocate %d bytes stack memory", (int)(frame->header.blocksize * channels * sizeof(*data)));
        return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
    }

    if (get_channels() == 3) {
        int16_t *dst = data;
        for (i = 0; i < frame->header.blocksize; ++i) {
            int16_t FL = (buffer[0][i] >> shift_amount);
            int16_t FR = (buffer[1][i] >> shift_amount);
            int16_t FCmix = (int16_t)((buffer[2][i] >> shift_amount) * 0.5f);
            int sample;

            sample = (FL + FCmix);
            if (sample > std::numeric_limits<int16_t>::max()) {
                *dst = std::numeric_limits<int16_t>::max();
            }
            else if (sample < std::numeric_limits<int16_t>::min()) {
                *dst = std::numeric_limits<int16_t>::min();
            }
            else {
                *dst = sample;
            }
            ++dst;

            sample = (FR + FCmix);
            if (sample > std::numeric_limits<int16_t>::max()) {
                *dst = std::numeric_limits<int16_t>::max();
            }
            else if (sample < std::numeric_limits<int16_t>::min()) {
                *dst = std::numeric_limits<int16_t>::min();
            }
            else {
                *dst = sample;
            }
            ++dst;
        }
    }
    else {
        for (i = 0; i < channels; ++i) {
            int16_t *dst = data + i;
            for (j = 0; j < frame->header.blocksize; ++j) {
                *dst = (buffer[i][j] >> shift_amount);
                dst += channels;
            }
        }
    }

    // Supposedly, the audio *should* be interleaved
    memcpy(m_audioFrame, data, (frame->header.blocksize * channels * sizeof(*data)));

    delete[] data;

    return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
}

void FLACDecoder::metadata_callback(const ::FLAC__StreamMetadata *metadata)
{
    /* print some stats */
    if (metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
        /* save for later */
        uint64_t total_samples = metadata->data.stream_info.total_samples;
        unsigned int sample_rate = metadata->data.stream_info.sample_rate;
        unsigned int channels = metadata->data.stream_info.channels;
        unsigned int bps = metadata->data.stream_info.bits_per_sample;


        fprintf(stderr, "blocksize    : %u bytes\n", metadata->data.stream_info.max_blocksize);
        fprintf(stderr, "sample rate    : %u Hz\n", sample_rate);
        fprintf(stderr, "channels       : %u\n", channels);
        fprintf(stderr, "bits per sample: %u\n", bps);
        fprintf(stderr, "total samples  : %llu\n", total_samples);
    }
}

void FLACDecoder::error_callback(::FLAC__StreamDecoderErrorStatus status)
{
    fprintf(stderr, "Got error callback: %d\n", status/*FLAC__StreamDecoderErrorStatusString[status]*/);
}

/* Helper function to fill up the audio buffer up to n frames. As the FLAC decoder can only do
    a whole file at once, or frame by frame */ 
void fillBuffer(FLACDecoder &d, uint32_t frames) {
    for (size_t i = 0; i < frames; ++i) {
        d.process_single();
        memcpy(&m_audioBuf[i], &m_audioFrame, d.get_blocksize() * d.get_channels());
    }
}

constexpr void SafeRelease(IUnknown** p) {
    if (p) {
        (*p)->Release();
    }
}

// TODO: Move everything out of the constructor once playback works.
// TODO: Have the class create a thread, instead of the burden of doing so being on the user.
WASAPIBackend::WASAPIBackend() : hr(0), pEnumerator(nullptr), pDevice(nullptr), pAudioClient(nullptr), pAudioRenderClient(nullptr), pMixFormat(nullptr)
{
    CoInitializeEx(nullptr, COINIT_MULTITHREADED);

    hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), reinterpret_cast<void**>(&pEnumerator));
    if (FAILED(hr)) {
        printf("Got error: %x, while creating MMDeviceEnumerator\n", hr);
    }

    hr = pEnumerator->GetDefaultAudioEndpoint(EDataFlow::eRender, ERole::eConsole, &pDevice);

    if (FAILED(hr)) {
        printf("Got error: %x, while attempting to fetch default audio endpoint (render)\n", hr);
    }

    hr = pDevice->Activate(__uuidof(IAudioClient3), CLSCTX_ALL, NULL, reinterpret_cast<void**>(&pAudioClient));

    if (FAILED(hr)) {
        printf("Got error: %x, while attempting activate IAudioClient3 (render)\n", hr);
    }

    // The sample file is a 2 channel, 16bit, 41000hz FLAC. Since this fetches the audio engine format, it should be fine for now.
    // Not that it would matter according to the docs. In shared mode, Windows takes care of converting to and from the desired audio format.
    hr = pAudioClient->GetMixFormat(&pMixFormat);


    if (FAILED(hr)) {
        printf("Got error: %x, while attempting get mix format (render)\n", hr);
    }

    hr = pAudioClient->GetSharedModeEnginePeriod(pMixFormat, &defaultPeriodInFrames, &fundamentalPeriodInFrames, &minPeriodInFrames, &maxPeriodInFrames);

    if (FAILED(hr)) {
        printf("Got error: %x, while attempting get shared mode periodicities (render)\n", hr);
    }

    hr = pAudioClient->InitializeSharedAudioStream(AUDCLNT_STREAMFLAGS_EVENTCALLBACK, minPeriodInFrames, pMixFormat, nullptr);

    if (FAILED(hr)) {
        printf("Got error: %x, while initializing shared audio stream (render)\n", hr);
    }

    HANDLE audioSamplesReadyEvent = CreateEventEx(NULL, NULL, 0, SYNCHRONIZE | EVENT_MODIFY_STATE);

    if (!audioSamplesReadyEvent) {
        printf("Got error: %x, attempting to create event\n", GetLastError());
    }

    hr = pAudioClient->SetEventHandle(audioSamplesReadyEvent);

    if (FAILED(hr)) {
        printf("Got error: %x, while attempting to set event handle (render)\n", hr);
    }

    hr = pAudioClient->GetService(__uuidof(IAudioRenderClient), reinterpret_cast<void**>(&pAudioRenderClient));

    if (FAILED(hr)) {
        printf("Got error: %x, while attempting to GetService(IAudioRenderClient) (render)\n", hr);
    }

    uint32_t bufferSize = 0;
    uint32_t safeToWrite = 0;
    uint32_t padding = 0;
    pAudioClient->GetCurrentPadding(&padding);
    pAudioClient->GetBufferSize(&bufferSize);

    // TODO: This is garbage, figure out how to organize the code at a later time.
    FLACDecoder d;
    // I got this file from OCRemix, remember to thank them later.
    d.init("audio/07 DaMonz - Choose Your Destiny (Super Smash Bros. Melee).flac");

    d.process_until_end_of_metadata();

    // Grab the entire buffer for the initial fill operation.
    hr = pAudioRenderClient->GetBuffer(bufferSize, &m_audioBuf);

    if (FAILED(hr)) {
        printf("Got error: %x, while retrieving audio buffer (render)\n", hr);
    }

    fillBuffer(d, bufferSize);

    hr = pAudioRenderClient->ReleaseBuffer(bufferSize, 0);

    if (FAILED(hr)) {
        printf("Got error: %x, while attempting to release audio buffer (render)\n", hr);
    }

    pAudioClient->Start();

    // TODO: Infinite loops without ending conditions are bad, so fix it up once everything works.
    while (true) {
        // In theory, this will only hang if the audio client hasn't started playback.
        WaitForSingleObject(audioSamplesReadyEvent, INFINITE);

        pAudioClient->GetCurrentPadding(&padding);

        // printf("Current padding: %d\n", padding);

        safeToWrite = bufferSize - padding;

        hr = pAudioRenderClient->GetBuffer(safeToWrite, &m_audioBuf);

        if (FAILED(hr)) {
            printf("Got error: %x, while retrieving audio buffer (rendering)\n", hr);
        }

        if (FAILED(hr)) {
            printf("Got error: %x, while retrieving current audio buffer padding (rendering)\n", hr);
        }

        // Fill all the "safe space" in the buffer with new data.
        fillBuffer(d, safeToWrite);

        hr = pAudioRenderClient->ReleaseBuffer(safeToWrite, 0);

        if (FAILED(hr)) {
            printf("Got error: %x, while attempting to release audio buffer (render)\n", hr);
        }
    }

    pAudioClient->Stop();

}

WASAPIBackend::~WASAPIBackend()
{
    CoTaskMemFree(pMixFormat);
    SafeRelease(reinterpret_cast<IUnknown**>(&pAudioRenderClient));
    SafeRelease(reinterpret_cast<IUnknown**>(&pAudioClient));
    SafeRelease(reinterpret_cast<IUnknown**>(&pDevice));
    SafeRelease(reinterpret_cast<IUnknown**>(&pEnumerator));
    CoUninitialize();
}

Sorry for the massive blocks of code, If I knew what was wrong, I would have sent the suspect code only. I'm getting mixed signals all over the place. According to my console output, it should be working, as I get no errors, and I get this: relevant console output which is the output from the FLAC decoder metadata_callback.

Using function pointer forward declaration as lamba declaration

What's the closest I can get to something like this?

.h:
    typedef bool (*DoWorkFunc)(uint32_t dParam1, uint32_t dParam2, bool bParam, float fParam1, float fParam2, MyClass& c1, MyClass2& c2);
    void DoWork(DoWorkFunc func);

.cpp:
    bool MyClass::MyFunc(uint32_t val) {
        DoWork(DoWorkFunc { return c2.mVal < c1.mVal + fParam1 + fParam2; } );

        auto f1 = DoWorkFunc { return (bParam ? dParam1 : c1.mVal) < mVal; };
        auto f2 = DoWorkFunc { return ((dParam1 & dParam2) == 0) == bParam; };

        auto f = val < 3 ? f1: f2;
        DoWork(f);
    }

This is the closest clean solution I've been able to get, which requires a mostly copy-pasted solution for the lambda forward declaration.

.h:
    typedef bool (*DoWorkFunc)(uint32_t dParam1, uint32_t dParam2, bool bParam, float fParam1, float fParam2, MyClass& c1, MyClass2& c2);
    #define DoWorkLambda [](uint32_t dParam1, uint32_t dParam2, bool bParam, float fParam1, float fParam2, MyClass& c1, MyClass2& c2) -> bool
    void DoWork(DoWorkFunc func);

.cpp:
    bool MyClass::MyFunc(uint32_t val) {
        DoWork(DoWorkLambda { return c2.mVal < c1.mVal + fParam1 + fParam2; } );

        auto f1 = DoWorkLambda { return (bParam ? dParam1 : c1.mVal) < mVal; };
        auto f2 = DoWorkLambda { return ((dParam1 & dParam2) == 0) == bParam; };

        auto f = val < 3 ? f1: f2;
        DoWork(f);
    }

This works alright for one-off solution, but ends up with a pretty messy header for multiple functions declarations

.h:

    typedef bool (*DoWorkFunc1)(uint32_t dParam1, uint32_t dParam2, bool bParam, float fParam1, float fParam2, MyClass& c1, MyClass2& c2);
    #define DoWorkLambda1 [](uint32_t dParam1, uint32_t dParam2, bool bParam, float fParam1, float fParam2, MyClass& c1, MyClass2& c2) -> bool
    void DoWork1(DoWorkFunc1 func);

    typedef bool (*DoWorkFunc2)(uint32_t dParam1, uint32_t dParam2, bool bParam, float fParam1, float fParam2, MyClass& c1, MyClass3& c2);
    #define DoWorkLambda2 [](uint32_t dParam1, uint32_t dParam2, bool bParam, float fParam1, float fParam2, MyClass& c1, MyClass3& c2) -> bool
    void DoWork2(DoWorkFunc2 func);

    ...

For reference, this is what the code looks like without the preprocessor:

.h:
    typedef bool (*DoWorkFunc)(uint32_t dParam1, uint32_t dParam2, bool bParam, float fParam1, float fParam2, MyClass& c1, MyClass2& c2);
    void DoWork(DoWorkFunc func);

.cpp:
    bool MyClass::MyFunc(uint32_t val) {
        DoWork([](uint32_t dParam1, uint32_t dParam2, bool bParam, float fParam1, float fParam2, MyClass& c1, MyClass2& c2) -> bool
            {
                return c2.mVal < c1.mVal + fParam1 + fParam2;
            }
        );

        auto f1 = [](uint32_t dParam1, uint32_t dParam2, bool bParam, float fParam1, float fParam2, MyClass& c1, MyClass2& c2) -> bool
        {
            return (bParam ? dParam1 : c1.mVal) < mVal;
        };
        auto f2 = [](uint32_t dParam1, uint32_t dParam2, bool bParam, float fParam1, float fParam2, MyClass& c1, MyClass2& c2) -> bool
        {
            return ((dParam1 & dParam2) == 0) == bParam;
        };

        auto f = val < 3 ? f1: f2;
        DoWork(f);
    }