vendredi 31 juillet 2020

Why this Knapsack problem's solution is not working?

I was recently solving a knapsack problem. In this version of knapsack, instead of weight, value is taken into the state.

The problem is the same as general Knapsack: There are n items, Item i has a weight of wi and a value of vi. The capacity of the knapsack is W. Find the maximum possible sum of the values of items that can be filled in the knapsack.

Constraints: 1<= n <=100 1<= W <=10^9 1<= wi <=W 1<= vi <=1000

Input: n W
w1 v1 w2 v2 w3 v3 ..... wn vn

Due to large value of weight, We have to take value in the state and the result will be the minimum weight. Although I have explained the problem but in case you need more details this is the problem link.

The below code is my attempt to solve the problem. I have used 1-based indexing. I'm not able to find out the error. I have tried debugging the code but that didn't help. I'm stuck on this from 2 days. Please help.

  #include <iostream>
  #include <limits.h>
  using namespace std;

  int main()
  {
    int n,W;

    cin>>n>>W;    // no. of elements and maxm. Weight
    int v[n+1],w[n+1];   // array for value and weight 
    int dp[n+1][100001];  // dp array with size n+1 and 10^5+1 (for v max value 1000, and for n 100)

    // Initializing arrays

    v[0]=INT_MAX; w[0]=INT_MAX;

    for (int i = 0; i < n+1; ++i)
    {
      for (int j = 0; j < 100001; ++j)
      {
        dp[i][j]=INT_MAX;      
      }
    }

    for (int i = 1; i < n+1; ++i){
      cin>>w[i]>>v[i];
    }
    
    dp[1][0]=0; // for 0 value, no value for weight
    dp[1][v[1]]=w[1]; 

    
    for (int i = 2; i < n+1; ++i) 
    {
      dp[i][0]=0;
      
      for (int j = 1; j < 100001; ++j)
      {
        dp[i][j]=dp[i-1][j]; // excluding the element

        if(j-v[i]>=1){ 
          dp[i][j]=min(dp[i][j],w[i]+dp[i-1][j-v[i]]); // min of including and excluding element
        }
      }
    }

    // to find the max value for which weight is <=W
    for(int i=100000; i>=1; i--){
      if(dp[n][i]<=W){
        cout<<i; break;
      }
    }

    return 0;
  }

Assigning a value returned by copy to a reference

In a codebase that I am working on I am seeing a lot of things like:

std::map<int,int> m;
// ...some code...
const auto& p = m.find(10);

with reference in the type of p. The map's find returns an iterator and not a reference to one, so what is the point of writing such code and how does it work - does it call an iterators copy ctor on the returned value, as it can not just reference the temporary that is being returned, right?

This is just one example, while there are many similar cases throughout that codebase when the functions are returning by value but the caller uses

type& name = func_call()

is there some benefit to doing this that I am missing?

How to check if a template parameter is a struct/class?

For a small example like this, I want to only accept T if T is a struct/class and reject builtin types like 'int', 'char', 'bool' etc.

template<typename T>
struct MyStruct
{
   T t;
};

How to visualize a QPushButton after hovering on a QLabel

How do I visualize a QPushButton after hovering on a QLabel?

Given a very simple user interface composed of a QLabel and a QComboBox shown below:

vis1

The user clicks on the QComboBox below (promoted as QPixmapComboBox), and a list of colors shows up. The user clicks one of this color and a QPixmapPopUp shows up. This QPixmapPopUp is also sub-classed as a QLabel to allow the override of the paintEvent. The popup shows up and after you hover on it it changes color. It was very difficult to arrive to this point for the small verifiable example. Problem: But now I got stuck because as I hover the popup, I have been trying to understand how to show two push button. Those buttons should also disappear as the user does not hover anymore on the popup. For completeness the whole minimal verifiable example can also be downloaded from here if needed:

Below the current behavior and the expected behavior:

Current Behavior:

vis2

Expected Behavior:

vis3

Below the most important part of the code where the animation and the paint event is taken care of: qpixmappopup.h

#include <QLabel>
#include <QTimer>
#include <QVariantAnimation>
#include <QStyleOptionButton>
#include <QStylePainter>
#include <QEvent>

class QPixmapPopUp : public QLabel
{
    Q_OBJECT
public:
    QPixmapPopUp(QWidget *parent = nullptr);
    void show(int msecs = 3000);

signals:
    void clicked();

protected:
    void mousePressEvent(QMouseEvent *e) override;
    void paintEvent(QPaintEvent *) override;
    
private:
    QTimer *mTimer;
    void animateHover(bool in);
    QVariantAnimation *m_transition;
    int m_duration;
    QColor m_currentColor;

};

qpixmappopup.cpp

#include "qpixmappopup.h"
#include <QMouseEvent>
#include <QStyleOptionButton>

QPixmapPopUp::QPixmapPopUp(QWidget *parent)
    : QLabel { parent }
{
    setFrameShape(QLabel::Box);
    setWindowFlag(Qt::Popup);
    setFocusPolicy(Qt::WheelFocus);
    mTimer = new QTimer(this);
    mTimer->setSingleShot(true);
    connect(mTimer, &QTimer::timeout, this, &QLabel::hide);
}

void QPixmapPopUp::show(int msecs)
{
    QLabel::show();
    mTimer->start(msecs);
}

void QPixmapPopUp::mousePressEvent(QMouseEvent *e)
{
    emit clicked();
    hide();
    QLabel::mousePressEvent(e);
}

void QPixmapPopUp::paintEvent(QPaintEvent *)
{
    QStylePainter painter(this);
    QStyleOptionButton option;
    QPalette p(palette());
    option.state |= QStyle::State_MouseOver;

}

void QPixmapPopUp::animateHover(bool in)
{
    const QColor &baseColor(palette().brush(QPalette::Light).color());
    const QColor &highlightColor(palette().brush(QPalette::Highlight).color());
    QColor startValue(in ? baseColor : highlightColor);

    if (m_transition) {
        startValue = m_transition->currentValue().value<QColor>();
        m_transition->stop();
    }

    m_transition = new QVariantAnimation(this);

    m_transition->setStartValue(startValue);
    m_transition->setEndValue(in ? highlightColor : baseColor);
    m_transition->setDuration(m_duration);

    connect(m_transition, &QVariantAnimation::valueChanged, [this](const QVariant &value){
        m_currentColor = value.value<QColor>();
        repaint();
    });

    connect(m_transition, &QVariantAnimation::destroyed, [this](){
        m_transition = nullptr;
    });

    m_transition->start(QAbstractAnimation::DeleteWhenStopped);
}

I have been doing extensive research on how to solve this problem and consulted this source which was good because it explained how the hovering should or should not occur.

I moved initially to re-implementation of the protected memebers void enterEvent(QEvent *ev) override and void leaveEvent(QEvent *ev) override found in this source, and thought it could have been a good idea moving in that direction. But after a bit of trial-error I arrived nowhere.

I tried to search as much as possible a possible solution in the official documentation of Qt5 but didn't really find any useful lead on how to move on from here.

Please if anyone had the same problem, point to the right solution on how to solve this issue as of now I don't have any additional idea on how to move on.

Strange things with c++ string input

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

const int BUFFER_SIZE = 80;

void getstr(char* &str);    

int main()
{
    char* str;
    while(true)
    {
        getstr(str);
        if (!strlen(str))
            break;
    }
    delete [] str;
    return 0;
}

void getstr(char* &str)
{
    char temp[BUFFER_SIZE];
    cout<<"Enter a string(empty line to quit): ";
    cin.get(temp, BUFFER_SIZE);
    while(cin.get()!='\n')
        continue;
    str = new char [strlen(temp)+1];
    strcpy(str, temp);
}

I have string reading loop above and entering empty line to terminate loop doesn't work(after entering empty line program stops responding to any input). But when I replace a loop in getstr with single cin.get() all works fine. What's wrong?

numpy pickle data exchange with C++ Eigen or std::vector

I am writing numpy data to sqlite database with pickling.

Is there anyway to read this pickle from c++ to EigenMatrix or std::vector ?

Best

How to make a variadic template method that takes references rather than copies?

We have a template method that generically executes some member function in parallel, according to the number of system threads available, using a thread pool.

Two of the arguments this method must take are fixed, the first being the thread index and the second being the number of threads.

This is so these methods can do something like the following:

for(i = threadIndex; i < workContainer.size(); i += numThreads) 
{
  // So this thread will only do every numThreads piece of the work from the workContainer, with no overlap between threads
}

This is good, and here is what that method looks like:


  template <class S, class Args>
  void parallelWork(S* self, void (S::*workfcn)(const unsigned, const unsigned, Args*), Args* args)
  {
    auto work = [&](const unsigned threadIndex, const unsigned nthreads, S* self, Args* args)

    {
      std::string* rc = nullptr;

      try
        {
          (self->*workfcn)(threadIndex, nthreads, args);
        }
      catch (std::exception& err)
        {
          rc = new std::string(err.what());
        }

      return rc;
    };

    ulong nthreads = size();
    std::vector<std::string*> rc(nthreads);

    if (1 == nthreads)
      {
        rc[0] = work(0, 1, self, args);
      }
    else
      {
        std::vector<std::future<std::string*>> frc(nthreads);

        for (unsigned i = 0; nthreads > i; ++i)
          frc[i] = enqueue(work, i, nthreads, self, args);

        // Wait for all
        for (unsigned i = 0; nthreads > i; ++i)
          rc[i] = frc[i].get();
      }

    for (unsigned i = 0; nthreads > i; ++i)
      {
        if (rc[i])
          {
            HELAS_ERROR(std::string("Thread ") + std::to_string(i) + ": " + *rc[i]); delete rc[i];
          }
      }
  }

However, this is limited. The current solution requires that we effectively put all of the arguments (some of which are references) into a structure, and then pass a pointer to that structure to this parallelWork() method.

Wouldn't it be great, if instead we could directly pass the arguments the method should take? IE, instead of doing this:

struct ThreadArgs 
{
  const std::vector<int>& inArg1;
  double inArg2;
  SomeClass* inarg3;
  std::vector<std::vector<double>> outArg1; // outer vector is per-thread
}
void MyClass::doFooInParallel() 
{
  std::vector<int> inArg1;
  double inArg2;
  SomeClass* cp = getSomeClass();
  std::vector<std::vector<double>> outArg1(numThreads);

  ThreadArgs args = ThreadArgs(inArg1, inArg2, cp, outArg1);

  parallelWork(this, &MyClass::foo, &args);
}

