mercredi 31 août 2022

Shall I try to use const T & as much as possible?

I am learning books <Effective C++>, i think use const reference is a good practice. because it can avoid unnecessary copy.

so, even in initialize a object, i use const T & t = T();

here is the code:

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

using namespace std;

template <class T>
inline std::vector<std::string> Split(const std::string &str, const T &delim, const bool trim_empty = false) {
  if (str.empty()) return {}; 
  size_t pos, last_pos = 0, len;
  std::vector<std::string> tokens;
  std::string delim_s = ""; 
  delim_s += delim;
  while(true) {
    pos = str.find(delim_s, last_pos);
    if (pos == std::string::npos) pos = str.size();
    len = pos-last_pos;
    if ( !trim_empty || len != 0) tokens.push_back(str.substr(last_pos, len));
    if (pos == str.size()) break; 
    else last_pos = pos + delim_s.size();
  }   
  return tokens;
}

int main() {
  const std::string& str = "myname@is@haha@";  // compare with std::string = "", will this be better(in speed and memory)?
  const std::string& s = Split(str, "@").front();  // this crashed
  // std::string s = Split(str, "@").front();  // this ok
  cout << "result is " << s << endl;
}

As you see above, this code is used to split a string into vector<std::string>,

in main function:

I have two method to get the first element of the splited results.

1.const std::string& s = Split(str, "@").front();

2.std::string s = Split(str, "@").front();

in my test, option 1 will crashed, option2 is ok.

could you talk some difference of these?

and is it necessary to do this (const std::string& s = "asd";)?

comparing to std::string s = "asd", what is the advantages and disadvantages of them?

The input contains 4 space-separated integers G, S, A, B

Print "Gold" (without quotes) if the Gold egg costs equal to or more than the silver egg. Otherwise, print "Silver" (without quotes). Note that the output is case-sensitive.

mardi 30 août 2022

How to manage pointer member variable in class?

I need to manage a pointer in a class, here is a demo:

class Shared {
 public:
  Shared(int i) : i_(i) {}
  void call() {}
  int i_;
};

class CreateObj {  // this class create Shared class
 public:
  CreateObj(int i) : s_(std::shared_ptr<Shared>(new Shared(i))) {

  }
  std::shared_ptr<Shared> s_;  // i used shared_ptr, so i don't need delete it
};

class UserObj {  // this class use Shared
 public:
  void SetShared(Shared* s) {  // here is the problem, shall i use shared_ptr, or just use pointer? seems shared_ptr is better, but i think raw pointer is ok? 
    s_ = s;
  }
  void call() {
    s_->call();
  }
  Shared*s_;  // std::shared_ptr<Shared> s_; is another choice, what is the difference?
};

int main() {
  CreateObj cobj(3);
  UserObj uobj;
  uobj.SetShared(cobj.s_);
}

please see the notes in UserShared, i think use raw pointer is also ok, but in this case, could you let me know what is the difference?

Returning a Poco session without creating new connection

Depending on if a condition is met I want to return a session but don't want to create a new connection.

Poco::Data::Session initialise(){
 if(some condition){
   Poco::Data::Session temp1('odbc',someSettings1)
   return temp1

  }else{
   Poco::Data::Session temp2('odbc',someSettings2)   
   return temp2
   }
}

int main(){
 Poco::Data::Session  sess(initialise());
}
  1. Does the above create a new connection when I pass the function as a constructor argument?
  2. Would it make a difference if I returned it as an anonymous object i.e. return Poco::Data::Session('odbc',someSettings1)
  3. Or is there a better way overall to achieve what I want?

Is it necessary to passing smart pointer object by reference?

assume I have a class, which contains a smart pointer as its member variable.

please see the code:

class B;

class A {
 public:
  A(const std::shared_ptr<B>& b) : b_(b) {}  // option1: passing by reference
  A(std::shared_ptr<B> b) : b_(b) {}  // option2: passing by value
  std::shared_ptr<B> b_;
};

I have two choice for A's constructor: construct by smart pointer and construct by smart pointer's reference.

could you help on this? what is the advantages and disadvantages of these two method?

will the copy between smart pointer cost big waste?

What happens to a temporary named object when it is returned and used in initialisation? [duplicate]

If I have a class below which has standard constructors and desturctor

class A {
 private:
  int data
 public:
 //normal constructor 
  A(int other)

 //move constuctor
  A(A&& other)
 
 //move operator
  A& operator=(A&& other)
 
 //copy constructor
  A(const A& other)

 //copy assignment operator
  A& operator=(const A& other)
 
 //destrcutor
 ~A()

}

What happens when I return an object from a function and use that as a constructor? Is the copy constructor called on the return of the function and a new object created? And is the destructor for the temporary object in the function called when the function call ends?

A initialise(bool b){
 if(b==true){
   A Temp1(1)
   return Temp1
   }
  else{
   A Temp2(2)
   return Temp2
   }
  }

int main(){
 A a(initialise(true));
}

lundi 29 août 2022

std::alignment_union for a lambda expression

This is a follow up question to : this question - replacing an std::function with none allocating one , that does not use std .

Was wondering if there is something more robust that can replace: std::aligned_union

 typedef unsigned char callable_array[100];
 typename std::aligned_union<0, callable_array, CallableT<void(*)()>, CallableT<void (CallableT<void(*)()>::*)()>>::type callable_;
                                        

The suggested code to do that is causing an compilation error: link

CallableT<decltype([]()->void {})>, // error: lambda expression in an unevaluated operand

trying both c++11 and c++14

It also uses std::max - was hoping for some ideas on how to replace it as well.

How to read the headers of a .txt files and put them as headers of a QTableView

I have a small problem trying to propoerly parse a .txt files and show its content on a QTableView. Specifically how to extract the headers of the file and show them into a QTableView.

The .txt file is composed of a first row which carries the headers, and all the other rows, which are data.

I can successfully upload the .txt file on a QTableView but for some reasons, the whole file appears under one gigantic column instead of properly parsing all the different headers and put them on the QTableView.

Below the example .txt file I am uploading on the QTableView - specifically the headers:

tax_id  Org_name    GeneID  CurrentID   Status  Symbol  Aliases description other_designations  map_location    chromosome  genomic_nucleotide_accession.version    start_position_on_the_genomic_accession end_position_on_the_genomic_accession   orientation exon_count  OMIM    

Below the rows of some exmaple data:

1041930 Methanocella conradii HZ254 11971032    0   live    mRNA    MTC_RS04550, Mtc_0908   coenzyme-B sulfoethylthiotransferase subunit alpha  coenzyme-B sulfoethylthiotransferase subunit alpha          NC_017034.1 886220  887887  plus    0       
79929   Methanothermobacter marburgensis str. Marburg   9705221 0   live    mRNA    MTBMA_RS07375, MTBMA_c15120 coenzyme-B sulfoethylthiotransferase subunit alpha  coenzyme-B sulfoethylthiotransferase subunit alpha          NC_014408.1 1393293 1394954 minus   0       
523846  Methanothermus fervidus DSM 2088    9962464 0   live    mRNA    MFER_RS03735, Mfer_0734 coenzyme-B sulfoethylthiotransferase subunit alpha  coenzyme-B sulfoethylthiotransferase subunit alpha          NC_014658.1 713917  715581  plus    0       

Currenlty this upload the .txt file into the QTableView. However it is not divided per header, but it is just a gigsntic column

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    model = new QStandardItemModel(this);

    ui->tableView->setModel(model);
    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    setWindowTitle("Viewer Example");
}

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

void MainWindow::on_loadTXTBtn_clicked()
{
    auto filename = QFileDialog::getOpenFileName(this, "Open", QDir::rootPath(), "txt file (*.txt)");
    if(filename.isEmpty()) {
        return;
    }
    QFile file(filename);
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        return;
    }
    QTextStream xin(&file);
    int ix = 0;
    while (!xin.atEnd()) {
        model->setRowCount(ix);
        auto line = xin.readLine();
        auto values = line.split("   ");
        const int colCount = values.size();
        model->setColumnCount(colCount);
        for(int jx = 0; jx < colCount; ++jx) {
            setValueAt(ix, jx, values.at(jx));
        }
        ++ix;
        ui->pathLineEdit->setText(filename);
    }
    file.close();
}

void MainWindow::setValueAt(int ix, int jx, const QString &value)
{
    if (!model->item(ix, jx)) {
        model->setItem(ix, jx, new QStandardItem(value));
    } else {
        model->item(ix, jx)->setText(value);
    }
}

I went more in depth of the parsing problem of the headers, and also used the following parse function to extract the headers from the .txt file and put them on the QTableView but no success:

void MainWindow::parse(QTableView *table)
{
    QString filters("TXT files (*.txt);;All files (*.*)");
    QString defaultFilter("TXT files (*.txt)");
    QString fileName = QFileDialog::getSaveFileName(0, "Save file", QCoreApplication::applicationDirPath(),
                       filters, &defaultFilter);
    QFile file(fileName);

    QAbstractItemModel *model =  table->model();
    if (file.open(QFile::WriteOnly | QFile::Truncate)) {
        QTextStream data(&file);
        QStringList strList; // <-- I was trying to loop through the headers here
        for(int i = 0; i < ui->tableView->model()->columnCount(); i++)
        {
          strList.append(ui->tableView->model()->headerData(i, Qt::Horizontal).toString());
        }

        for (int i = 0; i < model->columnCount(); i++) {
            if (model->headerData(i, Qt::Horizontal, Qt::DisplayRole).toString().length() > 0)
                strList.append("\"" + model->headerData(i, Qt::Horizontal, Qt::DisplayRole).toString() + "\"");
            else
                strList.append("");
        }
        data << strList.join(";") << "\n";
        for (int i = 0; i < model->rowCount(); i++) {
            strList.clear();
            for (int j = 0; j < model->columnCount(); j++) {

                if (model->data(model->index(i, j)).toString().length() > 0)
                    strList.append("\"" + model->data(model->index(i, j)).toString() + "\"");
                else
                    strList.append("");
            }
            data << strList.join(";") + "\n";
        }
        file.close();
    }
}

In doing research on how to solve the problem I found this post useful and also this one. In particular the last post was very useful for understanding how to parse through the headers but I still was not able to properly understand how to extract those and show them into a QTableView. Please any pointers on how to solve would be great!

Bytetrack cpp with cv::Rect csa export

I want to use byteTrack-cpp with my cv::rect box exported to csv. Still some error.

Base Bytetrack code is here : https://github.com/Qengineering/YoloX-Tracking-ncnn-RPi_64-bit

cv::Rect Rect;
Rect.x = 77;
Rect.y = 88;
Rect.width = 98;
Rect.height=123;

struct Object
        {
            cv::Rect_<float> rect;
            int label;
            float prob;
        };
Object  obj ;
obj.label = 1;
obj.prob = 0.33;
obj.rect = Rect;
std::vector<Object> objects;
objects.push_back (obj);
vector<STrack> output_stracks = tracker.update(objects);

from the repo main code is in : https://github.com/Qengineering/YoloX-Tracking-ncnn-RPi_64-bit/blob/main/src/yoloX.cpp

so easy to see from there than to copy all here.

I want to read from bbox rectangle per frames from csa file and push to the tracker.

minimal example above give some error:

../TrackerB/main.cpp:48:52: error: no viable conversion from 'vector' to 'const vector' vector output_stracks = tracker.update(objects); ^~~~~~~

somehow I can't see the solution ...:(

const reference to temporary variable does not work for std::function whose type does not match its declaration

class Context {
public:
    Context(){
        field2values_["age"] = std::vector<int>{1,2,3};
    }

