mercredi 30 septembre 2020

C++11 uniform initialization: ambiguity between initializer list and multiple-parameter constructors?

Currently trying to wrap my head around C++11's uniform initialization. I came upon this ambiguous case: consider a class which can either be constructed from either a two-argument constructor or an initializer list of any length:

class Foo {
  public:
    Foo(int a, int b) {
      std::cout << "constructor 1" << std::endl;
    }
    Foo(std::initializer_list<int>) {
      std::cout << "constructor 2" << std::endl;
    }
};

Following uniform initialization convention, I'd expect the following to work:

Foo a (1, 2) prints constructor 1 (duh)

Foo b {1, 2} prints constructor 1

Foo c = {1, 2} prints constructor 2

However, it seems like the compiler interprets Foo b {1, 2} as a list initialization, and calls constructor 2. Is the () syntax the only way to force the compiler to consider other kinds of constructors when an initializer-list constructor is present?

How correctly read data from file and insert to linked list in c++? [duplicate]

I have a file with numbers in a file( one number per line), and I need to insert it to the linked list, but I think the error (libc++abi.dylib: terminating with uncaught exception of type std::invalid_argument: stoi: no conversion Abort trap: 6) is happening because of the conversion function

void MyLinkedList::addFront(const int& elem){
some code
}
void MyLinkedList::loadData(string path)
{
    
    ifstream infile;
    //string path;
    infile.open("file1.txt");
    Node *current = head;
    

    while(!infile.eof())
    {
    getline(infile, path);
    cout << path<<endl;
    int a=stoi(path);
    addFront(a);
    
    //current->elem = stoi(path);
    //current=current->next;
    }
    infile.close();
    
}

my addFront function works correctly, but i think it reads empty string and crushes. What should i do, Thanks in advance!

draw shifts in QGraphicsView

I have a weird shift when I draw in a QGraphicsView object,

enter image description here

The black square with inner red squares should be drawn in the upper left corner.

The .ui file :

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>600</width>
    <height>600</height>
   </rect>
  </property>
  <property name="sizePolicy">
   <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
    <horstretch>0</horstretch>
    <verstretch>0</verstretch>
   </sizepolicy>
  </property>
  <property name="windowTitle">
   <string>Wator</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <layout class="QGridLayout" name="gridLayout">
    <item row="0" column="0">
     <widget class="QScrollArea" name="scrollArea">
      <property name="widgetResizable">
       <bool>true</bool>
      </property>
      <widget class="QWidget" name="scrollAreaWidgetContents">
       <property name="geometry">
        <rect>
         <x>0</x>
         <y>0</y>
         <width>580</width>
         <height>536</height>
        </rect>
       </property>
       <layout class="QGridLayout" name="gridLayout_2">
        <item row="0" column="0">
         <widget class="QGraphicsView" name="graphicsView"/>
        </item>
       </layout>
      </widget>
     </widget>
    </item>
   </layout>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>600</width>
     <height>22</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>

How .ui looks like in designer mode : enter image description here

And finally, the code in MainWindow that I draw from :

#include "Mainwindow.hpp"
#include "ui_mainwindow.h"
#include "Environment.hpp"
#include <iostream>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    scene = new QGraphicsScene();
    ui->graphicsView->setScene(scene);
    scene->setBackgroundBrush(QColor(0, 0, 255));

    grid_pen = QPen(Qt::black);

    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(drawEnvironment()));
    timer->start(1000);
    tick = 0;

    initializeEnvironment();

    QRect rcontent = ui->graphicsView->contentsRect();
    ui->graphicsView->setSceneRect(0, 0, rcontent.width(), rcontent.height());
    ui->graphicsView->setFixedWidth(50 * environment->getWidth());
    ui->graphicsView->setFixedHeight(50 * environment->getHeight());
    ui->graphicsView->setInteractive(false);
    drawEnvironment();
}

void MainWindow::initializeEnvironment(){
    this->environment = new Environment(10, 10);

    std::vector<Agent*> agents;
    for(uint32_t i = 0; i < 20; i++){
        agents.push_back(new Agent());
    }

    this->environment->placeAgents(agents);
}

void MainWindow::drawEnvironment(){
    scene->clear();
    scene->addRect(0, 0, ui->graphicsView->width(), ui->graphicsView->height(), grid_pen, ocean_brush);
    uint16_t cell_width = 50;
    uint16_t cell_height = 50;
    std::vector<Agent*> agents = environment->getAgents();
    for(uint16_t i = 0; i < agents.size(); i++){
        uint16_t x = agents[i]->getX();
        uint16_t y = agents[i]->getY();
        QBrush agent_brush(agents[i]->getColor());
        scene->addRect(x * cell_width, y * cell_height,cell_width, cell_height, grid_pen, agent_brush);
        std::cout << "(" << x << ";" << y << ")" << std::endl;
    }
    tick++;
}

MainWindow::~MainWindow()
{
    delete timer;
    delete environment;
    delete scene;
    delete ui;
}

I verified the coordinates of my Agents, and they are indeed between 0 and 10, so the squares should be drawn in [0; 500]px. What could cause such issue ?

Error comes out with precision, how can I get rid from this? [duplicate]

Answer comes wrong when using decimal places!

I'm running the following program:

#include<stdio.h>

#include<math.h>

main()

{

float x,y,div;

printf("Enter two numbers x,y \n");

scanf("%f%f",&x, &y);

div=x/y;

printf("div=%12.10f\n",div;

return 0;

}

After running, when I put x=1 and y=3 then answer comes 0.3333333433, but answer should be 0.3333333333. Why this error comes ? How can I get rid from this kind of error ? Please help.

passing a temporary lambda by const std::function reference should fail but seems to work

This is a simplified version of what I am doing:

#include <iostream>
#include <functional>

class thing
{
public:
    void register_fn(const std::function<void()> &fn)
    {
        m_fn = fn;
    }
    void run()
    {
        m_fn();
    }
    std::function<void()> m_fn;
};

int main() {

    // Create a thing object
    thing t;

    // In a limited scope
    {
        // Local lambda
        auto afn = []{std::cout << "hi\n";};
        // Store the lamda by reference
        t.register_fn(afn);
    }

    // Run the stored lambda (which should be destroyed - therefore dangling reference??)
    t.run();

    // Take a copy
    thing t2 = t;
    t2.run();

    return 0;
}

see it running here: https://godbolt.org/z/6qW3ro

So, I have a class that stores a temporary lambda passed by reference. The lamda afn's scope is limited so that once it is passed to the register function it goes out of scope. Then outside of this scope I call the run function which should be running the (dangling?) reference to the lambda.

This has been working, but recently looking back at my code I have a doubt. Since the lambda is temporary (done here by limiting the scope of my lambda object afn) - this should not work... I can't quite get my head around why it is working - unless by luck and this is undefined behaviour?

Or... what have I mis-understood here? - because that is probably the most likely explanation!

How to assign a default (empty) value to the reference of a std::unordered_map in the declaration of a function?

I have a question, I've been doing some googling but I can't find a solution (yet).

I have a function that may / or may not receive a value of type std::unordered_map, as I indicate, on some occasions this std::unordered_map will be received empty and no processing of any kind will be executed on it, to achieve this, I assigned a value by default in declaration, like this:

bool existence_checker(const std::string& = "", std::unordered_map<std::string,std::string> = {});

Declaring the function as indicated does not present any errors, since as far as I know (and would like opinions), a std::unordered_map can be assigned as empty in the same way as a std::vector.

The problem arises when I want to assign a default value to the reference of the std::unordered_map, I have done some tests with some answers found in google, but have not been successful. Something like this:

bool existence_checker(const std::string& = "", std::unordered_map<std::string,std::string>& = {});

The error it throws is: error: could not convert ' ()' from '' to 'std :: unordered_map <std :: __ cxx11 :: basic_string , std :: __ cxx11 :: basic_string > & '|

In short: How can I assign a default (empty) value to the reference of a std::unordered_map in a function declaration?

PD. Thanks in advance and sorry for the bad English.

mardi 29 septembre 2020

How to handle Qthread termination during app quit()?

I've read many stackoverflow answers and a few blog posts(including QThread documentation as well) but I'm still not sure how to handle exiting main app while QThreads are still running(and not crash application meanwhile). What makes this difficult is the fact that those QThread instances contain different sorts of blocking functions such as curl queries, c++ file io etc making it hard to use isInterruption requested api(which I would've used in an ideal case). To top that, I've to make sure these work fine across Linux, Windows and OSX. We can assume here any file io corruption or incomplete network queries don't worry us and are taken care of. Here is the whole working example zipped. I use Qthreads two different ways which I'll demonstrate here and the general idea is to bind application's aboutToQuit() with thread's terminate() assuming that this is safe since the app is going to close anyway -


  1. Worker/Controller

     class Worker : public QObject
     {
         Q_OBJECT
     public slots:
         void doWork(const QString &msg) { QThread::sleep(10); emit resultReady("Finished"); }  // simulates thread doing work
     signals:
         void resultReady(const QString &result);
     };
    
     class Controller : public QObject
     {
         Q_OBJECT
         QThread workerThread;
     public:
         Controller() {
             Worker *worker = new Worker;
             worker->moveToThread(&workerThread);
             connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater);
             connect(this, &Controller::operate, worker, &Worker::doWork);
             connect(worker, &Worker::resultReady, this, &Controller::handleResults);
             connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()), this, SLOT(terminateThread()));
             workerThread.start();
         }
         ~Controller() { workerThread.quit(); workerThread.wait(); }
     public slots:
         void handleResults(const QString &msg);
         void terminateThread() { workerThread.terminate(); workerThread.wait(); }
     signals:
         void operate(const QString &msg);
     };
    
     // can be started like
     Controller c;
     emit c.operate("Starting Thread");
    

  1. Method run() override

     class WorkerThread : public QThread
     {
         Q_OBJECT
         void run() override { QThread::sleep(10); emit resultReady("Finished");}
    
         signals:
         void resultReady(const QString &s);
    
     public slots:
         void terminateThread() { workerThread.terminate(); workerThread.wait(); }
     };
    
     class MyObject : public QObject {
         Q_OBJECT
    
     public slots:
         void handleResults(const QString &msg);
     public:
         void startWorkInAThread() {
             WorkerThread *workerThread = new WorkerThread();
             connect(workerThread, &WorkerThread::resultReady, this, &MyObject::handleResults);
             connect(workerThread, &WorkerThread::finished, workerThread, &QObject::deleteLater);
             connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()), workerThread, SLOT(terminateThread()));
             workerThread->start();
         }
     };
    
     // can be started like
     MyObject obj;
     obj.startWorkInAThread();
    