We could do this:

void MyClass::doFooInParallel() 
{
  std::vector<int> inArg1;
  double inArg2;
  SomeClass* cp = getSomeClass();
  std::vector<std::vector<double>> outArg1(numThreads);

  parallelWork(this, &MyClass::foo, inArg1, inArg2, cp, outArg1);
}

It seems like a variadic template would be the solution, changing the start of the method to this:

  template <class S, class... Args>
  void parallelWork(S* self,void (S::*workfcn)(const unsigned, const unsigned, Args... args),Args... args)
  {
    auto work = [&](const unsigned threadIndex, const unsigned nthreads,S* self, Args... args)

And this does compile with our current usage of the method. However, there is a problem - these arguments are pass-by-value instead of pass-by-reference.

For inputs this may not be bad and some may be eliminated by copy elision. But for variables passed which are outputs of the method (like a vector nthreads in size with output from each thread), that obviously doesn't work - it will mean doing the work in parallel results in nothing being actually done.

I tried making them references like so:

  template <class S, class... Args>
  void parallelWork(S* self,void (S::*workfcn)(const unsigned, const unsigned, Args&&... args),Args&&... args)
  {
    auto work = [&](const unsigned threadIndex, const unsigned nthreads,S* self, Args&&... args)

However, this fails when we try to use it.

could not match type-parameter 0-1&& against (the actual parameter we tried to pass)

(Single-reference also failed, but I tested just in case)

What may be a solution to this? Is it possible in C++11, or only with features from later C++ standards?

Would std::forward or std::ref or std::cref help at all here somehow?

This is really more of a conceptual question, so please forgive me that all of this code can't be run, it'd be an enormous amount of work to get a runnable example of all this up and I think the question is explained well enough to cover it, but let me know if it needs to be clarified.

How to declare a static lookup table using C++11

I have C++11 program which needs to pick a value from a range of values. Each of the ranges have an assigned value to pick a value from.

Following is my range of values with assigned values for each.

1-10 = 5
11-14 = 13
15-20 = 17
21-28 = 24
29-36 = 31
37-47 = 43
48-52 = 50
53-60 = 53
61-68 = 65

So, as you can see above 5 should be return value if the input falls between 1-10, 13 should be chosen if the input falls between 11-14 and so on.

Above requirement could be acheived with the following program with a big dirty list of if else statements.

#include <iostream>

// Following are return values to chosen based on which range the input value falls within
// 1-10 = 5
// 11-14 = 13
// 15-20 = 17
// 21-28 = 24
// 29-36 = 31
// 37-47 = 43
// 48-52 = 50
// 53-60 = 53
// 60-68 = 65

unsigned int GetValueBasedOnRange(const int value) {
    int value_picked_from_appropriate_range = 0;

    if (value > 1 && value < 10) {
        value_picked_from_appropriate_range = 5;
    } else if (value > 11 && value < 14) {
        value_picked_from_appropriate_range = 13;
    } else if (value > 15 && value < 20) {
        value_picked_from_appropriate_range = 17;
    } else if (value > 21 && value < 28) {
        value_picked_from_appropriate_range = 24;
    } else if (value > 29 && value < 36) {
        value_picked_from_appropriate_range = 31;
    } else if (value > 37 && value < 47) {
        value_picked_from_appropriate_range = 43;
    } else if (value > 48 && value < 52) {
        value_picked_from_appropriate_range = 50;
    } else if (value > 53 && value < 60) {
        value_picked_from_appropriate_range = 53;
    } else if (value > 61 && value < 68) {
        value_picked_from_appropriate_range = 65;
    } 

    return value_picked_from_appropriate_range;
}

int main() {
    unsigned int value_within_a_range = 42;
    std::cout << GetValueBasedOnRange(value_within_a_range) << std::endl;
}

Above program works fine but the big if else list of statements is bad. Also, if there are more values and ranges coming in future, they affect the if else logic. Is there way in C++ 11 that I could set up a nice static look up table to achieve this without having to write if else? Some static table that I could declare in a header file with the output values in there?

Some smart way of doing this in C++11? I can probably try an std::map<std::pair<unsigned int, unsigned int>, unsigned int>? But, wondering of a nice way using that or an even simpler approach..

PS: I am not sure if its called a look up table or something else. But, something that picks a hard coded value for a certain pair/range of values.

Unable to build OpenCV project due to build folder not containing opencv_core340.lib

I have a QT 5.4 (Visual Studio 2013 x86 compiler) project that I'm trying to port to QT 5.12(Visual Studio 2017 x64 compiler).

The project is using OpenCV 2.4.9 and I'm trying to upgrade that to OpenCV 3.4.0.

  1. The first thing that I've tried was using the lib folder inside of the pre-compiled build folder that comes along the OpenCV package. But that didn't help because opencv_core340.lib didn't get compiled with the build folder.

  2. I tried building the source folder that comes alongside opencv3.4.0 using CMake however that didn't yield a opencv_core340.lib file inside of the new build folder that I generated.

  3. I tried building OpenCV's source folder with QT Creator which comes alongside the build folder in the initial package. This did get me closer to my goal because after the compilation I did manage to find opencv_core340.lib inside of the directory. However throughout the compilation I've gotten a bunch of errors in the compile output, more prominently something about an internal compiler error.

I'll read more about the problem throughout the weekend in hopes of finding a solution to this problem. My best guess right now is that the library opencv_core___.lib has been now merged into another library.

Let me know if you'd like me to provide more information about the issue..

Reduce time taken in Line Sweep for vertical and horizontal line segments

I have used std::set to implement line sweep algorithm for vertical and horizontal lines. But the final range search on the lower bound and uppper bound of 'status' set takes a lot of time. Is there some way to avoid this? I chose std::set because it is based on balanced BST and insertion, deletion and search take logn time. Is there a better data structure to implement this?


// before this I initialize the events set with segments with increasing x co-ordinates. The segment struct has 2 points variable and 1 type variable for identifying vertical segment(1), horizontal segment starting(0) and ending(2).

for(auto iter = events.begin(); iter != events.end(); iter++)
    {
        segment temp = *iter;

        if(temp.type == 0)
            status.insert(temp.p1);
        else if(temp.type == 2)
            status.erase(temp.p2);
        else
        {    
            auto lower = status.lower_bound(std::make_pair(temp.p1.x, temp.p1.y));
            auto upper = status.upper_bound(std::make_pair(temp.p2.x, temp.p2.y));
            
            // Can the no of elements in the interval be found without this for loop
            for(;lower != upper; lower++)
            {
                count++;
            }
        }
    }

How do I assign to member of type std::function

I have a custom Dialog class (derived from wxDialog). I want to add a setter so you can set a call back function MyDialog::m_f with some function of type std::function<bool(wxString&)>. Later, the dialog will call this function. I want to be able to pass in a lambda function (otherwise I could solve my problem with ordinary function pointers). It must also be possible to call this setter multiple times, the last set value for m_f should be valid, thus erasing any previous set values (the value being a new function). But, if I declare the member m_f, does it have to be initialized in the initializer list in the constructor? For my use case that would not really work. I have to be able to set MyDialog::m_f after the dialog has been constructed (but before ShowModal is called).

Should my member m_f be a (unique) pointer to a std::function<bool(wxString&)>, so it can be set to nullptr in MyDialog::MyDialog?

My basic problem is I do not fully understand std::function. How can you make a variable of some std::function<...> type and assign a value (concrete function) to it later? What does it mean to have a variable like described which is uninitialized? How can I test whether it is (un)assigned? Is it at all possible to delay this assignment, that is: have a separate declaration and later initialization, or should a variable of std::function<...> be initialized immediately (like a const or reference)?

Thanks for any help.

BTW, the language is C++11 and we can't upgrade due to restrictions at work.

How is this code finding the occurrences of x? [closed]

enter image description hereHow is this code working? explain in details please.

How to store into and read back multiple number values on an `uint16_t` using bitwise manipulation?

Using bitwise operations, is it possible to package and read back the following set of values into an uint16_t variable? I think yes but I am trying to figure out how using a sample program.

Lets say following is the set of values I want to package into an uint16_t.

unsigned int iVal1 = 165 // which is 8 bits
unsigned int iVal2 = 28  // which is 5 bits
unsigned int iVal3 = 3   // which is 2 bits
bool bVal = true;        // which can stored in 1 bit if we use 0 for true and 1 for false

Following is my program which aims to write in the values and needs to read back. How can write and read the values back using C++ 11?

#include <iostream>

uint16_t Write(unsigned int iVal1, unsigned int iVal2, unsigned int iVal3, bool bVal) {
    // Is this technique correct to package the 3 values into an uint16_t?
    return static_cast<uint16_t>(iVal1) + static_cast<uint16_t>(iVal2) + static_cast<uint16_t>(iVal3) + static_cast<uint16_t>(bVal);
}

unsigned int ReadVal1(const uint16_t theNumber) {
    // How to read back iVal1
}

unsigned int ReadVal2(const uint16_t theNumber) {
    // How to read back iVal2
}

unsigned int ReadVal3(const uint16_t theNumber) {
    // How to read back iVal3
}

bool ReadVal4(const uint16_t theNumber) {
    // How to read back bVal
}

int main() {
    unsigned int iVal1 = 165; // which is 8 bits
    unsigned int iVal2 = 28;  // which is 5 bits
    unsigned int iVal3 = 3;   // which is 2 bits
    bool bVal = true;        // which can stored in 1 bit if we use 0 for true and 1 for false

    const uint16_t theNumber = Write(iVal1, iVal2, iVal3, bVal);

    std::cout << "The first 8 bits contain the number: " << ReadVal1(theNumber) << std::endl;
    std::cout << "Then after 8 bits contain the number: " << ReadVal2(theNumber) << std::endl;
    std::cout << "Then after 2 bits contain the number: " << ReadVal3(theNumber) << std::endl;
    std::cout << "Then after 1 bit contains the number: " << ReadVal4(theNumber) << std::endl;
}

Check for template type parameter, during compile time, for type specific operation

First of all, the code is restricted to C++11, so I cannot make use of if constexpr

Following is my sample code snippet:

class A{
 public:
    int a;
    int b;
}

class B{
 public:
    int key;
    int val;
}

class C{
 public:
    int n1;
    int n2;
}

class D{
 public:
    int n1;
    int n2;
}

class E{
 public:
    int n1;
    int n2;
}

template<typename T>
void func1(T data) {
   if (T == type(A)) {             // Just pseudo template-check code
    std::cout<<data.a<<data.b;              //<------1
   } else if (T == type (B)) {    // Just pseudo template-check code
    std::cout<<data.key<<data.val;          //<------2
   } else {
    std::cout<<data.n1<<data.n2;            //<------3
}


int main() {
A a;
B b;
C c;
D d;
E e;

func1(a);
func1(b);
func1(c);
func1(d);
func1(e);

return 0;
}

Currently, I get a compile-time error at,

1: B,D,E,F has no member a & b
 & 
2: A,D,E,F has no member key & val
 &
3. A, B has no member n1 & n2

I tried using is_same() & also this, but I get same compile time error every time.

  1. I cannot make use of C++14/C++17
  2. How could I make use of specialized template functions?

Edited the code to highlight the need of a template.

How to Initialize EigenMatrix from json or list of float strings?

I have :

Eigen::MatrixXf feature(1000,512);

and json :

[0.035114631056785583, 0.008220021612942219, -0.0018898098496720195, -0.10943937301635742, 0.03327044099569321, 0.0637984350323677, -0.04793999344110489, -0.0251377634704113, -0.042602453380823135, 0.06513188034296036, 0.04789276421070099, -0.04806295037269592
............]

512 float number.

How can I initialize Eigen::MatrixXf feature(1000,512); each row with above json?

After initialization is eigen-Matrix continues ?

how to change std flag of clang in mac? current clang version 10.0.1 is using c++98 flag

Though documentation of clang says version 10.0.1 uses c++11 but I am trying to compile c++ programs using clang compiler and clang compiler explicitly need -std=c++11 flag to compile with c++11 version.Otherwise it gives error in codes.

Is there a way to change Default Nontype Template Parameters when overloading `std::ostream` operator?

#include <iostream>

struct Foo {
  template <int bias = 5>
  void print() {
    std::cout << bias << std::endl;
  }
};

template <int bias = 5>
std::ostream &operator<<(std::ostream &os, const Foo &foo) {
  return os << bias;
}

int main() {
  Foo a;
  a.print();
  a.print<>();
  a.print<1>();
  std::cout << a << std::endl;
  return 0;
}

By showing this code, I mean, despite the terrible implementation, is there a way to change the default parameter 5 while using std::cout and keeping the struct unchanged?

Hello, does anybody know how to remove a file and it do not lead to race condition?

I try to remove a file and recreate it if it is corrupted. I used remove() and unlink(), but both might lead to race conditions.(I found it while I run static analyzes) Does anybody know an alternative? Thanks in advantages.

jeudi 30 juillet 2020

How to create a reference to any class implementing square bracket operator in C++?

I use std::vetor<double> in some of my logic, but mainly the operator[]. Some data is coming from google's protocol buffer library in a repeated field. An example for the proto file:

message My_message{
  repeated double numbers = 1;
}

So far I've only been using vectors, and converted the protobuf field to vector as described in another question.

void my_function(const std::vector<double> my_numbers){
  ...
  double i_shall_copy_this = my_numbers[0];
  std::copy(my_numbers.begin(),my_numbers.end(), inside_vector.begin());
  ...
}

int main(){
  My_message my_msg;
  ...
  std::vector<double> my_vec = {my_msg.numbers().begin(),my_msg.numbers().end()};
  my_function(my_vec);
  return 0;
}

Unfortunately this comes with unneccessary copying of data, which I would like to avoid. To avoid copying I would like to use references.

void my_function(const std::vector<double>& my_numbers){
  ...
}

int main(){
  My_message my_msg;
  ...
  my_function({my_msg.numbers().begin(),my_msg.numbers().end()}); //(1)
  my_function(reinterpret_cast<std::vector<double>>(my_msg.numbers())); //(2)
  return 0;
}

So far, adding it by temporary works( //(1) ), but it involves copying.

Despite the fact that both google::protobuf::RepeatedField and std::vecDor implements operator[], a reinterpret cast have failed //(2) :

error: invalid cast from type ‘const google::protobuf::RepeatedField<double>’ to type ‘std::vector<double>’

So a solution I have been thinking about is to add a third type, which requires only operator[] and the iterators implemented ( and a contigous guarantee ).

Unfortunately common inheritance is not an option here: Both types come from official libraries, and I am just a mortal unworthy of maintaining a fork of those for a project. What options do I have here?

Use case of explicit deletion of move constructor in C++

I understand move constructor, but in some places I see move constructor is deleted. In what scenarios is deleting a move constructor is useful/makes sense?

Even if the the object needs to be singleton, we can delete the copy constructor but not the move constructor.

Application aborts when webkit_web_view_run_javascript is called

I have a c++11 application that utilizes webkit and gtkmm. I've created a window application containing a container with a webview inside. I'm able to navigate to a URL without issue; however, when I attempt to call webkit_web_view_run_javascript(webview, script, NULL, web_view_javascript_finished, NULL); the application aborts. Has anyone ran into the same issue? I'm really at a loss here. I've tried everything I can think of, and searched google and bing for days.

The breakdown of how the program works is:

  • start main
    • start logic thread
    • detach logic thread
      • waits for webview to initialize
      • waits for home page to be loaded
      • runs javascript against home page
    • start webview thread
    • join webview thread

Some code is redacted and URIs are changd. I.E. https://www.google.com/ is not the actual home page and text encapsulated in [] are changed/shortened for ease of reading.

Here is the webkit code:

        WebKitWebView * webview;
        WebKitSettings * webview_settings;
        bool home_page_loaded;
        void start(const int width, const int height, const std::string name, const std::string title, const bool full_screen, const std::string uri, int argc, char** argv)
        {
            // Create application
            auto application = Gtk::Application::create(argc, argv, name);
            // Create window
            Gtk::Window window;
            window.set_default_size(width, height);
            window.set_title(title);
            // Create webview
            this->webview = WEBKIT_WEB_VIEW(webkit_web_view_new());
            // Create container and place webview inside
            Gtk::Widget * container;
            container = Glib::wrap(GTK_WIDGET(webview));
            // Add container to window
            window.add(*container);
            // Create webview settings
            this->webview_settings = webkit_settings_new();
            // Enable javascript for webview
            g_object_set(this->webview_settings, "enable-javascript", TRUE, NULL);
            // Bind load_handler to load-changed signal
            g_signal_connect(this->webview, "load-changed", G_CALLBACK(this->load_handler), NULL);
            // Apply settings to webview
            webkit_web_view_set_settings(this->webview, this->webview_settings);
            // Place window in full screen if necessary
            if (full_screen)
            {
                window.fullscreen();
            }
            // Navigate to URI
            gchar *g_uri = g_strdup_printf(uri.c_str());
            webkit_web_view_load_uri(this->webview, g_uri);
            // Show all components within window
            window.show_all();
            // Run window application
            application->run(window);
        }
        void run_javascript(const std::string script)
        {

            gchar *g_script = g_strdup_printf(script.c_str());
            webkit_web_view_run_javascript(this->webview, g_script, NULL, web_view_javascript_finished, NULL);
            std::cout << "finished running javascript" << std::endl;
        }
        static void
        web_view_javascript_finished (GObject      *object,
                                    GAsyncResult *result,
                                    gpointer      user_data)
        {
            WebKitJavascriptResult *js_result;
            JSCValue               *value;
            GError                 *error = NULL;

            js_result = webkit_web_view_run_javascript_finish (WEBKIT_WEB_VIEW (object), result, &error);
            if (!js_result) {
                g_warning ("Error running javascript: %s", error->message);
                g_error_free (error);
                return;
            }

            value = webkit_javascript_result_get_js_value (js_result);
            if (jsc_value_is_string (value)) {
                JSCException *exception;
                gchar        *str_value;

                str_value = jsc_value_to_string (value);
                exception = jsc_context_get_exception (jsc_value_get_context (value));
                if (exception)
                    g_warning ("Error running javascript: %s", jsc_exception_get_message (exception));
                else
                    g_print ("Script result: %s\n", str_value);
                g_free (str_value);
            } else {
                g_warning ("Error running javascript: unexpected return value");
            }
            webkit_javascript_result_unref (js_result);
        }
        static void load_handler (WebKitWebView *webview,
                                WebKitLoadEvent load_event,
                                gpointer data)
        {
            switch (load_event) {
                case WEBKIT_LOAD_STARTED:
                    // Do something here later...
                    break;
                case WEBKIT_LOAD_REDIRECTED:
                    // Do something here later...
                    break;
                case WEBKIT_LOAD_COMMITTED:
                    // Do something here later...
                    break;
                case WEBKIT_LOAD_FINISHED:
                    // Get current URI of webview
                    std::string loaded_uri = webkit_web_view_get_uri(webview);
                    // Set p_is_playing based on URI
                    if (loaded_uri == g_strdup_printf("https://www.google.com/"))
                    {
                        home_page_loaded = true;
                    }
                    else
                    {
                        home_page_loaded = false;
                    }
                    break;
            }
        }

Here is how it's implemented in main and how the run_javascript function is called:

bool web_started = false;

void web_handler(std::string uri, int argc, char** argv)
{
    web_started = true;
    //initialize
    web_helper.start(1920, 1080, "Some.Name", "Some Name", true, uri, argc, argv);
}
[some void here]
[some logic here]
    javascript = "window.document.getElementById('pop-up').style.display = 'none';";
    web_helper.run_javascript(javascript);
[end some logic here]
[end some void here]
int main(int argc, char** argv)
{
    std::string uri = "https://www.google.com/"
    std::thread logic_thread([some logic thread]);
    logic_thread.detach();
    std::thread web_thread(web_handler, uri, argc, argv);
    web_thread.join();
}

When are function arguments copied?

I am interested to know when the arguments of a function are copied.

#include <vector>

void foo (std::vector<float> a)
{
   std::vector<float> y = std::move(a);
   //do something with vector y
}

int main()
{
   std::vector<float> x {1.0f, 2.0f, 3.0f};
   std::cout << x.at(0) << " " << x.at(1) << " " << x.at(2) << std::endl; //1.0 2.0 3.0
   foo(x);
   std::cout << x.at(0) << " " << x.at(1) << " " << x.at(2) << std::endl; //print nothing
}

Does the function copy its argument from the start? If not, how do we know when the arguments are copied? From the above code, I assume that the arguments are not copied because std::move still affects variable x.

Safe way to get number of bytes for a data type in C++

I'm using C++11 and higher and I was asking myself if it is safe to get the number of bytes required for a datatype like std::uint16_t to send over length agnostic protocols. More precise is it safe to call sizeof(std::uint16_t) and can I assume that this is always 2? What about std::int16_t?

Why am I getting a re-definition error in C++?

I wrote a Fraction class to do some work with Fraction objects and overloading and such and I need to separate the implementation from the definitions of the methods but I get a redefinition error when it comes to the constructors of the class Fraction.

Code snippet from Fraction.h

class Fraction
{
private:
   int calcGCD(int n1, int n2) const;
   int compare(const Fraction& fraction) const;
   int m_numerator;
   int m_denominator;
public:
   Fraction(int numerator = 0, int denominator = 1) : m_numerator(numerator), m_denominator(denominator);
   Fraction(const Fraction& fraction) : m_numerator(fraction.numerator()), m_denominator(fraction.denominator());
   Fraction(const Fraction& orig);
};

Code snippet from Fraction.cpp

#include "Fraction.h"

Fraction::Fraction(int numerator, int denominator) 
   : m_numerator(numerator), m_denominator(denominator)
{}

Fraction::Fraction(const Fraction& fraction)
   : m_numerator(fraction.numerator()), m_denominator(fraction.denominator())
{}

This is resulting in the following errors:

Fraction.h:26:5: error: 'Fraction::Fraction(const Fraction&)' cannot be overloaded with 'Fraction::Fraction(const Fraction&)'
Fraction.h:25:5: note: previous declaration 'Fraction::Fraction(const Fraction&)'
Fraction.h:24:105: error: expected '{' at end of input

Followed by some others which I think are just a cascading effect of one or two main errors. But I can post them if really needed.

I think it has something to do with how I'm declaring the constructor in the .cpp file because I know some things do not carry over such as access modifiers and static and etc.

Sorry if this is a silly error, I am new to C++ and I can not find the answer anywhere.

Passing data from constructor to member function

I am trying to write a class that do matrix multiplication. The class matrix declared like below:

class matrix
{
public:
    vector<vector<int> > M;

    matrix();
    matrix(int m, int n);
    matrix(vector<vector<int> > &m);
    matrix Mul(matrix m1);
    void Inverse();
    bool SquareMatrix();
    void GetDet();
    int Det(vector<vector<int> > &m);
    void Print();
};

I initialize and enter the elements of the matrix M in this constructor:

matrix::matrix(int m, int n)
{
    vector<vector<int> > M(m, vector<int>(n, 0));
    cout << "Enter the elements: " << endl;

    for (int i = 0; i < m; i++)
    {
        for (int j = 0; j < n; j++)
        {
            cin >> M[i][j];
        }
    }
}

However, the member function "Mul" do not receive the data I input through the constructor.

matrix matrix::Mul(matrix m1)
{
    int **ppInt;
    ppInt = new int *[M.size()];
    for (int i = 0; i < M.size(); i++)
    {
        ppInt[i] = new int[m1.M[0].size()];
    }

    if (M[0].size() != m1.M.size())
    {
        cout << "Cannot do multiplication!" << endl;
        return matrix();
    }
    else
    {
        for (int i = 0; i < M.size(); i++)
        {
            for (int j = 0; j < m1.M[0].size(); j++)
            {
                int ele_buf = 0;
                for (int k = 0; k < M[0].size(); k++)
                {
                    ele_buf += M[i][k] * m1.M[k][j];
                }
                ppInt[i][j] = ele_buf;
            }
        }
    }
    int d1 = M.size(), d2 = m1.M[0].size();

    for (int i = 0; i < M.size(); i++)
    {
        M[i].clear();
    }
    M.clear();

    for (int i = 0; i < d1; i++)
    {
        for (int j = 0; j < d2; j++)
        {
            M[i][j] = ppInt[i][j];
        }
    }
}

How can I fix it?

Please let me know if my problem is not clear enough.

Parsing a complete JSON array from a text buffer

I'm receiving a JSON array over web sockets, and I have a buffer which is built up, currently I'm assuming that I'll receive the complete JSON array, with nested JSON objects and arrays. But I know from experience that often these strings can be broken up. So I need to check for a valid JSON array before I should try to process the text. Obviously due to the nested arrays, I can't just check for the presence of an opening and a closing square bracket.

I'm using libcereal to parse the JSON, but I can't see anything in the documents to suggest that it can do this. What would people suggest would be the simplest thing? A C++11 regex for JSON?

Initialize member array of user defined objects in the constructor in C++

How do I initialize member array in my constructor? The member array is an array of user-defined objects(classes). Also, the number of elements in the array could be large more than 100, so I do not prefer to use initializer-list available in C++11 (unless there's some better way)

For instance, refer following code:

class Foo {
private:
   void *a;
   int b;
public:   
   Foo(void *, int);
   ~Foo();
}

class Bar {
private:
    Foo mObj[150];
public:
    Bar();
    ~Bar();
};

Bar::Bar() {
// ???
}

For sake of simplicity, assume I would like to initialize the members as follows: let's say member int b stores Sr. no & void *a store null ptr as of now... so mObj[0] = {0, nullptr}, mobj[1] = {1, nullptr} & so on..

  1. What should my Bar::Bar() constructor be like?
  2. Do I need to have Default const, Copy const & operator= for Foo()?
  3. Having Vector instead of an array a better option?

Google Unit test Concurrency

I have an application built upon google unit test comprising of four different test suites (currently) say A, B, C and D. Each suite has 3 test functions- A1, A2, A3, B1, B2, ... D2, D3. This application has the ability to process any random sequence of input in the order specified, for example- A.A3, B.B2, A.A1, D.D1, C.C1, D.D3. The catch here is that all these tests execute sequentially one after the another. I want to leverage this such that the test-suites [which appear in the input sequence] execute their tests CONCURRENTLY along with other suites since there's no link between any of the suites and this way I save lot of time.

Also there's only 1 binary of the application generated and the input is taken using an XML format/UI as it is upto the user to choose the sequence. I tried creating threads for the respective suites but alas it didn't work since only one gtest-instance is created for a process, in this case my application being the process. So the threads are going to share this instance if they try to run in parallel.

Hence need your help in resolving this design dilemma.

C++11 GCC 4 Fast Optimization don't store implementation class from abstract class in the stack

So guys, I have an abstract class, other class that stores an implementation from this class in the stack (I don't want heap allocations and I don't know other way to do it without making the caller explicitly declares the implementation) and another that stores a reference of this interface class. But, it seems that GCC don't store the implementation class in the stack and when the interface class is used probably the implementation class vtable is not found.

Basically, everything works fine when compiled with GCC 4.8.1 without optimizations, but when I try to use it, the program crashes and then returns 139.

I don't know why GCC 4 doesn't support it, while GCC 5 does, but I see that they generate different instructions.

Compiler Explorer: https://godbolt.org/z/Wfvj65

#include <cstdio>

#define FORCEINLINE inline __attribute__((always_inline))

class IFormatter
{
public:
    virtual void Format(const void* InData) const = 0;
};

template<typename T>
class TFormatter :
    public IFormatter
{
public:
    TFormatter() = delete;
};

using Scalar = float;

// Implemented, fine.
struct RVector2
{
    Scalar X;
    Scalar Y;
};

// Not implemented, get error.
struct RVector3
{
    Scalar X;
    Scalar Y;
    Scalar Z;
};

template<>
class TFormatter<RVector2> :
    public IFormatter
{
public:
    virtual void Format(const void*) const override
    {
        printf("[RVector2]\n");
    }
};

template<typename T>
class TCustom
{
public:
    FORCEINLINE TCustom(const T& InValue) :
        Value(InValue),
        Format(TFormatter<T>{})
    {
    }

    FORCEINLINE const T* Data() const
    {
        return &Value;
    }

    FORCEINLINE const IFormatter& Formatter() const
    {
        return Format;
    }

private:
    const T& Value;
    TFormatter<T> Format;
};

template<typename T>
FORCEINLINE TCustom<T> MakeCustom(const T& InValue)
{
    return TCustom<T>{ InValue };
}

class RCustom
{
public:
    FORCEINLINE RCustom(const void* InValue, const IFormatter& InFormatter) :
        Data(InValue),
        Formatter(InFormatter)
    {
    }

    template<typename T>
    FORCEINLINE RCustom(TCustom<T> const& InCustom) :
        RCustom(InCustom.Data(), InCustom.Formatter())
    {
    }

    FORCEINLINE const IFormatter& Get() const
    {
        return Formatter;
    }

private:
    const void* Data;
    const IFormatter& Formatter;
};

int main()
{
    const RVector2 Vector{};
    const RCustom Custom = MakeCustom(Vector);
    Custom.Get().Format(nullptr);
    
    return 0;
}

mercredi 29 juillet 2020

g++ optimization makes the program unable to run

I implemented a path planning algorithm based on D*-Lite. When I do not turn on optimization (-O0), the program can run normally. But when I turn on the optimization level (-O1/2/3), the program cannot be terminated. In Visual Studio, both debug mode and release mode can run normally. In the above cases, the codes are the same.I don’t know how to find the problem, can anyone help me?

Usage of Range Based Loop for Vector of Pointer

Hi, I am amateur. I'm stuck on range based loops.

I know how to use this:

std::vector<ExampleClass> vec;

But I don't know this one:

std::vector<ExampleClass*> vec;

which one should I use?

1:

for (auto x : vec)

2

for (auto& x : vec)

Thank you.

How parse .h file as c++ by ClangTool newFrontendActionFactory

I am learning to write a RecursiveASTVisitor based newFrontendActionFactory. I want input a .h file and parse it as c++ file. Why a .h file can't run to VisitRecordDecl

How can i go back to previous fuction

the image that shows my code i want to go back if an individual enter the long year of birth the program must tell him/her is Long and hence he must repeat again

What is the semantics of std::async with automatic (launch::async|launch::deferred) launch policy?

The std::async has two overloads, one of them makes the parameter std::launch policy explicit while the other omits this parameter. The policy is a bitmask, so both launch::async|launch::deferred may be specified (or you may avoid the policy using the function that omits this parameter). Under the hood the policy is selected automatically in this case, and the choice is not guaranteed. I wonder what should be the reason of using this "unknown" policy.

First of all, you shouldn't use this policy together with wait functions: you may just get the future_status::deferred response to discover that calling this function was useless. Next, you may use default policy if you plan just to get the value on some point, but I see no reason to leave this selection on the system/library implementation, because even std::launch::async may optimize the number of threads used for the execution. Anyway, the actual explicitly selected policy strongly impacts the pattern of usage, and that is very strange to use the function that hides this information by design.

What may be a practical use case when someone would prefer to leave the policy selection to the system?

Technical reasons that C++11 can't support templated typedefs

In C++03, you couldn't template aliases, but since C++11 it's allowed with the using syntax.

For example, the following (using typedef) is invalid:

template<class T>
typedef vector<T> v;

Whereas the following (using using) is fine:

template<class T>
using v = vector<T>;

My question is not related to the rationale of The Committee for only supporting templated aliases with using.

My question is, is there any technical reason that this couldn't be supported? Basically, were the committee to allow this with typedef, would there be any implementation problems? For example, would it conflict with something else or cause some weird parsing issue?

For any cases I've been able to come up with, it should be fine, but I'm no expert which is why I'm asking here.

Research I've done, that doesn't answer the question:

standard string rfind not finding period

I am trying to extract the name of file, without the extension or qualified path e.g. extract file from /path/to/file.txt

I have the following:

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

int main()
{
    string temp = "dir/filename.txt";
    auto bpos = temp.rfind('/')+1, epos = temp.rfind('.')-1;
    cout << temp.substr(bpos,epos) << endl;
    return 0;
}

The output is filename.tx and I am not sure why this is the case. Is rfind() just not able to find the period? Escaping the character does not work either, same output.

How to declare operator++(int) in an abstract class?

I have an abstract class that is basically meant to serve as an "iterator interface". That is, it is an abstract iterator that a few concrete classes will later implement. To make the abstract class an iterator, I need to overload T operator++(int), where T is the class for which the operator is overloaded.

class AbstractClass {
    virtual AbstractClass operator++(int) = 0; // compile time error
    virtual AbstractClass& operator++() = 0;   // but this is fine
}

However, I cannot write AbstractClass operator++(int) as only pointers and references to an abstract class are permitted as return values.

Is there a way to require the subclasses to overload operator++(int) in plain C++11?

Can modern C++ compilers optimise the assignment operator for temporary variables?

Below is MyStruct class implementation which has default and copy constructors.

struct MyStruct {
    MyStruct(const string& name) {
        cout << "Default constructor called" << endl;
        name_ = name;
    }
    MyStruct(const MyStruct& S) {
        cout << "Copy constructor called" << endl;
        name_ = S.name_;
    }
    string name_;
}

Creating an object in the following way: MyStruct S = MyStruct("Hello"); calls a default constructor with "Hello" argument. I suspect my compiler (gcc version 7.5.0) does the optimisation by avoiding to create a temporary MyStruct("Hello") object.

However, the compiler does not optimize the analogous case for assignment operators:

MyStruct& operator=(const string& name) { // First assignment operator
    name_ = name;
    return *this;
}
MyStruct& operator=(const MyStruct& S) { // Second assignment operator
    name_ = S.name_;
    return *this;
}

Reassigning S to another struct:

MyStruct S = MyStruct("Hello"); // initial construction
S = MyStruct("world"); // reassignment

calls a constructor for the second time to construct the temporary MyStruct("world") object. After that, the second assignment operator is called.

Question:

  • is there a way to modify the code such that the call to the first assignment operator with an argument "world" would be called?

  • Is the first optimisation part of the modern C++ standard (i.e. will work with all compilers), or only works with specific compilers?

How to make a hierarchy of different object "generators" in plain C++11

What I need is the following hierarchy of classes (given here as a sketch):

class DataClass {}

class AbstractGenerator {
public:
    // Generates DataClass objects one by one. In a lazy manner
    virtual DataClass produce() = 0;
}

class RandGenerator : AbstractGenerator {
public:
    RandGenerator(int maximal_int) : maximal(maximal_int) {}
    DataClass produce() {
        // get a random number from 0 to this->maximal
        // make a DataClass object from the random int and return it
    }

private:
    int maximal;
}

class FromFileGenerator : AbstractGenerator {
public:
    FromFileGenerator(string file_name) : f_name(file_name) {}
    DataClass produce() {
        // read the next line from the file
        // deserialize the DataClass object from the line and return it
    }

private:
    string f_name;
}

What I want to support for both RandGenerator and FromFileGnerator is:

RandGenerator rg();
for (DataClass data : rg) {...}

And also some method of taking "first n elements of the generator".

What are the appropriate tools in the plain C++11 that one could use to achieve this, or whatever is the closest to this in C++11?

How to pass a JSON object inside a QTextEdit

I have a small GUI that I use to load/save json configuration files, the most important parameters are in the gui below:

conf

The problem I have been trying to solve is that I am not able to create an object inside a QTextEdit and am not sure why despite I am following official documentation on how to do that.

Below a snippet of code both for the load and save button. Also for the sake of brevity I only kept how I did the spinbox and, of course, the textedit:

void SettingsForm::on_loadBtn_clicked()
{
  // Opening file dialog....

  if(listDocksConfig.isEmpty())
  {
    QMessageBox::information(this, tr("Message"), tr("Please Open Configuration"));
  }
  else
  {
    QJsonDocument doc;
    QJsonObject obj;
    QByteArray data_json;
    QFile input(listDocksConfig);
    if(input.open(QIODevice::ReadOnly | QIODevice::Text))
    {
      data_json = input.readAll();
      doc = doc.fromJson(data_json);
      obj = doc.object();

      const double xposValue = obj["X Pos"].toDouble();
      QTextEdit textEdit     = QTextEdit::setText(obj["comments"]);  // <- Error Here

      ui->doubleSpinBox_XPos->setValue(xposValue);
      ui->textEdit->setText(textEdit);      // <- Error Here
    }
    else
    {
       // do something
    }
  }
}

void SettingsForm::on_saveBtn_clicked()
{

  // saving configuration with file dialog....

  if(listDocksConfig.isEmpty())
  {
    // do something...
  }
  else
  {
    const double xposValue = ui->doubleSpinBox_XPos->value();
    QTextEdit textEdit     = ui->textEdit->setPlainText();  // <- Error Here

    QJsonDocument doc;
    QJsonObject obj;

    obj["X Pos"] = xposValue;
    obj["comments"] = textEdit.toString();     // <- Error Here

    doc.setObject(obj);
    QByteArray data_json = doc.toJson();
    QFile output(listDocksConfig);
  }
}

What I have done so far:

  1. I consulted the official documentation on how to solve this problem, but could not figure out why that was not working. I also went ahead and try to use an alternative such as setText but still no luck.

  2. I came across this source which I used as guidance for my example and solved almost all problems but the QTextEdit one.

  3. This additional post was useful but still couldn't solve the problem.

Thanks for pointing to the right direction for solving this problem.

How to change the output of my time_t function in c++? [duplicate]

Currently the function

    time_t now1 = time(0);
    CString AuditDate1 = ctime(&now1);

Exports the time to the database as

Day Mon DD HH:MM:SS YYYY
For Example: Tue Jul 28 14:22:01 2020

I need the time to be outputted as

YYYY.MM.DD HH:MM:SS

I don't even need the time, more importantly the date. The time is a bonus.

Your help is much appreciated!

g++ does not link depending on optimization settings

So, this is eating me for the last two days:

I can't link my application, depending on which compiler I use and what optimizations levels are used:

  • gcc plays nicely with -O1, -O2, -O3 but fails with -O0 and
  • clang plays nicely with -O2 and -O3 and fails with -O1 and -O0.

There are a bunch of horrible templates in it, but I see no reason for this obscure behaviour.

Here is a minimal amount of code that reproduces the problem:

#include <map>
#include <memory>
#include <iostream>

using id_type = long;

class CB : public std::enable_shared_from_this<CB>
{
public:
    CB() = default;
    virtual ~CB() = default;
};

template<class F, class C> class SC : public CB
{
};

class FB
{
public:
    virtual ~FB() = default;
    template<class T, class B> T* as(B* v) const { return dynamic_cast<T*>(v);}
};

template<class T>
class F : public FB
{
public:
    virtual std::shared_ptr<CB> create() const
    {
        auto n = std::make_shared<T>();
        return n;
    }
};

struct  B
{
    virtual ~B() = default;
    static const id_type ID = 1;
};

class A : virtual public B, virtual public SC<A, B>
{
public:
    A() = default;
};

static std::map<id_type, std::shared_ptr<FB>> crtrs {
        {A::ID, std::make_shared<F<A>>()}
    };

int main()
{
    std::cout << crtrs.size();
}

Here is the same online https://gcc.godbolt.org/z/sb9b5E

And here are the error messages:

fld@flap ~/work/p/test1                                                                                                                                                                                                                                                           
> $ g++ -O1 main.cpp                                                                                                                                                                                                                                                                        
                                                                                                                                                                                                                                                                                             
fld@flap ~/work/p/test1                                                                                                                                                                                                                                                          
> $ g++ -O2 main.cpp                                                                                                                                                                                                                                                                        
                                                                                                                                                                                                                                                                                             
fld@flap ~/work/p/test1                                                                                                                                                                                                                                                         
> $ g++ -O3 main.cpp                                                                                                                                                                                                                                                                        
                                                                                                                                                                                                                                                                                             
fld@flap ~/work/p/test1                                                                                                                                                                                                                                                           
> $ g++ -O4 main.cpp                                                                                                                                                                                                                                                                        
                                                                                                                                                                                                                                                                                             
fld@flap ~/work/p/test1                                                                                                                                                                                                                                                            
> $ g++ -O0 main.cpp                                                                                                                                                                                                                                                                        
/tmp/cc8D7sNK.o: In function `__static_initialization_and_destruction_0(int, int)':
main.cpp:(.text+0x1c0): undefined reference to `B::ID'
collect2: error: ld returned 1 exit status
                                                                                                                                                                                                                                                                                             
fld@flap ~/work/p/test1                                                                                                                                                                                                                                                            
> $ clang++ -O0 main.cpp                                                                                                                                                                                                                                                                    
/tmp/main-c49b32.o: In function `__cxx_global_var_init.1':
main.cpp:(.text.startup+0x7a): undefined reference to `B::ID'
clang-8: error: linker command failed with exit code 1 (use -v to see invocation)
                                                                                                                                                                                                                                                                                             
fld@flap ~/work/p/test1                                                                                                                                                                                                                                                           
> $ clang++ -O1 main.cpp                                                                                                                                                                                                                                                                    
/tmp/main-cf18ee.o: In function `__cxx_global_var_init.1':
main.cpp:(.text.startup+0x3c): undefined reference to `B::ID'
clang-8: error: linker command failed with exit code 1 (use -v to see invocation)
                                                                                                                                                                                                                                                                                             
fld@flap ~/work/p/test1                                                                                                                                                                                                                                                            
> $ clang++ -O2 main.cpp                                                                                                                                                                                                                                                                    
                                                                                                                                                                                                                                                                                             
fld@flap ~/work/p/test1                                                                                                                                                                                                                                                           
> $ clang++ -O3 main.cpp                                                                                                                                                                                                                                                                    
                                                                                     

If someone has any ideas what might be the reason, any hints are more than welcome.

C++ typedef with tuple of indefinite size

I am working with some C++ code that creates a set from quaternary tuples.

I would like to generalise the code so that tuples of any magnitude could be added to the set.

Is there a way of creating a typedef for a tuple of an indefinite number of elements?

For the sake of compatibility with the project that I working on I would like this to be implemented with C++11 features. I am hoping to keep typedefs if possible so that it is consistent with the rest of the programming.

I have looked at a lot of information on variadic functions and templates, but I am still unsure how to proceed.

#include <set>
#include <functional>
#include <iostream>



typedef std::set<std::tuple<int, int, int, int>> QuaternarySet;
typedef std::tuple<int, int, int, int> QuaternaryTuple;

int main () {

    QuaternaryTuple x = std::make_tuple(1, 2, 3, 4);
    QuaternaryTuple y = std::make_tuple(5, 6, 7, 8);
    QuaternaryTuple z = std::make_tuple(1, 2, 3, 4);

    QuaternarySet s;

    s.insert(x);
    s.insert(y);
    s.insert(z);

    std::cout << s.size() << std::endl;
}

Ideally, I am looking for some code that allows me to define something like this but I am not sure what to replace the ellipses with.

typedef std::set<std::tuple<int ...>> IndefiniteSet;
typedef std::tuple<int ...> IndefiniteTuple;

That is to say, I need a run time variable size container of a single type, int.

I want the user to input hello world and cout to be "Hello World " [closed]

int main(){
string x; cin>>x; cout<<x`enter code here`<<emdl;
// I want the input to be hello world and output Hello World
// Input: a letter Output: A letter}

How should i "interpret" a user command in c++? [closed]

Goodmorning, i think i need some advices about a project i have to develop for a university exam. The first part of the program must be able to read a sentence entered from the user. the user must specify the name of a "table" in which he will insert records. so, for exemple, the user enters : CREATE TABLE CUSTOMERS (ID INT, NAME TEXT, AGE INT) meaning that he wants to create a table called customers: in this exemple, for every record 3 fields must be filled.

The user can enter different type of commands.

  1. he can for exemple delete a record, update a record and many others possible commands
  2. the names of the variable he enters must be single words (no spaces allowed)

My question is, should i create a sort of "dictionary", where every word is linked to a certain function and search for a "match" between the each substring and the dictionary?

which is the most efficient way to "interprete" the user sentence by using only the STL?

Multiple condition in for loop not working in c++

I am trying to print all occurring even numbers up to 20. The code is working fine with if condition, but not working with multiple conditions in loop.

    ```  
    #include<iostream>
    using namespace std;
    int main() {
     for(int i = 1; ((i <= 20) && (i % 2 == 0)); i ++) cout << i << endl;
    }
    ```

emscripten C++11 with boost support issue

enter image description here

I have an issue when building my C++ project that uses boost in Emscripten as shown on the screenshot, it says that '_Atomic' is a C11 extension however even if i add -std=c++11 or even -std=c11 i am still getting the error, the _Atomic use is defined from boost.

any idea on how to work around on this? reading around it does say that C++11 is already supported in Emscripten.

my setup. compiler: emscripten/em++ Clang 12.0.8

mardi 28 juillet 2020

C++ library to convert JPEG and PNG images to RAW image format

I have tried searching for a day for converting JPEG & PNG to RAW image format(*.raw format), but couldn't find any and all the result were RAW to JPEG. Finally i decided to ask here hoping will get the answer.

So, i want to convert images of format JPEG & PNG to RAW image format(*.raw) only and for that i need C++ library which can do this work.

Please tell me some library for the same. Your help is highly appreciated.

Thanks

C++ Comparing strings to determine palindrome

I am trying to determine if a string is a palindrome by reversing the string and then comparing the letters of both strings. The code is provided underneath. So far whatever I put I always get "is a palindrome " as an output. I am aware of the short cut method for doing this easily and efficiently but trying to understand the long way as well. I am using C++ 11

#include <iostream>
#include <string>

using namespace std;
string reversed = " ";

void reverse_sentence(string s)
{
    
    for (int i = 0; i <= s.length(); i++)
    {
        reversed = s[i] + reversed;
        
    }
    cout << reversed;
    
}

void is_pal(string reversed, string s)
{
    int flag = 0;
    
    // if(s == string(s.rbegin(), s.rend())){
    //   cout << "is a palindrome"<<endl;
    
    // }else{
    //   cout <<"failed"<<endl;
    
    // }
    
    for (int i = 0; i <= s.length(); i++)
    {
        for (int j = 0; j <= reversed.length(); j++)
        {
            if (s[i] != reversed[j - 1])
            {
                flag = 1;
            }
            
        }
    }
    if (flag == 1)
    {
        cout << "is palindrome" << endl;
    }
    else
    {
        cout << "not palindrome" << endl;
    }
}

int main()
{
    string s = "hello";
    reverse_sentence(s);
    is_pal(s, reversed);
    
    return 0;
    
}

C++ version is 98 (199711) but I can still work with C++11 features [duplicate]

2 related questions:

How come my C++ version is 98 (199711) but can work with Lambdas and other C++11 features.

And also - in my project properties (on VS 2019) I tried to reconfigure the language, to be the latest instead of the default. I added /std:c++latest to the 'additional options' and also configured the language to be C++17 but still, when I print the C++ version (__cplusplus) I get 199711.

what is "powers of 2" and "word"?

I'm recently following C++ Primer Book In chapter 2 and I'm at this point

Most computers deal with memory as chunks of bits of sizes that are powers of 2. The smallest chunk of addressable memory is referred to as a “byte.” The basic unit of storage, usually a small number of bytes, is referred to as a “word.” In C++ a byte has at least as many bits as are needed to hold a character in the machine’s basic character set. On most machines a byte contains 8 bits and a word is either 32 or 64 bits, that is, 4 or 8 bytes.

Most computers associate a number (called an “address”) with each byte in memory. On a machine with 8-bit bytes and 32-bit words, we might view a word of memory as follows

I don't understand well what does he mean with chunks of bits of sizes that are powers of 2 and what's a word also? he say a small number of bytes but that's not clear for me, can anyone explain?

Adding another custom comparator for std::set::upper_bound or lower_bound for a set of structs

Here I've sorted a set of structs using a comparator functor. But the upper_bound and lower_bound methods of std::set also use this same comparator for finding out the element.

struct segment{
    int ax, ay;
    int bx, by;

    segment(){};
    segment(int a1, int a2, int b1, int b2)
    :ax(a1), ay(a2), bx(b1), by(b2){}
    
};

struct classCompare{
    bool operator()(const segment& l, const segment& r)
    {
            // I donot wish to use this comparison for upper_bound or lower_bound 
            // just want to include the else part
            if(l.ay == r.ay)
                return l.ax < r.ax;
            else
                return l.ay < r.ay;
    }
};
...
//(inside main)
   if(temp.ax > temp.bx)
            {
                int k = temp.ax;
                temp.ax = temp.bx;
                temp.bx = k;
            }
            segs_H.insert(temp);
        }            
    }

    int count(0);
    for(unsigned int i=0;i<segs_V.size();i++)
    {
        std::cout << segs_V[i].ax << "," << segs_V[i].ay << "  " << segs_V[i].bx << "," << segs_V[i].by << std::endl ;

        //Here
        auto iter_L = segs_H.lower_bound(segment(segs_V[i].ax, segs_V[i].ay, segs_V[i].ax,                                                        
                                                 segs_V[i].ay));
        auto iter_U = segs_H.upper_bound(segment(segs_V[i].bx, segs_V[i].by, segs_V[i].bx, 
                                                 segs_V[i].by));
        
        for(;iter_L != iter_U; iter_L++)
        {   
            std::cout << iter_L->ax << "," << iter_L->ay << "  " << iter_L->bx << "," << iter_L->by << std::endl ;
            if( iter_L->ax <= segs_V[i].ax && segs_V[i].ax <= iter_L->bx )
            {
                count++;
            }
        }
        std::cout << std::endl;
    }

Is there a way to define another comparator that can be used by upper_bound or lower_bound. I tried using std::upper_bound but that dosen't seem to properly iterate through the set.

Return NULL from a method returning double [closed]

Consider the following code:

struct mult
{
  double operator()(double a, double b)
  {
    if (a.is_null() || b.is_null()) {
      return NULL;
    } else {
      return a * b;
    }
  }
};

Is there any way to return NULL? I don't want to return 0. a or b can be NULL. I want to achieve the result to be NULL if either one of that is NULL. I am considering NaN

ERROR: Process dir does not contain event

I am afraid I cannot describe my problems well. I am making some tests which are only different in 2 parameters. If I make only a test on the front-end. it will go well. But there are many test files. So I put them on the back-end by &. " Gen_tf.py --ecmEnergy=13000.0 --jobConfig=$PWD --outputEVNTFile=tmp.EVNT.root --maxEvents=10000 &" Then errors come as:

  1. /proc/9699: No such file or directory (or no this process ) /proc/9690: No such file or directory..enter image description here
  2. then “ ERROR Process dir /C1N2_Stau_1000_300/PROC_MSSM_SLHA2_0 does not contain events? ” I don't know if, in the back-end, these processes can make a conflict? Since I can run one test well at the front-end.

Double free or corruption (fasttop) error when trying to use setter

I have created a basic class object with setter and getters based on the text book. The code work fine but when I attempt to change the data in name from Square to Circle, I get error : double free or corruption (fasttop).

Can someone enlighten me what is happening here? Is this due to some kind of memory allocation error?

Below is a reproducible code:

#include <iostream>
#include <string>
#include <cstring>

using namespace std;

class Shape
{
    protected:
        string name;
        bool contains = false;
        
    public:
        Shape(string name, bool contains)
        {
            setName(name);
            setContains(contains);
        }
        
        string getName();
        bool getContains();
        string setName(string name);
        bool setContains(bool contains);
};

string Shape :: setName(string inputName)
{
    name = inputName;
}

bool Shape :: setContains(bool inputContains)
{
    contains = inputContains;
}

string Shape :: getName()
{
    return name;
}

bool Shape :: getContains()
{
    return contains;
}

int main()
{
    Shape object1("Square", true);
    cout << "Testing" << endl;
    cout << object1.getName() << endl;
    cout << object1.getContains() << endl;

    object1.setName("Circle");
    cout << object1.getName() << endl;
    return 0;
}

Edit:

Interesting, when running the code in OnlineGDB without object1.setName("Circle"); and cout << object1.getName() << endl; will report a segmentation fault error. What is the way to tackle this issue?

Is there a complete and consistent example set of C++ overloaded operators? [duplicate]

Despite much searching, I can't find a complete set of fully implemented operators anywhere online.

I find myself using various sources for each operator, and consequently have an inconsistent set of operators.

lundi 27 juillet 2020

Build c program for release and build

The original makefile comes for Release build.

Original

APP:= deepstream-app

TARGET_DEVICE = $(shell gcc -dumpmachine | cut -f1 -d -)

NVDS_VERSION:=5.0

LIB_INSTALL_DIR?=/opt/nvidia/deepstream/deepstream-$(NVDS_VERSION)/lib/
APP_INSTALL_DIR?=/opt/nvidia/deepstream/deepstream-$(NVDS_VERSION)/bin/

ifeq ($(TARGET_DEVICE),aarch64)
  CFLAGS:= -DPLATFORM_TEGRA
endif

SRCS:= $(wildcard *.c)
SRCS+= $(wildcard ../../apps-common/src/*.c)

INCS:= $(wildcard *.h)

PKGS:= gstreamer-1.0 gstreamer-video-1.0 x11

OBJS:= $(SRCS:.c=.o)

CFLAGS+= -I../../apps-common/includes -I../../../includes -DDS_VERSION_MINOR=0 -DDS_VERSION_MAJOR=5

LIBS+= -L$(LIB_INSTALL_DIR) -lnvdsgst_meta -lnvds_meta -lnvdsgst_helper -lnvdsgst_smartrecord -lnvds_utils -lm \
       -lgstrtspserver-1.0 -ldl -Wl,-rpath,$(LIB_INSTALL_DIR)

CFLAGS+= `pkg-config --cflags $(PKGS)`

LIBS+= `pkg-config --libs $(PKGS)`

all: $(APP)

%.o: %.c $(INCS) Makefile
    $(CC)  -c -o $@ $(CFLAGS) $<

$(APP): $(OBJS) Makefile
    $(CC) -o $(APP) $(OBJS) $(LIBS)

install: $(APP)
    cp -rv $(APP) $(APP_INSTALL_DIR)

clean:
    rm -rf $(OBJS) $(APP) 

Modified for both Release and Debug

APP:= deepstream-app
DEBUGAPP:= deepstream-app-debug

TARGET_DEVICE = $(shell gcc -dumpmachine | cut -f1 -d -)

NVDS_VERSION:=5.0

LIB_INSTALL_DIR?=/opt/nvidia/deepstream/deepstream-$(NVDS_VERSION)/lib/
APP_INSTALL_DIR?=/opt/nvidia/deepstream/deepstream-$(NVDS_VERSION)/bin/

ifeq ($(TARGET_DEVICE),aarch64)
  CFLAGS:= -DPLATFORM_TEGRA
endif

SRCS:= $(wildcard *.c)
SRCS+= $(wildcard ../../apps-common/src/*.c)

INCS:= $(wildcard *.h)

PKGS:= gstreamer-1.0 gstreamer-video-1.0 x11

OBJS:= $(SRCS:.c=.o)

CFLAGS+= -I../../apps-common/includes -I../../../includes -DDS_VERSION_MINOR=0 -DDS_VERSION_MAJOR=5

LIBS+= -L$(LIB_INSTALL_DIR) -lnvdsgst_meta -lnvds_meta -lnvdsgst_helper -lnvdsgst_smartrecord -lnvds_utils -lm \
       -lgstrtspserver-1.0 -ldl -Wl,-rpath,$(LIB_INSTALL_DIR)

CFLAGS+= `pkg-config --cflags $(PKGS)`

LIBS+= `pkg-config --libs $(PKGS)`

all: $(APP)

%.o: %.c $(INCS) Makefile
    $(CC)  -c -o $@ $(CFLAGS) $<
%.o: %.c $(INCS) Makefile
    $(CC) -g3  -c -o $@ $(CFLAGS) $<

$(APP): $(OBJS) Makefile
    $(CC) -o $(APP) $(OBJS) $(LIBS)
$(DEBUGAPP): $(OBJS) Makefile
    $(CC) -g3 -o $(DEBUGAPP) $(OBJS) $(LIBS)

install: $(APP)
    cp -rv $(APP) $(DEBUGAPP) $(APP_INSTALL_DIR)

clean:
    rm -rf $(OBJS) $(APP) $(DEBUGAPP)

But it doesn't produce deepstream-app-debug. What should I change for both release and debug?

Pass inherited arguments to base class constructor, then do something in derived class constructor

Consider the following:

I derive a class Child from another class Parent. Parent has a ton of overloaded constructors. The Child class does not need any more parameters for construction. But once the base class constructor has been called, I want to do some more stuff during object construction.

So my question is: Using Modern C++, can I write a single constructor that accepts all arguments that any of the overloaded base class constructors accept and just forwards them to the respective one?

To be explicit: I am aware of the using Parent::Parent syntax, but that would not give me the opportunity to do anything after the base class constructor is called, as far as I understand.

I have searched around here on SO and in the depths of the internet, but I could not find anything like that, even though it seems like a fairly common use case to me. Any help would be much appreciated.

Problem in sorting a vector using recursion

i am getting the inputed vector as the output as it is.

code:

#include <bits/stdc++.h>
using namespace std;
void insert(vector<int> v,int val){
   if(v.size()==0 || v[v.size()-1]<=val ){
     v.push_back(val);
     return;
   }
   int x = v[v.size()-1];
   v.pop_back();
   insert(v,val);
   v.push_back(x);
   return;
}
void fun(vector<int> v){
   if( v.size()==0 )
    return;
   int val = v[ v.size()-1 ];
   v.pop_back();
   fun(v);
   insert(v,val);
   return;
}
int main() {
 vector<int> v{9,4,1,-2,10,1,12,5,0,-4};
 fun(v);
 auto x= v.begin();
 for(;x!=v.end();x++)
    cout<<*x<<" ";
  }

the out put is the same input vector ,i.e O/p : 9,4,1,-2,10,1,12,5,0,-4 please tell where am i going wrong

Using typedef types in definition

I have a class as follows,

template<size_t N>
class A 
{
   typedef int(*ARRAY)[N];
   array getArray();

   ARRAY array;
};

Then how can I use the type ARRAY in the definition? I have tried this

template<size_t N>
ARRAY A<N>::getArray()
{
   return array;
}

But, it tells me that ARRAY is not defined.

Putty and RaspberryPi : How to speed up a QProcess instruction

I wrote a small GUI as basic example that replicates the problem I have. I am using Windows 10 with Qt5. Given the remote access tool Putty. I am able to log in inside a RaspberryPi that is mounted on a robot. In order to check the robot's latitude/longitude I can give on a Git Bash terminal the following command :

$ plink.exe robot1@166.130.166.166-pw xxxxxx -P 1234"sudo cat /dev/serial0"

and the output of the command is as follows:

0.88,6.9,M,-33.7,M,0000,000059 $GPGSA,A,3,24,04,06,22,28,17,03,12,19,02,,,1.36,0.88,1.0401 $GPRMC,154725.000,A,4224.2007,N,07044.9218,W,5.54,76.03,270720,,,D4F $GPVTG,76.03,T,,M,5.54,N,10.26,K,D3B $GPGGA,154726.000,4224.2010,N,07044.9198,W,2,10,0.88,6.9,M,-33.7,M,0000,000057 $GPGSA,A,3,24,04,06,22,28,17,03,12,19,02,,,1.36,0.88,1.0401 $GPRMC,154726.000,A,4224.2010,N,07044.9198,W,5.56,76.41,270720,,,D45 $GPVTG,76.41,T,,M,5.56,N,10.30,K,D38

Now in order to avoid to manually type that command I automated the process and created a small .ui carrying 1 QPushButton, 1 QLineEdit and 1 QTextEdit, and use QProcess to execute any command line instruction.

The problem I have is that as I push the button I see the output but only after an extremely long time (i.e. > 3 minutes or more sometimes) which is not great because it is taking too much to show the output on the QTextEdit. How can I solve that?

proc

Below the code of the GUI:

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    check_GPSStatus();
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::check_GPSStatus()
{
    // Execution of the QProcess
    this->executeGPSCommand = new QProcess(this);
    this->executeGPSCommand ->setProcessChannelMode(QProcess::MergedChannels);
    connect(this->executeGPSCommand , QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
            [this, script = this->executeGPSCommand ](int exitCode, QProcess::ExitStatus exitStatus){
        qDebug() << "[EXEC] FINISHED: " << exitCode << exitStatus;
        if(exitCode == 0)
        {
            QString stdOutput = QString::fromUtf8(this->executeGPSCommand ->readAllStandardOutput());
            qDebug() << stdOutput;
            ui->textEdit_EC_GPS->setText(stdOutput);
            ui->lineEdit_EC_GPS->setText("SUCCESS: ACQUIRING GPS COORDINATES");
        }
        else
        {
            QString stdErr = QString::fromUtf8(this->executeGPSCommand ->readAllStandardError());
            qDebug() << stdErr;
            QString stdOutput = QString::fromUtf8(this->executeGPSCommand ->readAllStandardOutput());
            qDebug() << stdOutput;
            ui->textEdit_EC_GPS->setText(stdErr + "\n" + stdOutput);
            ui->lineEdit_EC_GPS->setText("CONNECTION ERROR");
        }
        ui->pushBtn_EC_GPS->setEnabled(true);
    });
}


void MainWindow::execute_GPS_CommandIn_Pi(QString command)
{
    // will start new process without blocking
    QString args = "robot1@166.130.166.166-pw xxxxxx -P 1234";
    QStringList args_list = args.split(' ', QString::SkipEmptyParts);
    this->executeGPSCommand ->start("plink.exe", args_list << command);
}


void MainWindow::on_pushBtn_EC_GPS_clicked()
{
    qDebug() << "Launching GPS Troubleshooting";
    execute_GPS_CommandIn_Pi("sudo cat /dev/serial0");
    ui->pushBtn_EC_GPS->setEnabled(false);
}

I am not very much familiar with Putty, but I was able to write the automation procedure using QProcess, which is a good and quick way to test the correctness of my thoughts. After trying several combinations of commands I arrived to the one I posted in the code that successfully inquire the Raspberry Pi about the position asked. I did a good amount of research but didn't see Putty used on a lot of application similar to the one I am writing. Please if anyone has ever had a similar problem, point to the right direction for solving it.

c++ void function not returning control to the caller after the condition is met

I am having an issue returning out of a void function. Here is the function:

void findTreeNodeRecursively(unsigned indent, const TreeNode* node, const std::function<bool(const TreeNode*)>& name_checker){

    for (unsigned i = 0; i < indent; i++)
    {
        std::cout << "   ";
    }
    if (!node)
    {
        std::cout << "!nullptr!" << std::endl;
        return;
    }

    indent++;

    if(name_checker(node) == true){
        return;
    }

    if (auto control = dynamic_cast<const ControlNode*>(node))
    {
        for (const auto& child : control->children())
        {
            findTreeNodeRecursively(indent, child, name_checker);
        }
    }
    else if (auto decorator = dynamic_cast<const DecoratorNode*>(node))
    {
        findTreeNodeRecursively(indent, decorator->child(), name_checker);
    }
}

Here is the file where this function is implemented:

static const char* xml_text = R"(

 <root main_tree_to_execute = "MainTree" >

     <BehaviorTree ID="MainTree">
        <Sequence name="root_sequence">
            <ApproachObject name="approach"/>
            <CheckBattery   name="battery_ok"/>
            <OpenGripper    name="open_gripper"/>
            <ApproachObject name="approach_object"/>
            <CloseGripper   name="close_gripper"/>
        </Sequence>
     </BehaviorTree>

 </root>
 )";
int main(){
    auto tree = factory.createTreeFromText(xml_text);
    const std::string name_to_find = "open_gripper";
    auto name_checker = [&name_to_find](const TreeNode* node) -> bool {
      std::cout<<node->name()<<std::endl;
      if (node->name() == name_to_find)
      {
          return true;
      }
      else
      {
          return false;
      }
    };

    findTreeNodeRecursively(0, tree.root_node, name_checker);

    return 0;
}

I can see the output printed when the name (input) is found, which returns true. The void function should return if the lambda (or name_checker) function returns true, but it still implementing remaining part of the function.

The effect of memory barriers on data visibility to other threads

When a thread, T, reads an object at any point in time, the value it sees could be:

  1. The initial value of the object.
  2. A value stored by T.
  3. A value stored by another thread.

And there are memory barriers (Load-Load, Load-Store, Store-Load, and Store-Store), which can be defined as:

<Loads|Stores> before the barrier can't be reordered past the barrier and <Loads|Stores> after the barrier can't get reordered prior to the barrier.

Now, assume that a thread T1 is executing this piece of code:

load(X)
store(Y, 1)
-----------  <-- a barrier
load(Y)
store(X, 1)

while another thread, T2, is executing this piece of code:

load(X)
load(Y)

What would be the effect of the barrier in T1 on the visibility of X and Y to thread T2, when the barrier is:

  1. Load-Load
  2. Load-Store
  3. Store-Load
  4. Store-Store

Thanks!

How is an int function able to return long long variable?

int reverse(int x) {
        if(x==0)
            return 0;
        int y = abs(x);
        long long result = 0;
        while(y > 0) {
            result *= 10;
            result += y % 10;
            y /= 10;
        }
        if(result > INT_MAX || result < INT_MIN)
            return 0;
        if(x<0) {
            return -result;
        }
        return result;
        
    }

How is this code valid? It's clear that result is a long long variable but the return type of the code is int. The code still works.

c++ std::thread vs OpenMP perfoamnce

Hi I have below function :

PS: feat is vector or eigen matrix.

 #pragma omp parallel for
for (int x = 0; x < count_feature; x++) {                                                                                           
        
        auto distance = ( feat.row(x)- b_cmp ).squaredNorm();
        //        std::cout << id << "    "<< distance << std::endl ;
        if (distance < 0.5) {
                std::cout << std::endl << "Buldummm : " << x <<  "    " << distance <<std::endl;
                mutex1.lock();
                found_number.push_back(x);
                mutex1.unlock();

        }
}

also I am running the same function with :

std::vector<std::thread> threadList;
    for(int i = 0; i < n_thread_num; i++)
{
    std::cout << "chunks : " << i*chunk_number << " to " <<  (i+1)*chunk_number << std::endl;    
    threadList.push_back(std::thread (FindDistance,   std::ref(feat),   std::ref(b_cmp),       i*chunk_number, (i+1)*chunk_number));
}
std::cout<<"wait for all the worker thread to finish"<<std::endl;
std::for_each(threadList.begin(),threadList.end(), std::mem_fn(&std::thread::join));

Same thread number.

but OpenMP version is : 1.14889 second ThreadPoll version: 2.61334

why there is more than X2 difference ? Is this the best way ?

binary '==': 'tag' does not define this operator or a conversion to a type acceptable to the predefined operator

I am literally new with c++. Just learning. can anyone help me with this?

typedef pair<string, string> attr;
struct tag {
   int id;
   int parentIndex;
   string identifier;
   vector<attr> attributes;
};

int main() {
    vector<tag> ctags{ tag{1,1, "test"} };
    string query{"test"};
    auto utag = find(ctags.begin(), ctags.end(), [query](tag t) { return t.identifier == query; });
}

whenever I am trying to run that, I am getting the above error. So tried

bool operator==(tag& rhs)
{
    return this->identifier == rhs.identifier;
}

bool operator==(string& rhs)
{
    return this->identifier == rhs;
}

Nothing is working for, anyone??

Is there any way of creating a macro to define a constructor without needing to have the name of the containing class?

I have many classes which are like this:

struct A_Insert
{
    Data &d;
    A_Insert(d) : d(d){}

    // ...
}

struct A_Query
{
    Data &d;
    A_Query(d) : d(d){}

    // ...
}

struct B_Insert
{
    Data &d;
    B_Insert(d) : d(d){}

    // ...
}

struct B_Query
{
    Data &d;
    B_Query(d) : d(d){}

    // ...
}

The best thing I can think to do is define a macro like this:

#define Data_Query(name, body) struct name{Data &d; name(Data &d) : d(d) {} body}

but this leads to somewhat ugly code as I have to use parentheses to define my structs and my IDE doesn't handle it very well.

Data_Query(A_Insert, 
    int bind_params(stmt &stmt){}
    ...
)

I would like a macro which could allow me to get the name of the containing type for the constructor so I could write code like:

#define CONTAINING_TYPE
#define Data_Construct Data &d; CONTAINING_TYPE(Data &d) : d(d) {}

struct A_Insert { Data_Construct // ... }

and this way my IDE could treat it like a normal struct declaration. Any suggestions would be appreciated. A somewhat more readable alternative would be to do:

#define constructor CONTAINING_TYPE

and that way I could use it just like the JavaScript keyword while keeping it easier to copy and paste.

Atomic writes are visible immediately, even with memory_order_relaxed

Regarding memory_order_relaxed it is often written that this operation provides no synchronization, however in reality all writes to an atomic appear to propagate immediately to other threads, even with memory_order_relaxed, in fact the example given on https://en.cppreference.com/w/cpp/atomic/memory_order seems to be entirely dependent on this fact:

std::atomic<int> cnt = {0};
 
void f()
{
    for (int n = 0; n < 1000; ++n) {
        cnt.fetch_add(1, std::memory_order_relaxed);
    }
}
 
int main()
{
    std::vector<std::thread> v;
    for (int n = 0; n < 10; ++n) {
        v.emplace_back(f);
    }
    for (auto& t : v) {
        t.join();
    }
    std::cout << "Final counter value is " << cnt << '\n';
}

The final value of cnt is always 10 000. The atomicty of operation fetch_add is not enough to guarantee this, unless the value is always synchronized between the threads before the 'fetch_add', for example if the writing thread would not have synchronized with the thread who was writing latest value, the two modifications could be done on the same value, resulting in cnt < 10 000 at the end. It appears that every atomic write is immediately shared and made visible to other threads.

So my questions are:
1] is this immediate visibility/synchronization guaranteed in the C++ standard?
2] Is there any synchronization happening before calls to join()?
3] If there is no synchronization, how can the result be always 10 000?

The closest thing I found in CPP reference is this sentence: 'All modifications to any particular atomic variable occur in a total order that is specific to this one atomic variable.' Would this mean that in this case memory_order_relaxed appears to behave exactly like memory_order_seq_cst? (my limited benchmark showed that performance is identical in this case), that is there exists a total order, and the writing thread always gets the latest value in this order.

I would ask to refrain from explanations on the hardware level, im interested purely in C++ standard.