    const std::vector<int>& field2values(const std::string& field) const {
        auto it = field2values_.find(field);
        if (it == field2values_.end()) {
            return default_ints_;
        }
        return it->second;
    }

private:
    std::map<std::string, std::vector<int>> field2values_;
    std::vector<int> default_ints_;
};

Context ctx;

std::vector<int> ctx_field2values(const std::string& field) {
    return ctx.field2values(field);
}

class Checker {
public:
    explicit Checker():
            user_field_values_(ctx_field2values),
            user_field_values_nc_(ctx_field2values)
    {}

    void print(){
        const auto& values = user_field_values_("age");
        std::cout << "size=" << values.size() << std::endl;  // unexpected: 18446744073709535740
        const auto& values_nc = user_field_values_nc_("age");
        std::cout << "size=" << values_nc.size() << std::endl;  // expected: 3
    }

private:
    const std::function<const std::vector<int>&(const std::string&)> user_field_values_;
    const std::function<std::vector<int>(const std::string&)> user_field_values_nc_;
};

int main() {
    Checker checker;
    checker.print();
}

As we all know, const reference to temporary variable will extend the its lifetime. But in the code above, it does not work for user_field_values_ while it works for user_field_values_nc_. I guess this is because the type of user_field_values_ does not match its initialization, namely ctx_field2values. But why is there such a difference? Can anyone explain in principle why this rule (const reference to temporary variable) does not take effect? Thanks in advance.

dimanche 28 août 2022

Can I use __LINE__ or __FILE__ in inline function in C++?

I faced a problem while implementing the logger.

First, I used to LINE and FILE with standard C Macro function like below

// global.h
..
namespace MyLogger {

class Logger
{
    ..
    void _write(int _level, const char* _file, int _line, const char* _fmt, ...);
};
static Logger    logger;

}; // namespace MyLogger

..

// avoid conflict..
#undef error
#undef trace

#define error(_MESSAGE_, ...) _write(LOG_LEVEL_ERROR, (const char*)__FILE__, (int)__LINE__, (const char*)_MESSAGE_, ##__VA_ARGS__)
#define info(_MESSAGE_, ...)  _write(LOG_LEVEL_INFO,  (const char*)__FILE__, (int)__LINE__, (const char*)_MESSAGE_, ##__VA_ARGS__)
#define trace(_MESSAGE_, ...) _write(LOG_LEVEL_TRACE, (const char*)__FILE__, (int)__LINE__, (const char*)_MESSAGE_, ##__VA_ARGS__)
..

// main.cpp

using namespace MyLogger;

// using like this
logger.error("- log error");
logger.info("- log info %s", "test 1");
..

In fact, it seems to work well. However, the problem occurred while using openv.

error and trace seem to conflicted with error and trace in opencv.

error: expected primary-expression before ‘int’ [build] CV_EXPORTS CV_NORETURN void error(int _code, const String& _err, const char* _func, const char* _file, int _line);

So I'm thinking about other methods using inline functions, not macros.

// global.h
..
    //void _write(int _level, const char* _file, int _line, const char* _fmt, ...);
    static inline void error(/* Is it possible to toss __LINE__ or __FILE__ ? */);
    static inline void info(/* .. */);
    static inline void trace(/* .. */);
..

// main.cpp
logger::error("- log error");
logger::info("%d %c %f, 1, 'A', '0.1');

Can I know the line or file of the location where the log was output through a method other than a macro?

How to convert from std::chrono::nanoseconds to std::chrono::seconds using any methods/functions from std::chrono?

I need a simple conversion code to convert from std::chrono::nanoseconds to std::chrono::seconds. Any solution for this ?

How to dynamically save data into a database file .db and show them into a QTableView

I have a small GUI where I have a QTableView and a QPuchButton. The function of the QPushButton is mainly dinamyc, which means that the operations that needs to happen when clicking the button would be following:

void writeTemporaryFilesOnDatabase::on_addMsgBtn_clicked() {}

  1. Create a database file dynamically (.db)
  2. Create a temporary Database connection
  3. Create some dinamically tabular data using the subclassed QAbstractTableModel
  4. Store the data into the database file created at 1)
  5. Read the file.db with the data and show it into the QTableView on the ui

The problem is that the database does not open and consequenlty, no files are temporarliy stored in the NewFile.db and I cannot read/show the data in the QTableView

void writeTemporaryFilesOnDatabase::on_addMsgBtn_clicked()
{

    // 1 - Create a database file dinamically and store the file.db in the following document folder as an example

    QString path("/home/to/Documents/");
    QDir dir; // Initialize to the desired dir if 'path' is relative

    // We create the directory if needed
    if (!dir.exists(path))
        dir.mkpath(path); // You can check the success if needed

    QFile file(path + "NewFile.db");
    file.open(QIODevice::WriteOnly); // Or QIODevice::ReadWrite

    // 2 - Create a table in runtime mode and fill out with temporary data
    QList<QString> contactNames;
    QList<QString> contactPhoneNums;

    contactNames.append("Thomas");
    contactNames.append("Richard");
    contactNames.append("Harrison");
    contactPhoneNums.append("123");
    contactPhoneNums.append("222");
    contactPhoneNums.append("333");

    // 3 - Create a database in runtime mode and fill out with temporary data just created

    QSqlDatabase *database = new QSqlDatabase();
    database->QSqlDatabase::addDatabase("QSQLITE","/home/to/Documents/NewFile.db");
    database->open();
    if (database->open()) {
        qDebug() << __LINE__ << QString("Open Db!");
    } else {
        qDebug() << __LINE__ << QString("Db not opening!");
    }

    // Create Phone Book with subclassed QAbstractTableModel:
    TestModel *PhoneBookModel = new TestModel(this);
    // Populate model with data:
    PhoneBookModel->populateData(contactNames,contactPhoneNums);

    // Connect model to table view:
    QSqlTableModel  *tableModel = nullptr;
    QTableView *tView = new QTableView;
    tView->setModel(PhoneBookModel);

    // Make table header visible and display table:
    tView->horizontalHeader()->setVisible(true);  // <-- This run correctly and appears as soon as I launch the application (I did it for debugging reasons and the table is correctly created)
    tView->show();

    if (database->open()) {
        qDebug() << __LINE__ << QString("Open Db or not?????");
        QSqlQuery query;
        query.exec("DROP TABLE items");
        query.exec(
                    "CREATE TABLE items ("
                        "Name TEXT NOT NULL,"
                        "Phone INTEGER NOT NULL ''"
                    ")"
                    );

        query.prepare("INSERT INTO items (Name, Phone) VALUES (?,?)");
        query.addBindValue(newItem->name());
        query.addBindValue(newItem->phone().toInt());

        tableModel = new QSqlTableModel(this, *database);
        tableModel->setTable("items");
        tableModel->setEditStrategy(QSqlTableModel::OnFieldChange);
        tableModel->select();
        tView->setModel(PhoneBookModel);

       // Read the data created in the `TestModel *PhoneBookModel = new TestModel(this);`

        if( file.open( QIODevice::WriteOnly ) )
        {
            QTextStream ts( &file );
            QStringList strList;

            for (int i=0; i<PhoneBookModel->rowCount(); i++)
            {
                strList.clear();

                for (int j=0; j<PhoneBookModel->columnCount(); j++)
                    strList << PhoneBookModel->data(PhoneBookModel->index(i,j)).toString();

                ts << strList.join(" ") + "\n";
            }
            ts << &strList;
            file.close();
        }
    } else {
        qDebug() << __FUNCTION__ << QString("Error!");
        return;
    }


    // 4 - LOOP THROUGH THE HEADERS OF THAT FILE AND SHOW THE TABLE
    for(int i=0; i< ui->tableWidget->rowCount(); i++)
        {
            QString viewFieldName = ui->tableView->item(i, 0)->text();
            mModel->setHeaderData(i, Qt::Horizontal, viewFieldName);
            mModel->submitAll();
        }
}

Specifically, the Qt Objects QAbstractTableModel (sub-classed in this example) and QTableView are used mostly for practice on how to use the QAbstractTableModel but I am not sure what I am doing wrong here. Any help would be very appreciated.

In case you are wondering how I subclassed the QAbstractTableModel see below:

class TestModel : public QAbstractTableModel
{
    Q_OBJECT

public:
    TestModel(QObject *parent = 0);

    void populateData(const QList<QString> &contactName,const QList<QString> &contactPhone);

    int rowCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE;
    int columnCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE;

    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE;
    QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE;

    bool addItem(itemExample *newItem);

private:
    QList<QString> tm_contact_name;
    QList<QString> tm_contact_phone;
    QString mError;
};

Thanks for any help! Sources I consulted to help me but without solving the problems are: this, this one and also this one.

samedi 27 août 2022

I tried to implement the RSA encryption algorithm using cpp, but it takes too long and I don't know if it will work

My code is here

//RSA.cpp
#include <iostream>
#include <cstring>
#include <ctime>
#include <random>
#include <vector>
#include <string>
#include "BigNum.hpp"
using namespace std;

BigNum mygcd(BigNum a, BigNum b)
{
    while(a != b)
    {
        if(a>b)
        {
            a = a - b;
        }
        else 
        {
            b = b - a;
        }
    }
    return a;
}
BigNum prime(int n)
{
    vector<BigNum> ans;
    ans.push_back(BigNum(2));
    ans.push_back(BigNum(3));
    for (int i = 0; i < n; i++)
    {
        BigNum addend = 1;
        for (auto j : ans)
        {
            addend = addend * j;
        }
        ans.push_back(addend + 1);
    }
    return ans[ans.size() - 1];
}
BigNum exgcd(BigNum a, BigNum b, BigNum &x, BigNum &y)
{
    if (b == 0)
    {
        x = 1, y = 0;
        return a;
    }
    BigNum g = exgcd(b, a - (a / b) * b, x, y);
    BigNum t;
    t = x;
    x = y;
    y = t - a / b * y;
    return g;
}
BigNum niyuan(BigNum a, BigNum b)
{
    BigNum x, y;
    BigNum aa = exgcd(a, b, x, y);
    return (x + b) - ((x + b) / b) * b;
}
vector<BigNum> yinshu(BigNum n)
{
    vector<BigNum> ans;
    int a = 2;
    while (n / 2 > a)
    {
        if (n % a == 0)
        {
            ans.push_back(a);
        }
        a++;
    }
    return ans;
}
vector<int> ToBit(BigNum obj){
    vector<int> r;
    while (obj != 0){
        r.push_back( (obj - (obj / 2) * 2 == 0) ? 0 : 1 );
        obj = obj / 2;
    }
    return r;
}
BigNum jiami(BigNum e, int i, BigNum n)
{
    BigNum addend = i;
    BigNum result = 1;
    vector<int>bitE = ToBit(e);
    int now = 0;
    while (now != bitE.size())
    { //将e二进制展开(其实就是使用位运算和右移运算)
        if (bitE[now])
        {
            result = addend * result;
            result = result - (result / n) * n;
        }
        addend = addend * addend;
        now = now + 1;
    }
    return result;
}
BigNum jiemi(BigNum d, BigNum i, BigNum n)
{
    BigNum addend = i;
    BigNum result = 1;
    vector<int>bitD = ToBit(d);
    int now = 0;
    while (now != bitD.size())
    {
        if (bitD[now])
        {
            result = addend * result;
            result = result - (result / n) * n;
        }
        addend = addend * addend;
        now = now + 1;
    }
    return result;
}
int main()
{
    srand(time(0));
    BigNum p = prime(rand() % 20 + 1); 
    srand(time(0));
    BigNum q = prime(rand() % 20 + 1); 
    BigNum N = p * q;                  
    BigNum r = (p - 1) * (q - 1);      
sss:
    srand(time(0));
    BigNum e = random() + 2;
    if (mygcd(e, r) - BigNum(1) > 0)
        goto sss;
    vector<BigNum> yinshus = yinshu(r);                        
    BigNum d = BigNum(niyuan(e, r));                             
    cout << "Alice send(" << N << ',' << e << ")to Bob" << endl; 
    cout << "Please input your massage:";                        
    string m;
    cin >> m; 
    vector<int> message;
    for (auto i : m)
    {
        message.push_back((int)i);
    }
    vector<BigNum> miwen;
    for (auto i : message)
    {
        miwen.push_back(jiami(e, i, N));
    }
    cout << "coded text:";
    for (auto i : miwen)
    {
        cout << i << " ";
    }
    vector<BigNum> minwen;
    for (auto i : miwen)
    {
        minwen.push_back(jiemi(d, i, N));
    }
    cout << "明文:";
    for (auto i : minwen)
    {
        cout << i << " ";
    }
    cout << endl;
}