and I test both of these methods using main() that looks like -

    QCoreApplication a(argc, argv);
    std::puts("Starting app");
    //    Controller c;
    //    emit c.operate("Starting Thread");

    MyObject obj;
    obj.startWorkInAThread();

    QTimer::singleShot(2000, [&]{
        std::puts("Quit pressed");
        a.quit();
    });
    return a.exec();

Now the issues -

  1. If I use Controller method, Linux gives some error message about exception not being caught while exiting. That message goes away if I remove .wait() calls but those are supposedly necessary. Windows exits fine but the return code is some negative large number. OSX crashes the application, maybe due to .wait() call.

     Qt has caught an exception thrown from an event handler. Throwing
     exceptions from an event handler is not supported in Qt.
     You must not let any exception whatsoever propagate through Qt code.
     If that is not possible, in Qt 5 you must at least reimplement
     QCoreApplication::notify() and catch all exceptions there.
    
     (process:3416): GLib-CRITICAL **: 22:45:51.656: g_source_unref_internal: assertion 'source != NULL' failed
    
  2. If I use run() overriding, Linux works perfectly fine and so does OSX. On Windows the program never finishes, stuck on .terminate() call or if I remove that then on .wait() call.

  3. There are also some usages(in actual application, not in given examples) where the run() overriding is used but the run method's owner class is initialized as - WorkerThread *workerThread = new WorkerThread(this); and due to this being setup as it's parent, it crashes the program on exit somehow.

  4. I actually don't want to wait on threads and want them to exit asap when my program quits, some blocking network operations could take several minutes to complete.


I suppose I've explained everything in detail but to summarize, I want my app to quit gracefully with running background threads and not crash at all. And do this on all supported(mentioned) QT platforms.

What is a common 'map frame'?

I'm going through pcl's tutorial on How to incrementally register pairs of clouds and I came across the following sentence in the introduction:

Your data set should consist of clouds that have been roughly pre-aligned in a common frame (e.g. in a robot’s odometry or map frame) and overlap with one another.

What do they mean by a common map frame?

I'm going to be using an input from a depth cam/lidar which will provide me with a consecutive depth frames at 30fps, is each pair of following depth frame already in a common map frame?

If not, what is the process of combining them into such?

Recursive variadic template specialization

My target is to define a Recursive class, templated on an int N and one or more types T, ...Ts, which should behave like a std::pair with

  • a std::array of N items of type T as the first,
  • and, as second, an optional std::vector of Recursive instances templated on the same N and on the remaining template arguments Ts....

In trying to write down the class given the above requirements, I've come up with this non-working code (where I've also defined some necessary, as they help a lot, aliases for two instantiations of Recursive), and I don't know if I have mis-designed what I described above (or if it is an ill-formed description!), or if I'm misusing the language syntax.

#include <array>
#include <boost/hana/fwd/optional.hpp>
#include <boost/hana/optional.hpp>
#include <string>
#include <utility>
#include <vector>

template <int N, typename T1, typename T2, typename ...Ts>
struct Recursive : std::pair<std::array<T1, N>,
                             boost::hana::optional<std::vector<Recursive<N, T2, Ts...>>>
                            > {};

template <int N, typename T>
struct Recursive<N, T> : std::array<T, N> {};

template<typename ...T>
using Recursive2 = Recursive<2u, T...>;

template<typename ...T>
using Recursive3 = Recursive<3u, T...>;

int main() {
    Recursive2<int> x(std::make_pair(std::array<int, 2>{0,0}, boost::hana::nothing));
}

Unable to delete an object from heap allocated array

I am a beginner, and I want to delete an item from an array, non-STL.

This doesn't seem possible? Below. So, out of share curiosity, how can I delete or remove an item from a regular array, I am not using STL. I want to know how this can be done with one dynamic array that's been allocated on the HEAP.

Object here can be a random class e.g. a Monster class.

#include <iostream>

int main()
{
    int size = 10;
    Object* o = new Object[size];
    
    for(int i = 0; i<size; i++){
        o[i] = new Object("Monster " + i);
    }
    
    for(Object* ptr = o; ptr!=o+size; o++){
        delete ptr;
    }
}

_CrtSetDbgFlag not working as expected: returns NULL

I have added below lines of code in application :

#define _CRTDBG_MAP_ALLOC
#include
#include <crtdbg.h>
#ifdef _DEBUG
#define DEBUG_NEW new(_NORMAL_BLOCK, FILE, LINE)
#define new DEBUG_NEW
#endif

and

HANDLE hLogFile;
hLogFile = CreateFileA("c:\\memoryLeaksDump.txt", GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, hLogFile);
_CrtSetReportFile(_CRT_ERROR, hLogFile);
_CrtSetReportFile(_CRT_ASSERT, hLogFile);

_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

i don't see any memory leaks detected in the output file. I see below lines printed:

(null)(-1) : atlTraceGeneral - Error 1 in XML File

Can someone me out in resolving the issue and help me in getting the memory leaks

Classes and code throwing errors and strange unexpected behavior

I am working on a tiny project. And I am running into some issues, I've been trying to figure this out for weeks now. But, I finally decided to come to SO, and post this here. I am trying to get two of my functions to work properly:

Remove(...) and SearchWithName(...), I am using the C++ Range-based for loops. But, the Remove doesn't delete the pointer of Employee in Array. I get some memory thrown error. And for some reason, even if names match, or don't match I still get matched. Strange. I am trying to make it partially match or full match.

class Employee {
    
public:
    Employee() = default;
    Employee(std::string name, std::string address);
    
    std::string getName() { return this->name; }
    std::string getAddress() { return this->address; }
    
private:
    std::string name = "";
    std::string address = "";
    
};

class EmployeeArray {
public:
    EmployeeArray(int max) : max(max) {
        employees = new Employee[max];
    }
    
    void remove(Employee* e) {
        for(Employee* ee=employees; ee!=employees + current_total; ++ee)
        {
            if(ee == e){
                delete ee;
                ee = nullptr;
                current_total--;
            }
        }
    }
    
    Employee* SearchWithName(std::string name) {
        for(Employee* e = employee; e!=employees + current_total; ++e)
        {
            if(e->getName() == name)
            {
                return e;
            }
        }
        
        return NULL;
    } 
    
private:
    Employee* employees;
    int max = 0;
    int current_total = 0;
}

int main(){
    
    EmployeeArray* empArr = new EmployeeArray[2]
    {
        Employee("Richard Johnson", "1801 E 10th St Pueblo, CO 81001"),
        Employee("David Paras", "15 Spring St Rear Peabody, MA 01960"),
    }
    
    std::cout << (empArr->SearchWithName("lol") != NULL ? "Employee found!" : "This employee couldn't be found!") << std::endl;
    
    empArr->remove(*(Employee("Richard Johnson", "1801 E 10th St Pueblo, CO 81001"))));
    
    return 0;
}

lundi 28 septembre 2020

Reading from a file and into a dynamically allocated array of type Student in C++

So this is an assignment revolving around fstreams and struct's, I have a decent understanding of fstreams and struct's (I thought), but for some reason I can't figure out what's wrong with my code. The file I'm reading from starts with an integer 'n' that represents the amount of students in the file, it's then used as the size of the dynamically allocated array of Students.

I go on to read each name, major, and grade from the file into the array of type Student. But for whatever reason it's only reading the first "line" in the file (as in it reads the first name, major, and grade), and does that n times. I messed around with the code and I believe I've narrowed the problem down to the array not actually being of size n. It correctly reads the first int in the file as I've printed it out to make sure that's working, and I've tried manually reading in each Student for the array from the file with the same issues.

This is an assignment so I'm not looking for any straight forward answer, but a nudge in the right direction would be incredibly helpful. Thanks in advance!

Here's a link to my code, and also the input file I'm reading from.

[[carries_dependency]] what it means and how to implement

I was reading about [[carries_dependency]] in this SO post.

But what I could not understand is the below sentences in the accepted answer :

"In particular, if a value read with memory_order_consume is passed in to a function, then without [[carries_dependency]], then the compiler may have to issue a memory fence instruction to guarantee that the appropriate memory ordering semantics are upheld. If the parameter is annotated with [[carries_dependency]] then the compiler can assume that the function body will correctly carry the dependency, and this fence may no longer be necessary.

Similarly, if a function returns a value loaded with memory_order_consume, or derived from such a value, then without [[carries_dependency]] the compiler may be required to insert a fence instruction to guarantee that the appropriate memory ordering semantics are upheld. With the [[carries_dependency]] annotation, this fence may no longer be necessary, as the caller is now responsible for maintaining the dependency tree."

Lets take it step by step:

"if a value read with memory_order_consume is passed in to a function, then without [[carries_dependency]], then the compiler may have to issue a memory fence instruction to guarantee that the appropriate memory ordering semantics are upheld."

So for an atomic variable in release-consume memory model when atomic variable is being passed as a parameter to the function the compiler will introduce a fence hardware instruction so that it always has the latest and updated value of the atomic variable provided to the function.

Next -

"If the parameter is annotated with [[carries_dependency]] then the compiler can assume that the function body will correctly carry the dependency, and this fence may no longer be necessary."

This is confusing me - the atomic variable value is already consumed and then what dependency the function is carried?

Similarly -

"if a function returns a value loaded with memory_order_consume, or derived from such a value, then without [[carries_dependency]] the compiler may be required to insert a fence instruction to guarantee that the appropriate memory ordering semantics are upheld. With the [[carries_dependency]] annotation, this fence may no longer be necessary, as the caller is now responsible for maintaining the dependency tree."

From the example its not clear what the point it is trying to state about carrying the dependency?

error: expected unqualified-id before numeric constant with boost library [closed]

hi guys i just installed boost libraries and built them and linked them to code:: blocks so in order to check if everything is working out I wrote a simple code to check for the existence of a text file . however, there is a strange error that I encountered i think it is related to the "boost" keyword cause the error happens in only the lines that contain "boost"

  #include <iostream>
#include <string>
#include<boost/filesystem.hpp>
using namespace std;

int main () {

cout<<"hello people , please help me out ."<<endl;

cout<<"test if \"d:\Array.txt\" exist"<<endl;
boost::filesystem::path 1_path("d:\Array.txt");

if(::filesystem::exists (1_path)){
    cout<<"the file exists !"<<endl;
}

}

