jeudi 30 septembre 2021

How to check that the address pointed by a pointer is pointing to an object not a garbage before reading or writing to this object? [duplicate]

If i have a pointer (static address) that will always point to a specific variable address (ex.health) then how to check if the game.exe destroyed and deallocates this object before program reads and writes to this non existing object at this time?

static DWORD baseAddress = 0x00000 ;
static DWORD healthPtr = (DWORD)(baseAddress + health_offset);

//when the game deallocates and destroys health object it's value become (??) garbage causing crash on reading or writing to it!

//So how to check here if the address pointing to health is realy pointing to a valid health object not a destroyed non sense garbage?

*(int*)(healthPtr) = 100;
// writing to a deallocated object will cause a crash

Declare signal from interface class and implement it

I'm new to QT and I want to ask:

How can I declare signal from interface class, later implement it in another subclass and connect to slot? I found: connect(dynamic_cast<QObject*>(obj_typeof_interface), SIGNAL(signal), this, SLOT(slot)); but doesn't work...

Complete code:

My interface

class InstrumentsCommunication : public QObject
{
    Q_OBJECT
public:
    virtual bool open(const std::string addr) = 0;
    virtual void transaction(Command cmd, qint16 rate) = 0;

signals:
    virtual void getData(const QString s) = 0;

private:
    virtual void write(const std::string cmd) = 0;
};

Q_DECLARE_INTERFACE(InstrumentsCommunication, "InstrumentsCommunication")

the implementation

class SerialCommunication : public InstrumentsCommunication
{
    Q_OBJECT
    Q_INTERFACES(InstrumentsCommunication)
public:
    SerialCommunication();
    bool open(const std::string addr) override;
    void transaction(Command cmd, qint16 rate) override;

signals:
    void getData(const QString s) override;

public slots:
    void read();

private:
    QSerialPort serial;
    QString buffer;
    void write(const std::string cmd) override;
};

//Methods implementations

void SerialCommunication::read(){
    buffer += serial.readAll();

    if(buffer.contains("\r\n")){
        qDebug() << "read()";
        emit this->getData(buffer.trimmed());
        buffer = "";
    }
}

I have implemented Facory Method...

Creator class

class Creator : public QObject{
    Q_OBJECT
public:
    virtual ~Creator(){};
    virtual InstrumentsCommunication* FactoryMethod() const = 0;
    bool open(const std::string addr);
    void write(Command cmd);

signals:
    void getData(const QString s);

public slots:
    void recvData(const QString s);

private:
    InstrumentsCommunication* instrComm;
};


bool Creator::open(const std::string addr){
    instrComm = this->FactoryMethod();
    //Doesn't work
    //QObject::connect(instrComm, &InstrumentsCommunication::getData, this, &Creator::recvData);

    //Doesn't work
    //QObject::connect(dynamic_cast<QObject*>(instrComm), SIGNAL(getData), this, SLOT(recvData));

    bool isConn = instrComm->open(addr);
    return isConn;
}

//...

void Creator::recvData(const QString s){
    qDebug() << "recv";
    emit this->getData(s);
}

All declaration classes are in different .h file

Debug assertion failed Expression: C++ vector subscript out of range

I have coded my meta-heuristic math model in C++ and I used CPLEX to solve the two mini math models within my code to get the initial feasible solution. to speed up the process I want to limit the number of possibilities in each mini math model to make sure the model does not go over all possibilities. my problem now is when I ower the limit, in some instances at a certain number it gives me the " Debug assertion failed Expression: C++ vector subscript out of range" error.

here is the part of my code that I used the limits.

//top of the code
const long int maxNumPRAPerCourse = 7;
const long int maxNumPf2fPerCourse = 7;
bool KeepGoing = true;

while (KeepGoing == true && RoomPossibilities[c].size() < maxNumPRAPerCourse) { 
 
//////solving the first mini math model//////

}
while (KeepGoing == true && RoomPossibilities[c].size() < maxNumPf2fPerCourse) { 
 
//////solving the second mini math model//////

}

in this particular case, with the limit set to 7, it works but when I change it to 6, it gives the error.

Why intrusive pointers and containers were never allowed into any C++ standard?

It seems that every single high performance and low latency platform I work with use intrusive pointers and containers to manage the lifetime cycle of their objects. Game engines, trading systems, avionics and others.

Intrusive pointers have been available from boost for more than a decade and intrusive/flat containers are widely available as well (eg google dense hash map).

If C++ is a performance-oriented language, why is that then intrusive pointers and containers never made it into a C++ standard even though they are one of the most widely used tools to achieve very low latency?

How to delete the selected random data in std::vector?

How to delete the selected random data in vector?

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> shuf{ 1, 2, 3, 4, 5 };
    int random = shuf[rand() % shuf.size()];
    std::cout << random; // to get the random data in shu
    std::find(shuf.begin(), shuf.end(), random);
    shuf.erase(random);

    for (int k = 0; k < shuf.size(); k++)
    {
        std::cout << shuf.at(k) << ' ';
        break;
    }
}

For example data in shuf vector is { 1, 2, 3, 4, 5 } then the random data for example is 4 so that the 4 will be deleted in vector, so the data in vector will be shuf{ 1,2,3,5 }

This is the error I got

no matching function for call to 
'find(std::vector<int>::iterator, std::vector<int>::iterator, int&)'

Use of decltype Gives warning Reference to Local Variable

I am trying to understand how decltype works in C++ and so going through examples. Just when i thought i understood what it means, i tried to create examples to confirm that and i got something that i cannot understand. The example is as follows:

#include <iostream>


template<typename T> 
auto func2(T a, T b) -> decltype(b < a ? a:b)
{ 
    //return a;//this gives warning of reference to local variable
    //return b;//this gives warning of reference to local variable
    
    return (b < a ? a:b);//this does not give warning of reference to local variable
}
int main()
{
   std::cout << "Hello World" << std::endl; 
   int b = func2(4,3);
   return 0;
}

As shown in the above code when i use the statement return a; or return b; i get a warning saying reference to local variable which is because we should never pass reference or pointers to local variable to outside their scope. But what i don't understand is that why are we not getting the same warning when i use return (b < a ? a:b);.

My thinking is that decltype(b < a ? a:b) should result in int&. And so when i write return (b < a ? a:b); a reference to local a or b should be returned depending on whether which one is greater and we should get the warning.

Check out the code here

Optimal control of 1 producer 2 consumer with maximum buffer size problem

I'm trying to code a multithreading application to feed images to my machine learning models. Initially I had only one consumer thread (image processing) per each producer thread (in charge of doing image acquisition and feeding them to the buffer if there is empty space). Now I need two consumers to get all the images in the buffer.

For the single producer-consumer I used one mutex and two semaphores to make sure the buffer doesn't go above the maximum size I've established. The code is something like this:


sem_init(&waitPop, 0, bufferLimitSize) //wait pop is used to limit size of buffer
sem_init(&waitPush, 0, 0) //wait push is used to avoid trying to load from an empty buffer
    
void *producer(){
    while(thereAreImages){
        
        image = loadimage()
        sem_wait(&waitPop)
        mutex.lock()
        
//This part may be unnecesary or not well coded but adds more safety on limiting buffer size 
        if(buffer.size>=bufferLimitSize){
            mutex.unlock()
            mutex.lock()
        }

        buffer.push_front(image)
        mutex.unlock()
        sem_post(waitPush)
    }
}

void *consumer(){
    while(thereAreImages || !buffer.empty()){
        
        sem_wait(&waitPush)
        mutex.lock()

        data = buffer.back()
        image = data.clone()

        buffer.pop_back()

        mutex.unlock()

        sem_post(waitPop)

        doImageProcessing(image)
    }
}

This worked fine for me and I've tested it a lot but now I need one more consumer thread processing all the images that go to the buffer. Basically, I need both consumers to process the same images even though their processing times are not the same. I've been wondering for some days how could I manage that using as little resources as possible and I haven't found a way that doesn't make the buffer size bigger than desired.

To summarize, I need both consumers to clone every single image that goes into the buffer while avoiding feeding to the buffer more images than the buffer limit established and trying to access to the buffer when is empty.

Thanks in advance!

Discrimination When Using auto specifier to deduce the type of a Prvalue in C++

I am trying to understand why the C++ standard/compiler discriminates against the behavior of auto. The example that i have is as follows:

int main()
{
    
    const int i = 34;//top level const on rhs. i is const int
    const auto &p = i;// low level const on rhs. p is const int&
    
    
    auto &g = i;//g is const int& . In this case the compiler is able to deduce that only reference to const can be bound to a const int 
    
    //auto &k = 5;//but in this case the compiler is not able(allowed) to deduce that only a reference to const can be bound to a prvalue 
    
    return 0;
}

As seen in the above code example, the compiler is able/allowed to deduced the type of variable g since only a reference to const type can be bound to a const type whereas in the next case the compiler is not able to deduce the type of variable k even though only a reference to const type can be bound to a const type. Ofcourse a rvalue reference can also be bound to a prvalue or xvalue.

My question is that even though we have a lvalue reference to some auto deduced type then why is the C++ standard does not allow the compiler to deduce k as const int& just as in the case of variable g? This seems intuitive enough to me. Maybe there are some problems associated with this which any of you can tell me.

Edit

I know that top level const of the initializer are ignored. For example,

const int i = 5;
auto k = i; //k is deduced to be int because the top level const of the initializer i is ignored

My question is about the implicit addition/deduction of the low level const on the rhs.

How to check a dangling pointer before writing to it [duplicate]

while program is executing in the runtime the game at sometime deallocates the address pointed by the pointer and it becomes a dangling one, The program inturn writes to this deallocated place of memory resulting in a crash! So is there anyway to make a condition to check if the address pointed by this pointer is always existing in memory before the program writes to it? im still newbie to pointers but as far as i know the dangling ptr doesn't equal a null.

DWORD moduleBase = (DWORD)GetModuleHandle("game.exe");
DWORD zoom_addy = *(DWORD*)(moduleBase + 0x657686);

//writing to address
*(int*)(zoom_addy + offset) = //value

mercredi 29 septembre 2021

I have a homework question which I need to submit by today and please excuse me if the format of my question is wrong,I'll be frank about the question [closed]

I have to write 3 separate programs and the questions are as below -

1-Move a JSON object from one part of the structure (denoted by keyOld) to another (denoted by keyNew).

2-Write a JSON structure in memory to a file.

3-Insert a new JSON object with one key value pair into a JSON data structure.This function uses the last used node as parent key.