I used a self-defined data structure called BigNum in order to store some large integers without them overflowing.

//BigNum.hpp
#include <iostream>
#include <cstring>
#include <string>
#include <iomanip>
#include <algorithm>
using namespace std;

#define MAXN 9999
#define MAXSIZE 10
#define DLEN 4

class BigNum
{
private:
    int a[999]; //可以控制大数的位数
    int len;    //大数长度
public:
    BigNum()
    {
        len = 1;
        memset(a, 0, sizeof(a));
    }                                  //构造函数
    BigNum(const int);                 //将一个int类型的变量转化为大数
    BigNum(const char *);              //将一个字符串类型的变量转化为大数
    BigNum(const BigNum &);            //拷贝构造函数
    BigNum &operator=(const BigNum &); //重载赋值运算符,大数之间进行赋值运算

    friend istream &operator>>(istream &, BigNum &); //重载输入运算符
    friend ostream &operator<<(ostream &, BigNum &); //重载输出运算符

    BigNum operator+(const BigNum &) const; //重载加法运算符,两个大数之间的相加运算
    BigNum operator-(const BigNum &) const; //重载减法运算符,两个大数之间的相减运算
    BigNum operator*(const BigNum &) const; //重载乘法运算符,两个大数之间的相乘运算
    BigNum operator/(const int &) const;    //重载除法运算符,大数对一个整数进行相除运算
    BigNum operator/(const BigNum &) const;

    BigNum operator^(const int &) const;   //大数的n次方运算
    int operator%(const int &) const;      //大数对一个int类型的变量进行取模运算
    bool operator>(const BigNum &T) const; //大数和另一个大数的大小比较
    bool operator>(const int &t) const;    //大数和一个int类型的变量的大小比较

    bool operator<(const BigNum &) const;
    bool operator<=(const BigNum &) const;
    bool operator>=(const BigNum &) const;
    bool operator==(const BigNum &) const;
    bool operator!=(const BigNum &) const;

    void print(); //输出大数
};
BigNum::BigNum(const int b) //将一个int类型的变量转化为大数
{
    int c, d = b;
    len = 0;
    memset(a, 0, sizeof(a));
    while (d > MAXN)
    {
        c = d - (d / (MAXN + 1)) * (MAXN + 1);
        d = d / (MAXN + 1);
        a[len++] = c;
    }
    a[len++] = d;
}
BigNum::BigNum(const char *s) //将一个字符串类型的变量转化为大数
{
    int t, k, index, l, i;
    memset(a, 0, sizeof(a));
    l = strlen(s);
    len = l / DLEN;
    if (l % DLEN)
        len++;
    index = 0;
    for (i = l - 1; i >= 0; i -= DLEN)
    {
        t = 0;
        k = i - DLEN + 1;
        if (k < 0)
            k = 0;
        for (int j = k; j <= i; j++)
            t = t * 10 + s[j] - '0';
        a[index++] = t;
    }
}
BigNum::BigNum(const BigNum &T) : len(T.len) //拷贝构造函数
{
    int i;
    memset(a, 0, sizeof(a));
    for (i = 0; i < len; i++)
        a[i] = T.a[i];
}
BigNum &BigNum::operator=(const BigNum &n) //重载赋值运算符,大数之间进行赋值运算
{
    int i;
    len = n.len;
    memset(a, 0, sizeof(a));
    for (i = 0; i < len; i++)
        a[i] = n.a[i];
    return *this;
}
istream &operator>>(istream &in, BigNum &b) //重载输入运算符
{
    char ch[MAXSIZE * 4];
    int i = -1;
    in >> ch;
    int l = strlen(ch);
    int count = 0, sum = 0;
    for (i = l - 1; i >= 0;)
    {
        sum = 0;
        int t = 1;
        for (int j = 0; j < 4 && i >= 0; j++, i--, t *= 10)
        {
            sum += (ch[i] - '0') * t;
        }
        b.a[count] = sum;
        count++;
    }
    b.len = count++;
    return in;
}
ostream &operator<<(ostream &out, BigNum &b) //重载输出运算符
{
    int i;
    cout << b.a[b.len - 1];
    for (i = b.len - 2; i >= 0; i--)
    {
        cout.width(DLEN);
        cout.fill('0');
        cout << b.a[i];
    }
    return out;
}

BigNum BigNum::operator+(const BigNum &T) const //两个大数之间的相加运算
{
    BigNum t(*this);
    int i, big; //位数
    big = T.len > len ? T.len : len;
    for (i = 0; i < big; i++)
    {
        t.a[i] += T.a[i];
        if (t.a[i] > MAXN)
        {
            t.a[i + 1]++;
            t.a[i] -= MAXN + 1;
        }
    }
    if (t.a[big] != 0)
        t.len = big + 1;
    else
        t.len = big;
    return t;
}
BigNum BigNum::operator-(const BigNum &T) const //两个大数之间的相减运算
{
    int i, j, big;
    bool flag;
    BigNum t1, t2;
    if (*this > T)
    {
        t1 = *this;
        t2 = T;
        flag = 0;
    }
    else
    {
        t1 = T;
        t2 = *this;
        flag = 1;
    }
    big = t1.len;
    for (i = 0; i < big; i++)
    {
        if (t1.a[i] < t2.a[i])
        {
            j = i + 1;
            while (t1.a[j] == 0)
                j++;
            t1.a[j--]--;
            while (j > i)
                t1.a[j--] += MAXN;
            t1.a[i] += MAXN + 1 - t2.a[i];
        }
        else
            t1.a[i] -= t2.a[i];
    }
    t1.len = big;
    while (t1.a[t1.len - 1] == 0 && t1.len > 1)
    {
        t1.len--;
        big--;
    }
    if (flag)
        t1.a[big - 1] = 0 - t1.a[big - 1];
    return t1;
}

BigNum BigNum::operator*(const BigNum &T) const //两个大数之间的相乘运算
{
    BigNum ret;
    int i, j, up;
    int temp, temp1;
    for (i = 0; i < len; i++)
    {
        up = 0;
        for (j = 0; j < T.len; j++)
        {
            temp = a[i] * T.a[j] + ret.a[i + j] + up;
            if (temp > MAXN)
            {
                temp1 = temp - temp / (MAXN + 1) * (MAXN + 1);
                up = temp / (MAXN + 1);
                ret.a[i + j] = temp1;
            }
            else
            {
                up = 0;
                ret.a[i + j] = temp;
            }
        }
        if (up != 0)
            ret.a[i + j] = up;
    }
    ret.len = i + j;
    while (ret.a[ret.len - 1] == 0 && ret.len > 1)
        ret.len--;
    return ret;
}
BigNum BigNum::operator/(const int &b) const //大数对一个整数进行相除运算
{
    BigNum ret;
    int i, down = 0;
    for (i = len - 1; i >= 0; i--)
    {
        ret.a[i] = (a[i] + down * (MAXN + 1)) / b;
        down = a[i] + down * (MAXN + 1) - ret.a[i] * b;
    }
    ret.len = len;
    while (ret.a[ret.len - 1] == 0 && ret.len > 1)
        ret.len--;
    return ret;
}
int BigNum::operator%(const int &b) const //大数对一个int类型的变量进行取模运算
{
    int i, d = 0;
    for (i = len - 1; i >= 0; i--)
    {
        d = ((d * (MAXN + 1)) % b + a[i]) % b;
    }
    return d;
}
BigNum BigNum::operator^(const int &n) const //大数的n次方运算
{
    BigNum t, ret(1);
    int i;
    if (n < 0)
        exit(-1);
    if (n == 0)
        return 1;
    if (n == 1)
        return *this;
    int m = n;
    while (m > 1)
    {
        t = *this;
        for (i = 1; i << 1 <= m; i <<= 1)
        {
            t = t * t;
        }
        m -= i;
        ret = ret * t;
        if (m == 1)
            ret = ret * (*this);
    }
    return ret;
}
bool BigNum::operator>(const BigNum &T) const //大数和另一个大数的大小比较
{
    int ln;
    if (len > T.len)
        return true;
    else if (len == T.len)
    {
        ln = len - 1;
        while (a[ln] == T.a[ln] && ln >= 0)
            ln--;
        if (ln >= 0 && a[ln] > T.a[ln])
            return true;
        else
            return false;
    }
    else
        return false;
}
bool BigNum::operator>(const int &t) const //大数和一个int类型的变量的大小比较
{
    BigNum b(t);
    return *this > b;
}

void BigNum::print() //输出大数
{
    int i;
    cout << a[len - 1];
    for (i = len - 2; i >= 0; i--)
    {
        cout.width(DLEN);
        cout.fill('0');
        cout << a[i];
    }
    cout << endl;
}

bool BigNum::operator<(const BigNum &obj) const
{
    for (int i = 0; i < len; i++)
    {
        if (a[i] < obj.a[i])
            return true;
        if (a[i] > obj.a[i])
            return false;
    }
    return false;
}
bool BigNum::operator<=(const BigNum &obj) const
{
    for (int i = 0; i < len; i++)
    {
        if (a[i] < obj.a[i])
            return true;
        if (a[i] > obj.a[i])
            return false;
    }
    return true;
}
bool BigNum::operator>=(const BigNum &obj) const
{
    for (int i = 0; i < len; i++)
    {
        if (a[i] > obj.a[i])
            return true;
        if (a[i] < obj.a[i])
            return false;
    }
    return true;
}
bool BigNum::operator==(const BigNum &obj) const
{
    for (int i = 0; i < len; i++)
    {
        if (a[i] != obj.a[i])
            return false;
    }
    return true;
}
bool BigNum::operator!=(const BigNum &obj) const
{
    for (int i = 0; i < len; i++)
    {
        if (a[i] != obj.a[i])
            return true;
    }
    return false;
}
BigNum BigNum::operator/(const BigNum &op2) const
{
    BigNum temp(*this);
    if (op2 == 0)
    {
        cout << "ERROR!!";
        for (int i = 0; i < len; i++)
            temp.a[i] = 0;
    }
    else if (*this < op2)
    {
        for (int i = 0; i < len; i++)
            temp.a[i] = 0;
    }
    else if (*this == op2)
    {
        temp.a[len - 1] = 1;
    }
    else if (op2 == 1)
    {
        temp = *this;
    }
    else if (op2 == 2)
    {

        int from = 0;
        for (int i = 0; i < len; i++)
        {
            if (temp.a[i] != 0)
            {
                from = i;
                break;
            }
        }

        int carry = 0;
        for (int i = from; i < len; i++)
        {
            if (temp.a[i] & 1)
            {
                if (carry == 1)
                    temp.a[i] = (temp.a[i] + 10) / 2;
                else
                    temp.a[i] = temp.a[i] / 2;
                carry = 1;
            }
            else
            {
                if (carry == 1)
                    temp.a[i] = (temp.a[i] + 10) / 2;
                else
                    temp.a[i] = temp.a[i] / 2;
                carry = 0;
            }
        }
    }
    else
    {
        BigNum begin(1), end("500000000000000000000000000000"); // 500000000000000000000000000000
        while (begin < end)
        {
            BigNum mid = (begin + end) / 2;
            BigNum res = mid * op2;

            if (res == 0 || res >= *this)
                end = mid;
            else
                begin = mid + 1;
        }
        temp = begin;
        if (temp == 1)
            return 0;

        int tmp = len - 1;
        while (temp.a[tmp] == 0)
        {
            temp.a[tmp] = 9;
            tmp++;
        }
        temp.a[tmp]--;
        return temp;
    }
    return temp;
}