How to define the value type for iterator which points to an element in another container in c++

The purpose I want to achieve is that: I have an unordered_map<int, list<int>::iterator> mp and a list<int> lst. How can I store the iterator of an element in lst. And later, by using the iterators in map, I can manipulate (e.g.,erase) the element in the list. (Assume free of iterator invalidation problem) The following snippet won't work:

unordered_map<int, list<int>::const_iterator> mp;
list<int> lst;
lst.push_back(1);
mp[1]=lst.crbegin(); //error here
lst.erase(mp[1]);
...

I have also tried to store raw pointers, but I was not able to erase an element in the list by using a raw pointer. I was wondering what is the best way to fulfill my purpose.

How can I alter an array from inside a function in C++

I am trying to write a c++ rk4 algorithm and I seem to be running into the same error no matter what I try. I can compile the program but I keep getting a zsh: segmentation fault (core dumped) ./main. I believe that the problem is within the rk4 function here:

void funcs::rk4(double *p_vec, double h)
{

    double *k0, *k1, *k2, *k3, *l0, *l1, *l2;


    k0 = force( p_vec );

    for ( int inst = 0; inst < 2; ++inst )
    {
        l0[ inst ] = p_vec[ inst ] + h*( k0[ inst ] );
    }

    k1 = force( l0 );

    for ( int inst = 0; inst < 2; ++inst )
    {
        l1[ inst ] = p_vec[ inst ] + ( h/2 ) * ( k1[ inst ] );
    }

    k2 = force( l1 );

    for ( int inst = 0; inst < 2; ++inst )
    {
        l2[ inst ] = p_vec[ inst ] + ( h/2 ) * ( k2[ inst ] );
    }

    k3 = force( l2 );

    for ( int inst = 0; inst < 2; ++inst )
    {
        ( p_vec )[ inst ] += ( ( k0[ inst ] ) + 2*( k1[ inst ] ) + 2* ( k2[ inst ] ) + ( k3[ inst ] ) )*( h/6 );

    }

}

Here is the main function as well if that helps:

#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include "functions.h"

using namespace std;

int main( int argc, char **argv )
{
    float alpha = 0, beta = 1;
    int Number = 1000;
    double h = ( beta - alpha )/ Number;
    double postiton_0 = 1.0, velocity_0 = 0.0;

    vector<double> time = funcs::linspace( alpha, beta, Number );
    double p_vector[2] = { postiton_0, velocity_0 };

    for ( int inst = 0; inst <= Number; ++inst )
    {
        funcs::rk4( p_vector, h );

        cout << inst << ", " << p_vector[ 0 ]
            << ", " << p_vector[ 1 ] << endl;
    }

    return 0;

}

Thank you very much in advance!

Got undefined reference calling template function passing function pointer as a argument [duplicate]

I am write thread pooling code but when i compiled its show ' undefined reference to `std::future<decltype ({parm#1}({parm#2}...))> ThreadPool::enqueue<void* (&)(void*), void*>(void* (&)(void*), void*&&)'' as a error.

I mentioned function declaration, definition, and calling below.

Declaration:-

template<typename F, typename...Args> auto enqueue(F&& f, Args&&... args) -> std::future<decltype(f(args...))>;

Definition:-

template<typename F, typename...Args>
auto ThreadPool::enqueue(F&& f, Args&&... args) -> std::future<decltype(f(args...))>
 {
std::function<decltype(f(args...))() > func = std::bind(std::forward<F>(f), std::forward<Args>(args)...);
auto task_ptr = std::make_shared < std::packaged_task<decltype(f(args...))()>>(func);
std::function<void() > wrapper_func = [task_ptr]()
{
  (*task_ptr)();
};
mTasks.emplace(wrapper_func);
// debugLog->PrintLog("Inside Thread pool enqueue, function insert new function call\n");
cv.notify_one();
return task_ptr->get_future();

}

Calling:-

thread_pool->enqueue(fnReceive,(void *) sThreadStruct1);

I got the above error at calling and fnReceive is used by the thread pool to process.

Kindly help me to resolve this error.

Thanks and Regards, Vivek Singh

zip command issue on linux

I have a zip command issue on Linux.

  1. From command prompt:

    zip -r /../../../tst.zip /../../../tst/json
    creates tst.zip file.

    unzip tst.zip is successful.

  2. With in c++ code:

    char zipcommand[sqglobal::MAX_SQ_FILE_PATH_LENGTH]={0};
    sprintf (zipcommand, "zip -r %s %s", "/../../../tst.zip", 
                                         "/../../../tst/json");
    system(zipcommand);
    

from command prompt, unzipping the zip file generated by code fails.

[root@localhost bin]# unzip SoftwareInventory.zip
Archive:  SoftwareInventory.zip
file #1:  bad zipfile offset (local header sig):  0
[root@localhost bin]#

The size of json file is 1260 Bytes. zip file size is 522 bytes.

Why unzip fails? what the error implies?

field ‘ifru_addr’ has incomplete type ‘sockaddr’

I am doing the Standford CS144 lab, but the code cannot make

In file included from /home/wangyan/csLab/sponge/libsponge/util/tun.cc:7:
/usr/include/linux/if.h:211:19: error: field ‘ifru_addr’ has incomplete type ‘sockaddr’ 
struct sockaddr ifru_addr;

I try the others recommend,add the code

#include <sys/socket.h>

It still doesn't work

What is the time complexity of the following code fragment for Stock Buy & Sell?

Recently I was trying the problem of Stock Buy and Sell in which we can buy a stock on any day and sell it on any upcoming day, and we have to find the maximum profit that we can get.

The solution that first came to my mind was the code below but I'm not able to determine its time complexity. It would be very helpful if you can help with this.

int maxProfit(int price[], int start, int end){
  if(end<=start)
    return 0;

  int profit=0;

  for(int i=start; i<end; i++){

    for(int j=i+1; j<=end; j++){

      if(price[j]>price[i]){

        int curr_profit=price[j]-price[i]+maxProfit(price,start,i-1)+maxProfit(price,j+1,end);
        profit=max(profit,curr_profit);
      }
    }

    return profit;
  }
}

Trailing return type in non-template functions [duplicate]

I have seen people using the following syntax to implement functions:

auto get_next() -> int 
{
   /// ...
}

Instead of:

int get_next()
{
   /// ...
}

I understand both and I know that the trailing return type syntax is useful for template code using decltype. Personally I would avoid that syntax for other code since when reading code I prefer to read the concrete return type of a function first, not last.

Is there any advantage in using the trailing return type syntax for non-template code as shown above (except personal preference or style)?

dimanche 27 septembre 2020

std::sort function is not sorting a vector, and I don't know why?

I have written a code to implement the quicksort algorithm in c++, it is working but the std::sort() function is not working at all. Please explain to me why.

#include "header.h"

using namespace std;
using namespace std::chrono;
bool myfunction (int i,int j) { return (i<j); }
int Partition(vector<int>& A, int start, int end){
    int pivot_idx = (rand() % (end - start + 1)) + start;
    Xswap(A[pivot_idx], A[end]);
    int pivot = A[end];
    int P_index = start;
    for(int i=start; i < end; i++){
        if(A[i] <= pivot){
            Xswap(A[i], A[P_index]);
            P_index++;
        }
    }
    Xswap(A[P_index], A[end]);
    return P_index;
}

void Qsort(vector<int>& A, int start, int end){
    if(start < end){
        int middle = Partition(A, start, end);
        Qsort(A, start, middle-1);
        Qsort(A, middle+1, end);
    }
}

void quick_sort(void){
    srand(time(NULL));
    int n;
    cin >> n;
    vector<int> v;
    v.reserve(n);
    //v.shrink_to_fit();
    
    for(int i=0; i<n; i++)
        v[i] = rand() % 1000;
    
    /*for(int i=0; i<n; i++)
        cout << v[i] << " ";
    cout << endl << endl;*/
    auto start = high_resolution_clock::now(); 
    
    //Qsort(v, 0, n-1);
    sort(v.begin(), v.end(), myfunction);
    
    auto stop = high_resolution_clock::now(); 
    auto duration = duration_cast<microseconds>(stop - start);
    for(int i=0; i<n; i++)
        cout << v[i] << " ";
    cout << endl;
    cout << duration.count() << endl; 
}

If you want to know what output is being shown upon calling executing the snippet: Program output

And if you want to see the contents of the header file:

#ifndef HEADER_H
#define HEADER_H

#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <vector>
#include <chrono>
#include <time.h>
void bble_sort(void);
void improved_bble_sort(void);
void quick_sort(void);
void ins_sort(void);
void Qsort(std::vector<int>& A, int start, int end);

template <typename T>
void Xswap(T& a, T& b);

#endif /* HEADER_H */

The vector in the output is completely unsorted; I have tried range-based for loop and iterators but nothing helped out. Please provide me some solutions or ideas, I'm completely confused.

undefined symbol: typeinfo error when returning shared ptr from virtual function

ld.lld: error: undefined symbol: typeinfo for <derived classname>

Why am I getting this error for the following code?

base::getABC is never called directly. If I remove the definition of the virtual destructor I get an error about it.

class Base {
public:
 virtual const std::shared_ptr<ABC>  getABC() noexcept {
    return nullptr;
  }

  virtual ~Base() {
  }
};

class derived: public base {
 const std::shared_ptr<ABC> getABC() noexcept override {
   return abc_;
  }
};

Can you update the g++ command to compile with c++11 by default?

I'm new to c++ programming, and I'm also using emacs to write code in instead of using an IDE because my friend said getting comfortable with terminal and emacs will benefit me later on.

That said, I have to constantly compile my programs in the terminal using "g++ <file_name_here>" It's been great until today, when trying to learn vectors.

Here is the problem I ran into when I tried to compile like this: ~/Documents/cpp/cpp_practice master ?5 > g++ vector_prac_1.cpp

vector_prac_1.cpp:16:27: error: expected ';' at end of declaration
  vector <int> test_scores {100, 98, 89, 85, 93}; // you can also initialize elements just like array
                          ^
                          ;

Then after looking around I decided to try to compile with "g++ -std=c++11 vector_prac_1.cpp" And it worked with no problems.

So should I just compile everything with "g++ -std=c++11 <file_name_here>" from now on? Or is there a way to change something so I'm always compiling that way by default?

What is the easiest way to emulate a 'has focus' box around a wxButton?

I have a dialog and at the bottom a normal box sizer with 3 buttons in it. When I do