->These programs must make use of c++ programming(c++11).And as in for the libraries I'm using json.hpp(taken from nlohman's).Also,create a json structure in the program and make the functions based on that structure.(Also,you can write the entire program either in main,or can create a seperate function too)The user also must be able to input values.There is no other limiting factor,just need the programs for them.(And again,I apologize if I haven't conveyed it better with nicer format):)

SFINAE for unsigned type selection

I'm trying to use SFINAE to check if a type has an unsigned equivalent. While it seems to work for int and bool, it fails for float. From the error it seems a certain type is not defined. The question is if the template argument to enable_if is ill-formed, why isn't this removed from overload selection ?

#include <type_traits>
#include <iostream>

template <typename T>
std::enable_if_t<sizeof(std::make_unsigned<T>), bool> hasUnsigned(T x)
{
   return true;
}

bool hasUnsigned(...)
{
   return false;
}

int main()
{
   float x; // If it's int, or char, it below displays true
   std::cout << std::boolalpha << hasUnsigned(x) << std::endl;
}

Error with float

In file included from has_unsigned.cc:1:
/usr/include/c++/10/type_traits: In instantiation of ‘struct std::make_unsigned<float>’:
has_unsigned.cc:5:18:   required by substitution of ‘template<class T> std::enable_if_t<(sizeof (std::make_unsigned<_Tp>) != 0), bool> hasUnsigned(T) [with T = float]’
has_unsigned.cc:18:48:   required from here
/usr/include/c++/10/type_traits:1826:62: error: invalid use of incomplete type ‘class std::__make_unsigned_selector<float, false, false>’
 1826 |     { typedef typename __make_unsigned_selector<_Tp>::__type type; };
      |                                                              ^~~~
/usr/include/c++/10/type_traits:1733:11: note: declaration of ‘class std::__make_unsigned_selector<float, false, false>’
 1733 |     class __make_unsigned_selector;
      |           ^~~~~~~~~~~~~~~~~~~~~~~~

XCode12 Allegro "file not found"

I could use some help solving a linker error. Could just be because I'm new to developing for MacOS. I got my Allegro Libraries off of Homebrew by using brew install allegro. I followed the steps on the tutorial I watched nearly to a tee, as I opened XCode to make a Cocoa app, went to the target, edited my build settings, and changed my Header search path to /usr/local/include/** and my Library search path to /usr/local/lib/**, as well as set my Framework search path to /Library/Frameworks/**. I set my C++ dialect to GNU++11. I went back into my terminal, where I used the commands to pull up my Allegro libraries in the Cellar. I picked out all the necessary files to make the game work, and then drag n' dropped them all into my linked frameworks and libraries. I created a Copy Files build phase with a destination of my frameworks, and drag n' dropped those same Allegro files into it as folder references as shown here: My files After all that, it was time to create my main.cpp.

#include <stdio.h>
#include <vector>
#include <allegro5\allegro.h>
#include <allegro5\allegro_font.h>
#include <allegro5\allegro_acodec.h>
#include <allegro5\allegro_audio.h>
// ...

...and there in laid the problem. I had gotten the error: 'allegro5\allegro.h' file not found. Upon double checking by commenting out the troublesome lines, it had turned out none of the files I #included could be found. Is there some kind of step I'm missing?

Do regular expressions in the C++ library support lookahead?

I want to extract only the characters between '[' and ']' from the below string.
Only lookbehind ((?=\s\s\])) works, but lookahead ((?<=\[\s\s)) does not. The compiler throws exceptions.
Does c++ support lookahead? Or is there any way to retrieve the characters?

Thank you.

    string text = "Character[  r  ] = Frequency[ 1592 ]"
                  "Character[  ]  ] = Frequency[ 0 ]"
                  "Character[  T  ] = Frequency[ 76 ]"
                  "Character[  1  ] = Frequency[ 76 ]";

    regex pattern("(?<=\\[\\s\\s).(?=\\s\\s\\])");//  < ------

    bool bvalue = regex_search(text.begin(), text.end(), pattern);
    if (bvalue)
        cout << "Yes" << endl;
    else
        cout << "No" << endl;

When trying to create a makefile on linux I receive an error which reads:"id returned 1 exit status"

All of the files including the header, source file and main.cpp compiled, I have include "return 0;" at the end but I still see the error:"id returned 1 exit status" , I am coding on Ubuntu using g++ to compile, how do I fix this?

Is for( auto it : vect ) required to iterate in vect order? [duplicate]

Can I rely on the following loop to iterate in order:

vector<A> a;
for( auto i : a )
{
    // Does i loop from the first to the last element in a, or i can come in any order?
}

How to use a template template argument from a member templated type alias of a struct

I'm trying to use a template template argument coming from a member type alias of a struct, but I can't find the right syntax:

struct A
{
   template <typename T>
   using type = int;
};

template <template <typename> class C>
struct B
{
   // ...
};

B<typename A::type> b; // Does not compile: error: template argument for template template parameter must be a class template or type alias template
B<typename A::template type> b; // Does not compile: error: expected an identifier or template-id after '::'
B<typename A::template <typename> type> b; // Does not compile
B<typename A::template <typename> class type> b; // Does not compile

Will this create an object of Sales_data, or it will create variables inside the class?

I'm a 13 year old who's trying to learn C++. I bought C++ Primer and I came across something confusing for me:

struct Sales_data {/**/ } acum, trans, * salesptr = nullptr;
    struct Salees_data {};
    Salees_data accumm, transs, * salessptr;

I do understand what is a struct and class but I have no idea what this statement will do. Will it create objects of the Sales_data struct, or it will create variables inside the Sales_data struct?

Does a single load synchronize with multiple stores?

The following is a quote from C++ Standard - Memory Order:

If an atomic store in thread A is tagged memory_order_release and an atomic load in thread B from the same variable is tagged memory_order_acquire, all memory writes (non-atomic and relaxed atomic) that happened-before the atomic store from the point of view of thread A, become visible side-effects in thread B. That is, once the atomic load is completed, thread B is guaranteed to see everything thread A wrote to memory.

The synchronization is established only between the threads releasing and acquiring the same atomic variable. Other threads can see different order of memory accesses than either or both of the synchronized threads.

Consider an atomic variable v and the following steps:

  1. Thread A stores in v using memory_order_release
  2. Thread B stores in v using memory_order_release
  3. Thread C loads from v using memory_order_acquire

Is the following statement true: "thread C is guaranteed to see everything thread A or B wrote to memory."

How to generate a random string from a vector? [duplicate]

I am trying to come up with a way to take one random string out of my vector element and failed. It keeps printing out Mutant string over and over.

What am I doing wrong?

#include <iostream>
#include <stdlib.h>
#include <vector>

class Game {
public:
    Game(int attack, int health, int potions, int enemyAttack, int enemyHealth) {
        Attack = attack;
        Health = health;
        Potions = potions;
        EnemyAttack = enemyAttack;
        EnemyHealth = enemyHealth;
    }

    std::string getEnemy() {
        return Enemy[rand() % Enemy.size()];
    }

    void setPlayerName() {
        std::cout << "Type in your name: ";
        std::cin >> Name;
    }

    std::string getPlayerName() {
        return Name;
    }

     int attackEnemy() {
        srand(time(0));

        return EnemyHealth = EnemyHealth - rand() % Attack; }

     int getEnemyHealth() {
         return EnemyHealth;
     }

private:
    std::vector <std::string> Enemy = { "Orc","Mutant","Mutant elephant","Bear" };

    std::string Name;

    int Attack;
    int Health;
    int Potions;

    int EnemyAttack;
    int EnemyHealth;

};

int main() {
    Game begin = Game(10,100,2,5,40);

//  begin.setPlayerName();

    std::cout << begin.getEnemy();
    

    return 0;
}

C++ I need just a function that will take a constant reference to a string and will return a string

C++ I need a function that will take a constant reference to a string as its parameter and will return a string. The function should look through the string and return any repeated sequence of 4 digits. If there isn't a repeated sequence of 4 digits exact, return a empty string.

For example: If the inputted string is "397390362927390", the function should return "7390" as it is repeated twice. At most there will be one repeated sequence in the input.

This is what I have so far.

   string find_repeated(const string &line){
     string a = line;
     if (a.length() <= 4){
       for (string::size_type i=0; i < a.length(); i++) {
         return a;
       }
     }  
   }

brace-enclosed initializer list conversion error

I have the following old code that used to work on "older" combinations/versions of C++, QuantLib and Boost. While was playing around with the idea of upgrading to newer versions ie C++11, QuantLib >= 1.76, boost >= 1_71 building now throws the following "conversion" error(s).
I am using [options] g++ -std=gnu++11

hestonslvmodule.cpp:456:7: warning: narrowing conversion of ‘(QuantLib::FdmHestonGreensFct::Algorithm)greensAlgorithm’ from ‘Quant
Lib::FdmHestonGreensFct::Algorithm’ to ‘QuantLib::Real’ {aka ‘double’} [-Wnarrowing]
  456 |       greensAlgorithm,
      |       ^~~~~~~~~~~~~~~
hestonslvmodule.cpp:457:7: error: cannot convert ‘const QuantLib::FdmSquareRootFwdOp::TransformationType’ to ‘const QuantLib::FdmH
estonGreensFct::Algorithm’ in initialization
  457 |       transformationType,
      |       ^~~~~~~~~~~~~~~~~~
      |       |
      |       const QuantLib::FdmSquareRootFwdOp::TransformationType
hestonslvmodule.cpp:458:7: error: cannot convert ‘const QuantLib::FdmSchemeDesc’ to ‘const QuantLib::FdmSquareRootFwdOp::Transform
ationType’ in initialization
  458 |       schemeDesc
      |       ^~~~~~~~~~
      |       |
      |       const QuantLib::FdmSchemeDesc
hestonslvmodule.cpp:459:5: error: could not convert ‘<brace-enclosed initializer list>()’ from ‘<brace-enclosed initializer list>’
 to ‘const QuantLib::FdmSchemeDesc’
  459 |     };
      |     ^
      |     |
      |     <brace-enclosed initializer list>

I did pick up some comments on brace lists and having to have the "right" C++ version to be able to cope with these but my C++ is not good enough to pick up on what exactly the problem could be in (this is my opinion/best guess) of which part of the code is acting "funny" now, causing the problems.

  FdmSchemeDesc getFdmSchemeDesc(const std::string& schemeDescStr) {
    return  (schemeDescStr == "ModifiedCraigSneyd") ? FdmSchemeDesc::ModifiedCraigSneyd()
          : (schemeDescStr == "CraigSneyd") ? FdmSchemeDesc::CraigSneyd()
          : (schemeDescStr == "Hundsdorfer") ? FdmSchemeDesc::Hundsdorfer()
          : (schemeDescStr == "ModifiedHundsdorfer") ? FdmSchemeDesc::ModifiedHundsdorfer()
          : (schemeDescStr == "ImplicitEuler") ? FdmSchemeDesc::ImplicitEuler()
          : (schemeDescStr == "ExplicitEuler") ? FdmSchemeDesc::ExplicitEuler()
          : (schemeDescStr == "Douglas") ? FdmSchemeDesc::Douglas()
          : (stop("unknown scheme type"), FdmSchemeDesc::ExplicitEuler());
  }

ending up being used here ...