When I run it, sometimes I get the error "malloc(): corrupted top size", sometimes it will run and then nothing happens, when I debug it, I find that the problem is in the "mygcd" function, the algorithm I use is too slow for a huge The algorithm I'm using is too slow for the huge number, but I don't know how to change it. I'm not sure where in the two files something is going wrong that I don't know about, and I can't guarantee that all the algorithms I'm using are correct and appropriate. Can anyone help me? Thanks a lot. My system is Ubuntu 22.04.1LTS gcc version 11.2.0

How to pass reference of noncopyable type to SFINAE "catch-all" overload function?

I need to check data type, but can't handle the noncopyable class. Now I use pointer instead of references. Is there a better way?

#include <iostream>
#include <functional>

template <typename T, std::enable_if<std::is_integral<T>::value, bool> = true>
void data_type(T const& t) {
    std::cout << "integer" << std::endl;
}

void data_type(...) {
    std::cout << "unknown" << std::endl;
}

int main() {
    struct noncopyable_type {
        noncopyable_type() {}
        noncopyable_type(const noncopyable_type&) = delete;
    };

    int i;
    noncopyable_type s;

    // first try
    data_type(i);   // ok
    data_type(s);   // error: call to deleted constructor

    // try again
    data_type(std::cref(i)); // ok, but the type is std::reference_wrapper, not integer
    data_type(std::cref(s)); // ok
}

vendredi 26 août 2022

Inserting more data into JSON file using nlohmann

I have a json file genrated in python from another system that needs to be read/updated in another MFC application. I can successfully read the existing data from the json file using nlohmann json add-in. For example, the file consists of two data fields with one field having any array of two subfields as below

{
  "city_data":[
     {
       "t":"m",
       "l":[12.0,10.3,0.0,1.0]
     },
     {
       "t":"l",
       "l":[10.1,20.37,0.0,1.0]
     },
     {
       "t":"l",
       "l":[47.82,4.63,0.0,1.0]
     },
     {
       "t":"m",
       "l":[67.66,43.33,0.0,1.0]
     }
  ],
  "map_data":"JZDKZTCaTyWQymUwmk8lkMplMJpPJZDKZTCaTyWQymUwmk/8/+n8AVAZ1WCxk8rYAAAAASUVORK5CYII="
}

I would like to add more entries into "city_data" field as {"t":"x","l":[0.0,0.0,0.0,0.0]} while the "map_data" stays the same. Then I can write the json object into a new file with updates.

To read the json file,

std::ifstream f(file);
json data = json::parse(f);

To retreive "city_data" and then its type and location

json& cityInfo = data["city_data"];
for (unsigned int i = 0; i < cityInfo.size(); i++)
        {
            json& cityType = cityInfo[i];
            json& cityLoc = cityType["l"];
            std::float_t x = cityLoc[0];
            std::float_t y = cityLoc[1];
            // ignoring the other two values for now
            std::string ctyTyp = cityType["t"];         
        }
f.close();

To retreive map data

ofstream outfile;
outfile.open(m_strFolderPath + m_strFileName + ".png", ofstream::binary);
std::string mapFrame = data["map_data"];
string temp = base64_decode(mapFrame );
outfile.write(temp.c_str(), temp.size());
outfile.close();

base64_decode is another function, not shown here as it is not relevant here.

Any suggestions on how to insert new city_data fields into the nlohmann JSON object?

How to forward the micro args to format func?