m_buttonCancel->SetDefault();

the code works in the sense that pressing enter does cancel, but there is no visual clue that this is the default button. I would like the button to have a rectangle around it, similar to when I say

m_buttonCancel->SetFocus();

Problem is: other widgets often have the focus, like wxTextCtrl widgets in the dialog. Then this focus border around the button disappears, but I would like it to stay. Of course, I could put this button in a panel and set the border style, but then the size of this button would be different from the others or I must put these in separate panels also (but without border).

There must be an easier way to draw a border around a button, without changing the size of any button and without affecting the layout?

OS: CentOS, so wxWidgets uses Gtk.

wxWidgets pprogrammaticaly move to next input control

I originally had code that set the focus to the first widget in a dialog, in the onInit method. But there were problems with it: if I pressed TAB, indeed focus moved to next control (wxTextCtrl), which got the blue 'focus' color, but the 'focus' color/highlight was not removed from previous focus widget. So now it looked like both first and second control had focus at the same time...

When cycling manually (by pressing TAB) full circle (till last control and then wrap around to the first), suddenly all worked well. That is, when moving focus from first control to next one, the first visually lost focus (blue color was removed) as it should. From now on, only one item had the focus color/highlight.

So instead of setting focus on the first control, I tried a different approach: I set the focus to the last control in the dialog, which is always the OK button. Next, I want to emulate programmatically that a TAB is pressed and received by the dialog. So I wrote this (inside Dialog::onInit):

    m_buttonOK->SetFocus();
    wxKeyEvent key;
    key.SetEventObject(this);
    key.SetEventType(wxEVT_CHAR);
    key.m_keyCode=WXK_TAB;
    ProcessWindowEvent(key);

Now the focus indeed moves away from the OK button, but it does not wrap around to the first control. Only when I manually press TAB after the dialog opened, the first item gets focus.

Question: why does this wrapping around to set focus on first widget not work with the code shown above?

On the full double range std::uniform_real_distribution always returns inf

Consider the following minimal example:

#include <random>
#include <iostream>

int main (const int argC, char* argV[] ) {
    std::uniform_real_distribution<double> dist(std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max());
    std::random_device gen;
    std::cout << dist(gen) << std::endl;
    return 0;
}

I would expect the program to print basically any number in the range of double. However on my machine the output is always inf. The same is true if I replace double by float.

I can easily imagine how this can happen by a faulty implementation of std::uniform_real_distribution, as e.g. the length of the interval from which the numbers are drawn is not representable as a double. However my question is, is this indeed a bug in my standard library implementation, or did I miss some some restriction on the interval allowed by the C++ standard?

Undefined symbols for architecture x86_64: vtable

I'm doing a c++ project where I implemented my own Hash Table. Then I try to use this hash table and when intializing this, I got error at build stage from linker.

Undefined symbols for architecture x86_64:
  "bustub::LinearProbeHashTable<unsigned long, bustub::TmpTuple, bustub::HashComparator>::Insert(bustub::Transaction*, unsigned long const&, bustub::TmpTuple const&)", referenced from:
      bustub::HashJoinExecutor::Init() in hash_join_executor.cpp.o
      vtable for bustub::LinearProbeHashTable<unsigned long, bustub::TmpTuple, bustub::HashComparator> in hash_join_executor.cpp.o
  "bustub::LinearProbeHashTable<unsigned long, bustub::TmpTuple, bustub::HashComparator>::Remove(bustub::Transaction*, unsigned long const&, bustub::TmpTuple const&)", referenced from:
      vtable for bustub::LinearProbeHashTable<unsigned long, bustub::TmpTuple, bustub::HashComparator> in hash_join_executor.cpp.o
  "bustub::LinearProbeHashTable<unsigned long, bustub::TmpTuple, bustub::HashComparator>::GetValue(bustub::Transaction*, unsigned long const&, std::__1::vector<bustub::TmpTuple, std::__1::allocator<bustub::TmpTuple> >*)", referenced from:
      bustub::HashJoinExecutor::Next(bustub::Tuple*) in hash_join_executor.cpp.o
      vtable for bustub::LinearProbeHashTable<unsigned long, bustub::TmpTuple, bustub::HashComparator> in hash_join_executor.cpp.o
  "bustub::LinearProbeHashTable<unsigned long, bustub::TmpTuple, bustub::HashComparator>::LinearProbeHashTable(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, bustub::BufferPoolManager*, bustub::HashComparator const&, unsigned long, bustub::HashFunction<unsigned long>)", referenced from:
      bustub::HashJoinExecutor::HashJoinExecutor(bustub::ExecutorContext*, bustub::HashJoinPlanNode const*, std::__1::unique_ptr<bustub::AbstractExecutor, std::__1::default_delete<bustub::AbstractExecutor> >&&, std::__1::unique_ptr<bustub::AbstractExecutor, std::__1::default_delete<bustub::AbstractExecutor> >&&) in hash_join_executor.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[2]: *** [lib/libbustub_shared.dylib] Error 1
make[1]: *** [src/CMakeFiles/bustub_shared.dir/all] Error 2

My code to specify hash table type:

   using HashJoinKeyType = hash_t;
   using HashJoinValType = TmpTuple;
   using HT = LinearProbeHashTable<HashJoinKeyType, HashJoinValType, HashComparator>;

Value type is a class:

class TmpTuple {
 public:
  TmpTuple(page_id_t page_id, size_t offset) : page_id_(page_id), offset_(offset) {}

  inline bool operator==(const TmpTuple &rhs) const { return page_id_ == rhs.page_id_ && offset_ == rhs.offset_; }

  page_id_t GetPageId() const { return page_id_; }
  size_t GetOffset() const { return offset_; }

 private:
  page_id_t page_id_;
  size_t offset_;
};

There is my constructor for hash table

    template<typename KeyType, typename ValueType, typename KeyComparator>
    class LinearProbeHashTable : public HashTable<KeyType, ValueType, KeyComparator> {
    public:
        /**
         * Creates a new LinearProbeHashTable
         *
         * @param buffer_pool_manager buffer pool manager to be used
         * @param comparator comparator for keys
         * @param num_buckets initial number of buckets contained by this hash table
         * @param hash_fn the hash function
         */
        explicit LinearProbeHashTable(const std::string &name, BufferPoolManager *buffer_pool_manager,
                                      const KeyComparator &comparator, size_t num_buckets,
                                      HashFunction<KeyType> hash_fn);

I've been working on this for 3hrs and have no idea what to do, could anyone give me some insights/advice?

Are the following 3 ways to define objects identical?

When defining variables or objects, I notice there are three ways as follows.

What are the differences between the following?

Person p{};            // Case 1
Person p = Person{};   // Case 2
Person&& p = Person{}; // Case 3

How to install Boost library on Unix without root access? [duplicate]

I want to use the boost library on Unix to develop socket communication. However, I don't have root access to install the library. I have followed this thread but it still shows the library is not found. Can someone help me on how to install it without root access?

Vector.exe has triggered a breakpoint. CRT Detected. Heap Corruption Detected. Operator Assign not working properly

enter image description here

Vector.exe has triggered a breakpoint. enter image description here

Vector.h

#ifndef VECTOR_H

#include <cassert>
#include <cstring>

#include <iterator>
#include <initializer_list>

class Vector
{
public:
    Vector() : _capacity(1)
    {
        nums = new int[_capacity];
        validate();
    }

    Vector(std::initializer_list<int> numbers) 
        : _capacity(numbers.size())
    {
        nums = new int[_capacity];
        for(const int& i: numbers)
        {
            push_back(i);
        }

        validate();
    }

    virtual ~Vector()
    {
        validate();
        delete[] nums;
    }

    int size() const {
        return _size;
    }

    int capacity() const {
        return _capacity;
    }

    int* data() {
        return nums;
    }

    const int* data() const {
        return nums;
    }
    
    void push_back(int i) {
        if (_size >= _capacity)
            _capacity = _capacity * 2;

        nums[_size] = i;
        _size++;
        validate();
    }

    int& operator[](int i)
    {
        return nums[i];
    }

    const int& operator[](int i) const
    {
        return nums[i];
    }

    Vector& operator=(const Vector& v)
    {
        if (this == &v) return *this;

        delete[] nums;

        _capacity = v.capacity();
        _size = v.size();

        nums = new int[_capacity];
        std::memcpy(nums, v.data(), _capacity);

        return *this;
    }

protected:

    inline void validate() 
    {
        assert(_size <= _capacity);
    }

private:

    int* nums = nullptr;
    int _capacity = 0;
    int _size = 0;
};

#endif // !VECTOR_H

main.cpp

#include <algorithm>
#include <iostream>
#include "vector.h"

int main()
{
    Vector v1 = {0, 1, 2, 3, 4, 5, 6};
    Vector v2 = v1;

    for (int i = 0; i < v2.capacity(); ++i)
    {
        std::cout << v2[i] << std::endl;
    }

    return 0;
}

I am NOT sure, what's wrong with my operator= implementation. I want to be able to assign, and be able to delete the other object, and still be able to preserve, and delete the current object. I believe my operator= is correctly implemented, but not sure where it breaks exactly. I am unable to trace at the moment.

samedi 26 septembre 2020

std::make_unique invoking private ctro from friend class

I am seeing a behavior of std::make_unique while creating an object from friend class. Following is minimum reproducible example

#include<iostream>
#include<memory>

class A 
{
    friend class B;
    private: 
    A() = default;
};

class B 
{
    private: 
    std::unique_ptr<A> dPtr;
    public: 
    B() 
    {
        //dPtr = std::make_unique<A>(); // This is a compiler error
        dPtr = std::unique_ptr<A>(new A()); // This is working 
    }
};

gcc version 7.5.0 (Ubuntu 7.5.0-3ubuntu1~18.04)

What i understand that std::make_unique is a template function which is not actually fried with class A. How can i make std::make_unique a friend function of class A so that std::make_unique work in my example?

Why is rvalue reference to an integer legal

This might be a dumb question about C++11 but it really bothers me.

As my understanding, rvalue reference is also a reference, which means that it will algo point to some variable, just like the reference does.

For example,

const int &ref = 1;

The reference ref points to the pure rvalue 1, which can't be modified, that's why the compiler force us to use const.

Another example,

Bar&& GetBar()
{
    Bar b;
    return std::move(b);
}

This function will return a dangling reference because b is destructed after returning.

In a word, rvalue reference is algo a reference.

Now I'm confused. Please check the following code:

int &&rref = 1;

If rvalue reference is also a reference, so rref now points to the pure rvalue 1, which shouldn't be compilable as my understanding, because if it's compilable, what if I execute rref = 2? Does this mean that the pure rvalue is changed: 1 becomes 2?

But gcc told me that it was compilable...

Why? Why don't we need const int &&rref = 1?

Segmentation fault while working with 2D vectors

May I know exactly why my code is getting segmentation faults whenever I start traversing or taking input into the 2D vector? I don't understand what is causing the problem.

Edit: The myvect[ans].push_back is the part that's creating the problem.

So my question is why doesn't it just push back and create a vector at the myvect[ans] position? Isn't that what a dynamic vector is supposed to do? This is my code:

vector<vector<int>> myvect;
int ans = 2;

for(int i = 0; i < n; i++)
{
     myvect[ans].push_back(i+1);
     ans++;
}

for(int i = 0; i < myvect.size(); i++)
{
        if(!myvect[i].empty())
        {
            for(auto x: myvect[i])
                cout<<x<<" ";
        }
 }

Linker failing to find overloaded operator

I'm trying to overload the << operator for one of my classes, but the linker keeps failing to find the overload. Been searching online for anything I've missed on how to declare and implement the operator overload but nothing seems to stand out to me. Any ideas how I can fix this?

Undefined symbols for architecture x86_64:
  "memath::operator<<(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, memath::Vector3 const&)", referenced from:
      _main in mecli.cxx.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

vector3.h

#include <string>
#include <iostream>

namespace memath {

class Vector3 {

public:
    double x;
    double y;
    double z;

    Vector3();

    std::string to_string() const;

    friend std::ostream& operator<<(std::ostream &strm, const Vector3 &a);

};

};

vector3.cxx

#include <string>
#include <iostream>
#include <sstream>

#include "vector3.h"

using namespace memath;

Vector3::Vector3() : Vector3(0, 0, 0) {}

std::string Vector3::to_string() const {
    std::ostringstream r;
    r << "Vector3" << "(" << this->x << "," << this->y << "," << this->z << ")";
    return r.str();
}

std::ostream& operator<<(std::ostream &strm, const Vector3 &a) {
    strm << a.to_string();
    return strm;
}

mecli.cxx

#include <iostream>
#include <cstdlib>
#include <string>

#include "vector3.h"

int main(int argc, char** argv) {
    memath::Vector3 vec1;
    std::cout << vec1 << std::endl;
}

How to transfer data between main function and threads?

I want to store the threads that I have created in my main function in an array and later access them in my Thread class. What would be the best way to do this?. Below is the structure of my code.

Main.cpp:

int main(){
//do something

while ((new_socket = socket.Accept())) {
        std::thread mythread(&Myclass::MyThread, &myclass, 
                std::move(new_socket), para1);
        // I want to store the above threads created in an array which can later be accessed in a different thread class
    }
}

MyClass.cpp

MyClass::MyThread(....){
I want to access the array of threads here.
}

I have tried mutex and cv and add these threads into a queue but it is generating many errors. What is the best way to solve this?

Voting between Threads in c++11 [closed]

I want to implement a c++ code such that there will be 3 threads that would communicate with each other and vote and make a thread as the leader node. I am not really sure how can I start with this. I would appreciate any help!

working of universal initialization causing destructor to be called one extra time


        #include<iostream>
        #include<vector>

        class test {
            public:
                  virtual ~test() 
                  {
                      std::cout<<"inside destructor \n";
                  }
    
        };
    


        int main()
        {
            std::cout<<"---with universal initializer--------- \n";
            {
             test t1;
             std::vector<test> v{t1};
            }
            std::cout<<"----- ending universal initailizer ----- \n";
    
            std::cout<<"------------------------\n ";
            test t2;
            std::vector<test> v2(1,t2);
    

            return 0;
         }

output:

---with universal initializer--------- inside destructor inside destructor inside destructor ----- ending universal initailizer -----

inside destructor
inside destructor

my question is why destructor is called one extra time or extra object is created compared to other initialization when initialization done using universal initialization

vendredi 25 septembre 2020

How to initialize only a few elements of a global array in c++11 with gcc toolchain?

I have the following code:

#include <iostream>

int array[10] = {
  [2] = 200,
  [5] = 500
};

int main() {
  std::cout << "Hello World!\n";
  std::cout << array[5];
  return 0;
}

When I compile with g++ -std=c++11 -o main main.cpp, I get the following error:

main.cpp:6:1: sorry, unimplemented: non-trivial designated initializers not supported
 };
 ^