class HestonSLVFDMModel {
public:
  HestonSLVFDMModel(QuantLib::Date referenceDate,
                    QuantLib::Date maxDate,
                    Function localVol,
                    S4 hestonProcess,
                    S4 fdmParams) {
    if (!fdmParams.is("HestonSLVFDMParams"))
      stop("Last parameter needs to be of type HestonSLVFDMParams");

    const std::string greensAlgoStr
      = as<std::string>(fdmParams.slot("greensAlgorithm"));

    const FdmHestonGreensFct::Algorithm greensAlgorithm =
        (greensAlgoStr == "Gaussian") ? FdmHestonGreensFct::Gaussian
      : (greensAlgoStr == "ZeroCorrelation") ? FdmHestonGreensFct::ZeroCorrelation
      : (greensAlgoStr == "SemiAnalytical") ? FdmHestonGreensFct::SemiAnalytical
      : (stop("unknown Greens function type"), FdmHestonGreensFct::SemiAnalytical);

    const std::string trafoTypeStr
      = as<std::string>(fdmParams.slot("transformationType"));

    const FdmSquareRootFwdOp::TransformationType transformationType =
        (trafoTypeStr == "Plain") ? FdmSquareRootFwdOp::Plain
      : (trafoTypeStr == "Power") ? FdmSquareRootFwdOp::Power
      : (trafoTypeStr == "Log") ? FdmSquareRootFwdOp::Log
      : (stop("unknown transformation type"), FdmSquareRootFwdOp::Log);

    const std::string schemeDescStr
      = as<std::string>(fdmParams.slot("fdmSchemeType"));

    const FdmSchemeDesc schemeDesc = getFdmSchemeDesc(schemeDescStr);

    const HestonSLVFokkerPlanckFdmParams params = {
      as<unsigned>(fdmParams.slot("xGrid")),
      as<unsigned>(fdmParams.slot("vGrid")),
      as<unsigned>(fdmParams.slot("tMaxStepsPerYear")),
      as<unsigned>(fdmParams.slot("tMinStepsPerYear")),
      as<Real>(fdmParams.slot("tStepNumberDecay")),
      as<unsigned>(fdmParams.slot("predictionCorrectionSteps")),
      as<Real>(fdmParams.slot("x0Density")),
      as<Real>(fdmParams.slot("localVolEpsProb")),
      as<unsigned>(fdmParams.slot("maxIntegrationIterations")),
      as<Real>(fdmParams.slot("vLowerEps")),
      as<Real>(fdmParams.slot("vUpperEps")),
      as<Real>(fdmParams.slot("vMin")),
      as<Real>(fdmParams.slot("v0Density")),
      as<Real>(fdmParams.slot("vLowerBoundDensity")),
      as<Real>(fdmParams.slot("vUpperBoundDensity")),
      as<Real>(fdmParams.slot("leverageFctPropEps")),
      greensAlgorithm,
      transformationType,
      schemeDesc
    }; // THIS IS LINE 459

...

So my question would be - is there an elegant or quick way of fixing the code with respect to handling these <brace-enclosed initializer list>() "conversions"?
Like I said these are all "greek to me" so I would appreciate any hints of how to apply quick fixes to such (think I saw somewhere just additional set of {} curly braces being added)? And also feel free to correct me if I am on the wrong path regarding the error source here?
Thanks

Most efficient way to pass arguments (inclduing std::function) to costructor in multithreaded environment

The multithreaded program is similar to the following:

struct Timer {
   Timer (boost::asio::io_service& ios) : timer_{ios} {}
   boost::asio::steady_timer timer_;
};

struct TimerContext {
   void                *ctxt_{nullptr};
   void                *cookie_{nullptr};
   TimerEventCallback   teCallback_{nullptr};
};

class A {
   std::function<void(Timer *, const TimerContext&)>    callback_;
   int                                                  id_;
   std::string                                          name_;
   boost::asio::io_service                              ios_;
   std::thread                                          thread_;
};

A's constructor:

A::A (std::function<void(Timer *, const TimerContext&)> cb, int id, std::string name) :
   callback_{cb},
   id_{id},
   name_{name}
{
   thread_ = std::thread{[this] () {
         // some code
      }
   };
}

The callback function definition (free function as of now, written by me):

void
customCallback (Timer *timer, const TimerContext& ctxt) {
   log << __func__ << "timer id: " << (void *)timer;

   auto ret = ctxt.teCallback_(timer, ctxt.cookie_);

   log << __func__ << ret;
}

In main(),

for (int i = 0; i < 5; ++i) {
   int id = getId(i);
   std::string name = getName(i);

   A *a = new A{customCallback, id, name};

   vectorA.push_back(a);

}

I can think of two approaches:

  1. Pass constructor arguments by value and then std::move them in the constructor initializer list.
A *a = new A{customCallback, id, name};

A::A (std::function<void(Timer *, const TimerContext&)> cb, int id, std::string name) :
   callback_{std::move(cb)},
   id_{std::move(id)},
   name_{std::move(name)}
  1. Pass constructor arguments by const reference and then and allow the copy to occur in the constructor initializer list.
A *a = new A{customCallback, id, name};

A::A (const std::function<void(Timer *, const TimerContext&)> &cb, const int &id, const std::string &name) :
   callback_{cb},
   id_{id},
   name_{name}

Which one would be more efficient in terms of copy and performance? If there is a better approach (till and including c++14), please suggest.

how to inherit and resue the std::tuple function from base class in C++?

class common: public NotImportant
{
   public :
   common(); //default constuctor
   explicit common(xxx);
   
   ~common();

   virtual std::tuple<a,b> funcA();
   virtual void funcB();
   void  xx1();
   void  xx2();
   void  xx3();
   void  xx4();
}

class special: public base
{
   public :
   explicit special(xx);
   ~special()
   virtual void funcB() override;
}

The class common implemented all the functions, and the virtual funcA() is a pure virtual function in class Notimportant.

The class special will reuse all the implemented functions from class common except funcB, so the funcB will only be implemented for this class.This method i have used for long time and it works fine to reuse the functions in class common.

But now the problem is the return type of funcA in class common is std::tuple<a,b>, so when i compile the code i have one error:

error #2045: function "funcA" requires a virtual table thunk but its return type, "std::tuple<a, b>", is incomplete. 
Please ensure that "***std::tuple<a, b>***" is defined/instantiated in this translation unit. 

may i know how to solve it? is inherited class required to add sth like template for reuse std::tuple function?

this funcA must use std:tuple as it's a interface from the other class.

And the way i build is to write the make file to include the source file of class common.

How would I write a program that reads from a standard input and outputs only 6 characters to a line?

For example if the input was:

My name is Alex and
I also love coding

The correct output should be:

1:My nam  
1:e is A
1:lex an
1:d
2:I also 
2: love 
2:coding                         

So far I have this

   int  main () {
     string i;
     i.substr(0,6);
     while (getline(cin, i)){
       cout << i << endl;
     }  
   }

How to set only public key in OpenSSL 3.0 EVP_PKEY api

I am able to extract public and private keys from OSSL_PARAM array with these functions (i tried using special functions to get parameter by name, but they can't find actual parameters by that names)

std::vector<unsigned char> RSAKeyPair::GetNamedParam(EVP_PKEY *key, const std::string& name) {
    OSSL_PARAM *param_array;
    if (EVP_PKEY_todata(key, EVP_PKEY_PUBLIC_KEY, &param_array) == 0)
        throw std::runtime_error("cannot read parameters");

    OSSL_PARAM *cur_param;
    int i = 0;
    do {
        cur_param = &param_array[i++];
        if (std::string(cur_param->key) == name) {
            auto data = GetParameterData(cur_param);
            OSSL_PARAM_free(param_array);
            return data;
        }
    } while (cur_param->key != nullptr);

    throw std::runtime_error("cannot find parameter with name \"" + name + '"');
}

std::vector<unsigned char> RSAKeyPair::GetParameterData(OSSL_PARAM *param) {
    BIGNUM *bignum{nullptr};
    if(OSSL_PARAM_get_BN(param, &bignum) == 0)
        throw std::runtime_error("cannot read bignum");

    std::vector<unsigned char> bytes;
    int new_size = BN_num_bytes(bignum);
    bytes.resize(new_size);
    BN_bn2bin(bignum, bytes.data());

    return bytes;
}

The problem is when I try to build new key from raw bytes using the same approach

void RSAKeyPair::SetPublicKey(const std::vector<unsigned char> &key) {
    OSSL_PARAM *parameters = GetKeyParameters({key}, std::nullopt);
    SetKeyFromParameters(parameters);
    OSSL_PARAM_free(parameters);
}

void RSAKeyPair::SetKeyFromParameters(OSSL_PARAM *parameters) {
    auto ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, nullptr);
    if (EVP_PKEY_fromdata_init(ctx) <= 0)
        throw std::runtime_error("cannot init create key");

    EVP_PKEY_free(keys_);
    if (EVP_PKEY_fromdata(ctx, &keys_, EVP_PKEY_KEYPAIR, parameters) <= 0)
        throw std::runtime_error("cannot create key");
}

OSSL_PARAM *RSAKeyPair::GetKeyParameters(std::optional<std::reference_wrapper<const std::vector<unsigned char>>> public_key,
                                         std::optional<std::reference_wrapper<const std::vector<unsigned char>>> private_key) {
    auto param_bld = OSSL_PARAM_BLD_new();

    if (public_key.has_value()) {
        auto public_data = public_key.value().get();
        PushParamBuildBignum(param_bld, "n", public_data);
    }

    if (private_key.has_value()) {
        auto private_data = private_key.value().get();
        PushParamBuildBignum(param_bld, "d", private_data);
    }

    // default rsa exponent
    OSSL_PARAM_BLD_push_long(param_bld, "e", RSA_F4);

    auto parameters = OSSL_PARAM_BLD_to_param(param_bld);
    OSSL_PARAM_BLD_free(param_bld);

    return parameters;
}

void RSAKeyPair::PushParamBuildBignum(OSSL_PARAM_BLD *param_bld, const char *key, std::vector<unsigned char> &bytes) {
    BIGNUM *bignum = BN_bin2bn(bytes.data(), (int)bytes.size(), nullptr);
    OSSL_PARAM_BLD_push_BN(param_bld, key, bignum);
}

for some reason, function EVP_PKEY_fromdata() fails to create new key using my OSSL_PARAM array. What am I supposed to do to initialize ONLY public key on signature verifying end (where I cannot build full keypair with all parameters) ?

you can see full source code for this class at https://github.com/Valemos/course_work_inverted_index/blob/master/src/session/RSAKeyPair.cpp

How to use dynamic_pointer_cast with variadic templates?

My goal is to have a function (foo) which takes an arbitrary number of types (...TArgs), and tries to cast some shared pointers (myInt, myDouble and myChar (see below)) to the given corresponding shared pointer types (shared_ptr<TArgs...>). If the cast is successful it should do some stuff, otherwise just continue running.

I tried to achieve this with using dynamic_pointer_cast on variadic template arguments. However, the concept of variadic templates and how to use them is fairly new to me. I tried to use variations of the below code but none of them worked. Could you please help me out how can I create a function?

// Example program
#include <iostream>
#include <memory>

template <typename T>
struct Base {
    Base(T data) : _data(data){}
    T get() const {return _data;}
protected:
    T _data;
};

struct Int : Base<int>{
    Int(int data) : Base(data){}
};
struct Double : Base<double>{
    Double(double data) : Base(data){}
};
struct Char : Base<char>{
    Char(char data) : Base(data){}
};


template <typename ...TArgs>
void foo()
{
    const auto myInt = std::make_shared<Int>(1);
    const auto myDouble = std::make_shared<Double>(3.14);
    const auto myChar = std::make_shared<Char>('a');
    
    if (const auto x = std::dynamic_pointer_cast<TArgs>(myInt)...) // syntax error
    {
        std::cout << "casted myInt with value = " << x->get() << "\n";
    }
    if (const auto x = std::dynamic_pointer_cast<TArgs>(myDouble)...) // syntax error
    {
        std::cout << "casted myDouble with value = " << x->get() << "\n";
    }
    if (const auto x = std::dynamic_pointer_cast<TArgs>(myChar)...) // syntax error
    {
        std::cout << "casted myChar with value = " << x->get() << "\n";
    }
}

int main()
{
    foo<Int, Char>();
    return 0;
}

Expected output of above code:

casted myInt with value = 1
casted myChar with value = a

c++11 how to convert legacy class to template

I have a legacy class like:

class Wrapper{
public:
    Wrapper(void*);
    void* get();
};

I want to create a type safe wrapper like:

template<class T>
class Wrapper{
public:
    Wrapper(T);
    T get();
};

Stuff like this won't work because of C++11:

template<class T = void*> //Here I would need <>
class Wrapper...

typedef Wrapper<void*> Wrapper; //This isn't allowed

Is there a way to convert Wrapper to a template class without editing all places where it's already used?

Class's container get() member function usage vs copying

I have created a config class which loads configuration from a config YAML. I have created vector containers for each type

// Pseudo Code
class config
{
private:
    std::vector<std::string> c_name;

public:
    config(yaml_file_path)
    {
        // Handles reading from yaml and loading data to c_name container.
        load(yaml_file_path);
    }

    std::vector<std::string> get_name()
    {
        return c_name;
    }
};

I use this object in other class to get the name config.

class loadConfig 
{
    config cfg(yaml_file_path);
    std::vector<std::string> name = cfg.get_name();
    // Further use of vector name like checks.
}

Question : What would be better?(as code practice and execution time and/or memory space)

  1. Using get_name() function in various places in code. OR
  2. Copying value in container, as I have done?

mardi 28 septembre 2021

Handling Input/Output when creating own Bigint class

I'm trying to create my own BigInt class that can handle numbers up to 256 digits. Going off of this main file:

#include <iostream>
#include "Bigint.h"

using namespace std;


int main() {
    Bigint n1, n2;
    char op;
    
    while (cin >> n1 >> n2 >> op) {
        switch (op) {
            case '+' :
                cout << n1 + n2 << endl;
                break;
            case '-' :
                cout << n1 - n2 << endl;
                break;
            case '*' :
                cout << n1 * n2 << endl;
                break;
            case '/' :
                cout << n1 / n2 << endl;
                break;

        }
    }

    return 0;
}

I understand the best way to do this would be to overload the input operator so that it converts whatever number is entered as input into a digit array. And then from there I could then overload the binary operators. In terms of the class 'Bigint' my header is as follows:

#ifndef BIGINT_BIGINT_H
#define BIGINT_BIGINT_H

#include <iostream>

#define BIGINT_SIZE 256

class Bigint {
public:
        friend std::istream& operator>> (std::istream& in, Bigint& n);

        friend std::ostream& operator<< (std::ostream& out, const Bigint& n);

        // the binary + operator
        friend Bigint operator+ (const Bigint& n1, const Bigint& n2);

        // the binary - operator
        friend Bigint operator- (const Bigint& n1, const Bigint& n2);

        // the binary * operator
        friend Bigint operator* (const Bigint& n1, const Bigint& n2);

       // the binary / operator
       friend Bigint operator/ (const Bigint& n1, const Bigint& n2);

};


#endif //BIGINT_BIGINT_H

But I'm lost as to how I would actually go about overloading the input and output operator in the class cpp file.

std::istream& operator>> (std::istream& in, Bigint& n){
        
}
std::ostream& operator<< (std::ostream& out, const Bigint& n) {
   
}

I think I'm confusing myself, but I don't quite understand what std::istream& in, std::ostream out and Bigint& n are in the context of this. How would I handle these variables when writing something that converts the istream into a digit array? Thank you

How does dynamic arrays(std::vector) works in c++?

According to what I heard std::vector stores data contiguously and when you try to add or delete an element to it grow or shrink by allocating new memory and copies everything from the old memory to the new memory with the changes and deletes the old memory

in the code below I have a copy constructor it says copied every time the class gets copied it gave me 6 copied messages when I had 3 elements and that was fine but when I added another element it gave me 7 messages

Isn't it supposed to give me 10? And how to optimize that?

#include <iostream>
#include <vector>

struct Vertex
{
    int x, y, z;

    Vertex(int x, int y, int z) : x(x), y(y), z(z)
    {
    }

    Vertex(const Vertex &vetrex) : x(vetrex.x), y(vetrex.y), z(vetrex.z)
    {
        std::cout << "Copied" << std::endl;
    }
};

int main()
{
    std::vector<Vertex> vertices;
    vertices.push_back({1, 2, 3});
    vertices.push_back({4, 5, 6});
    vertices.push_back({7, 8, 9});
    vertices.push_back({10, 11, 12});
}

C++ : Confusion between Copy & Assignment

According to "C++ Primer, 5th Ed.", section 8.1.1:

ofstream out1, out2;
out1 = out2;              // error: cannot assign stream objects
// print function: parameter is copied
ofstream print(ofstream); // error: can't initialize the ofstream parameter
out2 = print(out2);       // error: cannot copy stream objects -- Line 4

Line 4 says "cannot copy stream objects". Is it implying on the print() command on line 4, or the =, that a copy is not permitted? The = to me is the assignment statement while the print(out2) is calling the constructor of ofstream passing the out2 argument. So I'm a bit confused here.

Can anyone explain better?

Implicitly declared destructor

If I'm correct, a default destructor is always implicitly declared, unless the user declares it. According to cppreference:

Deleting an object through pointer to base invokes undefined behavior unless the destructor in the base class is virtual

Now, consider this example:

struct B {};
struct D : B {};

Is the implicitly declared destructor B::~B() virtual? If not, should I always declare a virtual destructor when using inheritance?

lundi 27 septembre 2021

Variadic functions to take any number of objects

I have a class called parser with a member function madd_arguments(const argument args, ...). argument is a separate class and has a member variable arg_name to differentiate one from another. I want the function madd_arguments to accept any number of argument objects. To achieve this, I have the following code:

class argument{
private:
    std::string arg_name;                        
public:                             
    argument(const std::string& ARG_NAME) : arg_name(ARG_NAME){}     
    friend class parser;
};
#define add_arguments(...) madd_arguments(__VA_ARGS__, argument("END_HERE"))

#include "arg.h"

class parser {
private:
    std::vector<argument> known_arguments;                      //holds all arguments
public:
    void madd_arguments(const argument args, ...);
};


void parser::madd_arguments(const argument args, ...) {
    va_list vargs;
    for (va_start(vargs, args); args.arg_name != "END_HERE"; args = va_arg(vargs, const argument)){
        known_arguments.push_back(args);
    }

    va_end(vargs);
}

and my main:


int main() {

    argument a("name");
    a.set_flags("-v", "-verbose", "bobby", "jones");

    argument b("string argument");

    parser p;
    p.add_arguments(a,b);
}

but I get the following errors: error: passing ‘const argument’ as ‘this’ argument discards qualifiers [-fpermissive] _start(vargs, args); args.arg_name != "END_HERE"; args = va_arg(vargs, const argument)){ and error: passing ‘const std::vector<argument>’ as ‘this’ argument discards qualifiers [-fpermissive]known_arguments.push_back(args);

After looking at other posts on here I figured that I would have to make the member function madd_arguments a const function but I can't because I am going to make changes to the variable known_arguments which is a member of the parser object.

I used macro and the va_list based on this post: How do I write functions that accept unlimited arguments?. Anybody know how I can get around this or should I just go back to using variadic templates instead?

choose a constexpr based on a runtime value and use it inside a hot loop

I need to traverse a vector, read each element, and map to the modulo division value. Modulo division is fast for divisors of power2. So, I need to choose between a mod and mod_power2 during the runtime. Following is a rough outline. Please assume that I am using templates to visit the vector.

Bit manipulation tricks were taken from https://graphics.stanford.edu/~seander/bithacks.html

static inline constexpr bool if_power2(int v) {
  return v && !(v & (v - 1));
}

static inline constexpr int mod_power2(int val, int num_partitions) {
  return val & (num_partitions - 1);
}

static inline constexpr int mod(int val, int num_partitions) {
  return val % num_partitions;
}

template<typename Func>
void visit(const std::vector<int> &data, Func &&func) {
  for (size_t i = 0; i < data.size(); i++) {
    func(i, data[i]);
  }
}

void run1(const std::vector<int> &v1, int num_partitions, std::vector<int> &v2) {
  if (if_power2(num_partitions)) {
    visit(v1,
          [&](size_t i, int v) {
            v2[i] = mod_power2(v, num_partitions);
          });
  } else {
    visit(v1,
          [&](size_t i, int v) {
            v2[i] = mod(v, num_partitions);
          });
  }
}

void run2(const std::vector<int> &v1, int num_partitions, std::vector<int> &v2) {
  const auto part = if_power2(num_partitions) ? mod_power2 : mod;

  visit(v1, [&](size_t i, int v) {
    v2[i] = part(v, num_partitions);
  });
}

My question is, run1 vs run2. I prefer run2 because it is easy to read and no code duplication. But when when I check both in godbolt (https://godbolt.org/z/3ov59rb5s), AFAIU, run1 is inlined better than run2.

So, is there a better way to write a run function without compromising on the perf?

vector of atomics in c++: msvc vs gcc

I developed some code on Linux which uses a std::vector of std::atomic variables - one for each thread that I use, which might be set to a different number for some different computation. In simple form it looked something like:

Edit: also including a reset function:

class threadsafe_vals{
    std::vector<std::atomic<int> > vals;
public:
    threadsafe_vals(int _n){
        vals = std::vector<std::atomic<int> >(_n);
        for (auto &x:vals){
            x=0;
        }
    }
    void reset(int _i){
        vals =std::vector<std::atomic<int> >(n);
        for (auto &x:vals){
            x=0;
        }
    }
    int get(int _i){ return vals[_i];}
    void set(int _i,in _val){ vals[_i] = _val;}
};

I know that std::atomics have no copy constructor so I made sure I never used anything like erase push_back etc. etc., but simply treated the vector as a fixed array until I reset the whole thing. And whenever I reset the vector I always did so using the line vals = std::vector<std::atomic<int> >(n) such that the use of the copy constructor was avoided, and instead the existing atomics destructed and then simply initialised (I think). The code was not required to be threadsafe during the reset(int n) operation.

Anyway, for both Linux using gcc and Mac using Clang, this all worked.

I then however, tried to port my code to Windows under MSVC, and it won't compile.

I now get the compiler error

std::atomic<int>::atomic(const std::atomic<int> &): attempting to reference a deleted function

in file xmemory().

It looks like it is complaining that it is having to use the copy-constructor for the atomics I am using.

Now: gcc and clang were both smart enough to figure out I didn't actually use the copy constructor and compiled my code, so I'm assuming that this is a Microsoft c++ implementation thing.

But then the questions remains:

  1. Why does MSVC think I'm invoking the copy constructor here?

  2. More crucially, how I can I get the desired effect whereby I can have a vector of atomics without invoking the copy constructor according to MSVC (or any other method), similar to my original code, in a portable way?

I've tried searching for some similar questions, but the answers seem all over the place with some stating that vectors of atomics simply aren't possible. But this is false, at least according to the gcc and clang interpretations of the c++ standard.

How can I std::bind a user-provided function to a member variable of type std::function?

I have a class with a member variable std::function customCallback, and I need to let the user customize its behavior. customCallback should take as input a const std::array<int, N>& and a int, and return a std::array<int, N> (where N is a template parameter).

I am currently using std::bind to achieve this, but I can't understand why the compilation fails. What am I missing?

Since the original code involves inheritance and templates, I am including inheritance and templates in my minimal reproducible example (live code here) as well.

The user should be able to use both the constructor OR a member function to set the custom behavior.

base.h:

#include <array>
#include <functional>

template <std::size_t N>
class BaseClass {
public:
    virtual std::array<int, N> CustomBehavior(const std::array<int, N>& user_array, int user_number) = 0;    
protected:
    std::array<int, N> my_array = {0, 0};
};

derived.h:

#include <base.h>
#include <cstddef>

template <std::size_t N>
class DerivedClass : public BaseClass<N> {
public:
    DerivedClass() = default;

    DerivedClass(std::function<std::array<int, N>(const std::array<int, N>&, int)> custom_f)
        : customCallback(std::bind(custom_f, std::ref(std::placeholders::_1), std::placeholders::_2)) {}

    void SetCustomBehavior(std::function<std::array<int, N>(const std::array<int>&, int)> custom_f) {
        customCallback = std::bind(custom_f, std::ref(std::placeholders::_1), std::placeholders::_2);
    }

    std::array<int, N> CustomBehavior(const std::array<int, N>& user_array, int user_number) override {
        if (customCallback)
            this->my_array = customCallback(user_array, user_number);
        return this->my_array;
    }

private:
    std::function<std::array<int, N>(const std::array<int, N>&, int)> customCallback;
};

main.cpp:

#include <derived.h>
#include <cassert>

static constexpr std::size_t MySize = 2;

std::array<int, MySize> my_behavior(const std::array<int, MySize>& input_array, int a) {
    return {a * input_array[0], a * input_array[1]};
}

int main() {

    std::array<int, MySize> my_array = {1, 1};

    // Default constructor (COMPILES)
    DerivedClass<MySize> foo_1; // OK
    std::array<int, MySize> bar_1 = foo_1.CustomBehavior(my_array, 2);
    assert(bar_1[0] == 0 && bar_1[1] == 0);

    // Custom constructor (ERROR)
    DerivedClass<MySize> foo_2(my_behavior); // COMPILATION ERROR
    std::array<int, MySize> bar_2 = foo_2.CustomBehavior(my_array, 2);
    assert(bar_2[0] == 2 && bar_2[1] == 2);

    // Custom behavior set later on (ERROR)
    DerivedClass<MySize> foo_3;  // OK
    foo_3.SetCustomBehavior(my_behavior); // COMPILATION ERROR
    std::array<int, MySize> bar_3 = foo_3.CustomBehavior(my_array, 2);
    assert(bar_3[0] == 2 && bar_3[1] == 2);

    return 0;
}

I am not including the whole compilation error since it's fairly long, but it can be seen live code here.

Lock/unlock std::unique_lock in different functions

I'm writing a program that uses a condition variable as such:

bool flag;
std::mutex mtx;
std::condition_variable cond;

{
  std::unique_lock<std::mutex> lock(mtx);
  cond.wait(lock, [&]{ return flag; });

  // ... do some stuff
  // ... do some more stuff

  flag = false;

} // lock unlocked here

Now I'm faced with the problem that "do some stuff" and "do some more stuff" are actually implemented in two separate callback functions invoked one after the other from somewhere else, i.e.:

void callback1() {
   std::unique_lock<std::mutex> lock(mtx);
   cond.wait(lock, [&]{ return flag; });

   // ... do some stuff
} // ERROR! lock unlocked too early

void callback2() {
   // ... do some more stuff
  flag = false;
} // lock should be unlocked here

How can I solve this issue? I could encapsulate both callbacks in some object that holds the lock as a member variable but that seems to me like it goes against the intended semantics of std::unique_lock.

EDIT: more context:

Someone else has written a class Foo that looks as follows:

class Foo
{
public:
  void bar() {
    before_bar_callback();

    // ...
    
    after_bar_callback();
  }

private:
  virtual void before_bar_callback() {}
  virtual void after_bar_callback() {}
};

I can't modify Foo::bar and it runs in a separate thread. I would like to wait on a condition variable in before_bar_callback and then set flag = false and unlock the associated lock in after_bar_callback.

Implementing a "temporarily suspendable" concurrent loop in C++

I'm writing a program whose main thread spawns a worker thread that performs some work, sleeps for a set amount of time in an infinite loop, i.e. the worker thread executes:

void do_work() {
  for (;;) {
    // do some work
    
    std::this_thread::sleep_for(100ms);
  }
}

Now, I would additionally like to be able to temporarily completely disable this worker thread from the main thread, i.e. I would like to write the following functions:

  • disable_worker(): disable the worker thread
  • enable_worker(): enable the worker thread again

What I've come up with is the following:

#include <chrono>
#include <condition_variable>
#include <mutex>
#include <thread>

using namespace std::literals::chrono_literals;

bool enabled;
std::mutex mtx;
std::condition_variable cond;

void disable_worker() {
  std::lock_guard<std::mutex> lock(mtx);
  enabled = false;
}

void enable_worker() {
  {
    std::lock_guard<std::mutex> lock(mtx);
    enabled = true;
  }

  cond.notify_one();
}

void do_work() {
  for (;;) {
    std::unique_lock<std::mutex> lock(mtx);
    cond.wait(lock, []{ return enabled; });

    // ... do some work ...

    std::this_thread::sleep_for(100ms);
  }
}


int main() {
  std::thread t(do_work);

  // ... enable/disable t as necessary ...
}

I suppose this works (at least I can't spot any issues), however, I would also like to guarantee that when either of enable_worker and disable_worker return (in the main thread), the working thread is guaranteed to be either blocking on the condition variable or sleeping, i.e. not performing any work. How can I implement this without any race conditions?

define constants in a struct

I'm trying to create a struct with some constants in it like this:

#include <CoreAudio/CoreAudio.h>
...
struct properties {
    //Volume control
    const AudioObjectPropertyAddress volume = {
        kAudioDevicePropertyVolumeScalar, //mSelector
        kAudioDevicePropertyScopeOutput, //mScope
        0 //mElement
    };
    //Mute control
    const AudioObjectPropertyAddress mute = { 
        kAudioDevicePropertyMute,
        kAudioDevicePropertyScopeOutput,
        0
    };
};

However, I cannot access the constants in this class;

//Function used to for example set volume level or set mute status
//bool setProperty(UInt32 data_to_write, AudioObjectPropertyAddress addr_to_write_to);
//Following line should mute the system audio
setProperty(1, properties::mute);

This will make the compiler return the following error:

error: invalid use of non-static data member 'mute'

So, I tried making the constants static like this:

const static AudioObjectPropertyAddress volume = { ...

But now, I get a different error:

error: in-class initializer for static data member of type 'const AudioObjectPropertyAddress' requires 'constexpr' specifier

The last thing I tried is changing const static to static constexpr, however again, I cannot access the constants. Every time I try to access them, the compiler show this error:

Undefined symbols for architecture x86_64:
  "properties::mute", referenced from:
      _main in main-fefb9f.o
ld: symbol(s) not found for architecture x86_64

I'm not really sure what's going on here, I tried converting my struct into a class, but I ended up getting the same Undefined symbols error. I know I could just define the two constants as global variables, but I thought putting them into a struct/class would make the code look "nicer" or just more organized. Could someone please explain what's wrong here and provide a possible solution?

Segmentation fault when applying std::sort to a vector of vectors of integers

I am writing a struct for sorting generic data types allowing for multiple values of the same in each object to be sorted (e.g. sorting a vector of vectors of integers). The code below is a simplified example of the code I've written, with an example using ints and the inner vectors sized to 2.

// Sort object
template <class te_DataType, int te_mValue>
struct Sort_Data
{
  std::size_t iData;
  std::array<te_DataType, te_mValue> Values;
};

// Sort object comparator
template<class te_DataType, int te_mValue>
inline bool isLess_Sort_Data(const Sort_Data<te_DataType, te_mValue>& data0, const Sort_Data<te_DataType, te_mValue>& data1)
{
  FORDO(ivalue, te_mValue)
    if(data0.Values[ivalue] >= data1.Values[ivalue]) continue;
    else return true;

  return false;
}

// Sorting struct
template <class te_DataType, int te_mValue>
struct Sorter
{
  // List of sorting objects
  std::vector<Sort_Data<te_DataType, te_mValue> > SortDataList;

  // Constructor/Destructor
  Sorter(const size_t mdata) : SortDataList(mdata) {}
  ~Sorter() = default;

  // Method to sort the objects in SortDataList
  inline void DataSort()
  {
    std::sort(SortDataList.begin(), SortDataList.end(),
              [](const Sort_Data<te_DataType, te_mValue>& a, const Sort_Data<te_DataType, te_mValue>& b) -> bool
              {
                FORDO(ivalue, te_mValue)
                  if(a.Values[ivalue] >= b.Values[ivalue]) continue;
                  else return true;
                return false;
              });
  }
};

When I randomly initialise the entries in the vector of vectors of ints (sized to 1e3), I get segmentation fault (core dumped) when I call the DataSort() method. I have run my code through Valgrind as well, and while it definitely picks up errors, I cannot make sense of them. Can anyone give me some advice on this?

std::random_device randDevi;
std::mt19937 randomEngine(randDevi());
std::uniform_int_distribution<int> randGenerInt(0, 1e7);

// Load randomised data
int mData = 1e3;
Sorter<int, 2> sorter(mData);
for(int idata = 0; idata < mData; ++idata)
{
  sorter.SortDataList[idata].iData = idata;
  for(int ii = 0; ii < 2; ++ii) sorter.SortDataList[idata].Values[ii] = randGenerInt(randomEngine);
}

sorter.DataSort(); // Segmentation fault occurs here

dimanche 26 septembre 2021

Overloading an input operator

Currently have a assignment in which I've to create my own BigInt class. The issue I'm having is that I'm not sure how I would be able to overload the input operator the same way I've overloaded =.

My header file is as follows:

#ifndef BIGINT_BIGINT_H
#define BIGINT_BIGINT_H

#include <iostream>

#define BIGINT_SIZE 256

class Bigint {
    public:
        friend std::ostream& operator>> (std::ostream& out, const Bigint& n);

        friend std::ostream& operator<< (std::ostream& out, const Bigint& n);

        // the binary + operator
        Bigint operator+ (const Bigint& n);

        // the binary - operator
        Bigint operator- (const Bigint& n);

        // the binary * operator
        Bigint operator* (const Bigint& n);

        // the binary / operator
        Bigint operator/ (const Bigint& n);

        // the binary = operator:   bigint = bigint
        Bigint& operator= (const Bigint& n);

        // the binary = operator with int:   bigint = int
        Bigint& operator= (int n);

        // the constructor and destructor
        Bigint(int size = BIGINT_SIZE) {digits = size; number = new char[digits]; }

        ~Bigint() { delete[] number; }


    private:
        int  digits;
        char *number;
};


#endif //BIGINT_BIGINT_H

And my cpp file is:

#include "Bigint.h"
#include <iostream>


std::istream& operator>> () {

}


std::ostream& operator<< (std::ostream& out, const Bigint& n) {
    int cntr = 0;

    while ((n.number[cntr] == 0) && (cntr < n.digits-1))
        cntr++;

        while (cntr < n.digits)
            out << (int)n.number[cntr++];

            return out;
}


Bigint& Bigint::operator= (int n) {
    int cntr;

    cntr = digits - 1;
    while (cntr >= 0) {
        number[cntr--] = n % 10;
        n /= 10;
    }

    return *this;
}

Bigint Bigint::operator+ (const Bigint& n) {
    Bigint sum( (digits > n.digits) ? digits : n.digits );
    int nptr, myptr, sumptr;
    char next_n1, next_n2;
    char carry = 0;

    for (sumptr = sum.digits - 1, myptr = digits - 1, nptr = n.digits - 1; sumptr >= 0; sumptr--, myptr--, nptr--) {
        next_n1 = (nptr < 0) ? 0 : n.number[nptr];
        next_n2 = (myptr < 0) ? 0 : number[myptr];
        sum.number[sumptr] = next_n1 + next_n2 + carry;
        if (sum.number[sumptr] > 9) {
            carry = 1;
            sum.number[sumptr] -= 10;
        }
        else{
            carry = 0;
        }
    }

    return sum;
}

I've only actually implemented code to handle the + and = so far.

SIGSEGV Fault in infix to postfix using stack

When I tried making if condition to while loop to remove more than one operator from stack in bracket (f+g/h) here output should be (fgh/+) but i am not able to run the code with while loop my output is coming (fgh/) due to if condition , how do I put while loop without SIGSEGV, im getting run-time error SIGSEGV ?

#include<bits/stdc++.h>
using namespace std;

class Solution
{
    public:
    //Function to convert an infix expression to a postfix expression.
    string infixToPostfix(string s)
    {
        // Your code here
        stack<char> op;
        string res;
        int i=0;
        while(i<s.length()){
            if(s[i]>='a' && s[i]<='z' || s[i]>='A' && s[i]<='Z' ){
                res.push_back(s[i]);
                cout<<res<<" ";
            }
            else if(s[i]=='(')
                op.push(s[i]);
            else if(s[i]==')'){
                if(op.top()!='('){ //here SIGSEGV I want this in while loop not if statement
                    res.push_back(s[i]);
                    op.pop();
                    cout<<res<<" ";
                }
                op.pop();
            }
            else {
                if(op.empty())
                    op.push(s[i]);
                else if(precedence(s[i])>precedence(op.top()))
                    op.push(s[i]);
                else if(precedence(s[i])<precedence(op.top())){
                    while(precedence(s[i])<precedence(op.top())){
                        res.push_back(op.top());
                        op.pop();
                    }
                    op.push(s[i]);
                }
                else{
                    res.push_back(op.top());
                    op.pop();
                    op.push(s[i]);
                }
            }
        i++;
        }
        return res;
    }
    int precedence(char a)   //precedence function
    {
        if (a == '^')
            return 3;
        else if (a == '*' || a == '/')
            return 2;
        else if (a == '+' || a == '-')
            return 1;
        else if (a == '(' || a == ')')
            return 0;
    }
    

};

int main(){
    int t;
    t=1;
    cin.ignore(INT_MAX, '\n');
    while(t--){
        string exp;
        cin>>exp;
        Solution ob;
        cout<<ob.infixToPostfix(exp)<<endl;

    }
    return 0;
}

Efficient conversion of boost::multiprecision::cpp_dec_float_100 to std::string?

Problem

I have a vector containing cpp_dec_float_100 values from the boost::multiprecision library (i.e., an std::vector<cpp_dec_float_100>). My goal is to convert this to an std::vector<std::string> (i.e., to convert cpp_dec_float_100 types to strings).

What I've Tried

  • boost::exception::to_string() / boost::lexical_cast<std::string>: Boost provides some built-in tools for converting Boost types to std::string. Unfortunately, doing so on cpp_dec_float comes at a cost in precision, which is not sufficient for my purposes. For example, 1545596569.76676355 becomes 1.5456e+09. If I were, for example, to write this to a file using ostream, I'd retain full precision.
  • The std::stringstream approach: Boost's own documentation says:

For more involved conversions, such as where precision or formatting need tighter control than is offered by the default behavior of lexical_cast, the conventional std::stringstream approach is recommended.

I.e., this:

      // std::vector<cpp_dec_float_100> my_vector
      // contains my data set

      std::ostringstream ss;
      std::vector<std::string> my_vector_of_string;

      for(int i = 0; i < my_vector.size()-1; ++i){
        ss << setprecision(n) << my_vector[i];
        my_vector_of_string.push_back(ss.str());
      }

This works (and, not exactly surprisingly, gives the same precision I get with writing to a file). However (again, not exactly surprisingly), this is incredibly slow (in fact, impractically so my purposes) slow. My data set includes on the order of tens to hundreds of millions of elements.


Is there a more efficient method for converting a cpp_dec_float_100 to std::string? My concern is purely the time taken to do so.

Please, let me know if there are any questions or if I've left anything important out. I'm not terribly familiar with Boost or c++.

Trying to write a C++ program that lists all the polite numbers in the upper value

For example, if the user enters the number 21, I want all the polite numbers listed. so for 21, the output would be 3, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21. I am new for loops and I am having a difficult time trying to get this to work. I cant include any global variables for this assignment. Any help would be greatly appreciated. Thank you.

Here is my code so far:

 #include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

int main() {

    //Display a welcome message
    std::cout << "Welcome to the polite numbers program" << std::endl;

    int upValue;
    int p3=3;
    int p5=5;

    cout << "What is the upper value? "; //Ask user for upper limit
    cin >> upValue; //Stores user input into upValue

    while (upValue < 1) //Validate user input of upper limit
    {
        cout << "What is the upper value? (must be an integer > 0) ";
        cin >> upValue;
    }

    
    if (upValue==3) //only display polite num 3
    {
        cout<<p3<<endl;
    }
    else if (upValue==5) //only display polite number 5 and 3
    {
        cout<<p3<<endl;
        cout<<p5<<endl;
    }
    else {
        cout << p3 << endl; 
        cout << p5 << endl;
        for (int curSeq = 2; curSeq <= upValue; curSeq++) {
            int n;
            int nextPNum = n + (log((n + (log(n) / log(2))))) / log(2);
            cout << nextPNum << endl;

        }
    }

    return 0;
}

Im attempting to make a program which displays the polite number

For example, if you put 9, it will display 3,5,6,7,9. I can only use cmath, iostream, iomanip. what I have so far is this, and im kinda lost.enter image description here

Lambda captures vs parameters - any performance difference?

auto lambdaFunction1 = [](someClass& obj, int x){/**/};
auto lambdaFunction2 = [&someClassObj, x](){/**/};

Will there be any performance difference for using lambda that captures variables or passing them as parameters? If I'm in position that I can use whatever, should I always prefer one of those options over other? Are there any rules about that? Or it's just a matter of which one likes?

PS: I'm aware that in same cases I will have don't have such choice, for example using stl algorithms, I'm asking about situation where I can use both

Why is a function taking a pointer preferred over a function taking an array reference?

Consider the following program:

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

void print(const char *pa) { 
        cout << "Print - using pointer" << endl;
}

void print(const char (&arr)[]) {
        cout << "Print - using reference" << endl;
}

int main() { 
        char ca[] = {'B', 'A', 'D', 'C', '\0'};
        print(ca);
}

Results:

Print - using reference

Why is reference preferred over pointers?
According to C++ Primer 5th Ed., section 6.6.1:

In order to determine the best match, the compiler ranks the conversions that could be used to convert each argument to the type of its corresponding parameter. Conversions are ranked as follows:

  1. An exact match. An exact match happens when:
    • The argument and parameter types are identical.
    • The argument is converted from an array or function type to the corresponding pointer type. (§ 6.7 (p. 247) covers function pointers.)
    • A top-level const is added to or discarded from the argument.
  2. Match through a const conversion (§ 4.11.2, p. 162).
  3. Match through a promotion (§ 4.11.1, p. 160).
  4. Match through an arithmetic (§ 4.11.1, p. 159) or pointer conversion (§ 4.11.2, p. 161).
  5. Match through a class-type conversion. (§ 14.9 (p. 579) covers these conversions.)

No mentioned of reference here. Any idea?
Thanks

c++ function returns two different types

I'm creating a queue template class using C++.

The queue class has multiple function members. One of the functions is called front() to retrieve the first value of queue. Basically, the front() function will first check if the queue is empty or not (using another bool function is_empty()).

If it is empty, the function will throw error message and return 1 to indicate there is an error. If the queue is not empty, it will return the first value, whose type is same as that of data in queue. As you can see, there are two different types of return values. How can I specify those two types together when define the function?

Sample code is below. The return type is T. But the function also returns 1. Is this acceptable in C++? If not, how to modify it? Thanks in advance!

template <class T>
T MyQueue<T>::front() {
    if (! is_empty()) {
        return my_queue[0];
    }
    else {
        cout << "queue is empty!" << endl;
        return 1;
    }
}

using named lambda vs function - extra space usage for a variable in case of lambda?

So simplified code snippet (1) would be

void f2(someClass* ptr, int x)
{
//some code
}

void f(someClass* ptr, bool cond)
{
//do something with ptr
    if (someConditionThatIsResultOfFunctionWork)
   {
    if (cond)
    {
      //do something else with ptr
      f2(ptr, x1);
    }
     else
        {
          //do something else with ptr
          f2(ptr, x2);
        } 
    }
}

code snippet (2):

void f(someClass* ptr, bool cond)
{
 auto f2asLambda = [](someClass* ptr, int x)
{
//some code
};
//do something with ptr
if (someConditionThatIsResultOfFunctionWork)
{
if (cond)
{
  //do something else with ptr
  f2asLambda(ptr, x1);
}
 else
    {
      //do something else with ptr
      f2asLambda(ptr, x2);
    } 
}
}

Are those code snippets same in terms of performance etc? In case (2) extra variable will be created for the lambda, and we might not call it at all, does it make using function over named lambda preferable?

How to make a simple loop more generic

The below method will concatenate all warnings into one string. It works but obviously need to create almost the same method again for info and error.

struct MyItem
{
  std::vector<std::string> errors;
  std::vector<std::string> warnings;
  std::vector<std::string> infos;
};
std::vector<MyItem> items;


std::string GetWarnings()
{
  std::string str;
  for (auto item : items)
  {
    for (auto warn : item.warnings)
    {
      str += warn;
      str += " ";
    }
  }
  return str;
}

What would be a good generic way to implement one "Concatenate" method? One solution would be to define an enum (error\warning\item), pass it as input argument and make a switch case on argument value. Any more elegant solutions?

Strange behavior of std::pair [duplicate]

Absolutely don't understand, why this code:

vector<int>v={1,2,3,4,5};
vector<pair<int,int>> pairs;
pairs.push_back(make_pair(1, 1));
for (auto el:v) {
   for (auto p:pairs) {
      pairs[0].second++;
      cout<<p.second;
   }
}

prints "12345", and this code:

vector<int>v={1,2,3,4,5};
vector<pair<int,int>> pairs;
pairs.push_back(make_pair(1, 1));
for (auto el:v) {
   for (auto p:pairs) {
      p.second++;
      cout<<p.second;
   }
}

prints "22222" (The only difference is in changing pairs[0].second++ on p.second++)

Is this proper usage of smart pointers C++

I was wondering if the following is correct usage of a shared pointer. All I want to do with the originally created pointer is add it onto the vector on class A, which will be later on retrieved

class A
{
public:
   void AddToVec(std::shared_ptr<B> b)
   {
      myVec_.push_back(b);
   }

   std::vector<std::shared_ptr<B>>GetVec()
   {
      return myVec_;
   }
private:
   std::vector<std::shared_ptr<B>> myVec_;

}

Then on main, a pointer is created and passed with the following way

int main()
{
   A a;

   std::shared_ptr<B> ptr = std::make_shared<B>(...);
   a.AddToVec(std::move(ptr));
}
  1. Is the usage of the std::move correct on the main function?
  2. Is it okay to simply create the shared ptr on main and move ownership using the AddToVec function?

How to copy part of int16_t to char[4] in c++?

I have a variable:

int16_t label : 12

I want to take the 4 lower bits and put them in a variable of type:

char nol[4]

How can I do that in c++?

Why access deleted pointer won't crash the program?

#include <iostream>
#include<list>

using namespace std;
template <class T>
class Ptr {
public:
    Ptr() {
        a = nullptr;
        l.push_back(0);
    }

std::list<int> l;
void print_this() {
    cout<<this<<endl;
}

protected:
    int *a;
};

int main()
{
    Ptr<int> *ptr = new Ptr<int>();
    delete ptr;
    //ptr = nullptr; //if uncomment this line will crash
    auto p = &(ptr->l);  
    cout<<"p is "<<p<<endl;
    ptr->print_this();
    ptr->l.push_back(1);
    cout<<"size is "<<ptr->l.size()<<endl;
    cout<<"end";
    return 0;
}

I run code here: https://www.programiz.com/cpp-programming/online-compiler/ output is :

p is 0x5628eb47deb0
0x5628eb47deb0
size is 2
end

if I set ptr to nullptr after delete, it will crash at push_back. But still fine when I access the list.

How is it even possible that I push data to a dangling pointer without crashing it??

How can I update CLion's default C++ compiler on MacOS?

I'm currently using the CLion IDE and it seems that I'm running an older version of my current compiler because I can't seem to access common functions that should be the standard library. I don't know how to view the version of my current compiler, and I certainly don't know how to update it. If someone could guide me on this, I'd really appreciate it. Thanks in advance.

samedi 25 septembre 2021

How to push back a vector into a map

What I want to do here is to create a map like this:

0 -> 0,1,...,4;
1-> 0,1,...,4;
...
9 -> 0,1,...,4;
int main(){
    map<int, vector<int>> m;
    for(int i=0; i<10; i++){
        vector<int> temp;
        for(int j=0; j<5; i++){
            temp.push_back(j);
        }
        m.insert({i, m.push_back(temp)});
    }
}

But when I try to push back temp = {0,1,2,3,4} vector, it's giving me an error.

I guess there is some problem in the syntax of the underlined line.

Can you tell me how to solve this error?

Screenshot of the code

Why doesn't move-assigning a std::vector seem to have any performance benefit over copying in this code?

Since move-assigning a std::vector is is a O(1) time operation and copying a std::vector to another is O(N) (where N is the sum of the sizes of the 2 vectors), I expected to see move-assignment having a significant performance advantage over copying. To test this, I wrote the following code, which move-assigns/copies a std::vector nums2 of size 1000 to nums 100,000 times.

#include <iostream>
#include <vector>
#include <chrono>

using namespace std;

int main()
{
    auto start = clock();

    vector <int> nums;
    for(int i = 0; i < 100000; ++i) {

        vector <int> nums2(1000);
        for(int i = 0; i < 1000; ++i) {
            nums2[i] = rand();
        }

        nums = nums2; // or nums = move(nums2);

        cout << (nums[0] ? 1:0) << "\b \b"; // prevent compiler from optimizing out nums (I think)
    }

    cout << "Time: " << (clock() - start) / (CLOCKS_PER_SEC / 1000) << '\n';

    return 0;
}

The compiler I am using is g++ 7.5.0. When running with g++ -std=c++1z -O3, both the move-assign/copy versions take around 1600ms, which does not match with the hypothesis that move-assignment has any significant performance benefit. I then tested using std::swap(nums, nums2) (as an alternative to move-assignment), but that also took around the same time.

So, my question is, why doesn't move-assigning a std::vector to another seem to have a performance advantage over copy-assignment? Do I have a fundamental mistake in my understanding of C++ move-assignment?

C++: Question on the usage of = on the assignment to a constexpr constructor

I have the below code:

class Debug {
public:
  constexpr Debug(bool b = true) : hw(b), io(b) {} 
  constexpr bool isDebug() const { return this-> debug; }  
  bool getHw() {
     return this-> hw;
  }
  bool getIo() {
     return this-> io;
  }

private:
  bool hw;
  bool io;
};

int main() {
  constexpr Debug dbg = false;
  cout << dbg.getHw() << endl;
  cout << dbg.getIo() << endl;
}

Results:
1
<null>

I noticed that the "false" is only assiged to the hw. Why io value is null? How do you intepret the assignment statement there? Is it always assign to the first data member?

Thx

C++ allocate variables depending on Type of data in vector

I would like to create a function that is able to retrieve some information from files with scalar and or vector values.

The files have the following form:

If they are scalars:
some file header and information
data values
1
2
3
4

if they are vectors:
some file header and information
data values
(1 2 3)
(4 5 6)
(7 8 9)

I have written the function to collect the information from the file. Now I would like to create a function where the user passes a template type and it will look into the file and store the information in a vector<Type>

Currently, I have:

typedef std::vector<double> scalarField;
typedef std::vector<std::array<double, 3>> vectorField;

int main(int argCount, char *args[])
{

    vectorField a = readFile<vectorField> (filename);
    return 0;

}

In the readFile function I have:

template <typename Type>
Type readFile(std::string fileName)
{
     // create a vector to check data type and push_back data accordingly
    Type store;

    // routine to read the file and get the lines of interest

    // If it sees a vector of doubles
    if (*typeid(store[0]).name() == 'd')
    {
       // define a istringstream named iss  and get the double value
       iss >> variableToGetDouble;
       store.push_back(variableToGetDouble);
   }
   else if (*typeid(store[0]).name() == 'S')
   {
       // define a istringstream named iss  and x, y ,z doubles 
       store.push_back(std::array<double,3>{x,y,y})
   }
}

However, I get an error no known conversion for argument 1 from ‘double’ to ‘std::vector<std::array<double, 3> >::value_type&& {aka std::array<double, 3>&&}

I would like to know if it is possible to allocate variables depending on the data type in the vector. Am going in the right track or is there a better solution?

Best Regards

Are destructors called after throwing exception or std::exit [duplicate]

As a follow up to this question.

I would like to ask the following:

I have a class A

class A
{
    public:
        ~A(){std::cout << "The destruction of A is called" << std::endl;}
};

and a function which is going to force the shutdown of the program

void GetUserInput()
{
    //std::exit(EXIT_FAILURE);
    throw std::runtime_error("one two three");
}

The main function is:

int main(int argCount, char *args[])
{

   A obj1;
   GetUserInput();

    return 0;

}

When the std::runtime_error or the std::exit command is executed the class destructor is not called. Is this normal behavior? When the program exits shouldnt it destroy the objects that were previously created?

Converting HEXA 64 bits numbers to int

I'm making a college job, a conversion between hexa numbers enclosed in a stringstream. I have a big hexa number (a private key), and I need to convert to int, to put in a map<int,int>. So when I run the code, the result of conversion is the same for all the two hexa values inserted, what is incorrect, it should be differente results after conversion. I think it's an int sizes stack problem, because when I insert short hexas, it works greatly. As shown below the hexa has 64 bits.

Any idea to get it working?

int main() {

unsigned int x;
std::stringstream ss; ss << std::hex <<0x3B29786B4F7E78255E9F965456A6D989A4EC37BC4477A934C52F39ECFD574444"; ss >> x;

std::cout << "Saida" << x << std::endl;
// output it as a signed type
std::cout << "Result 1: "<< static_cast<std::int64_t>(x) << std::endl;

ss << std::hex << "0x3C29786A4F7E78255E9A965456A6D989A4EC37BC4477A934C52F39ECFD573344";
ss >> x;
std::cout << "Saida 2 " << x << std::endl;
// output it as a signed type
std::cout << "Result 2: " << static_cast<std::int64_t>(x) << std::endl;

}

Safely shutting down program from c++ function

I want to make a program that will perform some math after reading from user input files.

During the reading process (a function) I want to check if the user syntax in the file is correct, otherwise I would like to shutdown the program so that the user can modify the file(s= accordingly and run it again.

The structure will be something like this:

int main(int argCount, char *args[])
{
   std::string fileName = "PathOfFile";
   int a = GetUserInput(fileName, variableName);
   int b = GetUserInput(fileName, variableName);

   // Other functions will be placed here
   return 0;
}

int GetUserInput(std::string filename, std::string variableName)
{
 // Some routine to read the file and find the variableName 
 // Some routine to check the syntax of the user input. 
    // Let us assume that the integers are to be fined as: variableName 1;
    // and I want to check that the ; is there. Otherwise, shutdown the program.     
}

How can I shutdown the program safely from the function GetUserInput? Is there any C++ to signal that the program must wrap up and exit?

Find exact word match in C++ string

I have the following strings:

std::string s1 = "IAmLookingForAwordU and I am the rest of the phrase";
std::string keyWord = "IAmLookingForAword";

I want to know if the keyWord as an exact match in s1

I used:

   if ( s1.find(keyWord) != std::string::npos )
    {
        std::cout << "Found " << keyWord << std::endl;
    }

but the find function catches the IAmLookingForAword in IAmLookingForAwordU and the if statement is set to true. However, I would like to only catch the exact match of the keyWork I am looking for.

Any way to do this with C++ strings?

Was LWG1203 "More useful rvalue stream insertion" retroactively applied to C++11 or C++20?

Inspired by discussion in my recent question.

There is an LWG 1203 C++ Standard Library Issue. It changes operator>>(istream&&, T&&) into a more generic operator>>(Stream&&, T&&) (with some restraints on Stream) so the type of stream can be preserved and code like (stringstream{} << 123).str() works.

As far as I understand, this issue has been changed from WP to C++20 status in pre-Varna mailing and hasn't been changed since.

However, this change on cppreference mentions that it was retroactively applied to C++11. Moreover, it looks like all of libstdc++, libc++ and Microsoft STL implement LWG 1203 strictly before C++20 as well and have removed the old behavior.

Am I missing some other C++ Standard memos that applied LWG 1203 to C++11, C++14 and C++17 as well?

vendredi 24 septembre 2021

How to extract one row of a 2D string vector to vector of double?

I have a function to calculate moving average:

void MovingAverage(double inputSeries[]
                 , size_t inputSize, size_t window, float* output ) 

My train of thought to do my calculation:

  1. construct a loop and extract one row of vec2D each time
  2. use the MovingAverage function to get output

For the first step, the 2d-vector is parsed from a csv file:

std::vector<std::vector<std::string>> vec2D{
    {"S0001","01","02","03"}, {"S0002","11","12","13"}, {"S0003","21","22","23"}
};

I want to extract one row of this 2D vector (say the 2nd) and store the row as a 1d vector std::vector<double> copyRow then calculate the moving average for each row.

copyRow = {11,12,13}

I tried vector<double> copyRow(vec2D[0].begin(), vec2D[0].end()); but it doesn't work because the 2D vector is std::string type.

I also tried for loops:

int rowN = vec2D.size();
int colN = vec2D[0].size();
double num;
for (int i = 0; i < rowN; i++) 
{
    for (int j = 0; j < colN; j++) 
    {
        num = stod(vec2D[i][j]);
        copyRow[i][j].push_back(num);
    }
}

But it appends all values from all rows into the vector. What would be the best way to do this?

What actually is done when `string::c_str()` is invoked?

What actually is done when string::c_str() is invoked?

  1. string::c_str() will allocate memory, copy the internal data of the string object and append a null-terminated character to the newly allocated memory?

or

  1. Since string::c_str() must be O(1), so allocating memory and copying the string over is no longer allowed. In practice having the null-terminator there all the time is the only sane implementation.

Somebody in the comments of this answer of this question says that C++11 requires that std::string allocate an extra char for a trailing '\0'. So it seems the second option is possible.

And another person says that std::string operations - e.g. iteration, concatenation and element mutation - don't need the zero terminator. Unless you pass the string to a function expecting a zero terminated string, it can be omitted.

And more voice from an expert:

Why is it common for implementers to make .data() and .c_str() do the same thing?

Because it is more efficient to do so. The only way to make .data() return something that is not null terminated, would be to have .c_str() or .data() copy their internal buffer, or to just use 2 buffers. Having a single null terminated buffer always means that you can always use just one internal buffer when implementing std::string.

So I am really confused now, what actually is done when string::c_str() is invoked?

I cannot get operator+ function to work, have I maybe made a mistake with one of the constructors?

This operator will receive a string with the format "x,y." x represents an x coordinate and y represents a y coordinate. If the coordinates are valid (that is within the valid range of the chess board) then the appropriate variables should be set with these variables. If the coordinates are invalid, then nothing should happen. Constructors: Piece::Piece(Piece *newPiece){ *newPiece = new Piece; }

Piece::Piece(string pType, char side, int x, int y){
string pT = pType;
char s = side;
}
Piece& operator+(string move)


Piece& Piece::operator+(string move){
if(xPos <= side && yPos <= side)
        move = xPos "," yPos;
}

Conversion Error doing bulk_write in mogocxx driver

I'm trying to learn to use c++ driver for mongodb. I am already familiar with pymongo usage. This is what i'm trying to do: read all docs from a collection, append it to an array, process the data, and then do a bulk replace operation, which is basically writing the same docs again. For now, I'm ignoring the process part and only doing the mongo to array and array to bulk replace.

Here's the code:

#include <cstdint>
#include <iostream>
#include <vector>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/stdx.hpp>
#include <mongocxx/uri.hpp>
#include <mongocxx/instance.hpp>
#include <bsoncxx/builder/stream/helpers.hpp>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/builder/stream/array.hpp>


using bsoncxx::builder::stream::close_array;
using bsoncxx::builder::stream::close_document;
using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::finalize;
using bsoncxx::builder::stream::open_array;
using bsoncxx::builder::stream::open_document;

using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_document;


int main(){
    mongocxx::instance instance{}; // This should be done only once.
    mongocxx::client client{mongocxx::uri{}};
    mongocxx::database db = client["mydb"];
    mongocxx::collection coll = db["mycollection"];

    mongocxx::cursor cursor = coll.find({});

    std::vector<bsoncxx::document::view> docs;
    for(auto doc : cursor) {
        docs.push_back(doc);
    }

    std::cout<<docs.size() << std::endl;

    auto bulk = coll.create_bulk_write();

    for (auto doc : docs){
        auto temp = make_document(kvp("_id", doc["_id"]));
        mongocxx::model::replace_one replace_op{temp.view(), doc};
        bulk.append(replace_op);
    }
    bulk.execute();
}

I keep getting this following error while compiling :


In file included from /usr/local/include/bsoncxx/v_noabi/bsoncxx/builder/basic/array.hpp:19:0,
                 from /usr/local/include/mongocxx/v_noabi/mongocxx/collection.hpp:18,
                 from /usr/local/include/mongocxx/v_noabi/mongocxx/database.hpp:23,
                 from /usr/local/include/mongocxx/v_noabi/mongocxx/client.hpp:20,
                 from mongotest.cpp:5:
/usr/local/include/bsoncxx/v_noabi/bsoncxx/builder/basic/impl.hpp: In instantiation of 'typename std::enable_if<((! std::is_convertible<T, std::function<void(bsoncxx::v_noabi::builder::basic::sub_document)> >::value) && (! std::is_convertible<T, std::function<void(bsoncxx::v_noabi::builder::basic::sub_array)> >::value)), void>::type bsoncxx::v_noabi::builder::basic::impl::generic_append(bsoncxx::v_noabi::builder::core*, T&&) [with T = bsoncxx::v_noabi::document::element; typename std::enable_if<((! std::is_convertible<T, std::function<void(bsoncxx::v_noabi::builder::basic::sub_document)> >::value) && (! std::is_convertible<T, std::function<void(bsoncxx::v_noabi::builder::basic::sub_array)> >::value)), void>::type = void]':
/usr/local/include/bsoncxx/v_noabi/bsoncxx/builder/basic/impl.hpp:60:19:   required from 'void bsoncxx::v_noabi::builder::basic::impl::value_append(bsoncxx::v_noabi::builder::core*, T&&) [with T = bsoncxx::v_noabi::document::element]'
/usr/local/include/bsoncxx/v_noabi/bsoncxx/builder/basic/sub_document.hpp:86:27:   required from 'void bsoncxx::v_noabi::builder::basic::sub_document::append_(std::tuple<const char (&)[n], V>&&) [with long unsigned int n = 4; V = bsoncxx::v_noabi::document::element&&]'
/usr/local/include/bsoncxx/v_noabi/bsoncxx/builder/basic/sub_document.hpp:47:9:   required from 'void bsoncxx::v_noabi::builder::basic::sub_document::append(Arg&&, Args&& ...) [with Arg = std::tuple<const char (&)[4], bsoncxx::v_noabi::document::element&&>; Args = {}]'
/usr/local/include/bsoncxx/v_noabi/bsoncxx/builder/basic/document.hpp:112:5:   required from 'bsoncxx::v_noabi::document::value bsoncxx::v_noabi::builder::basic::make_document(Args&& ...) [with Args = {std::tuple<const char (&)[4], bsoncxx::v_noabi::document::element&&>}]'
mongotest.cpp:43:57:   required from here
/usr/local/include/bsoncxx/v_noabi/bsoncxx/builder/basic/impl.hpp:55:5: error: no matching function for call to 'bsoncxx::v_noabi::builder::core::append(bsoncxx::v_noabi::document::element)'
     core->append(std::forward<T>(t));
     ^~~~
In file included from /usr/local/include/bsoncxx/v_noabi/bsoncxx/builder/basic/sub_array.hpp:19:0,
                 from /usr/local/include/bsoncxx/v_noabi/bsoncxx/builder/basic/impl.hpp:17,
                 from /usr/local/include/bsoncxx/v_noabi/bsoncxx/builder/basic/array.hpp:19,
                 from /usr/local/include/mongocxx/v_noabi/mongocxx/collection.hpp:18,
                 from /usr/local/include/mongocxx/v_noabi/mongocxx/database.hpp:23,
                 from /usr/local/include/mongocxx/v_noabi/mongocxx/client.hpp:20,
                 from mongotest.cpp:5:
/usr/local/include/bsoncxx/v_noabi/bsoncxx/builder/core.hpp:175:11: note: candidate: bsoncxx::v_noabi::builder::core& bsoncxx::v_noabi::builder::core::append(const bsoncxx::v_noabi::types::b_double&)
     core& append(const types::b_double& value);
           ^~~~~~
/usr/local/include/bsoncxx/v_noabi/bsoncxx/builder/core.hpp:175:11: note:   no known conversion for argument 1 from 'bsoncxx::v_noabi::document::element' to 'const bsoncxx::v_noabi::types::b_double&'
/usr/local/include/bsoncxx/v_noabi/bsoncxx/builder/core.hpp:189:11: note: candidate: bsoncxx::v_noabi::builder::core& bsoncxx::v_noabi::builder::core::append(const bsoncxx::v_noabi::types::b_utf8&)
     core& append(const types::b_utf8& value);
           ^~~~~~
/usr/local/include/bsoncxx/v_noabi/bsoncxx/builder/core.hpp:189:11: note:   no known conversion for argument 1 from 'bsoncxx::v_noabi::document::element' to 'const bsoncxx::v_noabi::types::b_utf8&'
/usr/local/include/bsoncxx/v_noabi/bsoncxx/builder/core.hpp:203:11: note: candidate: bsoncxx::v_noabi::builder::core& bsoncxx::v_noabi::builder::core::append(const bsoncxx::v_noabi::types::b_document&)
     core& append(const types::b_document& value);
           ^~~~~~
/usr/local/include/bsoncxx/v_noabi/bsoncxx/builder/core.hpp:203:11: note:   no known conversion for argument 1 from 'bsoncxx::v_noabi::document::element' to 'const bsoncxx::v_noabi::types::b_document&'
/usr/local/include/bsoncxx/v_noabi/bsoncxx/builder/core.hpp:217:11: note: candidate: bsoncxx::v_noabi::builder::core& bsoncxx::v_noabi::builder::core::append(const bsoncxx::v_noabi::types::b_array&)
     core& append(const types::b_array& value);
           ^~~~~~
/usr/local/include/bsoncxx/v_noabi/bsoncxx/builder/core.hpp:217:11: note:   no known conversion for argument 1 from 'bsoncxx::v_noabi::document::element' to 'const bsoncxx::v_noabi::types::b_array&'
/usr/local/include/bsoncxx/v_noabi/bsoncxx/builder/core.hpp:231:11: note: candidate: bsoncxx::v_noabi::builder::core& bsoncxx::v_noabi::builder::core::append(const bsoncxx::v_noabi::types::b_binary&)

I'm able to do the same thing in python like so:

docs = []
for doc in conn['mycoll'].find({}):
    docs.append(doc)
    
rep = []
for doc in docs:
    rep.append(ReplaceOne({'_id': doc['_id']}, doc))

conn['mycoll'].bulk_write(rep)

I want to understand what's going on and what i'm doing wrong here.