#define LOG_INFO(str, ...)                                              \
  logger.NewLogStateMent(__FILE__, __LINE__,                            \
                         fver::base::log::Logger::LogLevel::kInfo, str, \
                         ##__VA_ARGS__)
void NewLogStateMent(const char* filename, const int len, LogLevel lev, ...) {
  std::cout << fmt::format("{} {} {} {} {}", filename, lne, lev, ...);
}
// use case
int main () {
  LOG_INFO("hello, world %d", 1);
}

Now i want to this LOG_INFO(str, ...) to a fmt::format();

But the Gcc give me a lot of errors gcc version: 12.2.0

c++ version: c++17

How can i finish it?

Please help me!

Why this two different implementations of Tuple have a different size?

I have two different implementations of a Tuple class template. One with specialization for any number of arguments and one using variadic templates. When using an empty class for some of the tuple elements the two implementations have different sizes. Why does the second one using a variadic template have a bigger size and is it possible to be fixed to have the same size as the first one?

#include <iostream>

using namespace std;

struct Nil {};

template <typename T1 = Nil, typename T2 = Nil>
struct Tuple1 : Tuple1<T2>
{
  T1 x;

  using Base = Tuple1<T2>;

  Base* base() { return static_cast<Base*>(this); }
  const Base* base() const { return static_cast<const Base*>(this); }

  Tuple1(const T1& t1, const T2& t2)
    : Base{ t2 }, x{ t1 } {}
};

template <> struct Tuple1<> {};

template <typename T1>
struct Tuple1<T1> : Tuple1<>
{
  T1 x;

  using Base = Tuple1<>;

  Base* base() { return static_cast<Base*>(this); }
  const Base* base() const { return static_cast<const Base*>(this); }

  Tuple1(const T1& t1)
    : Base{}, x{ t1 } {}
};

// ---------------------------------------------------------------------------

template <typename...> struct Tuple2;

template <> struct Tuple2<> {};

template <typename Head, typename... Tail>
struct Tuple2<Head, Tail...> : Tuple2<Tail...>
{
  Tuple2(const Head& head, const Tail&... tail)
    : Base{ tail... }, m_head{ head } {}

private:
  using Base = Tuple2<Tail...>;
  Head m_head;
};

int main()
{
  cout << "Tuple1 sizes:\n";
  cout << sizeof(Tuple1<>) << '\n';
  cout << sizeof(Tuple1<int*>) << '\n';
  cout << sizeof(Tuple1<int*, Nil>) << '\n';

  cout << '\n';

  cout << "Tuple2 sizes:\n";
  cout << sizeof(Tuple2<>) << '\n';
  cout << sizeof(Tuple2<int*>) << '\n';
  cout << sizeof(Tuple2<int*, Nil>) << '\n';

  return 0;
}

The result of the execution of the program with MSVC 2022 is the following:

Tuple1 sizes:
1
8
8

Tuple2 sizes:
1
8
16

jeudi 25 août 2022

Cython: error: no matching function for call to …

I'm taking my first steps in Cython to write a Python extension of some C++ code. Also, I have only superficial knowledge of C++. Now I face an error which I do not understand, when cythonizing my .pyx file. The C++11 code is generated successfully, but that code does not compile. The first lines of the compiler error message are:

$ python setup.py build_ext --inplace
Compiling py_foo.pyx because it changed.
[1/1] Cythonizing py_foo.pyx
running build_ext
building 'pyfoo' extension
creating build
creating build/temp.linux-x86_64-3.9
gcc -pthread -B /home/…/compiler_compat -Wno-unused-result -Wsign-compare -DNDEBUG -O2 -Wall -fPIC -O2 -isystem /home/…/include -I/home/…/include -fPIC -O2 -isystem /home/…/include -fPIC -I. -I./ -I/home/…/include/python3.9 -c ./example.cpp -o build/temp.linux-x86_64-3.9/./example.o -std=c++11
gcc -pthread -B /home/…/compiler_compat -Wno-unused-result -Wsign-compare -DNDEBUG -O2 -Wall -fPIC -O2 -isystem /home/…/include -I/home/…/include -fPIC -O2 -isystem /home/…/include -fPIC -I. -I./ -I/home/…/include/python3.9 -c ./foo.cpp -o build/temp.linux-x86_64-3.9/./foo.o -std=c++11
gcc -pthread -B /home/…/compiler_compat -Wno-unused-result -Wsign-compare -DNDEBUG -O2 -Wall -fPIC -O2 -isystem /home/…/include -I/home/…/include -fPIC -O2 -isystem /home/…/include -fPIC -I. -I./ -I/home/…/include/python3.9 -c py_foo.cpp -o build/temp.linux-x86_64-3.9/py_foo.o -std=c++11
py_foo.cpp: In function ‘void __pyx_pf_5pyfoo_9PyDerived_2__dealloc__(__pyx_obj_5pyfoo_PyDerived*)’:
py_foo.cpp:1913:24: warning: deleting object of polymorphic class type ‘nspace::Derived’ which has non-virtual destructor might cause undefined behavior [-Wdelete-non-virtual-dtor]
 1913 |   delete __pyx_v_self->c_derived;
      |                        ^~~~~~~~~
py_foo.cpp: In function ‘int __pyx_pf_5pyfoo_5PyFoo___cinit__(__pyx_obj_5pyfoo_PyFoo*, __pyx_obj_5pyfoo_PyBase*)’:
py_foo.cpp:2134:66: error: no matching function for call to ‘std::unique_ptr<nspace::Base>::unique_ptr(PyObject*&)’
 2134 |     __pyx_t_2 = new nspace::Foo(((std::unique_ptr<nspace::Base> )__pyx_t_1));
      |                                                                  ^~~~~~~~~
In file included from /usr/include/c++/9/memory:80,
                 from py_foo.cpp:729:
/usr/include/c++/9/bits/unique_ptr.h:281:2: note: candidate: ‘template<class _Up, class> std::unique_ptr<_Tp, _Dp>::unique_ptr(std::auto_ptr<_Up>&&)’
  281 |  unique_ptr(auto_ptr<_Up>&& __u) noexcept;
      |  ^~~~~~~~~~
/usr/include/c++/9/bits/unique_ptr.h:281:2: note:   template argument deduction/substitution failed:
py_foo.cpp:2134:66: note:   mismatched types ‘std::auto_ptr<_Up>’ and ‘PyObject*’ {aka ‘_object*’}
 2134 |     __pyx_t_2 = new nspace::Foo(((std::unique_ptr<nspace::Base> )__pyx_t_1));
      |
...

These are the relevant files of my MWE:

example.h:

#ifndef EXAMPLE_H
#define EXAMPLE_H

namespace nspace
{
    class Base
    {
    public:
        virtual void print_() const = 0;
    };

    class Derived : public Base
    {
    private:
        int i;

    public:
        Derived(int i);
        void print_() const;
    };
}
#endif /* EXAMPLE_H */

example.cpp:

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


namespace nspace
{
    Derived::Derived(int i)
    {
        this->i = i;
    }

    void Derived::print_() const
    {
        std::cout << this->i << std::endl;
    }
}

foo.h:

#ifndef FOO_H
#define FOO_H

#include <memory>
#include "example.h"

namespace nspace
{
    class Foo
    {
    public:
        Foo();
        Foo(std::unique_ptr<Base> base);
        void print_();

    private:
        std::unique_ptr<Base> base;
    };
}

#endif // FOO_H

foo.cpp:

#include "foo.h"
#include "example.h"

namespace nspace
{
    Foo::Foo()
    {
        this->base = std::unique_ptr<Base>(new Derived(0));
    }

    Foo::Foo(std::unique_ptr<Base> base)
    {
        this->base = std::move(base);
    }

    void Foo::print_()
    {
        this->base->print_();
    }
}

cpp_foo.pxd:

from libcpp.memory cimport unique_ptr


cdef extern from "foo.h" namespace "nspace":
    cdef cppclass Foo:
        Foo() except +
        Foo(unique_ptr[Base] cpp_base) except +
        print_()

cdef extern from "example.h" namespace "nspace":
    cdef cppclass Base:
        pass

    cdef cppclass Derived(Base):
        Derived(int i) except +

py_foo.pyx:

# distutils: language = c++
# distutils: extra_compile_args = -std=c++11

cimport cython
from cpp_foo cimport Foo, Base, Derived
from libcpp.memory cimport unique_ptr


cdef class PyBase:
    pass

cdef class PyDerived(PyBase):
    cdef Derived* c_derived

    def __cinit__(self, int i):
        self.c_derived = new Derived(i)

    def __dealloc__(self):
        del self.c_derived


cdef class PyFoo:
    cdef Foo* foo

    def __cinit__(self, PyBase py_base):
        self.foo = new Foo(
            cpp_base=<unique_ptr[Base]>(py_base.c_derived)
        )


    def __dealloc__(self):
        del self.foo

    def print_(self):
        self.foo.print_()

setup.py:

from distutils.core import setup, Extension

from Cython.Build import cythonize

extensions = [
    Extension("pyfoo",
        sources=[
            "py_foo.pyx",
            "./foo.cpp",
            "./example.cpp",
        ],
        include_dirs=["./"]
    )
]

setup(
    ext_modules=cythonize(
        extensions,
        language_level=3,
    ),
)

I'm very sure my error comes from a misconception I have regarding Cython (and maybe C++ too). Any help or tip is appreciated.

Why the tuple has a larger size than expected?

I had the following definition of a tuple class template and tests for its size.

template <typename...> struct Tuple;

template <> struct Tuple<> {};

template <typename Head, typename... Tail>
struct Tuple<Head, Tail...> : Tuple<Tail...>
{
  Tuple(const Head& head, const Tail&... tail)
    : Base{ tail... }, m_head{ head } {}

private:
  using Base = Tuple<Tail...>;
  Head m_head;
};

#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include <doctest/doctest.h>

struct Nil {};

TEST_CASE("test size")
{
  using T0 = Tuple<>;
  CHECK(sizeof(T0) == 1);

  using T1 = Tuple<double, std::string, int, char>;

  struct Foo
  {
    double d;
    std::string s;
    int i;
    char c;
  };

  CHECK(sizeof(T1) == sizeof(Foo));

  using T2 = Tuple<int*, Nil>;
  CHECK(sizeof(T2) == sizeof(int*));

  using T3 = Tuple<int*, Nil, Nil>;
  CHECK(sizeof(T3) == sizeof(int*));
}

I expect because of the empty base class optimization the T2 and T3 tuples to be a pointer size, but the result is different.

[doctest] doctest version is "2.4.9"
[doctest] run with "--help" for options
===============================================================================
C:\projects\cpp\cpp_programming_language\28_metaprogramming\variadic_tuple.cpp(21):
TEST CASE:  test size

C:\projects\cpp\cpp_programming_language\28_metaprogramming\variadic_tuple.cpp(39): ERROR: CHECK( sizeof(T2) == sizeof(int*) ) is NOT correct!
  values: CHECK( 16 == 8 )

C:\projects\cpp\cpp_programming_language\28_metaprogramming\variadic_tuple.cpp(42): ERROR: CHECK( sizeof(T3) == sizeof(int*) ) is NOT correct!
  values: CHECK( 16 == 8 )

===============================================================================
[doctest] test cases: 1 | 0 passed | 1 failed | 0 skipped
[doctest] assertions: 4 | 2 passed | 2 failed |
[doctest] Status: FAILURE!

Why is this and is it possible somehow to enable the empty base class optimization?

Looping through all functions in a namespace in c++

My goal is to iterate over all functions of the namespace until a function returns me a valid strategy(enum). Each function can take different arguements.

enum class strategyType
{
    Strategy1,
    Strategy2,
    Strategy3,
    Strategy4,
    Strategy5,
    InvalidStrategy
}

namespace allFunctionStrategy
{
   strategyType algorithmMl(int v1,int v2);
   strategyType algorithmHeuristic(int v3,string s1);
   strategyType algorithmHeuristic(string s1,string s2);
   ... n such function's
}

class strategyContext
{
    int v1,v2,v3;
    string s1,s2;

/*i want to add iterator logic here*/
}

Why the base case with no template arguments for variadic tuple is not working?

As an exercise, I'm trying to define a variadic template for a Tuple but I found that the base case with no elements is not working.

template <typename Head, typename... Tail>
struct Tuple : Tuple<Tail...>
{
  Tuple(const Head& head, const Tail&... tail)
    : Base{tail...}, m_head{head} {}

private:
  using Base = Tuple<Tail...>;
  Head m_head;
};

template <> struct Tuple<> {};

MSVC 2022 gives the following error:

C:\projects\cpp\cpp_programming_language\28_metaprogramming\variadic_tuple.cpp(12): error C2976: 'Tuple': too few template arguments
  C:\projects\cpp\cpp_programming_language\28_metaprogramming\variadic_tuple.cpp(2): note: see declaration of 'Tuple'
C:\projects\cpp\cpp_programming_language\28_metaprogramming\variadic_tuple.cpp(12): error C2913: explicit specialization; 'Tuple' is not a specialization of a class template

Why this does not work and how to fix it?

Can Anyone explain the output to this piece of code using Late binding [duplicate]

#include <stdio.h>

int main() {
    int i=5;
    
    int j= ++i * i++ * ++i * i++;
    printf("%d ",j); // Output is 2688

    return 0;
}

I am unable to understand how late binding is working in this case. can anyone help me by explaining this?

mercredi 24 août 2022

std::vector

I have a C11 std::vector of structures. The structure contains an iterator to another structure of the same type, describing a tree.

Using a forward declaration doesn't work, because vector needs to have the full definition of the structure, but vector can't have the full definition of the structure until definition is complete.

#include <vector>

template <class Payload>
class Tree
{
    public:
        typedef struct _Node Node;
        struct _Node
        {
            Payload t_payload;
            //error: invalid use of incomplete type '_Value_type {aka struct _Node}'
            std::vector<Node>::iterator pst_father;
        };

        std::vector<Node> gast_tree;
};

int main()
{
    Tree<int> my_tree;
    return 0;
}

in instantiation of 'void std::_Destroy(_ForwardIterator, _ForwardIterator) [with _ForwardIterator = _Node*]':
required from 'void std::_Destroy(_ForwardIterator, _ForwardIterator, std::allocator<_T2>&) [with _ForwardIterator = _Node*; _Tp = _Node]'
required from 'std::vector<_Tp, _Alloc>::~vector() [with _Tp = _Node; _Alloc = std::allocator<_Node>]'
required from here
error: invalid use of incomplete type '_Value_type {aka struct _Node}'

I want std::vector to serve as container for the Node structure, and I want Node(s) to link with each others to build a tree. It would be trivial using int indexes instead of iterators and resolving the reference later, but I'm trying to learn std::vector<>::iterators. This compiles just fine:

#include <vector>

template <class Payload>
class Tree
{
    public:
        typedef struct _Node
        {
            Payload t_payload;
            //use a dumb index
            int s32_father_index;
        } Node;

        std::vector<Node> gast_tree;
};

int main()
{
    Tree<int> my_tree;
    return 0;
}

I tried several ways, but I can't get the iterator to compile. Is it possible to have an iterator to an object inside the object?

Strongly typed c++ varargs [duplicate]

I'm writing a utility function in c++ 11 that adds an element of a single type to a vector. Most variable argument docs/guides I've found show a template with the typedef type, but I'm looking to only allow a single type for all the variable arguments (const char*). The following is the relevant snippet of code:

Item.hpp:

// Guard removed
#include <vector>

class Item {
  public:
    Item(const char* n, bool (*optionChange)(uint8_t), const char*...);
  private:
    std::vector<const char*> options;
    void addOption(const char*);
}

Item.cpp:

#include "Item.hpp"

void Item::addOption(const char* option) {
  options.push_back(option);
}

Item::Item(
  const char* n, 
  bool (*optionChange)(uint8_t),
  const char* opts...
): name(n), type(MENU_TYPE_OPTS), selectedOpt(0) {
  addOption(opts...); // Doesn't compile
}

Compilation of the above code fails with the message error: expansion pattern 'opts' contains no argument packs.

Why is this template instantiated in two different types from the same typedef? [duplicate]

The title might be misguiding, but I had to give one, so let's at least base it on my suspicions.

I have a program that depends on this type and the following functions, declared in one header file (in this case, named particle.hpp) and implemented in a source file (particle.cpp):

using World = std::vector<Particle>;

World* initWorld();
void update(World* w, double dt);
void draw(World* w);
void destroyWorld(World* w);

These functions compile fine. The given files are correctly included and recognized by the build system, according to all the tests I've made to ascertain it. However, when they are used in the rest of my code, ld fails with the following:

main.cpp:(.text+0x65): undefined reference to `initWorld()'
/usr/bin/ld: main.cpp:(.text+0xa6): undefined reference to `update(std::vector<._anon_156, std::allocator<._anon_156> >*, double)'
/usr/bin/ld: main.cpp:(.text+0xdb): undefined reference to `draw(std::vector<._anon_156, std::allocator<._anon_156> >*)'
/usr/bin/ld: main.cpp:(.text+0xf9): undefined reference to `destroyWorld(std::vector<._anon_156, std::allocator<._anon_156> >*)'

Stranger yet, g++ gives these warnings:

/home/whoanders/projects/particle/mainloop.hpp:12:6: warning: ‘void destroyWorld(World*)’ used but never defined
   12 | void destroyWorld(World* w);
      |      ^~~~~~~~~~~~
/home/whoanders/projects/particle/mainloop.hpp:11:6: warning: ‘void draw(World*)’ used but never defined
   11 | void draw(World* w);
      |      ^~~~
/home/whoanders/projects/particle/mainloop.hpp:10:6: warning: ‘void update(World*, double)’ used but never defined
   10 | void update(World* w, double dt);
      |      ^~~~~~
/home/whoanders/projects/particle/mainloop.hpp:9:8: warning: ‘World* initWorld()’ used but never defined

This is the core of my problem: these functions compile correctly, but are not recognized in other files. What is suspect to be the source of the problem is the definition of type World. In ld's warnings, it does not seem to be defined as a std::vector of a Particle, but rather as that of an anonymous type, which leads me to believe that the compiler thinks the definition of a World is different between the various files of the source tree, and that because of that, it doesn't see the functions as defined in particle.cpp and those used in the rest of the code as one and the same.

My question is, if this explanation is correct, why does this problem surface and how do I solve it?

mardi 23 août 2022

String Transformation binary [closed]

I'm doing an exercise about C++

The structure of the Input is:

  • Line 1: The string S1 consists of consecutive 0 and 1
  • Line 2: The string S2 consists of a sequence of character pairs am, bn, (m, n are integers) (1<=m,n<=100)

The request is: Transform the string S1: Going from left to right of the string s1, if there is a consecutive segment consisting of m 1's, replace it with the string am, if there is a consecutive segment of n 0's, replace it with the string bn, and so on. to the end of the string. With the string s2, do opposite.

example: INPUT: 11001010 a5b3a4

OUTPUT: a2b3a1b1a1b1 111110001111

Help me code this in C++ please. Thank you!

How to delete specific line from text file c++

This is my text file content.

1
2
3

I want to delete line of this file.

#include <iostream>
#include <fstream>
#include <string>
std::fstream file("havai.txt", ios::app | ios::in | ios::out);

int main()
{
    std::string line;
    int number;
    std::cout << "Enter the number: ";
    std::cin >> number;
    while (file.good())
    {
        getline(file, line);
        if (std::to_string(number) == line)
        {
            // how to delete that line of my text file
        }
    }
    return 0;
}

how to delete that line in if statement?

What is the best practice of defining and using classes in c++? [closed]

Hello guys i am new in c++ and there're some things that makes me confused so i wanted to consult you.

#include <iostream>
#include <utility>
#include <vector>
#include <string>
using namespace std;
class A {
    public :
    A() { cout << "constructor called" << endl;}
    ~A() { cout << "destructor called" << endl;}
    A(A&&) {cout << "move constructor called"<< endl; return;}
    A& operator=(A&&) {cout << "move assignment operator called"<< endl; return *this;}

};
A fun() {
    A a; // 5. constructor called
    return a; // 6. move assignment operator called
    // 7. destructor called on this local a
}
void foo(A){
    return;
}
int main()
{
    A a; // 1. constructor called 
    A b; // 2. constructor called
    A c{std::move(b)}; // 3. move constructor called
    c = std::move(a); // 4. move assignment operator called
    a = fun();
    foo(std::move(c)); // 8. move constructor called

}

where the code is copied from

In c++ we're able to override many operators in classes and also there're some concepts called "copy cosntructor, copy assignment, move assignment, move constructor etc.
There may be some certain cases that would be appropriate to use these concepts but in general wouldn't be easy to access classes via pointers? class *A = new A(); thus any subsequent assignment movement or any operation would easily be performed as if it was a built in type.

Since any modern oop languages(java, c# and others) comply with this simple idea i think this feature of c++ is a little obsolete and confusing.(it's good to have for flexibility tho.)
What do you think?
What is the best practice here?
Is it really a good practice to make the user-defined types as if they were built in types and force them to act like them?

C++ 11 conditional template alias to function

In C++ 11, I want to make a template alias with two specializations that resolve to a different function each.

void functionA();
void functionB();

template<typename T = char>
using Loc_snprintf = functionA;

template<>
using Loc_snprintf<wchar_t> = functionB;

So I can call e.g. Loc_snprintf<>() and it's resolve to functionA().

Apparently seems impossible (to compile). Is there something ultimately simple that mimics it (maybe using a class template)?

Segmentation Error: Help on the correct allocation memory when saving & loading binary files containing a specific structure from a class

This is my first time asking a question, so apologies if it is not done 100%:

I have a class which saves and loads a binary file with a specific data structure. If the program creates an instance of the class, save the binary file, and creates another instance of the class to load/read the binary file consequently, everything seems 100% correct.

However, if I run the program to save the binary file and then run it again to load/read that binary file, it gives me a segmentation fault at the end.

The program still does everything it needs to do before the segmentation fault, except deconstructing the class at the end (obviously). It looks like my allocation of the memory is not correct, but I am not sure where I am going wrong. A simplified version of the code follow (also here: https://github.com/LenteDreyer/Tests.git )

Can someone see where I am going wrong?

class header file that save/loads the file

#ifndef __TESTS_MAP_HH__
#define __TESTS_MAP_HH__
#include <iostream>
#include <fstream>
#include <string>
#include <vector> 
#include <algorithm>
#include <sstream> 
typedef struct test_struct{
    bool test_bool; 
    double test_double; 
    std::vector<double> test_vector; 
} test_struct_t; 
class map
{
private:
    std::string m_path, m_str; 
    double m_double; 
    test_struct m_struct; 
public:
    map(const std::string& a_id);
    void set_str(std::string a_str); 
    void set_double(double a_double); 
    void set_struct(test_struct a_struct);
    void load_file(); 
    void save_file() const;
    void show_file() const;   
    ~map();
};
#endif //__TESTS_MAP_HH__

class source file that save/loads the binary file

#include "map.hh"
map::map(const std::string& a_id)
{
    m_path = a_id + ".bin";
    m_str = "none"; 
    m_double = 0.0; 
    m_struct = {false, 0.0};  
}
void map::set_str(std::string a_str){
    m_str = a_str; 
}
void map::set_double(double a_double){
    m_double = a_double; 
} 
void map::set_struct(test_struct a_struct){
    m_struct = a_struct; 
}
void map::load_file(){
    std::ifstream l_inF;
    l_inF.open(m_path.c_str(), std::ios::binary | std::ios::in);
    l_inF.read((char*)&m_double,sizeof(double));
    l_inF.read((char*)&m_struct,sizeof(test_struct_t));
    size_t str_size; 
    l_inF.read((char*)&str_size, sizeof(str_size));
    m_str.resize(str_size); 
    l_inF.read((char*)&m_str[0], str_size);
    l_inF.close(); 
}
void map::save_file() const{
    std::ofstream l_outF;
    l_outF.open(m_path.c_str(), std::ios::binary | std::ios::out);
    l_outF.write((char*)&m_double,sizeof(double));
    l_outF.write((char*)&m_struct,sizeof(test_struct_t));
    size_t str_size = m_str.size(); 
    l_outF.write((char*)&str_size, sizeof(str_size));
    l_outF.write((char*)&m_str[0], str_size);
    l_outF.close(); 
}
void map::show_file() const{
    std::cout << ">>-----------------------------------------------" << std::endl; 
    std::cout << ">> double        : " << m_double << std::endl; 
    std::cout << ">> double        : " << m_double << std::endl; 
    std::cout << ">> struct.bool   : " << m_struct.test_bool << std::endl;
    std::cout << ">> struct.double : " << m_struct.test_double << std::endl;
    std::cout << ">> struct.vector : " << "size = " << m_struct.test_vector.size() <<  std::endl; 
    std::cout << ">> string        : " << m_str <<  std::endl; 
    std::cout << ">>-----------------------------------------------" << std::endl; 
}   
map::~map(){}

main function case 1 works, and case 2 gives the segmentation fault.

#include "map.hh"
int main(int argc, char const *argv[])
{
    std::string id = "mapfile"; 
    int action = 0; 
    if(argc > 1) action = std::stoi(argv[1]); 
    else {
        std::string input;
        std::cout << "Enter case (1 or 2): "; 
        std::cin >> input;
        action = std::stoi(input);
    } 
    switch (action)
    {
    case 1:
        {
            // This works 100% (no errors and it saves/reads class perfectly)
            std::vector<double> l_vect = {0.1, 0.0, 0.6};
            test_struct save_struct = {true, 5.0, l_vect}; 
            map test_save(id); 
            test_save.show_file(); 
            test_save.set_double(8.0); 
            test_save.set_str("save this string"); 
            test_save.set_struct(save_struct); 
            test_save.show_file(); 
            test_save.save_file(); 
            map test_load(id);
            test_load.load_file();
            test_load.show_file(); 
        }
        break;
    case 2:
        {
            // gives segmentation error at the end of the program
            map test_load(id);
            test_load.load_file();
            test_load.show_file(); 
        }
        break;
    
    default:
        break;
    }
    return 0;
}

lundi 22 août 2022

setwindowdisplayaffinity() is not working on window server 2012 R2

setwindowdisplayaffinity() is not working in Windows server 2012 R2

When I apply setwindowdisplayaffinity() in remote system get crashes without showing me any error. whereas if I don't apply setwindowdisplayaffinity() in remote system it works properly.

Could someone please help me out where I am going wrong.

Thanks

In C++ I am getting an Error while I am executing my code with get set and constructor methods [duplicate]

In my code I am using the get, set and Employee constructor for getting and take the employee data for that I am creating an one .h file and two .cpp file. While executing these files i am getting error.

So my first .h file is emp.h:

#include<iostream>
class Employee
{
  private:
  std::string emp_Name,emp_ID,emp_Address;
  public:
  Employee(std::string name, std::string id, std::string address):emp_Name(name),
    emp_ID(id),emp_Address(address)
  {
  }
  void setempname(std::string name);
  void setempid(std::string id);
  void setempage(std::string address);

  std::string getempname();
  std::string getempid();
  std::string getempaddress();
};

My first .cpp file is emp.cpp

#include "emp.h"
void Employee::setempname(std::string name)
{
        emp_Name=name;
}
void Employee::setempid(std::string id)
{
        emp_ID=id;
}
void Employee::setempage(std::string address)
{
        emp_Address=address;
}

std::string Employee::getempname()
{
        return emp_Name;
}
std::string Employee::getempid()
{
        return emp_ID;
}
std::string Employee::getempaddress()
{
        return emp_Address;
}

My second .cpp file is Main.cpp:

#include "emp.h"
int main()
{
        Employee emp[2];
        emp[0]= Employee ("Rohi","E345","Clk");
return 0;
}

The Error I am getting is:

g++ emp.cpp Main.cpp
Main.cpp: In function ‘int main()’:
Main.cpp:4:23: error: no matching function for call to ‘Employee::Employee()’
         Employee emp[2];
                       ^
In file included from Main.cpp:1:
emp.h:7:3: note: candidate: ‘Employee::Employee(std::__cxx11::string, std::__cxx11::string, std::__cxx11::string)’
   Employee(std::string name, std::string id, std::string address):emp_Name(name),
   ^~~~~~~~
emp.h:7:3: note:   candidate expects 3 arguments, 0 provided
emp.h:2:7: note: candidate: ‘Employee::Employee(const Employee&)’
 class Employee
       ^~~~~~~~
emp.h:2:7: note:   candidate expects 1 argument, 0 provided
emp.h:2:7: note: candidate: ‘Employee::Employee(Employee&&)’
emp.h:2:7: note:   candidate expects 1 argument, 0 provided

So Anyone please help me to solve these error.

dimanche 21 août 2022

How to get first element of typelist in C++-11

I am following C++ templates the complete guide and trying to get the first element from a typelist.

The following compiles:

#include <bits/stdc++.h>

using namespace std;

template <typename... Elements>
class Typelist;

using SignedIntegralTypes =
        Typelist<signed char, short, int, long, long long>;

template <typename List>
class HeadT;

template <typename Head, typename... Tail>
class HeadT<Typelist<Head, Tail...>> {
public:
    using Type = Head;
};

template <typename List>
using Head = typename HeadT<Typelist<List>>::Type;


int main() {
    static_assert(is_same<Head<SignedIntegralTypes>, SignedIntegralTypes>::value, "");
}

Head<SignedIntegralTypes> produces SignedIntegralTypes. I would expect it to produce signed char. Why is this happening? How do I fix it?

samedi 20 août 2022

what's the best way to hold constants in c++

I have some constant values such as color values, what's the best way to define and use them through projects? I've already tried static global variables in a single c++ file and included it in my files.

something like this:

    const std::string appName = "";

are there any other better ways to do so?

Problem with offset in pointers, cant fugure out why the lenght need to be 5 not 4;

so im doing a simple test where i copy an int memory to a char[] and then i can copy it agin to another integer

int i = 236;

char msg[sizeof(i)];

memcpy(&msg, &i, sizeof(i));
int j;
memcpy(&j, &msg, sizeof(i));

std::cout << j << std::endl;
return 0;

this works and im only passing one int, but im trying to pass 2 different integers in the same char[], knowing that a int is 4 bytes i would do

int i = 236;
int u = 69;

char msg[sizeof(int)*2];

memcpy(&msg, &i, sizeof(int));
memcpy(&msg + 4, &u, sizeof(int));

int j;
memcpy(&j, &msg+4, sizeof(int));

std::cout << j << std::endl;
return 0;

but this dont work and only when using 5 in the offset instead of 4 it works, but it makes no sense in my brain, lets say that msg[0],msg[1],msg[2],msg[3] are used by the first integer, so msg[4],msg[5],msg[6],msg[7] would be to the other integer, can someone explain that please...

vendredi 19 août 2022

Why can't use a inside pointer to initialize two difference shared_ptr?

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

class Base;

class Base {
public:
    int i;
    int j;
    Base(int _i, int _j) : i(_i), j(_j) {};
};

int main(void) {
    Base* q = new Base(5, 9);
    cout << q->i << endl;
    shared_ptr<Base> p(q);
    cout << p->j << endl;
    shared_ptr<Base> t(q);            // mark
    cout << p.use_count() << endl;
    // cout << t.use_count() << endl;
    return 0;
}

After I run it on visual studio 2022 with C++11, the reference count is 1 rather than two, and there's something wrong with delete that makes the programme failed.

However, when I change the code marked into "shared_ptr t(p)", everything goes well.

How?

can i make a time limit for a sprite in sfml/cpp?

I want to show a warning note on the screen with time-limit(for instance in a game).

I mean, is it possible to show up a sprite just for 10 sec with SFML?

Own kind of system_error for Win32

Some time ago I mentioned here that system_category() doesn't have a name() method that translates the error-code according to the current thread's locale under Win32. I also wrote that in the Microsoft developer forum and they said that they will fix this except for WinRT apps.
So I wrote my own class xsystem_category but I'm not sure if I did everything correctly. Maybe someone here more experienced with the innards of exception-hanling in C++ will check that:

#include <Windows.h>
#include <iostream>
#include <system_error>

struct xsystem_category : public std::error_category
{
    xsystem_category() = default;
    xsystem_category( xsystem_category const & ) = delete;
    virtual ~xsystem_category() override = default;
    void operator =( xsystem_category const & ) = delete;
    virtual char const *name() const noexcept override;
    virtual std::error_condition default_error_condition( int code ) const noexcept override;
    virtual bool equivalent( int code, std::error_condition const &condition ) const noexcept override;
    virtual bool equivalent( std::error_code const &code, int condition ) const noexcept override;
    virtual std::string message( int condition ) const override;
};

char const *xsystem_category::name() const noexcept
{
    return "xsystem_category";
}

std::error_condition xsystem_category::default_error_condition( int code ) const noexcept
{
    return std::error_condition( code, xsystem_category() );
}

inline bool xsystem_category::equivalent( int code, std::error_condition const &condition ) const noexcept
{
    return default_error_condition( code ) == condition;
}

inline bool xsystem_category::equivalent( std::error_code const &code, int condition ) const noexcept
{
    return *this == code.category() && code.value() == condition;
}

std::string xsystem_category::message( int condition ) const
{
    using namespace std;
    LCID lcid = GetThreadLocale();
    string errStr( 64, '\0' );
    while( !FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_MAX_WIDTH_MASK, nullptr, condition, lcid, errStr.data(), (DWORD)errStr.size(), nullptr ) )
        if( DWORD dwFmErr = GetLastError(); dwFmErr == ERROR_INSUFFICIENT_BUFFER )
            errStr.resize( 2 * errStr.size(), '\0' );
        else
            throw system_error( (int)dwFmErr, system_category(), "FormatMessage() failed" );
    errStr.resize( strlen( errStr.data() ) );
    return errStr;
}

jeudi 18 août 2022

MPI Matrix Multiplication - Task sharing when size(of procs) < rows of matrix

I am trying to perform matrix-matrix multiplication in MPI using c++.

I have coded for the cases where number_of_processes = number_of_rows_of_matrix_A (so that rows of matrix_A is sent across all processes and matrix_B is Broadcasted to all processes to perform subset calculation and they are sent back to root process for accumulation of all results into Matrix_C) and I have also coded for the case when number_of_processes > number_of_rows_of_Matrix_A

I have no idea how to approach for the case when number_of_processes < rows_of_matrix_A.

Lets say I have 4 processes and 8 * 8 matrix_A and matrix_B. I can easily allocate first 4 rows to respective ranks of processes, i.e 0,1,2,3. How should I allocate the remaining rows so that I wont mess up with synchronization of the results which I get from respective processes.

Side note of my implementation: I have used only MPI_Recv, MPI_Send for all the coding part which I have done.

Thanks in advance.

Calling a function object as a function pointer

i have the below - minimal reproducable code. I am building a REST API for an embedded device, and i am trying to bind a list of functions to a map. That way i can index them and execute depending on the parameters/endpoint that is passed in/visited by the user.

EDIT: Forgot my question - oops.

How do i call the function object as a function pointer? How do i execute the function passed into the lambda? I can't figure out the syntax.

Header File

typedef std::function<void(AsyncWebServerRequest *)> route_method;
typedef std::unordered_map<std::string, route_method> route_t;
typedef std::unordered_map<std::string, route_t> route_map_t;

route_t routes;
route_map_t route_map;

CPP

std::vector<std::string> APIServer::routeHandler(std::string index, route_t route)
{
    route_map.emplace(index, route);
    std::vector<std::string> indexes;
    indexes.reserve(route.size());

    for (const auto &key : route)
    {
        indexes.push_back(key.first);
    }

    return indexes;
}

void APIServer::setupServer()
{
    routes.emplace("wifi", [&](AsyncWebServerRequest *request)
                   { setWiFi(request); });
    routeHandler("built_in", routes);
}

void APIServer::handleRequest(AsyncWebServerRequest *request)
{
    auto it_map = route_map.find(param->name().c_str());
    auto it_method = it_map->second.find(param->value().c_str());
    {
        if (it_map != route_map.end())
        {
            if (it_method != it_map->second.end())
            {
                it_method->second(request); // how do i call the function object as a function pointer?
            }
            else
            {
                // return 404
            }
         }  
}

why I am getting garbage values by the function getMemberNames() in release mode

I am getting garbage values in a vector by the getMemberNames() function call of jsoncpp.dll in release mode in the visual studio. It is working fine in debug mode.

Json::Value dataOfFSISubReport = fileOPerations.GetJsonData(FSISubReportJsonFile);

std::vector<std::string> dataAttributes = dataOfCarpetTenementArea.getMemberNames();

How to solve core dumped problen while debugging code with gdb

This following code segment I ain't able to debug. The output is saying that

Aborted (core dumped) [1] + Aborted (core dumped) "/bin/gdb" --interpreter=mi --tty=${DbgTerm} 0<"/tmp/Microsoft-MIEngine-In-kgwsird3.a0t" 1>"/tmp/Microsoft-MIEngine-Out-j3ssuqn2.lsi"

'''Note that, I am using gdb in Linux and using Visual Studio as code editor.'''

#include <iostream>

int main() {
    int tt;
    std::cin >> tt;
    while(tt--) {
    int n;
    std::cin >> n;
    int h, m;
    std::cin >> h >> m;
    int time = 60 * h + m, ans = 24 * 60;
    for(int i = 0; i < n; ++i) {
        std::cin >> h >> m;
        int t = 60 * h + m - time;
        if(t < 0) t += 24 * 60;
        ans = (ans < t ? ans : t);
    }
    std::cout << ans / 60 << " " << ans % 60 << '\n';
}
    return 0;
}

mercredi 17 août 2022

Any builtin C/C++ library functions to encode domain names to DHCP option code 119 domain-search list?

Any builtin C/C++ library functions to encode domain names to DHCP option code 119 domain-search list

Example: I want to convert "google.com" to "0x06'google'0x03'com'0x00"

Any sample optimised programs would help too.

How do make ASP.NET React JS template usable?

I have followed a Microsoft template to get an ASP.NET Core React JS project in visual studio 2022. The end product displays a list of weather forecasts with no navigability in the website. I am trying to convert the site to be more adaptable and start building my own project. I have attached a navbar file that I would like to implement, and the removal of the weather forecast. Please can someone tell me how to do this?

screenshot of tutorial's front end

App.js

import React, { Component } from 'react';
import "bootstrap/dist/css/bootstrap.min.css";
import Navbar from './Navigation/Navbar.js';

export default class App extends Component {
    static displayName = App.name;

constructor(props) {
    super(props);
    this.state = { forecasts: [], loading: true };
}

componentDidMount() {
    this.populateWeatherData();
}

static renderForecastsTable(forecasts) {
    return (
        <table className='table table-striped' aria-labelledby="tabelLabel">
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Temp. (C)</th>
                    <th>Temp. (F)</th>
                    <th>Summary</th>
                </tr>
            </thead>
            <tbody>
                {forecasts.map(forecast =>
                    <tr key={forecast.date}>
                        <td>{forecast.date}</td>
                        <td>{forecast.temperatureC}</td>
                        <td>{forecast.temperatureF}</td>
                        <td>{forecast.summary}</td>
                    </tr>
                )}
            </tbody>
        </table>
    );
}

render() {
    let contents = this.state.loading
        ? <p><em>Loading... Please refresh once the ASP.NET backend has started. See <a href="https://aka.ms/jspsintegrationreact">https://aka.ms/jspsintegrationreact</a> for more details.</em></p>
        : App.renderForecastsTable(this.state.forecasts);

    return (
        <div>
            <h1 id="tabelLabel" >Weather forecast</h1>
            <p>This component demonstrates fetching data from the server.</p>
            {contents}
        </div>
    );
}

async populateWeatherData() {
    const response = await fetch('weatherforecast');
    const data = await response.json();
    this.setState({ forecasts: data, loading: false });
}

}

Index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
reportWebVitals();

Navbar.js

import React from "react";

const Navbar = () => {
return (
    <nav className="navbar navbar-expand-lg navbar-light bg-light">
        <a className="navbar-brand" href="#">
            Navbar
        </a>
        <button
            className="navbar-toggler"
            type="button"
            data-toggle="collapse"
            data-target="#navbarNavDropdown"
            aria-controls="navbarNavDropdown"
            aria-expanded="false"
            aria-label="Toggle navigation"
        >
            <span className="navbar-toggler-icon"></span>
        </button>

        <div className="collapse navbar-collapse" id="navbarNavDropdown">
            <ul className="navbar-nav">
                <li className="nav-item active">
                    <a className="nav-link" href="#">
                        Home <span className="sr-only">(current)</span>
                    </a>
                </li>
                <li className="nav-item">
                    <a className="nav-link" href="#">
                        Features
                    </a>
                </li>
                <li className="nav-item">
                    <a className="nav-link" href="#">
                        Pricing
                    </a>
                </li>
                <li className="nav-item dropdown">
                    <a
                        className="nav-link dropdown-toggle"
                        href="#"
                        id="navbarDropdownMenuLink"
                        data-toggle="dropdown"
                        aria-haspopup="true"
                        aria-expanded="false"
                    >
                        Dropdown link
                    </a>
                    <div
                        className="dropdown-menu"
                        aria-labelledby="navbarDropdownMenuLink"
                    >
                        <a className="dropdown-item" href="#">
                            Action
                        </a>
                        <a className="dropdown-item" href="#">
                            Another action
                        </a>
                        <a className="dropdown-item" href="#">
                            Something else here
                        </a>
                    </div>
                </li>
            </ul>
        </div>
    </nav>
);
};

export default Navbar;

mardi 16 août 2022

c++11 static_assert failed to compare const double variable

See this code snippet:

    const     int i1 = 1;
    constexpr int i2 = 1;
    static_assert(i1 == 1, "const     int is not compile-time const"); // ok
    static_assert(i2 == 1, "constexpr int is not compile-time const"); // ok

    const     double PI1 = 3.0;
    constexpr double PI2 = 3.0;  
    static_assert(PI1 == 3.0, "const     double is not compile-time const");  // error
    static_assert(PI2 == 3.0, "constexpr double is not compile-time const");  // ok

For latest clang-14 and gcc-12, the 3rd static_assert doesn't compile, saying:

read of non-constexpr variable 'PI1' is not allowed in a constant expression

This seems very strange to me: for int type, both const and constexpr compare compiles inside static_assert, but for double type, const cannot compare, but only constexpr passes.

What's the syntax rule behind this error? Thanks.

How fast is the build-in function SHGetValueA function (shlwapi.h) in C++?

I have been in doubt about what should be a better approach:

  1. To cache the registry and use it later (I won't be doing it multiple times).
  2. To run this function when needed (if it is fast)

How can I measure the speed of this function?

int ReadUACRegistryKey(LPCWSTR key)
{
    LPCWSTR pszSubKey, pszValue = key;
    const std::wstring sPath = L"XXXXXXXXXXX";

    pszSubKey = sSearchPattern.c_str();
    DWORD dwType = 0;
    DWORD dwValue = 0;
    DWORD dwValueSize = sizeof(dwValue);

    int retval = SHGetValue(HKEY_LOCAL_MACHINE, pszSubKey, key, &dwType, &dwValue, &dwValueSize);
    if (retval != ERROR_SUCCESS)
    {
        Trace(TRACE_ERROR, _T("ERROR: Failed to retrieve Registry setting and check Input_Image format."));
    }

    return dwValue;
}```

How to get the position of scrollbar thumb

I am trying to build a custom-scrollbar

example

To get Thumb length :

A/B = C/D

D = C * (A/B)

All fine so far. but struggling to find the Thumb position

example

Given an (viewport) offset, how to get the thumb offset? or any suggestions?

How to show hight value from list in this c++ program

this is my program of fee management i want to show the highest fee data first how is this possible:

#include <iostream>
#include <string>
#include <list>// library for List used in student storing 

using namespace std;
class StudentList;
class Student{
    private:
        //every student properties
        string name;
        string rollno;
        string classroom;
        double fee;
    
        
    public:
        //function names from every menu
        void selectionSheet();
         void manageData();
         void search();
         void Reports();
        
        
        //this funtion returns a new student object
     Student addData(){
        system("cls");
        cout<<"\n\n\t\tEnter the Name of student"<<endl;
            string name;
            cin>>name;
            system("cls");
            cout<<"\n\n\t\tEnter the RollNo of student"<<endl;
            string rollno;
            cin>>rollno;
            system("cls");
            cout<<"\n\n\t\tEnter the classroom of student"<<endl;
            string classroom;
            cin>>classroom;
            system("cls");
            cout<<"\n\n\t\tEnter the fee of student"<<endl;
            double fee;
            cin>>fee;
            return Student(name,rollno,classroom,fee);
        };
        
        
        
        
        
        
        //constructor
        Student(string n,string roll,string cl,double f){
            name=n;
            rollno=roll;
            classroom=cl;
            fee=f;
            
        }
        //no arguiment constructor
        Student(){
        }
        //Disctructor
        ~Student(){
        }
        
        //setters and getters
        string getName(){return name;} 
        string getRollNo(){return rollno;}
        string getClassRoom(){return classroom;}
        double getFee(){return fee;}
        
        void setName(string n){name=n;} 
        void setRollNo(string r){rollno=r;}
        void setClassRoom(string c){classroom=c;}
        void setFee(double f){fee=f;}
        
    
    
        
        
};
void Student::selectionSheet(){
    
    cout<<"\n\n\t\t1- Manage Data\t"<<"\n\t\t2- Search \n"<<"\t\t3- Reports\t"<<"\n\t\t4- Exit\n"
    <<"-----------------------------------\n";
}

void Student::manageData(){
            cout<<"\t\t1- Add Data\t"<<"\n\t\t2- Update Data\n"<<"\t\t3- Display Data\t"<<"\n\t\t4- Delete Data\t"<<"\n\t\t   5- Exit\n"
            <<"-----------------------------------\n";
        }
void Student::search(){
    
    cout<<"\n\n\t\tSearch Student via\n"<<"------------------\n"<<"\n\t\t1- Name\t\t"<<"\n\t\t2- RollNo\n"<<"\t\t3- Class\t"<<"\n\t\t4- exit\n"
            <<"----------------------------------------\n";
}

void Student::Reports(){
    cout<<"\n\n\t\t1- Top positions\t"<<"\n\t\t2- Result Report\t"<<"\n\t\t3- Exit\n"
            <<"------------------------------------------------\n";
}

//inheriting the student class with StudentList Class
class StudentList : public Student{
    private:
        list<Student> studentlist={};//list to store students
        list<Student> topStudentList={};
        list<Student>::iterator it;//iterator used to go through list
        public:
            Student s;
        void addStudent()
            {
                studentlist.push_back(s.addData());//push_back adds a new student in student list
            }
            
        void getStudentList()//this function prints all of the students in the list
        {
                    int i=0;
                for(Student S:studentlist){//for each loop to get each student one by one
                    cout<<"\n-----"<<i<<"-----\nName: "<<S.getName()<<"\nRollNo: "
                    <<S.getRollNo()<<"\nClassRoom: "<<S.getClassRoom()<<"\nFee: "<<S.getFee()
                    <<endl;
                    cout<<"------------------------\n";
                    cout<<"\n\n";
                    i++;
                }
            }
            
            void getStudentListReport()//report list for all of the students
        {
            system("cls");
                    int i=0;
                    cout<<"  Name:\t"<<"Rollno:\t"<<"ClassRoom:\t"<<"Fee:\t\t"
                    <<"\n----------------------------------------------\n";
                for(Student S:studentlist){//for each loop used to get each student one by one
                    
                    cout<<i<<":"<<S.getName()<<"\t"
                    <<S.getRollNo()<<"   \t"
                    <<S.getClassRoom()<<"\t\t"
                    <<S.getFee()<<endl;
                    cout<<"------------------------\n";
                
                    i++;
                
                
            }
            }
            
        void updateData()//function for updating an existing student information
        {
                    int x;
                    if(studentlist.size()>=1){//if checking if there is atleast 1 student in list
                    system("cls");
                cout<<"Which student would you like to update?\n";
                getStudentList();//shows the list of all the students to choose from
                cin>>x;
                it=studentlist.begin();//iterator it....begin sets the 'it' to the first object in list
                advance(it,x);//'it' is moved to x(entered by user) position
                studentlist.insert(it,s.addData());//inserts a new updated student at 'it'position
                x++;
        }
        else
            cout<<"no Students added\n";
            it=studentlist.begin();
            advance(it,x);
            studentlist.erase(it);//deletes the previous not updated student
    }
    
    
        void deleteData()//funtion used to delete a student
        {
                    int x;
                    if(studentlist.size()>=1){
                    
                cout<<"Which student would you like to remove?\n";
                getStudentList();//displays student list
                again:
                cin>>x;
                if(x>=0 && x<studentlist.size()){
                
                it=studentlist.begin();//moves 'it' to start
                advance(it,x);//moves 'it' to user selected postion
                studentlist.erase(it);//deletes the student
            }
            else    //if student selects a invalid option it goes back to selection again:
                {cout<<"Select a valid option\n";
                goto again;}
        }
        else
            cout<<"No students added\n";
        }
    
        void searchByName()//search a student by name;
        {
            bool f=true;
            string name;
            system("cls");
            cout<<"Enter name of student\n";
            cin>>name;//user enters a name
            for(Student S:studentlist){//loop to go through each student
                if(S.getName().compare(name)==0){//checks if the name entered and student is same and displays
                    f=false;
                    cout<<"'\nName: "<<S.getName()<<"\nRollNo: "<<S.getRollNo()<<"\nClassRoom: \n"
                    <<S.getClassRoom()<<"\nFee: "<<S.getFee()<<endl;
                    cout<<"------------------------\n";
                }
            }
                if(f==true) //f is set to true if sudent is is found it becomes false if not this statement is printed
            {
                    cout<<"No student with name "<<name<<" found:\n\n";
                }
                
        } 
        void searchByRollNo(){//search by roll no
            bool f=true;
            string RollNo;
            system("cls");
            cout<<"Enter RollNo of student\n";
            cin>>RollNo;
        for(Student t:studentlist){
            if(RollNo==t.getRollNo()){//check if entered rollnumber matches a student and displays it
                f=false;
            cout<<"\nName: "<<t.getName()<<"\nRollNo: "<<t.getRollNo()<<"\nClassRoom: \n"
            <<t.getClassRoom()<<"\nFee: "<<t.getFee()<<endl;
            cout<<"------------------------\n";
        }
    }
            if(f==true){//same as before
                cout<<"No student with name "<<RollNo<<" found:\n\n";
                }
        }
        void searchByClassRoom(){//search by classroom
            bool f=true;
            string cls;
            cout<<"Enter Classroom of student\n";
            cin>>cls;
        for(Student t:studentlist){
            if(cls==t.getClassRoom()){//checks if entered classroom is same as student and displays
                f=false;
            cout<<"\nName: "<<t.getName()<<"\nRollNo: "<<t.getRollNo()<<"\nClassRoom: \n"
            <<t.getClassRoom()<<"\n Fee: "<<t.getFee()<<endl;
            cout<<"------------------------\n";
        }
    }
                if(f==true){//same as before
                cout<<"No student in Classroom "<<cls<<" found:\n\n";
                }
        }
    };
    




int main(){
    StudentList s,st;//an object of studentlist class
//  Student st;//an object of student class
    int selection;
    while(true){ //used for always being in a menu
        back:
            system("cls");
    cout << "\n\n\n\n\t\t\t\t\tWelcome To The Fee Managtment system\t\t\t\t\n\n\n\n";
        cout<<"\n\nSelect an option\n------------------"<<endl;
        st.selectionSheet();
        cin>>selection;
        switch(selection){//used for different cases
        case 1:
            while(true){//this loop used to being in case1 menu untill exit by user
        here:
            int selection;
            st.manageData();//shows the managedata menu
            cin>>selection;
        
            
            switch(selection){//managedata menu list
                case 1:
                s.addStudent();//for addin student
                    break;
                case 2: 
                s.updateData();//for updating student
                    break;
                case 3:
                    s.getStudentList();//for getting studentlist
                    break;
                case 4:
                s.deleteData();//deleting student
                    break;
                case 5:
                    goto back;//exits this menu and goes to back in main menu
                break;
                default:
                cout<<"Select a proper option\n";//this is run if different case is selected
            }
        
            
        }
        case 2:
            while(true){//same as above
        int selection;
        st.search();//shows search menu
        cin>>selection;
        switch(selection){
            case 1:
                s.searchByName();//calls by name function
                break;
            case 2:
                s.searchByRollNo();//calls by rollno function
                break;
            case 3:
                s.searchByClassRoom();//calls by classroom function
                break;
            case 4:
                goto back;//exits this menu back to main menu
            break;
        }
        
    }
        case 3:
            while(true){//same as above
            int selection;
        st.Reports();//shows reports menu
        cin>>selection;
        switch(selection){
            case 1:
                s.getStudentListReport();//shows the report of students
                break;
            case 2:
                s.getStudentListReport();
                break;
            case 3:
                goto back;//exits this menu
                break;
            default:
                cout<<"Select a valid option\n";
        }   
        
    }
        case 4://case4 of main menu
            goto out;//exits the main menu and ends the program
        break;
        default:
            cout<<"Select a valid option\n";
            goto out;//exits the main menu and ends the program
    }
    

    if(selection==-1){
        out:    
            cout<<"The program ended:";
        break;
    }
    }
    
    return 0;
}

displaying method start from line 34 in this code. I only want to show the data of student who have highest fees stored in list or all the student data but in that order where higest fee student comes first