main.cpp:6:1: sorry, unimplemented: non-trivial designated initializers not supported

Is there any way to do this with g++? Clang works fine.

Lockless queue using std::atomic

I wish to create a lockless queue using std::atomic.
Here's my probably not so good first attempt at trying to do so:

template <typename T>
class atomic_queue
{
public:
    using value_type = T;
private:
    struct node
    {
        value_type m_value;
        node* m_next;
        node* m_prev;

        node(const value_type& value) :
            m_value(value),
            m_next(nullptr),
            m_prev(nullptr) {}
    };
private:
    std::atomic<node*> m_head = nullptr;
    std::atomic<node*> m_tail = nullptr;
public:
    void push(const value_type& value)
    {
        auto new_node = new node(value);

        node* tmp = nullptr;
        if (m_tail.compare_exchange_strong(tmp, new_node))
        {
            m_head.store(new_node, std::memory_order_relaxed);
            return;
        }

        node* old_tail;
        do {
            old_tail = m_tail;
            new_node->m_prev = old_tail;
        } while (!m_tail.compare_exchange_strong(old_tail, new_node));
        new_node->m_prev->m_next = new_node;
    }

    void pop()
    {
        if (m_head.load(std::memory_order_relaxed) == nullptr)
        {
            return;
        }

        node* tmp = nullptr;
        node* head = m_head;
        if (m_tail.compare_exchange_strong(head, tmp))
        {
            m_head.store(tmp, std::memory_order_relaxed);
            return;
        }

        node* old_head;
        do {
            old_head = m_head;
        } while (m_head && !m_head.compare_exchange_strong(old_head, old_head->m_next));
        if (old_head)
        {
            delete old_head;
        }
    }

    bool empty()
    {
        return m_head.load(std::memory_order_relaxed) == nullptr;
    }

    value_type& front()
    {
        node* head = m_head.load(std::memory_order_acquire);
        return head->m_value;
    }
};

Something to note here is that I store m_prev on node so that I could update the m_next of m_tail after successful push without actually doing so via m_tail incase it was changed already by another thread. So even if another thread got to push a new value already, the current thread would still link what it saw as the m_tail's m_next to the new node.

Now there're a few things that are not really thread-safe as far as I can tell and which I can't really think of a good way to solve these problems:

Let's assume thread1 pops from the queue the one and only item then we go inside the following if statement:

        node* tmp = nullptr;
        node* head = m_head;
        if (m_tail.compare_exchange_strong(head, tmp))
        {
            // Now thread2 kicks in
            m_head.store(tmp, std::memory_order_relaxed);
            return;
        }

And let's assume thread2 kicks in at the marked spot to push a new value to the queue the the following statement will be executed:

        node* tmp = nullptr;
        if (m_tail.compare_exchange_strong(tmp, new_node))
        {
            m_head.store(new_node, std::memory_order_relaxed);
            return;
        }

and let us assume it finished it's pushing without thread1 continuing and only then thread1 continues, then thread1 will execute:

        m_head.store(tmp, std::memory_order_relaxed);
        return;

and will basically undo thread2's push by setting m_head to nullptr. As far as I can understand memory orders can't help me in this scenario so I'm not sure what my options are?

Another problematic scenario is that let's assume we have 2 reader threads thread3 and thread4 doing the same job:

    while (true)
    {
        if (!q.empty())
        {
            int v = q.front();
            q.pop();
            std::stringstream stream;
            stream << "thread_3/4: " << v << '\n';
            std::cout << stream.str();
        }
    }

And let us assume the queue is of size 1, so both of them could see that the queue is not empty and get a reference to the front data and then pop the element and print the same result.
It seems to me that locking would help in this scenario, but I do no wish to use locking and also I do not wish the reading threads to care about synchronization problems because the interface itself should be the one responsible, but since front and pop are independent I don't see a good way to handle this.
Also there's the problem that front might access nullptr, so even here I'm not sure how to handle this. I can make the interface return a raw pointer, or std::optional but both solutions seems not correct in my eyes so would love to hear opinions on what should be done here.

Also, I'm not sure if I could go away with cheaper methods other than CAS, I know I could go with unique slot approach where each thread get an index into a fixed array by using fetch_add on atomic of type std::atomic<int> slot and so each thread pushes to the queue to a unique index, but I don't like this approach since it makes the limitation of a fixed size queue. On the other hand using new and delete is probably not the fastest thing either, I could use a pool allocator of sort, but then I would have to make sure it's synchronized as-well and that's a new level of pain.

I'm not even sure these are all the problems, these are the problems that I could spot with my implementation, I'm sure I didn't think of everything (or maybe I did?), anyway would love to hear yours thoughts on the described problems and maybe ways to overcome them.

How to concatinate multiple vectors of shared_ptr's?

I've seen other post but I am trying to do this using some of the <algorithm> methods. I have a pointer to a map which contains a key to a vector of pointers to BaseElement classes like the following.

using ElementV = std::vector<std::shared_ptr<BaseElement>>;
using ElementM = std::map<int, ElementV>;
using SElementM = std::shared_ptr<ElementM>;

SElementM elements;

What I am trying to do is concatenate each of the vectors (ElementV) stored as values in the map (ElementM) and populate one large ElementV. I'd like to not have to do deep copies and just access the original elements by their smart pointers (shared_ptr(BaseElement)) from the allElems vector.

The following is wrong, but gives the idea of what I'm trying to do.

ElementV allElems;

for (auto& index : indices) {
    allElems = elements->at(index);
}

I suspect I should be using lambas with std::copy, but have been unable to get something similar to the following to work and I think it's because of iterators.

std::copy(allElems.begin(), allElems.end(), [const elements &elems](std::vector<shared_ptr<BaseElement> &val) {
    elems ...?
}

Thoughts?

A question while I was revising the topic of pointers

Why can only pointers access heap memory in c++ or C ,i.e. what is that the special feature of pointer which allows it to access heap memory?

Loss of precision with pow function when surpassing 10^10 limit?

Doing one of my first homeworks of uni, and have ran into this problem:

Task: Find a sum of all n elements where n is the count of numerals in a number (n=1, means 1, 2, 3... 8, 9 for example, answer is 45)

Problem: The code I wrote has gotten all the test answers correctly up to 10 to the power of 9, but when it reaches 10 to the power of 10 territory, then the answers start being wrong, it's really close to what I should be getting, but not quite there (For example, my output = 49499999995499995136, expected result = 49499999995500000000)

Would really appreciate some help/insights, am guessing it's something to do with the variable types, but not quite sure of a possible solution..

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

using namespace std;

int main()
{
    int n;
    double ats = 0, maxi, mini;
    cin >> n;
    maxi = pow(10, n) - 1;
    mini = pow(10, n-1) - 1;
    ats = (maxi * (maxi + 1)) / 2 - (mini * (mini + 1)) / 2;
    cout << setprecision(0) << fixed << ats;
}

What is the output of the given code ? and explain why it is coming

I am not able to understand, why the output of the code is not what I was expecting.

#include <iostream>
using namespace std;
int main()
{
    int m = 2, n = 6;
    int &x = m;
    int &y = n;
    m = x++; 
    x = m++;
    n = y++;
    y = n++;
    cout<< m << " " << n; 
    return 0; 
}

I was expecting 4 8

IMPLEMENT A DOUBLY LINKED LIST OF STRUCTS [closed]

I WANT HELP FOR THE C++ SOURCE CODE FOR THIS PARTICULAR QUESTION

Problem description: A Zambia ICT College has a need to maintain student records such as their personal details and their grades. Currently, they are maintaining these records on papers. But that involves a lot of manual work for their employees to store and fetch the records. Also, sometimes they are facing some problems such as losing student records and taking a lot of time to search for a particular record. As the College is gaining more recognition, the number of students getting registered is increasing year by year. The College has a shortage of funds to hire more employees to maintain the records of student details. The College Management decides to hire you as an application developer to design an application that will be able to store and search their students’ records. The application should be capable of storing student’s personal records and their grades. Personal records include the Student’s First Name, Last Name, ID, and Date of Birth. Your task is to create the Double Linked List which implements the following functions: • Creates a Linked List to store student records. • Inserts an element at a particular position. • Displays student records. • Searches for a particular student record based on the Student ID. •Delete a node from the list.

SCHED_FIFO priority respect

It seems that the I do not manage to change correctly the priority of my threads with scheduling policy SCHED_FIFO.

The main thread with fifo priority 10 will launch the thread divisor and ratio.

divisor thread should get priority 2 so that the ratio thread with priority 1 will not evaluate a/b before b gets a decent value ( this is a completely hypothetical scenario only for the MCVE, not a real life case with semaphores or condition variables ).

Any hint welcome !

Note: environnment under Virtualbox

Normal execution OK

johndoe@VirtualBox:~/Code/gdb_sched_fifo$ g++ main.cc -o main -pthread
johndoe@VirtualBox:~/Code/gdb_sched_fifo$ ./main
Result: 0.333333

Normal execution KO

johndoe@VirtualBox:~/Code/gdb_sched_fifo$ g++ main.cc -o main -pthread
johndoe@VirtualBox:~/Code/gdb_sched_fifo$ ./main
Result: Inf

The MCVE:

#include <iostream>
#include <thread>

double a = 1.0F;
double b = 0.0F;

void ratio(void)
{
    struct sched_param param;
    param.sched_priority = 1;
    pthread_setschedparam(pthread_self(),SCHED_FIFO,&param);
    //error checking not shown for MCVE

    std::cout << "Result: " << a/b << "\n" << std::flush;
}

void divisor(void)
{
    struct sched_param param;
    param.sched_priority = 2;
    pthread_setschedparam(pthread_self(),SCHED_FIFO,&param);

    b = 3.0F;

    std::this_thread::sleep_for(std::chrono::milliseconds(2000u));
}


int main(int agrc, char * argv[])
{
    struct sched_param param;
    param.sched_priority = 10;
    pthread_setschedparam(pthread_self(),SCHED_FIFO,&param);

    std::thread thr_ratio(ratio);
    std::thread thr_divisor(divisor);

    thr_ratio.join();
    thr_divisor.join();

    return 0;
}

delphi and android dynamic library

I've compiled a small dynamic Android Arm library (in c ++) just to test how Delphi can interact with it (as a starting point for another real big project) : Here's my c++ :

const char* TestHelloWorld()

    {

    std::string a = "world";
    std::string b = (boost::format("hello: %s") % a).str();    
    char* c = const_cast<char*>(b.c_str());    
    LOGI("%s", c);// using android log ( adb )     
    return c;

    }

and here's my Delphi implementation :

procedure TForm7.Button1Click(Sender: TObject);
var
    DocDir, LibFN: string;
    _TestHelloWorld: function() : MarshaledAString; cdecl;   
    hLib: HMODULE;
    begin
     DocDir := IncludeTrailingPathDelimiter(TPath.GetLibraryPath);
      LibFN:=DocDir + 'libtest-cpp.so';
      hLib := LoadLibrary(PWideChar(LibFN));
      if hLib<>0 then
      begin
       _TestHelloWorld: GetProcAddress(hLib, 'TestHelloWorld');  
        ShowMessage(_TestHelloWorld: );     
      end;
    end;

The result in the Android Log :

enter image description here

The result with delphi :

enter image description here

So please what's the issue with my delphi code ; is related to using MarshaledAString ?

PS : I'm using RAD Studio Tokyo version .

Why the implementation of declval in libstdc++-v3 looks so complicated?

code snippet below comes from libstdc++-v3 std::type_traits, which is an implementation of std::declval.

  template<typename _Tp, typename _Up = _Tp&&> // template 1
    _Up
    __declval(int);
  template<typename _Tp> // template 2
    _Tp
    __declval(long);
  template<typename _Tp> // template 3
    auto declval() noexcept -> decltype(__declval<_Tp>(0));

But, I think I can implement declval as simple as:

template <typename T> T declval();

Here is my test code:

// filename: test.cpp
#include <iostream>
using namespace std;

struct C {
    C() = delete;
    int foo() { return 0; }
};

namespace test {
template <typename T> T declval();
};// namespace test

int main() {
    decltype(test::declval<C>().foo()) n = 1;
    cout << n << endl;
}

build and run commands are:

g++ -std=c++11 ./test.cpp
./a.out
  1. Why the implementation in libstdc++-v3 looks so complicated?
  2. What does the "template 1" do?
  3. Why __declval need an parameter(int/long)?
  4. Why "template 1"(int) and "template 2"(long) have different parameter type?
  5. Are there any problems with my simple implementation?

can anyone please help me [closed]

  1. Take two user inputs: lower limit and upper limit. Populate a 2-dimensional array with random numbers within the range given by the user. Call a function that calculates the average value each of the rows.
  2. Write a function that takes a string as a parameter, changes all the letters to uppercase letters and returns the updated string.
  3. Write a function that takes a string as a parameter and check the string is a palindrome or not palindrome. Then returns the result to the main function.
  4. Take a sentence as user input and call a function that prints it in backward order. Sample Input Sample Output Enter a sentence: DHAKA IS THE CAPITAL OF BANGLADESH Backward sentence: BANGLADESH OF CAPITAL THE IS DHAKA Enter a sentence: my name is nirob Backward sentence: nirob is name my 9.sWrite a function that takes a student ID as a string parameter, the checks if the ID is valid or not. If the ID is valid then find which semester and year, he/she got admitted in University and their unique ID. Sample Input Sample Input Student ID: 1821675 The ID is valid Year: 2018 Semester: Spring Unique ID: 1675 Student ID: 1701500 The ID is NOT valid
  5. Write a function that checks if a number is prime or not. If the number is prime the function returns true, otherwise false. Also try functions for checking perfect numbers and palindromes.

How to write a function to return the maximum number of balls in both baskets?

Given an array of balls of different colors, there are two baskets and the goal is to put the maximum number of balls in each basket. The only restriction is that each basket can have one or more balls of only one color you can start with any ball, but once you have started you cant skip a ball in the array. You will pick one ball from each color until you can not(i.e. you will stop when you have to pick from a third color type) Write a function to return the maximum number of balls in both baskets

Input format -> No. of balls
Followed by balls each per line

Input: 5
Red
Green 
Blue
Red
Blue

Output : 3

Explanation: Put 2 "Blue" balls in one basket and 1 "Red" ball in another basket

How would i be able to find the max value in a loop?

Im trying to find a maximum profit for a apartment complex. I used a loop to find all the different profits, but I need to find the maximum value of profit. How would I be able to find the max profit ? Should I be using a loop or another way to do this ? Im still new to coding, help is very appreciated.

#include <iostream>

using namespace std;

int main()
{
    // Containers for all variables
    int units;
    int rent;
    int incrent;
    int maintain;
    int profit;

    // User input
    cout << "How many units are being rented: ";
    cin >> units;
    cout << "How much is rent for each occupied room: $";
    cin >> rent;
    cout << "How much will rent need to increase for someone to leave: $";
    cin >> incrent;
    cout << "How much money does it cost to maintain a occupied room: $";
    cin >> maintain;
    //cout << "At max units rented you make $" << units * rent - maintain << endl;

    //Profit calculations
    while(units >= 0)
    {
    cout << "While at " << units << " rented you make $" << (units * rent) - (maintain * units) << endl;
    
    rent = rent + incrent;
    units--;
    }

jeudi 24 septembre 2020

Checking whether package is installed on android device in JNI C

I wanted to check whether specific set of packages are installed on the device in c++ ndk code as I don't wanted to check in Java code, so after research I had written code comparing code in java. My code checks packageinfo and if exception is thrown it treats it as package not found. Here is my code snippet

jboolean checkpackages(JNIEnv *env, jobject context, char packagePaths[][MAX_STRING_SIZE], int size) {

jstring packageName;
jobject packageManagerObj;
jobject packageInfoObj;
jclass contextClass = env->GetObjectClass(context);
jmethodID getPackageNameMid = env->GetMethodID(contextClass, "getPackageName",
                                               "()Ljava/lang/String;");
jmethodID getPackageManager = env->GetMethodID(contextClass, "getPackageManager",
                                               "()Landroid/content/pm/PackageManager;");
jclass packageManagerClass = env->FindClass("android/content/pm/PackageManager");
jmethodID getPackageInfo = env->GetMethodID(packageManagerClass, "getPackageInfo",
                                            "(Ljava/lang/String;I)Landroid/content/pm/PackageInfo;");
jclass packageInfoClass = env->FindClass("android/content/pm/PackageInfo");
jfieldID versionCodeFid = env->GetFieldID(packageInfoClass, "versionCode", "I");
packageManagerObj = env->CallObjectMethod(context, getPackageManager);
for (int i = 0; i < size; i++) {
    const char *path = packagePaths[i];
    //packageName = env->NewStringUTF(path);

     jstring packageNamet = env->NewStringUTF("com.mypackgage");
    packageInfoObj = env->CallObjectMethod(packageManagerObj, getPackageInfo, packageNamet, 0x0);
    int versionCode = env->GetIntField(packageInfoObj, versionCodeFid);
    if(env->ExceptionCheck()) {
        env->ExceptionClear();

        __android_log_print(ANDROID_LOG_DEBUG, DEBUG_TAG, "NATIVE: Package manager: Exception");
    } else {
          return true;
    }
}

return false;

}

Here even after putting exception check my code crashes with pending exception

JNI DETECTED ERROR IN APPLICATION: JNI GetIntField called with pending exception android.content.pm.PackageManager$NameNotFoundException

My code works if I put existing package on device.I'm using Android studio 4.0.1 and ndk 21.3. Please help me in how can I handle this or any other way we can do.

How can I fix this error "no matching function for call to ‘regex_replace..` "?

Given the following code:

std::string str;
str= std::regex_replace(str, std::regex("\r"), ""); // ERROR

I get the following error:
no matching function for call to ‘regex_replace(std::string&, std::regex, const char [1])’

How can I fix this error?

Qt Creator with MinGW 'no match for operator' Error

In order to deploy my project in Windows, I have got the Qt project from Linux and paste all the source files one paste on Windows 7 VM VirtualBox and tried to build it there.

Unfortunately, I am having the following error that I can't find a way to fix. The Qt Creator compiles well the example projects that come with it, but with my project, it pops that errors on many Qt files. And sorry, I don't have enough reputation to post images, so I'll let the links

(https://i.stack.imgur.com/7vBBC.png)

    In file included from C:/Qt/Tools/mingw810_64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/future:39,
                     from C:\Qt\5.15.1\mingw81_64\include/QtCore/qthread.h:51,
                     from C:\Qt\5.15.1\mingw81_64\include/QtCore/QtCore:245,
                     from C:\Qt\5.15.1\mingw81_64\include/QtWidgets/QtWidgetsDepends:3,
                     from C:\Qt\5.15.1\mingw81_64\include\QtWidgets/QtWidgets:3,
                     from ..\RaqMed/patientlineedit.h:54,
                     from ..\RaqMed\addappointmentform.h:13,
                     from ..\RaqMed\calendar.cpp:4:
    C:/Qt/Tools/mingw810_64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/thread: In function 'bool std::operator==(std::thread::id, std::thread::id)':
    C:/Qt/Tools/mingw810_64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/thread:273:26: error: no match for 'operator==' (operand types are 'std::thread::native_handle_type' {aka 'ptw32_handle_t'} and 'std::thread::native_handle_type' {aka 'ptw32_handle_t'})
         return __x._M_thread == __y._M_thread;
                ~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~

My .pro file:

QT       += core gui
QMAKE_CXXFLAGS  += -IC:\Users\BRUDEL\Desktop\postgresql\include -fpermissive
QMAKE_LFLAGS    += -LC:\Users\BRUDEL\Desktop\postgresql\lib -llibpq

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = RaqMed
TEMPLATE = app

CONFIG += c++11

# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
    addappointmentform.cpp \
    addpatientform.cpp \
    appointmentwidget.cpp \
    bstring.cpp \
    calendar.cpp \
    edittabmodel.cpp \
    main.cpp \
    patient.cpp \
    patientbdmodel.cpp \
    patientdelegate.cpp \
    patientlineedit.cpp \
    qutils.cpp

HEADERS += \
    addappointmentform.h \
    addpatientform.h \
    appointmentwidget.h \
    bstring.h \
    calendar.h \
    edittabmodel.h \
    patient.h \
    patientbdmodel.h \
    patientdelegate.h \
    patientlineedit.h \
    qutils.h

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

RESOURCES += \
    teste.qrc

FORMS += \
    calendar.ui \
    testes.ui

DISTFILES += \
    capa.png \
    icon0.png \
    icon2.png

I have installed only the following modules of Qt Creator

Qt 5.15.1

MinGW 8.1.0 64-bit
Qt Charts
Qt Debug Information Files

Developer and Designer Tools

Qt Creator 4.13.1 CDB Debugger Support
Debugging Tools for Windows
MinGW 8.1.0 64-bit
Qt Installer Framework 3.2
CMake 3.17.1 64-bit Ninja 1.10.0

I have found this similar question with no awnser "No match for operator" when including QtSql library in QT

I'm also having these messages when opening Qt Creator

(https://i.imgur.com/9ey08pV.png)

Thanks, and sorry for any posting error, I'm not habituated in English writing.

C++ Programming to display numbers in words

Write a C++ program which inputs a number from the user and returns the value in words. For Ex: for 590, it displays Five hundred ninety

compiling c++ with g++ from -c to -std=c++11

When I run my code for these files with g++ -c I don't get any errors, but when I run it with g++ -std=c++11 I am getting a linker error. I am assuming that means that the error isn't in the code of the files, but in the makefile. How can I fix this?

parse: parse.o scan.o
    g++ -std=c++11 -Wall parse.o scan.o -o parse
    #g++ -o parse parse.o scan.o

clean:
    rm -f parse.o parse

parse.o: scanpp.h parse.cpp 
    #g++ -c parse.cpp
    g++ -std=c++11 parse.cpp

scan.o: scanpp.h scan.cpp 
    #g++ -c scan.cpp
    g++ -std=c++11 scan.cpp

Here is the error I get when I run make

#g++ -c parse.cpp
g++ -std=c++11 parse.cpp
Undefined symbols for architecture x86_64:
  "scan()", referenced from:
      match(token) in parse-405e06.o
      _main in parse-405e06.o
  "_token_image", referenced from:
      match(token) in parse-405e06.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [parse.o] Error 1

Returning T(t) with T=int&, how?

template<typename T>
T foo(T&& t) {
    return T(t);
}

int main() {
    int x;
    foo(x);
}

So, I know T=int& here but I don't understand what happens at return line to make this vaild. Can someone explain how?

Inconsistent C style string output between different operating systems / compilers

I have a C++ program:

#include <iostream>

char * foo (char * bar, const char * baz) {
    int i = -1;

    do {
        i++;    
        *(bar + i) = *(baz + i);
    } while (*(baz + i));

    return bar;
}

int main (int argc, char *argv[]) {
    char bar[] = "";
    char baz[] = "Hello";

    foo(bar, baz);

    std::cout << "bar: " << bar << std::endl;
    std::cout << "baz: " << baz << std::endl;
}

Not that this is the important part, but the requirement for this program is that it copies one C style string into another using pointers.

When I compile and execute my binary on my Ubuntu 16.04 desktop, this is what I see:

$ g++ -std=c++11 test.cpp -o test && ./test
bar: Hello
baz: ello

Egad! The initial 'H' of baz has been dropped, but I don't see how my foo function changes baz at all. Hmm...

The g++ version on my Ubuntu desktop is thus:

$ g++ --version
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.12) 5.4.0 20160609
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

I thought this was an error or bug with my code (and it may still be), yet I discovered that when I compile and run on any other operating system I get different behavior.

Here is the output on macOS:

$ g++ -std=c++11 test.cpp -o test && ./test
bar: Hello
baz: Hello

Here is the g++ version on that macOS laptop:

$ g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
Apple clang version 12.0.0 (clang-1200.0.32.2)
Target: x86_64-apple-darwin19.5.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

When tested on other Linux boxes, on Windows, etc. it has the correct, expected out put of bar and baz both being Hello.

What is going on!?

tl;dr C++ program outputs a C style string differently on my desktop than any other computer. Why?

How can I fix this error 'no matching function for call'?

Given the following code:

    std::map<std::string, std::unique_ptr<Obj>> objs;
    std::string str;
    Obj obj;
    std::unique_ptr<Obj> objUniquePtr = std::unique_ptr<Obj>(new Obj(obj));
    objs.insert({ str, objUniquePtr });   <<<<<<<< ERROR

I get the following error:

no matching function for call to 'std::map<std::__cxx11::basic_string<char>, std::unique_ptr<Obj> >::insert(<brace-enclosed initializer list>)'

How can I fix this error?

value is

i have to open a txt file which contains lines like this :

route_id,service_id,trip_id,trip_headsign,trip_short_name,direction_id,block_id,shape_id,wheelchair_accessible
300820,20203011multint-1111100,71682319-20203011multint-1111100,"Place Jacques-Cartier (Sud)",,1,1000_1,08200529,2
300740,20203011multint-1111100,71680213-20203011multint-1111100,"Val-Bélair (Nord)",,0,1000_1,07400326,2

Right now i am doing this code :

void DonneesGTFS::ajouterVoyagesDeLaDate(const std::string &p_nomFichier)
{

    ifstream file(p_nomFichier);
    string str;

    if (!file) throw logic_error("Un problème est survenu lors de la lecture du fichier.");
    while (getline(file, str))
    {
        str.erase(remove(str.begin(), str.end(), '"'), str.end());
        if (str == "route_id,service_id,trip_id,trip_headsign,trip_short_name,direction_id,block_id,shape_id,wheelchair_accessible") {
            continue;
        }

        vector<string> string_vector = string_to_vector(str, ',');

        string trip_id = string_vector[2];

        unsigned int route_id = stoul(string_vector[0]);
        string service_id = string_vector[1];
        string headsign = string_vector[3];

        for(const auto& id : m_services)
        {
            if(string_vector[1] == id)
            {
                m_voyages.insert({trip_id, Voyage(trip_id, route_id, service_id, headsign)});
            }
        }

        }
    file.close();

}

The problem:

When using the debuguer on this line :

unsigned int route_id = stoul(string_vector[0]);

The value of route_id is assigned to and from what i read around here it could either be a problem ( bug in my code) or normal.

Could anyone confirm to me that it's not a bug ? Thanks

here's my debuger infos :

enter image description here

C++ - Bar graph and other types of Graphs for Statistics

I want to do Graph using C++, here Graph which i meant was Bar Graph, Compound Graph etc in Statistics.Can any one help about that ? But i didn't want these graphs as console output.

C++ algorithm code for Magical sequence that will generate desired output

The Magical Sequence

A Magical Sequence is defined as shown.

Magical[1] = 0
Magical[2] = 1
Magical[n] = 1*Magical[n-1] + 2*Magical[n-2] + n*1, for n > 2

Given n (1 <= n <= 10^9 ), find Magical[n].

Example 1: input: 3 Output: 4

Explanation:

Magical[n] = 1*Magical[n-1] + 2*Magical[n-2] + 3*1
    Magical[3] = 1*Magical[2] + 2*Magical[1] + 3*1
    Magical[3] = 1*1 + 2*0 + 3*1
    Magical[3] = 4

Example 2: input: 4 Output: 10

Magical[4] = 1*Magical[3]+2*Magical[2]+3*Magical[1]+4*1
          = 1*4+2*1+3*0+4 = 10

Example 3: input: 5 Output: 26

Magical[5] = 1*Magical[4]+2*Magical[3]+3*Magical[2]+4*Magical[1]+5*1
          = 1*10+2*4+3*1+4*0+5 = 26

I tried something like below :-

int CuckooNum(int n)
{
    if (1 == n)
    {
        return 0;
    }
    else if (2 == n)
    {
        return 1;
    }

    std::vector<int> vec;
    vec.resize(n);
    vec[0] = 4;
    vec[1] = 0;
    vec[2] = 1;

    int multiplyer = n;
    int result = 0;
    for (int index=3; index <= n; index++)
    {
        result += multiplyer * vec[index-1];
        vec[index] = result;
        multiplyer--;
    }
    return result;
}

Error while adding custom allocator in unordered map in c++

I am trying to add a unordered_map in OpenJDK code for experimental purpose. So instead of using global new and delete operators, I tried to pass an allocator to the unordered_map.

Here is my hpp file with defination of structure inheriting the std::allocator. I hope I got that right.

#include "memory/allocation.hpp"
#include <unordered_map>
#include <string>
#include <string.h>
#include <iostream>
template< class T >
struct MangedAllocator : std::allocator<T> {
    typedef typename std::allocator<T>::pointer pointer;
    typedef typename std::allocator<T>::size_type size_type;


    pointer allocate(size_type size,std::allocator<void>::const_pointer = 0) {
        void * p = (void *)AllocateHeap(size, mtInternal);
        if(p == 0) {
            throw std::bad_alloc();
        }
        return static_cast<pointer>(p);
    }

    void deallocate(pointer p, size_type) {
        FreeHeap((void*)p);
    }
} ;

using namespace std;
class StackTraceMap : CHeapObj<mtInternal>{
 private:

  static std::unordered_map<std::string,int,std::hash<std::string>,std::equal_to<std::string>,MangedAllocator<std::pair<const std::string, int>>> _frames;
  static std::unordered_map<int,std::string,std::hash<int>,std::equal_to<int>,MangedAllocator<std::pair<const int, std::string>>> _frames_reversed;
  static int _counter;
 public:
  static int addFrame(char* fr_name){
    if(_frames.find(fr_name)==_frames.end()){
        //not found
        _frames[fr_name]=_counter;
        _frames_reversed[_counter]=fr_name;
        ++_counter;
        return _counter-1;
    }
    else{
        return _frames[fr_name];

    }
  }
  static void printFrame(int n){
    cout<<_frames_reversed[n]<<"\n";
  }
  static void printMap(){
      cout<<"hello there\n";
      for (auto i : _frames)
        cout << i.first << "   " << i.second
             << endl;
      cout<<"done\n";
  }

};

And here is the cpp file with definitions of variables stated in hpp file.

#include "code/stackTraceMap.hpp"
using namespace std;
int StackTraceMap::_counter=1;
static std::unordered_map<std::string,int,std::hash<std::string>,std::equal_to<std::string>,MangedAllocator<std::pair<const std::string, int>>> _frames;
static std::unordered_map<int,std::string,std::hash<int>,std::equal_to<int>,MangedAllocator<std::pair<const int, std::string>>> _frames_reversed;

I am getting the following error while building:

/usr/bin/ld: /home/manavjeet/BTP/jdk14/build/linux-x86_64-server-slowdebug/hotspot/variant-server/libjvm/objs/thread.o: in function `StackTraceMap::addFrame(char*)':
/home/manavjeet/BTP/jdk14/src/hotspot/share/code/stackTraceMap.hpp:37: undefined reference to `StackTraceMap::_frames[abi:cxx11]'
/usr/bin/ld: /home/manavjeet/BTP/jdk14/src/hotspot/share/code/stackTraceMap.hpp:37: undefined reference to `StackTraceMap::_frames[abi:cxx11]'
/usr/bin/ld: /home/manavjeet/BTP/jdk14/src/hotspot/share/code/stackTraceMap.hpp:39: undefined reference to `StackTraceMap::_frames[abi:cxx11]'
/usr/bin/ld: /home/manavjeet/BTP/jdk14/src/hotspot/share/code/stackTraceMap.hpp:40: undefined reference to `StackTraceMap::_frames_reversed[abi:cxx11]'
/usr/bin/ld: /home/manavjeet/BTP/jdk14/src/hotspot/share/code/stackTraceMap.hpp:45: undefined reference to `StackTraceMap::_frames[abi:cxx11]'
/usr/bin/ld: /home/manavjeet/BTP/jdk14/build/linux-x86_64-server-slowdebug/hotspot/variant-server/libjvm/objs/thread.o: in function `StackTraceMap::printFrame(int)':
/home/manavjeet/BTP/jdk14/src/hotspot/share/code/stackTraceMap.hpp:50: undefined reference to `StackTraceMap::_frames_reversed[abi:cxx11]'
collect2: error: ld returned 1 exit status
* For target hotspot_variant-server_libjvm_objs_BUILD_LIBJVM_link:
/usr/bin/ld: /home/manavjeet/BTP/jdk14/build/linux-x86_64-server-slowdebug/hotspot/variant-server/libjvm/objs/thread.o: in function `StackTraceMap::addFrame(char*)':
/home/manavjeet/BTP/jdk14/src/hotspot/share/code/stackTraceMap.hpp:37: undefined reference to `StackTraceMap::_frames[abi:cxx11]'
/usr/bin/ld: /home/manavjeet/BTP/jdk14/src/hotspot/share/code/stackTraceMap.hpp:37: undefined reference to `StackTraceMap::_frames[abi:cxx11]'
/usr/bin/ld: /home/manavjeet/BTP/jdk14/src/hotspot/share/code/stackTraceMap.hpp:39: undefined reference to `StackTraceMap::_frames[abi:cxx11]'
/usr/bin/ld: /home/manavjeet/BTP/jdk14/src/hotspot/share/code/stackTraceMap.hpp:40: undefined reference to `StackTraceMap::_frames_reversed[abi:cxx11]'
/usr/bin/ld: /home/manavjeet/BTP/jdk14/src/hotspot/share/code/stackTraceMap.hpp:45: undefined reference to `StackTraceMap::_frames[abi:cxx11]'
/usr/bin/ld: /home/manavjeet/BTP/jdk14/build/linux-x86_64-server-slowdebug/hotspot/variant-server/libjvm/objs/thread.o: in function `StackTraceMap::printFrame(int)':
/home/manavjeet/BTP/jdk14/src/hotspot/share/code/stackTraceMap.hpp:50: undefined reference to `StackTraceMap::_frames_reversed[abi:cxx11]'
collect2: error: ld returned 1 exit status

When I try to use it using default allocator it works fine obviously after removing checks in openJDK makefile and source code. But I want it to work on normal CHeap of openjdk

Can someone explain what am I doing wrong? Thankyou.

Dereference list::end()

I was playing around with std::list. Similarly to other containers, std::list::end refers to the past-the-end element of a std::list (ref).

So, we would expect the below code to print 1, 2, 3, 4, 5 (which it does):

std::list<int> l { 1, 2, 3, 4, 5 };
for (auto it = l.begin(); it != l.end(); ++it)
{
    std::cout << *it << ", ";
}
std::cout << std::endl;

However, the second line of the second code snippet should not print 5, but it does:

std::cout << *l.begin() << std::endl;
std::cout << *l.end() << std::endl;

Output: 1 and 5.

Why? I'm using gcc 11 and C++11 (same for C++20 btw).

Algorithm for Magical sequence

The Magical Sequence

A Magical Sequence is defined as shown.

Magical[1] = 0
Magical[2] = 1
Magical[n] = 1*Magical[n-1] + 2*Magical[n-2] + 3*1, for n > 2

Given n (1 <= n <= 10 ), find Magical[n].

Example 1: input1: 3 Output: 4 Explanation:

Magical[n] = 1*Magical[n-1] + 2*Magical[n-2] + 3*1
    Magical[3] = 1*Magical[2] + 2*Magical[1] + 3*1
    Magical[3] = 1*1 + 2*0 + 3*1
    Magical[3] = 4

Is it normal for dev c++ to build and run just "hello world" for 10-20 secs?

I just started dev c++, I'm doing the first tutorial which is the printing hello world. I build and run the code, i waited for 10-20 secs before the "hello world" shows up. Is it normal? is there something I can do to make it faster? can i change the compiler to faster one? Is it because of my pc? Need help guyzz.

Missing missing return statement accepted by g++

class Foo
{
public:
    int bar()
    {
        bool bla = false;
        auto lambda = [&]() -> int {
            if (bla)
            {
                return 0;
            }
            // return 1;
        };
        (void)lambda;
        return 1;
    }
};

int main()
{
    Foo foo;
    foo.bar();
}

This example above perfectly compiles with g++ (Ubuntu 9.3.0-10ubuntu2) 9.3.0 and "-Wall -Wpedantic -Werror -Wextra".

However, e.g. https://cppinsights.io/ complains

/home/insights/insights.cpp:13:9: warning: non-void lambda does not return a value in all control paths [-Wreturn-type]
        };
        ^
1 warning generated.

Why does gcc not complain?

mercredi 23 septembre 2020

What's the difference between enum, class, and enum class in C++?

I've been studying Principles and Practice Using C++ and C++ Primer, but there's one concept (among many) that I still have a hard time grasping.

What's the difference between enum, class, and enum class, and when do we use them and how do we choose which one to use?

Thanks!

Raft Consensus Algorithm in C++

I want to implement the Raft Consensus Algorithm in C++11 with a sample client and server implementation. I have understood the concept of the Raft Consensus Algorithm but I am pretty new to coding in c++. Can someone help me on how to start coding this algorithm in c++11?