dimanche 31 janvier 2021

Simple C++ Class Undefined symbols for architecture x86_64

I'm new to C++.

Here is my header file:

#ifndef VEHICLE_H
#define VEHICLE_H

class Vehicle {
  protected:
    double S;
  public:
    Vehicle();
};

#endif

and cpp file:

#include "vehicle.h"

Vehicle::Vehicle() 
{
  this->S = 1.00;
}

And this is main.cpp:

#include "vehicle.h"

int main()
{
  Vehicle vehicle;
}

This is a super simple setup, but when I try to run on VSCode with my Mac, I"m getting:

Undefined symbols for architecture x86_64:
  "Vehicle::Vehicle()", referenced from:
      _main in main-9af6ab.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Any help appreciated. Thanks!

An unordered_map that returns pairs of different types c++

I am trying to implement an std::unordered_map that returns pairs of either double, int or std::string. The keys for the map are std::strings. Below is what I have tried so far:

#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <unordered_map>
#include <utility>
#include <vector>

// A base class for boundary class
class Boundbase {
    public:
    Boundbase(){};
    virtual ~Boundbase(){};
};

// A different map of boundaries for each different data type
template <class dType>
class Boundary : public Boundbase {
    std::pair<dType, dType> bpair;
    
    public:
    //Constructor
    Boundary(const std::string &lbound, 
        const std::string &ubound) {
        setbound(lbound, ubound);
    };

    //A method to set boundary pair
    void setbound(const std::string &lbound, 
        const std::string &ubound);
    
    // A method to get boundary pair
    std::pair<dType, dType> getbound() {return bpair;}
};

// Class to hold the different boundaries 
class Boundaries {
    std::unordered_map<std::string, Boundbase*> bounds;

    public:
    //Constructor
    Boundaries() {};

    // A method to set boundary map
    void setboundmap(std::unordered_map<std::string, 
            std::vector<std::string>> xtb);

    // A template to get boundaries.
    std::unordered_map<std::string, Boundbase*> getbounds()
        {return bounds;}
};

// A method to set covariate boundary
template <class dType> void
Boundary<dType>::setbound(const std::string &lbound, 
        const std::string &ubound) {
    dType val;
    std::istringstream isa(lbound);
    while(isa >> val) {
        bpair.first = val;
    }
    std::istringstream isb(ubound);
    while(isb >> val) {
        bpair.second = val;
    }
}

// A method to set boundary map
void Boundaries::setboundmap(std::unordered_map<std::string, 
        std::vector<std::string>> xtb) {
    for(auto s : xtb) {
        char type = s.second[1][0];
        switch(type) {
            case 'd': {
            std::pair<std::string, Boundbase*> opair;
            opair.first = s.first;
            opair.second = new Boundary<double>(
                    s.second[2], s.second[3]);
            bounds.insert(opair);
            }
            break;
            case 'i': {
            std::pair<std::string, Boundbase*> opair;
            opair.first = s.first;
            opair.second = new Boundary<int>(
                    s.second[2], s.second[3]);
            bounds.insert(opair);
            break;
            }
            case 'c': {
            std::pair<std::string, Boundbase*> opair;
            opair.first = s.first;
            opair.second = new Boundary<std::string>(
                    s.second[2], s.second[2]);
            bounds.insert(opair);
            break;
            }
        }
    }
}

This compiles ok using g++. When I try to run it though ( as follows):

int main() {
    Data D;
    Boundaries B;
    std::ifstream iss("tphinit.txt");
    D.read_lines(iss);

    auto dbounds = D.get_xtypebound();
    B.setboundmap(dbounds);

    auto tbounds = B.getbounds();
    auto sbound = tbounds["X1"];
    std::cout << sbound->bpair.first << "," 
        << sbound->bpair.second << std::endl;
}

I get 'class Boundbase' has no member named 'bpair' which is true because I am pointing to the base class and not the derived class. As far as I can tell, trying to get the derived member bpair requires that I use the visitor pattern. Now, it is clear that I am noob so when I had a look at different ways of doing this on SO I was a little in over my head (no reflection on the authors, just on my inexperience).

So my main question is: Is this the best and simplest way to go about this? I would like to avoid boost::variant if at all possible (mainly for the sake of purity: this cannot be that difficult). A sub-question is whether I have to use the visitor pattern or is there a better/simpler way to get the member pbair?

I will have to perform this lookup many times so I am hoping to make it as fast as possible but using the stl for the sake of simplicity.

Properly avoid SQL injection

According to MSDN error Invalid descriptor index is returned if the parameter is part of the SELECT list.

I'm trying to execute a query

SELECT obect_id(?);

and getting this error.

However the parameter is not really part of the SELECT list.

So how to properly avoid hardcoding the parameter in this case?

I want to query the table id from SQL Server.

Or I will have to hardcode the table name?

samedi 30 janvier 2021

Why my factory pattern return error while compiling?

I want to implement simle factory pattern but when I try compile code i get error like:

error: undefined reference to `vtable for Interface'

error: undefined reference to `typeinfo for Interface'

class Interface{
public:
    virtual void set(const std::string &data);
    virtual void get(const std::string &data);
    virtual void show();
    virtual ~Interface(){}
};

class InterX : public Interface{
public:
    void set(const std::string &data){x++;}
    void get(const std::string &data){x--;}
    void show(){std::cout << x << std::endl;}
private:
    int x = 1;
};

class InterY : public Interface{
public:
    void set(const std::string &data){y++;}
    void get(const std::string &data){y--;}
    void show(){std::cout << y << std::endl;}
private:
    int y = 2;
};

class Factory{
public:
   static Interface* getInterface(const std::string interface_name){
       if(interface_name == "x") return new InterX();
       if(interface_name == "y") return new InterY();
       return nullptr;
   }
};

int main()
{
    Interface* interface = Factory::getInterface("x");
    return 0;
}

How could I fix that? When I commented line in main, the programs comiles

Interface* interface = Factory::getInterface("x");

How can I change a global variable's value inside an if-else statement

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

int main()
{
  cout << "-------------\n|   |   |   |\n-------------\n|   |   |   |\n-------------\n|   |   |   |\n-------------" << endl; //signals the start of program
  int row;
  int col;
  string board[3][3];
  bool win = false; // set the intial state to not be winning

  for (int i =0;i<3;i++)
  {
    for(int j = 0; j<3 ; j++)
    {
      board[i][j]=" ";
    }
  }
  // The above code has intialized a matrix waiting to be filled in

  for (int i = 0;i<9;i++)
  {
    string player_input = "O";
    string * s_pointer = & player_input;
    if (i%2 == 0){
    string player_input = "X";
    }

    cout << "Player " << * s_pointer <<": Enter your desired row (1-3):" << endl;
    cin >> row;
    cout << "Player " << * s_pointer <<": Enter your desired column (1-3):" << endl;
    cin >> col;

    board[row-1][col-1] = * s_pointer;

    // The above code asks for input and then assign it to the row,col we've intialized before

    for (int i =0;i<3;i++) // this for loop basically prints out the whole grid beside the very last line of it
      {
        cout <<"-------------" << endl;
        for(int j = 0; j<3; j++)
          {
            cout << "| " << board[i][j] << " ";
          }
          cout<<"|"<<endl;
      }
      cout <<"-------------" << endl;}

      // The idea here is to use a for loop and switch between X and O input for each for loop, concantenate the string
      // Also the board's input switches between X and O depends on what turn it is, we can control this using if else
      // Check for the result of the match at 5-9 rounds as only till those rounds are results to be determined
      // Try utilize external function for cleaner format
  }
'''

Hi guys, I'm wondering why this code wouldn't work as it doesn't seem like the value of player_input changes from the if-else statement.

Also, why do I not need "return 0" and closing parentheses at the end? As it seems like If I include it, it warns 2 errors: " expected unqualified-id ", "extraneous closing brace ('}')"

Sorry if this question is too much of a newbie question, thank you so much, guys!

How do I call c++ function pointers created in one class and then passed to another?

I've sort of programmed myself into a corner and in the process, realized that I am really lacking in my understanding of c++ function pointers as well as virtual functions. The goal is to implement a temperature controller on a raspberry pi. I won't go into detail on the other components as they are not relevant. I am currently working on the button controller. This is more of an architecture question.

  • TempCtrl is the main class that calls all others. It also calls the ButtonController::addButton() to register buttons, and contains the callbacks.
  • ButtonCtrl reads the gpio registers and cycles through the registered buttons stored in a vector of type Button.
  • Button class was supposed to be a very simple container which had nothing other than an integer specifying the gpio, and callbacks. This is where the problem is.

I've never really done anything like this before, but I wanted something really clean. Basically, once I finish the button controller I wanted to be able to leave it alone unless I was adding functionality. For this reason, I wanted callback functions to be defined in the TempCtrl Function.

So far this has not worked. I'm sure my syntax is off if it is even possible. I would also be interested in alternative ways of achieving this.

Code below. I only posted the relevant headers, and the buttoncontroller.cpp as there is quite a lot of code. I will be glad to post more code if more information is needed, so please just ask:

button.hpp

#ifndef BUTTON_HPP
#define BUTTON_HPP

#include <ctime>
#include <cstdint>

#define HOLDTIME    500  // milliseconds

class TempCtrl;

enum State_E
{
  BP_LOW, 
  BP_HIGH
};

class Button
{
  public:
  Button(
    uint8_t _gpio, 
    void(TempCtrl::*)(), 
    void(TempCtrl::*)(), 
    void(TempCtrl::*)());

  ~Button();

  void update(State_E newValue);

  uint8_t getGpio() const;

  private:
  void (TempCtrl::*onFallingEdge)();

  void (TempCtrl::*onLongHold)();

  void (TempCtrl::*onRisingEdge)();
  
  uint8_t gpio;

  State_E state;

  time_t timeStamp;
};

#endif /* BUTTON_HPP */

buttonprocessor.hpp

#ifndef BUTTONPROCESSOR_HPP
#define BUTTONPROCESSOR_HPP

#include "button.hpp"
#include <cstdint>
#include <vector>

#define GPIO_MAX    53
#define BLOCK_SIZE  (4*1024)
#define GPLEV0      13
#define GPLEV1      14
#define SCAN_RATE   100  // milliseconds

class ButtonProcessor
{
  public:
  ButtonProcessor();

  virtual ~ButtonProcessor();

  bool init();

  bool shutdown();
  
  size_t addButton(Button button);

  void startEventLoop(bool &terminate);

  private:

  int fd; 

  volatile uint32_t *gpio_base;

  std::vector<Button> buttonDb;
};

#endif /* BUTTONPROCESSOR_HPP */

tempctrl.hpp

#ifndef TEMPCTRL_HPP
#define TEMPCTRL_HPP
#include "button.hpp"
#include "lcdscreen.hpp"
#include "buttonprocessor.hpp"

#include <cstdlib>
#include <vector>
#include <string>
#include <time.h>
#include <cstring>
#include <memory>

#define W1_DEV_ROOT "/sys/bus/w1/devices/w1_bus_master1/"
#define W1_SLAVE_COUNT W1_DEV_ROOT "w1_master_slave_count"
#define W1_SLAVES W1_DEV_ROOT "w1_master_slaves"
#define POLL_FREQ 1000

/***********************************************
*  A structure for holding a single data point *
*  of temperature in degrees celsius, as well  *
*  as the temp probe ID and a time stamp.      *
************************************************/

struct TempStruct
{
  time_t      ts;
  std::string id;
  float       temp;
};

enum TScale_E
{
  CELSIUS,
  FARENHEIT,
  KELVIN,
  RANKINE,
  MAX_VALUE_TSCALE
};

#define DEFAULT_TEMP_SCALE FARENHEIT

enum InputMode_E
{
  SETPOINT,
  LOAD_PROFILE,
  PID_TUNE,
  MAX_VALUE_INPUT_MODE
};

class TempCtrl 
{   
public:
  TempCtrl();
    
  virtual ~TempCtrl();
    
  /***********************************************
  *  Fetches the current time from the specified *
  *  temperature controller, and stores the      *
  *  returned value with time stamp and device   *
  *  id, in the tempStruct array.    
  ************************************************/
  void getTemp(int);

  void setTempScale(TScale_E);

  void lcdToggleEnable(int bits);

  void wait(size_t seconds);

  void printTemp(enum TScale_E);

  std::vector<std::string> slavesArr;

  std::vector<TempStruct> tempStruct;

  TScale_E tempScaleVal = CELSIUS;

  int fd;

// These should not be public 
  void onFallingEdge();

  void onLongHold();

  void onRisingEdge();

private:
  void lcdInit();

  uint8_t tempInit(void);

  /***********************************************
  * exclusive access to atomic safe lcdscreen    *
  * manipulation.  Logic is completely decoupled *
  ************************************************/
  std::unique_ptr<LcdScreen> mLcdScreen;

  /***********************************************
  * The responsibility of the button processor   *
  * is to detect edge changes in for specified   *
  * GPIO's, determine the type of press and call *
  * the relavant callback.                       * 
  ************************************************/
  std::unique_ptr<ButtonProcessor> mButtonProcessor;

};
#endif /* TEMPCTRL_HPP */

buttonprocessor.cpp

#include "button.hpp"

Button::Button(
    uint8_t _gpio,
    void(TempCtrl::*_onFallingEdge)(),
    void(TempCtrl::*_onLongHold)(),
    void(TempCtrl::*_onRisingEdge)())
: state(BP_LOW),
timeStamp(time(NULL)),
onFallingEdge(_onFallingEdge),
onLongHold(_onLongHold),
onRisingEdge(_onRisingEdge)
{
  
}
  
Button::~Button()
{ 
  
}

void Button::update(State_E newValue)
{   
  if(
    newValue != state &&
    state == BP_HIGH) // Rising edge
  { 
    timeStamp = time(NULL);
    state = newValue;
    // ((Button*)this)->Button::onRisingEdge(); 
  }
  else if(
    state == BP_HIGH && 
    newValue == state &&
    ((time(NULL) - timeStamp) > HOLDTIME)) // Long Hold
  {
    timeStamp = time(NULL);
    state = newValue; 
    // ((Button*)this)->Button::onLongHold(); 
  }
  else if(
    newValue != state && 
    state == BP_LOW) // Falling edge
  {      
    timeStamp = time(NULL);
    state = newValue;
    TempCtrl.(*((Button*)this)->Button::onFallingEdge());
    //onFallingEdge();
  }  
}   
    
uint8_t Button::getGpio() const
{   
  return gpio; 
}  

Stuck if-statement

#include<iostream>
using namespace std;
int main(){
double weight;
cout<<"Enter the weight of the package \n";
cin>>weight;
if(weight>0.0 || weight<= 1.0){
cout << "The shipping cost is 3.5 Dhs";}
else if (weight>1.0 || weight<=3.0){
    cout << "The shipping cost is 5.5 Dhs";
}
else if(weight>3.0 || weight<=10.0){
    cout << "The shipping cost is 8.5 Dhs";
}
else if (weight>10.0 || weight<=20.0){
    cout << "The shipping cost is 10.5 Dhs";
}
else{
    cout<<"Invalid weight";
}
}

Every time I try to enter a different weight it is always stuck in the first condition

An issue with #include statements [duplicate]

I am very new to C++ so please bear with me. I have the following five files:

// main.cpp
#include <iostream>
#include "food.h"
#include "food.cpp"
#include "dog.h"

int main(void)
{
    Food<int> *food = new Food<int>(10);
    Dog *dog = new Dog();
    dog->eat(*food);
    
    delete food;
    delete dog;
    
    return 0;
}
// food.h
#pragma once

template <class T>
class Food
{
public:
    Food(T value);
    ~Food();
    
    T value;
};
// food.cpp
#include "food.h"

template <class T>
Food<T>::Food(T value): value(value) {}

template <class T>
Food<T>::~Food() {}
// dog.h
#pragma once

class Dog
{
public:
    Dog();
    
    ~Dog();
    
    template <class T>
    void eat(Food<T>& food);
};
// dog.cpp
#include <iostream>
#include "food.h"
#include "dog.h"

Dog::Dog() {}

Dog::~Dog() {}

template <class T>
void Dog::eat(Food<T>& food)
{
    std::cout << "Eating food\n";
}

And when I compile with the command

g++ main.cpp food.cpp dog.cpp -o main

I get the error

Undefined symbols for architecture x86_64:
  "void Dog::eat<int>(Food<int>&)", referenced from:
      _main in main-083267.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I think the issue is related to the #include statements in my main.cpp but I've been racking my brain for over an hour trying different things and can't for the life of me figure it out.

read a file from the directory with c program

I want to read each file one by one from a folder in C. the below program keeps printing "." and does not aalow me to access the images. how can i handle the "." and ".." files the following is my program

 while (1) {
    folder = opendir("./result_img/");
    //char str1[100] = "./result_img/";
    while( (entry=readdir(folder)) != NULL)
    
    {
    closedir(folder);
    folder = opendir("./result_img/");
    char str1[100] = "./result_img/";
    if((strcmp(entry->d_name,".")==0 || strcmp(entry->d_name,"..")==0 || (entry->d_name) == '.' ) || (strcmp(entry->d_name,"Server_v1.py")==0))
    {
     printf("issue %s",entry->d_name);
     sleep(0.5);
     continue;
    }
//further processing of each image here
}
}

How to send data via a websocket using uWebsockets v0.14?

You can send data after connecting like:

 hubGroup->onConnection([](uWS::WebSocket<uWS::CLIENT> *ws, uWS::HttpRequest req) {
    std::cout << "connect, sending HELLO" << std::endl;
    std::string msg = "HELLO";
    ws->send(msg.data(), msg.size(), uWS::OpCode::TEXT);
});

How can I do ws->send() out of the event loop? That is, how can I send data without hubGroup->on*() methods?

i am new to c++ can someone help me pls? i dont understand 2lines of code [closed]

i dont understand this code

why is there a : at the beginning of the line? what does that mean? m_Name should return a string but it didnt return anything

vendredi 29 janvier 2021

Range based for loop through non-const literal c++

Compiler context: I am compiling with GDB v8.3 Ubuntu with options g++ -Im -O2 -std=c++0x.

Very frequently I need to complete some loop for two or three objects so I use wrap the expression in a range based for loop with a containing litteral.

In Python3 this would look like:

a = [1,2,3]
b = [4,5,6]

for v in (a,b):
    func(v)

In c++ this obviously isn't so simple. As far as I am aware, using {a,b} creates some type of initializer list, therefor casting does not properly work. In my attempts I come to something of this sort, but do no understand how I would properly pass by reference and also have it be mutable, as my compiler complains this is neccessarily const.

vector<int> a {1,2,3};
vector<int> b {4,5,6};

for(auto& v: {a,b}) // error non-const
    func(v);

Does the order of `const` and e.g. `int` make a difference in C? [duplicate]

I've looked around C and C++ FAQs and tutorials and haven't been able to find a clearcut answer.

What difference, if any, does it make to write:

const int i;
int const j;

While we are at it, is there any difference between

const int a[10];
int const b[10];

(Yes, I know about e.g. const int *p and int *const q, the first is a mutable pointer to a constant object, the second is a constant pointer to a mutable object).

Cannot enter while loop. Is it to do with using an unordered map?

I am trying to do a coding challenge where we have to shorten and minimise direction instructions. I am using an unordered map prior to implementing the while loop. The rest of the code works as expected but the while loop cannot be reached so I cannot output an appropriate value.

std::vector<std::string> dirReduc(std::vector <std::string>& arr)
{
    enum Direction
    {
        NORTH = 1, SOUTH = -1,
        EAST = 1, WEST = -1
    };
    int x=0, y=0;
    std::unordered_map<std::string, Direction> uMapDir = { {"North",NORTH},{"NORTH",NORTH},
                                                        {"South",SOUTH},{"SOUTH",SOUTH},
                                                        {"East",EAST},{"EAST",EAST},
                                                        {"West",WEST},{"WEST",WEST} };
    for (std::vector<std::string> ::const_iterator i =arr.begin(); i!=arr.end() ; i ++)
    {
        if ((*i=="North")||(*i == "NORTH")||(*i=="South")|| (*i == "SOUTH"))
        {
            y += uMapDir[*i];
        }
        else
        {
            x += uMapDir[*i];
        }
    }
    std::vector<std::string> outPutArr;
    while ((x!=0)&&(y!=0))
    {
        if (x<0)
        {
            x++;
            outPutArr.push_back("WEST");
        }
        else
        {
            x--;
            outPutArr.push_back("EAST");
        }

        if (y < 0)
        {
            y++;
            outPutArr.push_back("SOUTH");
        }
        else
        {
            y--;
            outPutArr.push_back("NORTH");
        }
    }
    return outPutArr;
}

code shows error in line 1034 which is not even in the code

this is the problem of leetcode..problem is to find the next permutation. it passes correctly on sample test cases but it shows error in line 1034 which is not even in the code..!! plz help

error code is-------

Line 1034: Char 34: runtime error: addition of unsigned offset to 0x602000000170 overflowed to 0x60200000016c (stl_vector.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:34

class Solution {
public:
    void nextPermutation(vector<int>& nums) 
    {
         int n = nums.size();
         int i=0,j=0;
      
        for(i=n-2;i>=0;i--)
        {
            if(nums[i]<nums[i+1])
                break;
        }
        if(i<0)
            sort(nums.begin(),nums.end());
        else
        {
             for(j=n-1;j>i;j--)
            {
                 if(nums[j]>nums[i])
                     break;
            }
        }
        swap(nums[i],nums[j]);
        sort(nums.begin()+i+1,nums.end());
    }
};

How do I use the destructor of an element of a doubly linked list? [closed]

My problem is the following, I have implemented a list in a class, which takes objects of type ListElement, where ListElements have a pointer to the next and previous list element. As in the example...

template <class value>
class ListElement
{

public:

    value content;
    ListElement* next;
    ListElement* previous;

    ListElement(value content, ListElement* next, ListElement* previous){
        this->content = content;
        this->next = next;
        this->previous = previous;
    };
    ~ListElement(){
        this->next = NULL;
        this->previous = NULL;
    };

};

template <class value>
class List : public Collection<value>
{

private:
    List<value>* first;
    Node<value>* last;


public:
    ListElement(){
        this->first = nullptr;
        this->last = nullptr;
    };
    ~ListElement(){
        if(!(this->isEmpty())){
             this->clear();
        }
        else{
            delete this->first;
            delete this->last;
        }
    };

    void clear(){
        Node<value>* currentNode = this->first, *nextNode = NULL;
    
        while (currentNode != NULL)
        {
            nextNode = currentNode->next;
            delete currentNode;
            currentNode = nextNode;
        }
    };
    

     void add(value t);
    
}

Now my question is how the destructor for a ListElement has to look like, with my solution so far it works, but i get an error when i check with valgrind for memory leaks.

The constructor of list element sets the next and the previous element, the destructor sets them to zero, the "content" can be ignored in this case, because I tried this only with int. When in destructor for ListElement delete this->next is executed I get a Segmentation Fault

Would be happy if someone could help me.

The DeleteFile function can be used to delete a file on close [closed]

I need a DeleteFile function. which can remove a file automatically when a program is closed. Please give me the DeleteFile function/method to delete a file on close in c++.

jeudi 28 janvier 2021

Need we use some runtime memory fence mechanism comparing with asm volatile

Let's say we have such a piece of c++ code:

auto t1 = getSystemTime(); // Statement 1
foo();                     // Statement 2
auto t2 = getSystemTime(); // Statement 3

auto elapsedTime = t2 - t1;

As my understanding, the compiler may optimize the code, meaning that it may reorder the execution order only if it doesn't break the as-if rule. For example, the order of execution of the code below

c = a + b;
d = e + f;

can be reordered as

d = e + f;
c = a + b;

So, the piece of code above may be reordered as below:

auto t1 = getSystemTime(); // Statement 1
auto t2 = getSystemTime(); // Statement 3
foo();                     // Statement 2

auto elapsedTime = t2 - t1;

which produces a totally different result.

After googling this issue, I got this: __asm__ __volatile__ ("" ::: "memory");. If I'm right, with this line, we can disable the optimisation of the compiler so the execution order won't be reordered.

If I use it correctly, the code would become as below:

__asm__ __volatile__ ("" ::: "memory");
auto t1 = getSystemTime(); // Statement 1
foo();                     // Statement 2
auto t2 = getSystemTime(); // Statement 3

auto elapsedTime = t2 - t1;

However, after reading some docs, I found that __asm__ __volatile__ ("" ::: "memory"); was just about compile-time, instead of runtime.

Now I'm confused. If __asm__ __volatile__ ("" ::: "memory"); works only during compile-time, does it mean that it is kind of totally useless because the execution order still can be changed at runtime? If so, is there some other mechanism to forbid the reordering at runtime? Or there is not any other mechanism so the execution order still can be reordered while runtime but with __asm__ __volatile__ ("" ::: "memory"); we can decrease the probability of reordering?

Besides, we have memory order in C++11, can the memory order help on this issue?

Interactively inputting data, assigning limits

I have zero experience in programming and am just starting For my COP3014 class, we have to write a program that accepts as input a pollutant number (integer), a number of grams emitted per mile (real), and an odometer reading (integer), and then prints an appropriate message indicating whether or not the emissions meet or exceed the legal limit for the vehicle. I kind of have the idea of it but I have no clue where to begin on the project.

Implementation of pattern "Multiplex" in c++11/14

Hey everybody and first of all forgive my poor english.

I have to implement the pattern "Multiplex" as described in "The Little Book of Semaphores" by Allen. B.Downey (it's a free resource).

I can't and I don't want use semaphores introduced in C++20 and so, only using mutex and condition variable, I came to the following code, maybe clumsy and twisted (spoiler):

/*
    PATTERN:    Multiplex

    TARGET:    allows multiple threads to run in the critical section at the
    same time, but it enforces an upper limit on the number of concurrent 
    threads. 
    In other words, no more than n threads can run in the critical section at 
    the same time
*/

//#include "stdafx.h"     // Only for MS Visual Studio
#include <mutex>
#include <condition_variable>
#include <iostream>
#include <thread>
#include <string>
#include <vector>

using namespace std;

//#define IF_EXPIRES_ON_ONLINE_COMPILER        //    comment/uncomment it if you need

mutex mtx_IO;    //    No interleaved output

vector<int> deb_evolution_of_threads_In_CR;    //    only for debug purposes

const int iterationForcpuConsumer = 1000;

void cpuConsumer(thread::id tid)    //    the first thing that came to my fingers
{
#ifndef IF_EXPIRES_ON_ONLINE_COMPILER
    {
        lock_guard<mutex> lg(mtx_IO);
        cout << "\n\tBEG cpuConsumer from #thread = " << tid;
    }

    string str = "str";
    for (int i = 0; i < iterationForcpuConsumer; ++i)
    {
        int j = i;
        try
        {
            str += str;
        }
        catch (...)
        {
            str = "";
        }
    }
    {
        lock_guard<mutex> lg(mtx_IO);
        cout << "\n\tEND cpuConsumer from #thread = " << tid;
    }
#else
    this_thread::sleep_for(chrono::milliseconds(1000));
#endif // !IF_EXPIRES_ON_ONLINE_COMPILER
}

const int totalNumThreadLaunched = 5;
const int upperLimitForThreadInCriticalRegion = 3;

const int nrOfIterations = 5;

mutex mtx_CR;
condition_variable cv;
int threads_In_CR = 0;

void threadLogic()
{
    for (int i = 0; i < nrOfIterations; ++i)
    {
        {
            lock_guard<mutex> lg(mtx_IO);
            cout << "\nElaboration that precedes the critical region for #thread = " << this_thread::get_id();
        }

        unique_lock<mutex> ul(mtx_CR);
        cv.wait(ul, []() {return (threads_In_CR < upperLimitForThreadInCriticalRegion); });
        ++threads_In_CR;
        deb_evolution_of_threads_In_CR.push_back(threads_In_CR);    //    only for debug purposes
        ul.unlock();

        cpuConsumer(this_thread::get_id());        //    Critical Region

        {
            lock_guard<mutex> lg(mtx_CR);
            --threads_In_CR;
            deb_evolution_of_threads_In_CR.push_back(threads_In_CR);    //    only for debug purposes
        }
        cv.notify_one();

        {
            lock_guard<mutex> lg(mtx_IO);
            cout << "\nElaboration that follows the critical region for #thread = " << this_thread::get_id();
        }
    }
}

int main()
{
    int DEBUG = 0;
    deb_evolution_of_threads_In_CR.push_back(0);

    vector<thread> vThreads;
    vThreads.reserve(totalNumThreadLaunched);
    for (int i = 0; i < totalNumThreadLaunched; ++i)
    {
        vThreads.push_back(thread(threadLogic));
    }

    for (int i = 0; i < totalNumThreadLaunched; ++i)
    {
        if (vThreads[i].joinable())
        {
            vThreads[i].join();
        }
    }

    for (auto i = deb_evolution_of_threads_In_CR.begin(); i != deb_evolution_of_threads_In_CR.end(); ++i)
    {
        cout << "\n" << *i;
    }

    return 0;
}

Here a link to Coliru.

I thought and thought again, I analyzed and reanalyzed, I watched the outputs (but you know that they are not a proof) but now I need a comparison.

Can you tell if this code is correct? And if not, where are the traps? Every other suggestion about a better design (inside the constraints of C++11/14) is well accepted.

PS: I suppose that something might be declared 'atomic' (correct me if I'm wrong) but anyway I didn't study deeply the C++ memory model and so suggestions in that direction are well accepted in any case but, at the moment, these notions are not at the top issue list; if I suppose the I don't really know something I don't want use it.

Finally: can you suggest some metodology, some tool, somewhat that can guide the approach to this kind of code/problems? I was thinking to Petri Nets

Probably this will not be my last question about the implementation of some similar patterns, I hope it will also join you in the next discussions.

Thank for your attention and for your time

C++ placement new not compatible with boost allocator

I'm using Boost.Interprocess shared memory, and I'm using interprocess Allocator with some STL compatible containers, when it comes to placement new, the code won't compile since placement new expect void * while boost::interprocess::allocator::pointer can't not be converted to void *.

below is a code to reproduce this


#include <memory>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>
namespace ipc = boost::interprocess;

typedef ipc::allocator<int, ipc::managed_shared_memory::segment_manager> ShmemAllocator;

int main() {
    struct shm_remove {
      shm_remove() { ipc::shared_memory_object::remove("MySharedMemory"); }
      ~shm_remove() { ipc::shared_memory_object::remove("MySharedMemory"); }
    } remover;
  ipc::managed_shared_memory segment(ipc::open_or_create, "MySharedMemory", 1024 * 1024 * 10);

  ShmemAllocator shm_alloc(segment.get_segment_manager());
  ShmemAllocator::pointer shm_ptr = shm_alloc.allocate(1);

  std::allocator<int> std_alloc;
  std::allocator<int>::pointer std_ptr = std_alloc.allocate(1);
  
  new(std_ptr) int(3);
  new(shm_ptr) int(3); // this line doesn't work

  return 0;
}

the compile error I got:

/home/ziqi.liu/ClionProjects/shared_memory_experiment/src/main_a.cpp: In function ‘int main()’:
/home/ziqi.liu/ClionProjects/shared_memory_experiment/src/main_a.cpp:22:21: error: no matching function for call to ‘operator new(sizetype, boost::interprocess::allocator<int, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> >::pointer&)’
   new(shm_ptr) int(3); // this line doesn't work
                     ^
In file included from /usr/include/c++/5/ext/new_allocator.h:33:0,
                 from /usr/include/x86_64-linux-gnu/c++/5/bits/c++allocator.h:33,
                 from /usr/include/c++/5/bits/allocator.h:46,
                 from /usr/include/c++/5/memory:63,
                 from /home/ziqi.liu/ClionProjects/shared_memory_experiment/src/main_a.cpp:1:
/usr/include/c++/5/new:111:7: note: candidate: void* operator new(std::size_t)
 void* operator new(std::size_t) _GLIBCXX_THROW (std::bad_alloc)
       ^
/usr/include/c++/5/new:111:7: note:   candidate expects 1 argument, 2 provided
/usr/include/c++/5/new:119:7: note: candidate: void* operator new(std::size_t, const std::nothrow_t&)
 void* operator new(std::size_t, const std::nothrow_t&) _GLIBCXX_USE_NOEXCEPT
       ^
/usr/include/c++/5/new:119:7: note:   no known conversion for argument 2 from ‘boost::interprocess::allocator<int, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> >::pointer {aka boost::interprocess::offset_ptr<int, long int, long unsigned int, 0ul>}’ to ‘const std::nothrow_t&’
/usr/include/c++/5/new:129:14: note: candidate: void* operator new(std::size_t, void*)
 inline void* operator new(std::size_t, void* __p) _GLIBCXX_USE_NOEXCEPT
              ^
/usr/include/c++/5/new:129:14: note:   no known conversion for argument 2 from ‘boost::interprocess::allocator<int, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> >::pointer {aka boost::interprocess::offset_ptr<int, long int, long unsigned int, 0ul>}’ to ‘void*’
In file included from /home/ziqi.liu/.tspkg/include/boost/interprocess/mem_algo/detail/mem_algo_common.hpp:35:0,
                 from /home/ziqi.liu/.tspkg/include/boost/interprocess/allocators/detail/allocator_common.hpp:35,
                 from /home/ziqi.liu/.tspkg/include/boost/interprocess/allocators/allocator.hpp:30,
                 from /home/ziqi.liu/ClionProjects/shared_memory_experiment/src/main_a.cpp:2:
/home/ziqi.liu/.tspkg/include/boost/container/detail/placement_new.hpp:24:14: note: candidate: void* operator new(std::size_t, void*, boost_container_new_t)
 inline void *operator new(std::size_t, void *p, boost_container_new_t)
              ^
/home/ziqi.liu/.tspkg/include/boost/container/detail/placement_new.hpp:24:14: note:   candidate expects 3 arguments, 2 provided
CMakeFiles/main_a.dir/build.make:62: recipe for target 'CMakeFiles/main_a.dir/src/main_a.cpp.o' failed
make[2]: *** [CMakeFiles/main_a.dir/src/main_a.cpp.o] Error 1
CMakeFiles/Makefile2:162: recipe for target 'CMakeFiles/main_a.dir/all' failed
make[1]: *** [CMakeFiles/main_a.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2

I'm sure there must a way to do this, since boost own containers are all compatible with boost::interprocess::allocator::pointer, but I'm not sure how they did it......I guess I should look for an alternative for placement new?

Fetching api with nlohmann/json

I want to use api with c++ and when I searched I found nlohmann/json library it looks really popular but no one talks about how to get the array that fetch function provides . How can I get the information from the api as variables in my cpp file

use of "&" operator in conditional statement in C++ [duplicate]

int main()
int n=5;
if(n & 1)
cout<<"odd";
else
cout<<"even";

how we are getting even or out using "&" operator it should have been like this

if(n%2!=0) to check the even or odd. can anyone explain what is that code doing.

Why the output of following code is value of variable k? [duplicate]

what programming concept is used here?

int main(){
int i = 1, j = 2, k = 4;
int p = (i,j,k);
cout << p;
return 0;
}

Undefined symbols for architecture x86_64 on gcc [duplicate]

I have read that I may have encountered some sort of bug or glitch with respect to the mac's regular GCC.. is this the case or is my code the culprit.. what do I mean??

% sh compile.sh                             
-- Conan: Adjusting output directories
-- Conan: Using cmake targets configuration
-- Conan: Adjusting default RPATHs Conan policies
-- Conan: Adjusting language standard
-- Current conanbuildinfo.cmake directory: /ch09_06_threadpool_local_queues/build
-- Configuring done
-- Generating done
-- Build files have been written to: /ch09_06_threadpool_local_queues/build
Scanning dependencies of target test_cpp_multi
[ 33%] Building CXX object CMakeFiles/test_cpp_multi.dir/src/helloworld.cpp.o
[ 66%] Linking CXX executable bin/test_cpp_multi
Undefined symbols for architecture x86_64:
  "thread-local wrapper routine for thread_pool::local_work_queue", referenced from:
      thread_pool::worker_thread() in helloworld.cpp.o
      thread_pool::run_pending_task() in helloworld.cpp.o
      std::__1::future<std::__1::result_of<std::__1::__bind<std::__1::list<int, std::__1::allocator<int> > (sorter<int>::*)(std::__1::list<int, std::__1::allocator<int> >&), sorter<int>*, std::__1::list<int, std::__1::allocator<int> > > ()>::type> thread_pool::submit<std::__1::__bind<std::__1::list<int, std::__1::allocator<int> > (sorter<int>::*)(std::__1::list<int, std::__1::allocator<int> >&), sorter<int>*, std::__1::list<int, std::__1::allocator<int> > > >(std::__1::__bind<std::__1::list<int, std::__1::allocator<int> > (sorter<int>::*)(std::__1::list<int, std::__1::allocator<int> >&), sorter<int>*, std::__1::list<int, std::__1::allocator<int> > >) in helloworld.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]: *** [bin/test_cpp_multi] Error 1
make[1]: *** [CMakeFiles/test_cpp_multi.dir/all] Error 2

This helloworld.cpp was working in the past.. and I am working with a C++ book trying to learn about concurrency where in which it adds this bit to the code.. but I am unable to compile..

https://github.com/anthonywilliams/ccia_code_samples/blob/main/listings/listing_9.6.cpp

class thread_pool
{
    std::atomic_bool done;
    thread_safe_queue<function_wrapper> work_queue;
    std::vector<std::thread> threads;
    join_threads joiner;

    thread_safe_queue<function_wrapper> pool_work_queue;
    typedef std::queue<function_wrapper> local_queue_type;
    static thread_local std::unique_ptr<local_queue_type> local_work_queue;

    void worker_thread()
    {
        local_work_queue.reset(new local_queue_type);

        while(!done)
        {
            run_pending_task();
        }
    }
...

    template<typename FunctionType>
    std::future<typename std::result_of<FunctionType()>::type> submit(FunctionType f)
    {
        typedef typename std::result_of<FunctionType()>::type result_type;
        std::packaged_task<result_type()> task(f);
        std::future<result_type> res(task.get_future());
        if(local_work_queue)
        {
            local_work_queue->push(std::move(task));
        }
        else
        {
            pool_work_queue.push(std::move(task));
        }
        return res;
    }

    void run_pending_task()
    {
        function_wrapper task;
        if(local_work_queue && !local_work_queue->empty())
        {
            task=std::move(local_work_queue->front());
            local_work_queue->pop();
            task();
        }
        else if(pool_work_queue.try_pop(task))
        {
            task();
        }
        else
        {
            std::this_thread::yield();
        }
    }

EDIT: For experimental purposes I went ahead and loaded up my code in a linux machine... same issue apparently, so it's not apple.. but not sure how to come to get it compiling

$ sh compile.sh 
-- The C compiler identification is GNU 9.3.0
-- The CXX compiler identification is GNU 9.3.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Conan: Adjusting output directories
-- Conan: Using cmake targets configuration
-- Conan: Adjusting default RPATHs Conan policies
-- Conan: Adjusting language standard
-- Current conanbuildinfo.cmake directory: /ch09_06_threadpool_local_queues/build
-- Conan: Compiler GCC>=5, checking major version 9
-- Conan: Checking correct version: 9
-- Configuring done
-- Generating done
-- Build files have been written to: /ch09_06_threadpool_local_queues/build
Scanning dependencies of target test_cpp_multi
[ 33%] Building CXX object CMakeFiles/test_cpp_multi.dir/src/thread_safe_queue.cpp.o
[ 66%] Building CXX object CMakeFiles/test_cpp_multi.dir/src/helloworld.cpp.o
[100%] Linking CXX executable bin/test_cpp_multi
/usr/bin/ld: CMakeFiles/test_cpp_multi.dir/src/helloworld.cpp.o: in function `TLS wrapper function for thread_pool::local_work_queue':
helloworld.cpp:(.text._ZTWN11thread_pool16local_work_queueE[_ZTWN11thread_pool16local_work_queueE]+0x9): undefined reference to `TLS init function for thread_pool::local_work_queue'
/usr/bin/ld: helloworld.cpp:(.text._ZTWN11thread_pool16local_work_queueE[_ZTWN11thread_pool16local_work_queueE]+0x19): undefined reference to `thread_pool::local_work_queue'
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/test_cpp_multi.dir/build.make:99: bin/test_cpp_multi] Error 1
make[1]: *** [CMakeFiles/Makefile2:76: CMakeFiles/test_cpp_multi.dir/all] Error 2
make: *** [Makefile:84: all] Error 2

doubly linked lists initiallisation

Hello so i'm something new to linked lists and data structrs generally so i want to creat two functions one initiallise the doubly linked list and the other one print it but when i compile it it doesnt print anything where did i miss exactly (i heard that i should use the debugger but i didnt understand how to use it on Dev c++ IDE)

  #include <iostream>
#include <stdlib.h>
using namespace std;
struct Node
{   int data;
    Node *next;
    Node *previous;
};
Node *head,*end;


Node* insertion()
{   
    Node *first_node =new Node;
    if (head==NULL || first_node==NULL)
        exit(EXIT_FAILURE);
        
    first_node->data=10;
    first_node->previous=NULL;
    first_node->next=NULL;
    head=first_node;
    end=first_node;
    return head;
}
void affiche()
{
    Node *current;
    current=head;
    if(head==NULL)
     exit(EXIT_FAILURE);
    while(current->next!=NULL)
    {
        cout<<current->data <<" ";
        current=current->next;
    }
}
int main()
{

    Node *MyList=insertion();
    affiche();
    return 0;
}

How is hexadecimal number 0x3F converted into decimal?

I recently saw this dude William Lin use this hexadecimal 0x3F in memset() where in the place where a character variable should be passed. Does 0x change the type of 3F. I think 3F in decimal is 63. And the in the ascii table, 63 corresponds to '? ' symbol. Instead of using the question mark, why did he use the hexadecimal? Or is there some other explanation? I really need to know! Thanks!

Using the armV5 compiler in keil with c99 and cpp11

I have a mixed project in Keil IDE with c and cpp files. I want to compile the cpp files with the cpp11 standard, but when I set the --cpp11 in the misc controls it compiles the C files as cpp files (and obviously that causes a lot of compilation errors) the c files needs to be compiles in the c99 standard. I ended up setting the --cpp11 flag just on a specific group to work around the issue. But I'm wondering if there is a way to set both of the rules (--cpp11 and --c99) to the entire project?

extern template declaration with alias payload

Consider this. There is a class Derived that inherits from some instantiation of a heavy templated class Base, and there are many uses of Derived in various source files. So it is reasonable to have only one Derived-specific instantiation of Base.

C++11 allows this via extern template, but the problem here is that I want to type the Derived-specific instantiation of Base only once. Technically it is possible, as Derived can hold an alias for that instantiation, but the question is: will it still force the compiler not to instantiate the template?

Here is the try:

// Base.hpp
template < typename Arg > struct Base { using TheArg = Arg; };

// Derived.hpp
#include "Base.hpp"
struct Derived : Base<int> { };
// The next line will be huge in real-world scenario, so I want to avoid it.
// extern template struct Base<int>;
// Instead I want this.
extern template struct Base<Derived::TheArg>;

// Derived.cpp
#include "Derived.hpp"
template struct Base<Derived::TheArg>;

// Use01.cpp
#include "Derived.hpp"
void use01() { Derived dd; }

The point here is to force Use01.cpp not to instantiate Base<int> and to refer to the explicit instantiation at Derived.cpp instead.

I am compiling with gcc-v9.3 and the questions are:

  1. Does extern template declaration takes effect to all instantiations in the translation unit, or only to those which appear after its declaration?
  2. Will using Derived::TheArg instead of int cause any problems with deferring the instantiation?

Putting the extern template declaration at the end of Use01.cpp and commenting out the explicit instantiation at Derived.cpp makes the compilation to fail, so this gives me some confidence that the extern template declaration doesn't have to appear before any instantiation, so the second question still makes sense.

Is there way to prevent defining user defined destructor of Derived class

Is there way to prevent defining user defined destructor of Derived class
I hope developers can't define user defined destructor of derived class of Class I made. My class supports some functions and users can utilize my class functions inheriting my class.

But defining custom destructor in derived class is dangerous, so I hope derived class has only default destructor.

I think I should make some macros about defining class, but I can't know how to. Or compile time make error when derived class has user defined destructor. (But I don't know how to do this)

Detecting Unicode in files in Windows 10

Now Windows 10 Notepad does not require unicode files to have the BOM header and it does not encode the header by default. This does break the existing code that checks the header to determine Unicode in files. How can I now tell in C++ if a file is in unicode? Source: https://www.bleepingcomputer.com/news/microsoft/windows-10-notepad-is-getting-better-utf-8-encoding-support/

The code we have to determine Unicode:

int IsUnicode(const BYTE p2bytes[3])
{
        if( p2bytes[0]==0xEF && p2bytes[1]==0xBB p2bytes[2]==0xBF) 
            return 1; // UTF-8
        if( p2bytes[0]==0xFE && p2bytes[1]==0xFF)
            return 2;  // UTF-16 (BE)
        if( p2bytes[0]==0xFF && p2bytes[1]==0xFE) 
            return 3; // UTF-16 (LE)
            
        return 0;
}

mercredi 27 janvier 2021

Bigger output than expected

I needed a program where a user orders items but the output was wrong. It was outputting 12-digit numbers when I only needed 2-3 digits. Why is it outputting bigger numbers than expected?

#include <iostream>
using namespace std;

int main()
    {
    //Order
    int Pfries = 80, Pburgers = 150, Pdonuts = 30, Picecream = 25, Psoftdrinks = 20;
    int Nfries, Nburgers, Ndonuts, Nicecream, Nsoftdrinks;
    int fries = Pfries * Nfries, burgers = Pburgers * Nburgers, donuts = Pdonuts * Ndonuts, icecream = 
    Picecream * Nicecream, softdrinks = Psoftdrinks * Nsoftdrinks;
    string customer;
    cout<<"Welcome to Murakani Cafe!"<<endl;
    cout<< "Enter the name of the customer: ";
    cin>>customer;
    cout<< "Enter the number of fries ordered:";
    cin>>Nfries;
    cout<< "Enter the number of burger(s) ordered: ";
    cin>>Nburgers;
    cout<< "Enter the number of donut(s) ordered: ";
    cin>>Ndonuts;
    cout<< "Enter the number of ice cream ordered: ";
    cin>>Nicecream;
    cout<< "Enter the number of soft drink(s) ordered: ";
    cin>>Nsoftdrinks;


    //Output
    cout<< "Hi "<< customer << "! Here is the summary of your order:"<<endl;
    cout<<""<<endl;
    cout<< Nfries << "    fries    "<< Pfries << fries <<endl;
    cout<< Nburgers<< "    burgers    "<< Pburgers << burgers<<endl;
    cout<< Ndonuts<< "    donuts    "<< Pdonuts << donuts<<endl;
    cout<< Nicecream<< "    ice cream    "<< Picecream << icecream<<endl;
    cout<< Nsoftdrinks<< "    soft drinks    "<< Psoftdrinks << softdrinks<<endl;


    return 0;
}

OpenGL 4.6, C++ drawing from different parts of glBufferStorage using glDrawArrays

Context: I am currently working on a 2D engine in Opengl 4.6 and C++. Part of the project is a large batch of sprites getting rendered in different batches, my current approach is using a combination of glBufferData and glBufferSubData to accomplish this. Recently been working on implementing something similar using persistent data mapping with glBufferStorage. However I have only been able to draw the first batch all consecutive batches don't get drawn and am a bit floored as to the reason why.

Code:

Renderer initialization

struct Renderer
    {
        Renderer(std::vector<GLuint> channel_sizes, GLuint indices_size, std::vector<GLuint> attribute_sizes)
            : current_material(nullptr), indices_size(indices_size), attribute_size(0), quad_count(0)
        {
            for (auto att : attribute_sizes)
                attribute_size += att;

            vertex_size = attribute_size * indices_size;

            auto max_sprites = 0;

            for (auto size : channel_sizes)
            {
                channels.push_back(max_sprites * vertex_size);
                max_sprites += size;
            }
            channels.push_back(max_sprites * vertex_size);

            this->channels = channels;
            this->curr_channel = this->channels.begin();
            this->next_channel = this->curr_channel + 1;

            glGenVertexArrays(1, &vao);
            glGenBuffers(1, &vbo);

            // Memory mapping flags
            GLbitfield fMap = GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT;

            // Buffer creation flags
            GLbitfield fCreate = fMap | GL_DYNAMIC_STORAGE_BIT;

            glBindVertexArray(vao);
            glBindBuffer(GL_ARRAY_BUFFER, vbo);

            // Initialize and allocate buffer object
            glBufferStorage(GL_ARRAY_BUFFER, (GLsizeiptr)(max_sprites * vertex_size), nullptr, fCreate);

            // Map from gpu to local 
            buffer = (float*)glMapBufferRange(GL_ARRAY_BUFFER, 0, (GLsizeiptr)(max_sprites * vertex_size), fMap);
            buffer_curr = buffer;

            auto stride = 0ull;
            for (auto i = 0; i < attribute_sizes.size(); ++i)
            {
                glEnableVertexAttribArray(i);
                glVertexAttribPointer(i, attribute_sizes[i], GL_FLOAT, GL_FALSE, attribute_size * sizeof(float), (GLvoid*)stride);
                stride += attribute_sizes[i] * sizeof(float);
            }
        }

        ~Renderer()
        {
            // delete allocated buffers
            glDeleteBuffers(1, &vbo);
            glDeleteBuffers(1, &vao);
        }

        GLuint max_sprites,
            indices_size,
            vertex_size,
            attribute_size,
            quad_count;

        std::vector<GLuint> channels;
        std::vector<GLuint>::iterator curr_channel;
        std::vector<GLuint>::iterator next_channel;

        float* buffer;
        float* buffer_curr;

        GLuint vbo;
        GLuint vao;

        Material* current_material;
    };
void flush(Renderer* renderer)
{
    if (!renderer->quad_count) return;

    if (!renderer->current_material)
    {
        renderer->quad_count = 0;
        renderer->buffer_curr = renderer->buffer;
        return;
    }

    // bind texture
    renderer->current_material->mat->bind(renderer->current_material->texture);

    // set uniforms and use shader
    renderer->current_material->mat->compile(renderer->current_material->shader);

    auto total_draws = (GLsizei)(renderer->quad_count * renderer->indices_size);
    auto first_pos = *renderer->curr_channel / renderer->attribute_size;

    // draw triangles
    glDrawArrays(GL_TRIANGLES, first_pos, total_draws);

    renderer->curr_channel++;
    renderer->buffer_curr = &renderer->buffer[*renderer->curr_channel];
    renderer->next_channel++;
    renderer->quad_count = 0;
}
void draw(Renderer* renderer, Src* src, Dest* dest, Material* material)
{
    if (renderer->next_channel == renderer->channels.end())
    {
        std::cerr << "not enough space to render batch: " << material->batch_id << std::endl;
        return;
    }

    if ((renderer->quad_count * renderer->vertex_size >= *renderer->next_channel || !renderer->current_material) || material->hash != renderer->current_material->hash)
    {
        pflush(renderer);
        renderer->current_material = material;
    }

    auto& buffer = renderer->buffer_curr;

    // first triangle
    *buffer++ = dest->dest.x;
    *buffer++ = dest->dest.w;
    *buffer++ = src->src.x;
    *buffer++ = src->src.w;

    *buffer++ = dest->dest.z;
    *buffer++ = dest->dest.y;
    *buffer++ = src->src.z;
    *buffer++ = src->src.y;

    *buffer++ = dest->dest.x;
    *buffer++ = dest->dest.y;
    *buffer++ = src->src.x;
    *buffer++ = src->src.y;

    // second triangle
    *buffer++ = dest->dest.x;
    *buffer++ = dest->dest.w;
    *buffer++ = src->src.x;
    *buffer++ = src->src.w;

    *buffer++ = dest->dest.z;
    *buffer++ = dest->dest.w;
    *buffer++ = src->src.z;
    *buffer++ = src->src.w;

    *buffer++ = dest->dest.z;
    *buffer++ = dest->dest.y;
    *buffer++ = src->src.z;
    *buffer++ = src->src.y;

    ++renderer->quad_count;
}
/*
    dest for sprites. with layer
eg:

  p1         
    *_______
    |       |
    |       |
    |       |
     -------*
             p2

    dest = {p1.x, p1.y, p2.x, p2.y}

*/
struct Dest
    {
        Dest(glm::vec4 dest)
            : dest(dest)
        {}

        Dest()
            : dest()
        {}

        glm::vec4 dest;
    };

struct Src : Component
    {
        Src()
            : src(0.0f)
        {}

        Src(glm::vec4 src)
            : src(src)
        {}

        glm::vec4 src;
    };

struct Material
    {
        Material(GLint tex_unit)
            : image(tex_unit)
        {}

        GLint image;

        void compile(Shader* shader) override
        {
            glUseProgram(shader->id);
            glUniform1i(glGetUniformLocation(shader->id, "image"), image);
        }

        void bind(Texture* tex)
        {
            glActiveTexture(GL_TEXTURE0 + image);
            glBindTexture(GL_TEXTURE_2D, tex->id);
        }
    };

main function (renders first 64 and not the next 64)

int main()
{
    // init gl/glad/glfw/etc...
    
    // load some textures and shaders...

    auto Texture1 = new Texture("tex src");
    auto Shader1 = new Shader("...vertex shader", "...fragment shader" )

    auto Texture2 = new Texture("tex src");
    auto Shader2 = new Shader("...vertex shader", "...fragment shader" )

    auto projection = glm::ortho(0.0f, static_cast<GLfloat>(800),
        static_cast<GLfloat>(600), 0.0f, -1.0f, 1.0f);
    
    glUniformMatrix4fv(glGetUniformLocation(Shader1->id, "projection"), 1, GL_FALSE, projection);
    glUniformMatrix4fv(glGetUniformLocation(Shader2->id, "projection"), 1, GL_FALSE, projection);   

    auto material1 = new Material(0);
    auto material2 = new Material(1);

    auto src = new Src({0,0,1,1});

    auto Dest dests[] = new Dest()[128];

    for(auto i = 0; i < 128; ++i)
    {
        auto x = (float)(std::rand() % 800) / 800.0f;
        auto y = (float)(std::rand() % 600) / 600.0f; 
        dests[i] = new Dest(x,y, x + 32, y + 32) 
    }
    auto renderer = new Renderer({128, 128},  6u, { 2u, 2u })
    
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    renderer->current_material = nullptr;
    renderer->quad_count = 0;
    renderer->buffer_curr = renderer_->buffer;
    renderer->curr_channel = renderer_->channels.begin();
    renderer->next_channel = renderer_->curr_channel + 1;
    
    for (auto i = 0; i < 64; ++i)
        draw(renderer, src, dest[i], material1);
    for (auto i = 64; i < 128; ++i)
        draw(renderer, src, dest[i], material2);
    flush(renderer);

    std::cin.ignore();
}

Export OpenEXR file from Google Colab

Right now, I have some code that is storing an OpenEXR file:

    FrameBuffer frameBuffer;
    frameBuffer.insert ("G", Slice(FLOAT, (char *)data, sizeof(*data),
                                   sizeof(*data)*width));
    frameBuffer.insert ("Z", Slice(FLOAT, (char *)rangeMod,
                                   sizeof(*rangeMod),
                                   sizeof(*rangeMod)*width));
    file.setFrameBuffer(frameBuffer);
    file.writePixels(height);

But how do I export this file out to a Google Drive folder from Colab?

Thank you!

templated class List

I have a header file ListTraits.h, with the following content:

#pragma once

//------------ Declarations for List traits used in Test1 in main.cpp

template <typename T>
class ListTraits
{
public:
    virtual unsigned int size() = 0;
    virtual ListTraits& insert(const T& item) = 0;
    virtual void print() = 0;
};

//------------ Declarations for List traits used in Test2 in main.cpp
template <typename T>
class ListTraitsExtended
{
public:
    virtual const T* getCurrentElement() const = 0;
    virtual void advance() = 0;
    virtual void rewind() = 0;
};

I am trying to implement a templated class List<T>, that models a singly linked list and implements its functionality, and I could use all the help you could give me.

The templated class List<T> will inherit the methods from the ListTraits.h


Then I must include "ListTraits.h in a main.cpp file and run this code,

that makes calls to the implementation of list in List<T>

Here is the main.cpp::

#include <iostream>
#include <cstdio>

#include "include/List.h"
#include <random>

void Test1()
{
    std::cout << "---------------------------- TEST 1 -------------------------------\n";
    std::cout << "Create a simple ordered list of specific items.\n";
    List<int> list;
    list.insert(1);
    list.insert(4);
    list.insert(2);
    list.insert(6);
    list.insert(3);
    list.insert(0);
    list.insert(2);
    std::cout << "List size should be 7: " << (list.size() == 7 ? "PASS" : "FAIL") << ".\n";
    std::cout << "Test should print: 0 1 2 2 3 4 6\n";
    std::cout << "Output:            ";
    list.print();

}

int main(int argc, char ** argv)
{
    if (argc < 2)
    {
        exit(-1);
    }
    int seed = 5;
    
    Test1();
    //Test2(seed);
    //Test3(seed);

    getchar();
}

I am not even sure how to get started with this, so I would be really grateful, and thankful, for any advice.

How to trim the alphabets along with leading zeroes from a std::string

I have a std::string variable with value as ABC000090007012.
I want to trim the alphabets and the leading zeroes prepending the actual number 90007012 into an unsigned int. What is the best way to do that using C++11?

Code:

std::string str = ABC000090007012;
unsigned int number = // How to get the 90007012 out of it?

Identify system table in Oracle 11

ALL,

Is there a way to identify the system tables in Oracle 11g?

If I call SQLTables() API, I will get a list of all tables available. What I'd like is to identify what table is internal Oracle and which one is user-made.

I'm connecting with the system account. (a dba one).

TIA!

Qt GUI thread is not responding when camera is streaming

I am using Basler camera to stream images and analyze the image at the same time. The program has camera class, an image detection class, an image acquisition class in a subproject static library. A GUI to show the stream in another GUI subproject. However, when the program is running, the GUI keeps "not responding" while the camera is streaming. What did I do wrong, do I need to implement QThread in this scenario? If I have to use QThread, should I use it in the main GUI thread or in the Acquisition? Camera class to grab image stream from Basler camera:

class ICam: public QObject
    ,public Pylon::CImageEventHandler  {
    Q_OBJECT
    public:
        ICam(QObject *parent = nullptr);
        Mat GetOpencvImage();
        void StartContinuousGrabbing();
    signals:
        void OneImageFinishSignal();
    protected:
        virtual void OnImageGrabbed(Pylon::CInstantCamera& camera, const Pylon::CGrabResultPtr& grabResult);
    private:
        CBaslerUniversalInstantCamera m_camera;
};

void ICam::OnImageGrabbed(Pylon::CInstantCamera& camera, const Pylon::CGrabResultPtr& grabResult)
{
    clock.Lock();
    m_ptr_grab_result = grabResult;//Pass the captured image out
    m_bitmap_image.CopyImage(grabResult);
    clock.Unlock();
    emit OneImageFinishSignal();
}

Mat ICam::GetOpencvImage(){
    return cv::Mat(m_bitmap_image.GetHeight(), m_bitmap_image.GetWidth(), CV_8UC3, (uint8_t *)m_bitmap_image.GetBuffer());
}

void ICam::StartContinuousGrabbing(){
    m_camera.StartGrabbing( Pylon::GrabStrategy_OneByOne, Pylon::GrabLoop_ProvidedByInstantCamera);
}

Detect class to do image processing to detect the iris eye:

class Detect : public QObject
{
    Q_OBJECT
    public:
       explicit Detect(QObject *parent = nullptr);
       cv::Point CalculateIrisOffset(cv::Mat img_input);
 };


cv::Point Detect::CalculateIrisOffset(cv::Mat img_input, bool show) {

    //Some Code to detect the iris

    return center_offset;
}

Acquisition class contains an icam object of ICam class and a detect object of Detect class as member attributes, it receives signal from the icam object when an image is grabbed and send signal to the GUI to display the image, at the same time, it calls the detect function of the Detect class to process the image:

class Acquisition: public QObject
{
    Q_OBJECT
    public:
        Acquisition (QObject *parent = nullptr);
        void StartContinuousGrabbing();
        Mat GetOpenCVImageFromICam();
    signals:
        void OneImageFinishSignal();
    private slots:
        void OneImageFinishSlot();
    private:
        ICam *icam;
        Detect *detect;
};
Acquisition:: Acquisition(QObject *parent) : QObject(parent)
                                                    ,icam(new ICam())
                                                    ,detect(new Detect())
{
    //connect(this->icam, SIGNAL(OneImageFinishSignal()), this, SIGNAL(OneImageFinishSignal()));
    connect(this->icam, SIGNAL(OneImageFinishSignal()), this, SLOT(OneImageFinishSlot()));
}

void Acquisition::OneImageFinishSlot(){
    cv::Mat img_input= icam-> GetOpencvImage ();
    cv::Point center_iris_offset;
    center_offset = detect->CalculateOffset(img_input, 0);
    emit(OneImageFinishSignal());
}
void Acquisition::StartContinuousGrabbing(){
    this->icam->StartContinuousGrabbing();
}
Mat CDLImageAcquisition::GetOpenCVImageFromICam(){
    return this->icam_->GetOpencvImage();
}

Main GUI class:

class MainWizard : public QWizard
{
    Q_OBJECT
    public:
        explicit MainWizard(QWidget *parent = nullptr);
    private slots:
        void OneImageFinishSlot();
        void ShowImage(QWidget *object, Mat image);
    private:
        virtual bool eventFilter(QObject *watched, QEvent *event);
        Acquisition *acquisition;
};

MainWizard::MainWizard(QWidget *parent) :
    QWizard(parent),
    ui(new Ui::MainWizard), 
    acquisition(new Acquisition())
{
    ui->setupUi(this);
    ui->dock_cnt_continuous_grab->installEventFilter(this);//Install Qt's event filter
    acquisition ->StartContinuousGrabbing();
    connect(acquisition, SIGNAL(OneImageFinishSignal()), this, SLOT(OneImageFinishSlot()));
}

void MainWizard::OneImageFinishSlot(){
    ui->dock_cnt_continuous_grab->update();

}

bool MainWizard::eventFilter(QObject *watched, QEvent *event)
{
  if (watched == ui->dock_cnt_continuous_grab && event->type() == QEvent::Paint)
  {
      cv::Mat opencv_image = acquisition->GetOpenCVImageFromICam();
      this->ShowImage(ui->dock_cnt_continuous_grab, opencv_image);
  }
  return false;
}

C++ : vector subscript out of range?

I'm new to C++ and I'm trying to write a program which opens a file "parameters.txt", which has 8 space-delimited numbers in it. Then I use these numbers in a separate function RK4() to get 3 arrays (y1, y2, t). Then I manipulate these arrays in main() and output a file "output.txt" to the working directory

This is my code:

#include <string>
#include <iostream>
#include <cmath>
#include <fstream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <tuple>
using namespace std;

tuple<vector<double>, vector<double>, vector<double>> RK4() {

    //open parameters.txt, put data into a vector
    ifstream fin("parameters.txt");
    vector<double> data;
    int element;
    while (fin >> element) {
        data.push_back(element);
    }

    //define tspan
    vector<double> tspan(2);
    tspan[0] = 0.0;
    tspan[1] = data[7];

    //define y0
    vector<double> y0(4);
    y0[0] = data[4];
    y0[1] = data[5];
    y0[2] = 0.0;
    y0[3] = 0.0;
    double theta1 = y0[0];
    double theta2 = y0[1];
    double omega1 = y0[2];
    double omega2 = y0[3];

    //define stepSize
    double stepSize;
    stepSize = data[6];

    //define range
    int range = int(tspan[1] / stepSize);

    //define other constants
    double m1, m2, l1, l2;
    m1 = data[0];
    m2 = data[1];
    l1 = data[2];
    l2 = data[3];
    double g = 9.81;

    //define y, t vectors
    vector<double> y1(range);
    vector<double> y2(range);
    vector<double> y3(range);
    vector<double> y4(range);
    vector<double> t(range);
    for (double i = 0.0; i < 1.0 * range; i++) {
        t[i] = i * stepSize;
    }

    //enter y0 into first value
    y1[0] = theta1;
    y2[0] = theta2;
    y3[0] = omega1;
    y4[0] = omega2;

    //loop to find y, t vectors
    for (int i = 0; i < range - 1; i++) {
        //finding all k values:
        //k1
        double dTheta1_1 = y3[i];
        double dOmega1_1 = (-g * (2 * m1 + m2) * sin(y1[i]) - m2 * g * sin(y1[i] - 2 * y2[i]) - 2 * sin(y1[i] - y2[i]) * m2 * (pow(y4[i], 2) * l2 + pow(y3[i], 2) * l1 * cos(y1[i] - y2[i]))) / (l1 * (2 * m1 + m2 - m2 * cos(2 * y1[i] - 2 * y2[i])));
        double dTheta2_1 = y4[i];
        double dOmega2_1 = (2 * sin(y1[i] - y2[i]) * (pow(y3[i], 2) * l1 * (m1 + m2) + g * (m1 + m2) * cos(y1[i]) + pow(y4[i], 2) * l2 * m2 * cos(y1[i] - y2[i]))) / (l2 * (2 * m1 + m2 - m2 * cos(2 * y1[i] - 2 * y2[i])));

        //k2
        double dTheta1_2 = y3[i] + 0.5 * stepSize * dTheta1_1;
        double dOmega1_2 = (-g * (2 * m1 + m2) * sin(y1[i] + 0.5 * stepSize * dTheta1_1) - m2 * g * sin((y1[i] + 0.5 * stepSize * dTheta1_1) - 2 * (y2[i] + 0.5 * stepSize * dTheta2_1)) - 2 * sin((y1[i] + 0.5 * stepSize * dTheta1_1) - (y2[i] + 0.5 * stepSize * dTheta2_1)) * m2 * (pow(y4[i] + 0.5 * stepSize * dOmega2_1, 2) * l2 + pow(y3[i] + 0.5 * stepSize * dOmega1_1, 2) * l1 * cos((y1[i] + 0.5 * stepSize * dTheta1_1) - (y2[i] + 0.5 * stepSize * dTheta2_1)))) / (l1 * (2 * m1 + m2 - m2 * cos(2 * (y1[i] + 0.5 * stepSize * dTheta1_1) - 2 * (y2[i] + 0.5 * stepSize * dTheta2_1))));
        double dTheta2_2 = y4[i] + 0.5 * stepSize * dTheta2_1;
        double dOmega2_2 = (2 * sin((y1[i] + 0.5 * stepSize * dTheta1_1) - (y2[i] + 0.5 * stepSize * dTheta2_1)) * (pow(y3[i] + 0.5 * stepSize * dOmega1_1, 2) * l1 * (m1 + m2) + g * (m1 + m2) * cos(y1[i] + 0.5 * stepSize * dTheta1_1) + pow(y4[i] + 0.5 * stepSize * dOmega2_1, 2) * l2 * m2 * cos((y1[i] + 0.5 * stepSize * dTheta1_1) - (y2[i] + 0.5 * stepSize * dTheta2_1)))) / (l2 * (2 * m1 + m2 - m2 * cos(2 * (y1[i] + 0.5 * stepSize * dTheta1_1) - 2 * (y2[i] + 0.5 * stepSize * dTheta2_1))));

        //k3
        double dTheta1_3 = y3[i] + 0.5 * stepSize * dTheta1_2;
        double dOmega1_3 = (-g * (2 * m1 + m2) * sin(y1[i] + 0.5 * stepSize * dTheta1_2) - m2 * g * sin((y1[i] + 0.5 * stepSize * dTheta1_2) - 2 * (y2[i] + 0.5 * stepSize * dTheta2_2)) - 2 * sin((y1[i] + 0.5 * stepSize * dTheta1_2) - (y2[i] + 0.5 * stepSize * dTheta2_2)) * m2 * (pow(y4[i] + 0.5 * stepSize * dOmega2_2, 2) * l2 + pow(y3[i] + 0.5 * stepSize * dOmega1_2, 2) * l1 * cos((y1[i] + 0.5 * stepSize * dTheta1_2) - (y2[i] + 0.5 * stepSize * dTheta2_2)))) / (l1 * (2 * m1 + m2 - m2 * cos(2 * (y1[i] + 0.5 * stepSize * dTheta1_2) - 2 * (y2[i] + 0.5 * stepSize * dTheta2_2))));
        double dTheta2_3 = y4[i] + 0.5 * stepSize * dTheta2_2;
        double dOmega2_3 = (2 * sin((y1[i] + 0.5 * stepSize * dTheta1_2) - (y2[i] + 0.5 * stepSize * dTheta2_2)) * (pow(y3[i] + 0.5 * stepSize * dOmega1_2, 2) * l1 * (m1 + m2) + g * (m1 + m2) * cos(y1[i] + 0.5 * stepSize * dTheta1_2) + pow(y4[i] + 0.5 * stepSize * dOmega2_2, 2) * l2 * m2 * cos((y1[i] + 0.5 * stepSize * dTheta1_2) - (y2[i] + 0.5 * stepSize * dTheta2_2)))) / (l2 * (2 * m1 + m2 - m2 * cos(2 * (y1[i] + 0.5 * stepSize * dTheta1_2) - 2 * (y2[i] + 0.5 * stepSize * dTheta2_2))));

        //k4
        double dTheta1_4 = y3[i] + stepSize * dTheta1_3;
        double dOmega1_4 = (-g * (2 * m1 + m2) * sin(y1[i] + stepSize * dTheta1_3) - m2 * g * sin((y1[i] + stepSize * dTheta1_3) - 2 * (y2[i] + stepSize * dTheta2_3)) - 2 * sin((y1[i] + stepSize * dTheta1_3) - (y2[i] + stepSize * dTheta2_3)) * m2 * (pow(y4[i] + stepSize * dOmega2_3, 2) * l2 + pow(y3[i] + stepSize * dOmega1_3, 2) * l1 * cos((y1[i] + stepSize * dTheta1_3) - (y2[i] + stepSize * dTheta2_3)))) / (l1 * (2 * m1 + m2 - m2 * cos(2 * (y1[i] + stepSize * dTheta1_3) - 2 * (y2[i] + stepSize * dTheta2_3))));
        double dTheta2_4 = y4[i] + stepSize * dTheta2_3;
        double dOmega2_4 = (2 * sin((y1[i] + stepSize * dTheta1_3) - (y2[i] + stepSize * dTheta2_3)) * (pow(y3[i] + stepSize * dOmega1_3, 2) * l1 * (m1 + m2) + g * (m1 + m2) * cos(y1[i] + stepSize * dTheta1_3) + pow(y4[i] + stepSize * dOmega2_3, 2) * l2 * m2 * cos((y1[i] + stepSize * dTheta1_3) - (y2[i] + stepSize * dTheta2_3)))) / (l2 * (2 * m1 + m2 - m2 * cos(2 * (y1[i] + stepSize * dTheta1_3) - 2 * (y2[i] + stepSize * dTheta2_3))));


        double theta1New = y1[i] + (stepSize / 6.0) * (dTheta1_1 + 2 * dTheta1_2 + 2 * dTheta1_3 + dTheta1_4);
        double omega1New = y3[i] + (stepSize / 6.0) * (dOmega1_1 + 2 * dOmega1_2 + 2 * dOmega1_3 + dOmega1_4);
        double theta2New = y2[i] + (stepSize / 6.0) * (dTheta2_1 + 2 * dTheta2_2 + 2 * dTheta2_3 + dTheta2_4);
        double omega2New = y4[i] + (stepSize / 6.0) * (dOmega2_1 + 2 * dOmega2_2 + 2 * dOmega2_3 + dOmega2_4);


        // updating y arrays 
        y1[i + 1] = theta1New;
        y2[i + 1] = theta2New;
        y3[i + 1] = omega1New;
        y4[i + 1] = omega2New;

    }
    return make_tuple(y1, y2, t);
}

int main() {

    //open parameters.txt, put data into a vector
    ifstream fin("parameters.txt");
    vector<double> data;
    int element;
    while (fin >> element) {
        data.push_back(element);
    }
   
    //define tspan
    vector<double> tspan(2);
    tspan[0] = 0.0;
    tspan[1] = 10.0;

    //define stepSize
    double stepSize;
    stepSize = data[6];

    //define range
    int const range = 1000;

    //define other constants
    double l1 = data[2];
    double l2 = data[3];

    //get y1, y2, t from RK4 function
    auto temp = RK4();
    vector<double> y1 = get<0>(temp);
    vector<double> y2 = get<1>(temp);
    vector<double> t = get<2>(temp);
    double x_1[range], y_1[range], x_2[range], y_2[range];

    //define x_1, x_2, y_1, y_2
    for (int i = 0; i < range; i++) {
        x_1[i] = { sin(y1[i]) * l1 };
        y_1[i] = { -cos(y1[i]) * l1 };
        x_2[i] = { sin(y1[i]) * l1 + sin(y2[i]) * l2 };
        y_2[i] = { -cos(y1[i]) * l1 - cos(y2[i]) * l2 };
    }

    //writing x,y positions at time t to output.txt
    ofstream myfile;
    myfile.open("C:\\mydirectory\\output.txt");
    if (myfile.is_open()) {
        myfile << "t: " << endl;
        for (int i = 0; i < range; i++) {
            myfile << t[i] << " ";
        }
        cout << endl;
        myfile << "x_1: " << endl;
        for (int i = 0; i < range; i++) {
            myfile << x_1[i] << " ";
        }
        cout << endl;
        myfile << "y_1: " << endl;
        for (int i = 0; i < range; i++) {
            myfile << y_1[i] << " ";
        }
        cout << endl;
        myfile << "x_2: " << endl;
        for (int i = 0; i < range; i++) {
            myfile << x_2[i] << " ";
        }
        cout << endl;
        myfile << "y_2: " << endl;
        for (int i = 0; i < range; i++) {
            myfile << y_2[i] << " ";
        }
        cout << endl;
        myfile.close();

    }
    else cout << "Unable to open file";

    return 0;
}

When I try to build and run the program (in Visual Studio) I get this error:

The thread 0x22c0 has exited with code 0 (0x0). Debug Assertion Failed!

Expression: vector subscript out of range

For information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts.

The program has exited with code 3 (0x3).

When I try to debug the program, I get:

Exception Thrown c++ coursework new.exe has triggered a breakpoint.

What is the problem?

ofstream not outputting file

I'm trying to output some arrays to a file "output.txt". I run this code with no errors but no output file seems to be created to the working directory

ofstream myfile("output.txt");
    if (myfile.is_open()) {
        myfile << "t: " << endl;
        for (int i = 0; i < range; i++) {
            myfile << t[i] << " ";
        }
        cout << endl;
        myfile << "x_1: " << endl;
        for (int i = 0; i < range; i++) {
            myfile << x_1[i] << " ";
        }
        cout << endl;
        myfile << "y_1: " << endl;
        for (int i = 0; i < range; i++) {
            myfile << y_1[i] << " ";
        }
        cout << endl;
        myfile << "x_2: " << endl;
        for (int i = 0; i < range; i++) {
            myfile << x_2[i] << " ";
        }
        cout << endl;
        myfile << "y_2: " << endl;
        for (int i = 0; i < range; i++) {
            myfile << y_2[i] << " ";
        }
        cout << endl;
        myfile.close();

    }
    else cout << "Unable to open file";

What's the problem?

How to properly use template class with an abstract pointer type

I created a List with a template Node class to hold different data types such as Node<int> but also more complex types such as Node<BaseEvent*>.

I also have an event container class to hold different event objects so it has a member argument

List<BaseEvent*> events;

where BaseEvent is an abstract class with derived classes that are not abstract.

In the event container I have a method called "add" (see below) that adds a new event to that events.

BaseEvent* eventClone = event.clone();

The clone returns a pointer to a new derived object such as:

new OpenEvent(*this);

Once it calls the list's insert method, it instantiates a new Node (see below), and in the Node constructor it assigns the value like so:

value(new T(new_value)) 

So basically it allocates a pointer memory (T=BaseEvent*).

I think I might be losing the eventClone pointer and have a memory leak. The problem is that when I debugged it I saw that both: T* value; (aka BaseEvent** value) and BaseEvent* eventClone have the same address in memory.

I'm not sure if when I do delete value in the destructor of Node it will just free the pointer allocation to BaseEvent* or also the data that it holds.

Any insights are welcome!


Relevant code snippets

Node<T>

    template <class T>
    class Node
    {
    public:

        Node(const T& new_value, Node* new_next = NULL, Node* new_prev = NULL);
        ~Node();

        const T& getValue() const;
        Node<T>* getNext() const;
        Node<T>* getPrev() const;
        void setNext(Node* node);
        void setPrev(Node* node);

    private:
        T* value;
        Node* next;
        Node* prev;
    };

    template <class T>
    Node<T>::Node(const T& new_value, Node* new_next, Node* new_prev) : 
        value(new T(new_value)) 
    {
        next = new_next;
        prev = new_prev;
    }

    template <class T>
    Node<T>::~Node()
    {
        delete value;
    }
    ...

Linked list that uses Node<T>

    template <class T>
    class List
    {
    public:
        List();
        ~List();
        
        int getSize() const;
        Node<T>* getFirst() const;
        Node<T>* getNext(Node<T>& node) const;
        Node<T>* getPrev(Node<T>& node) const;
        void insertStart(const T& data);
        void insertLast(const T& data);
        void insertAfter(Node<T>& target, const T& data);
        void insertBefore(Node<T>& target, const T& data);
        void removeNode(Node<T>& node);
        bool contains(const T data);


    private:
        Node<T>* head;
        int size;
    };

    template <class T>
    List<T>::List() : head(NULL), size(0)
    {
    }

    template <class T>
    List<T>::~List()
    {
        Node<T>* temp;
        while (head)
        {
            temp = head;
            head = head->getNext();
            delete temp;
            size--;
        }
    }
    ...
    template <class T>
    void List<T>::insertStart(const T& data) {
        if (size == 0)
        {
            head = new Node<T>(data);
        }
        else
        {
            Node<T>* temp = new Node<T>(data, head);
            head->setPrev(temp);
            head = temp;
        }

        size++;
    }
    ...

The event container class:

    class EventContainer
    {
    public:
        EventContainer() :
            events(List<BaseEvent*>()) {}
        ~EventContainer() {}

        virtual void add(const BaseEvent&);
        
        class EventIterator
        {
        public:
            EventIterator() :
                current(NULL) {}
            EventIterator(Node<BaseEvent*>& node) :
                current(&node) {}
            EventIterator(Node<BaseEvent*>* node) :
                current(node) {}
            ~EventIterator() {}

            EventIterator& operator=(const EventIterator& nodeIterator) {
                current = nodeIterator.current;
                return *this;
            }
            EventIterator& operator++() {
                current = current->getNext();
                return *this;
            }
            BaseEvent& operator*() const {
                return *(current->getValue());
            }

            friend bool operator==(const EventIterator& iterator1, const EventIterator& iterator2) {
                return iterator1.current == iterator2.current;
            }

            bool operator!=(const EventIterator& iterator) const {
                return !(*this == iterator);
            }

        private:
            Node<BaseEvent*>* current;
        };

        virtual EventIterator begin() const;
        virtual EventIterator end() const;

    private:
        List<BaseEvent*> events;
    };

The implementation of add method:

    void EventContainer::add(const BaseEvent& event) {
        BaseEvent* eventClone = event.clone();
        if (events.getSize() == 0)
        {
            events.insertStart(eventClone);
            return;
        }

        Node<BaseEvent*>* current = events.getFirst();
        while (current != NULL)
        {
            if (*eventClone < *(current->getValue()))
            {
                events.insertBefore(*current, eventClone);
                return;
            }
            current = current->getNext();
        }

        events.insertLast(eventClone);
    }

    EventContainer::EventIterator EventContainer::begin() const {
        return events.getFirst();
    }
    
    EventContainer::EventIterator EventContainer::end() const {
        return NULL;
    }

Class inheritance but encounter redefinition error in C++

I'm learning C++ Data Structure, about implementing Stack using Array and Linked List. The array is default in C++ but I've constructed a Linked List class. The code below is my Linked List header file

#pragma once
#include "Node.h"
#include "Stack.h"
class LinkedList
{
public:
    LinkedList() {head = NULL;}
    Node* AddNode(int index, float x, bool doubly);
    int FindNodeIndex(float x);
    Node* FindNodeAddress(float x);
    void DeleteNode(float x);
    void DisplayList();
    
private:
    Node* head;
    friend class Stack;
};

which also used the Node header file, but it is not relevant here. Then I would like to implement stack using both array and linked list. Below is my Stack header file:

#pragma once

class Stack
{
public:
    Stack(int size = 10);
    bool IsEmpty() { return top == -1;}
    bool IsFull() { return top == maxTop;}
    double Top();
    void Push(const double x);
    double Pop();
    void DisplayStack();
    void Clear();
private:
    int maxTop;
    int top;
    double* values;
};

class Stack: public LinkedList
{
public:
    Stack(){}
    double Top()
    {
        if (!head)
        {
            std::cout << "The stack is empty." << std::endl;
            return -1;
        }
        else
            return head->data;
    }
    void Push(const double x) {AddNode(0,x);}
    void DisplayStack() { DisplayList();}
}

You can see in the Top() method, which is used to find the top element of the linked list, used the head variable (or explicitly, pointer of Node), where in the implementation of array, I have the same Top() method but it only use indexed array. The compiler give me this error message

Stack.h:20:7: error: redefinition of 'class Stack'
   20 | class Stack: public LinkedList

I knew I've probably made some mistake here, but I think it is necessary to write two Stack classes because they have different purpose, for example the Top() method cannot be used for both. Is it possible to combine both as one Stack class, then notify the compiler whether to use array or linked list?

Idleness limit exceeded

I recently took part in a coding contest and I found idleness limit exceeded on test 1 in case of my submission while it was working perfectly fine on my offline ide. The link to the question is:

Alice and Bob are at yet another guessing game. Bob chooses a number k between 1 and n (1≤n≤10^9). Now, Alice makes a guess g:

if g<k, Bob responds with lesser and changes k to k−⌊k−g2⌋
if g>k, Bob responds with greater and changes k to k+⌊g−k2⌋
if g=k, Bob responds with guessed and Alice wins the game.

Alice is allowed to make not more than 16 guesses.

Input
A single integer n (1≤n≤109) such that the number k chosen by Bob is 1≤k≤n.

Output
Print your guess g (1≤g≤n) in a single line.

Interaction
To every g that you print, the judge may give one of the three responses- greater, lesser, guessed. As soon as you receive guessed, you have to terminate your program else you may receive any verdict. You are allowed to make not more than 16 guesses and must terminate your program irrespective of the response after the 16th guess.

and my submission is:


    #include<iostream>
    #include<cmath>
    using namespace std;
    
    int main()
    {
        long long int n;
        cin>>n;
        int g;
        long long int k=rand()%(n);
        int i=16;
        while(i--)
        {
            cin>>g;
            cout<<endl;
            if(g==k)
            {
                cout<<"guessed"<<endl;
                exit(0);
            }
            if(g<k)
            {
                cout<<"lesser"<<endl;
                k=k-floor((k-g)/2);
    
            }
            if(k<g)
            {
                cout<<"greater"<<endl;
                k=k+floor((g-k)/2);
    
            }
    
    
        }
    }

I searched on codeforces blog and found that in c we need to use fflush but I am using c++11 where it is automatically done when I use endl. Please help. thanks in advance!

mardi 26 janvier 2021

How to use std::partial_sum and output to a std::map?

I want an output map that has { {0,1},{1,2},{2,3},{3,4},{4,5} }, c++11 only. Any ideas?

std::map<int, int> m, out;
for( auto i=0; i < 5; ++i ) 
    m[i] = 1;

std::partial_sum( m.begin(), m.end(), std::inserter( out, out.begin() ),
        []( const std::pair<int,int>& a, const std::pair<int,int>& b ) 
             { return std::pair<int,int>( a.first, a.second + b.second ); } 
);

This gives compile error:

/usr/include/c++/5/bits/stl_pair.h: In instantiation of ‘std::pair<_T1, _T2>& std::pair<_T1, _T2>::operator=(std::pair<_U1, _U2>&&) [with _U1 = int; _U2 = int; _T1 = const int; _T2 = int]’:
/usr/include/c++/5/bits/stl_numeric.h:295:12:   required from ‘_OutputIterator std::partial_sum(_InputIterator, _InputIterator, _OutputIterator, _BinaryOperation) [with _InputIterator = std::_Rb_tree_iterator<std::pair<const int, int> >; _OutputIterator = std::insert_iterator<std::map<int, int> >; _BinaryOperation = main()::<lambda(const std::pair<int, int>&, const std::pair<int, int>&)>]’
../src/test_cumsum.cpp:43:130:   required from here
/usr/include/c++/5/bits/stl_pair.h:188:10: error: assignment of read-only member ‘std::pair<const int, int>::first’
first = std::forward<_U1>(__p.first);

why a 2-dimensional vector of auto_ptr in C++ does not work?

I am working on a 2-dimensional vector (vector of vector) to carry some pointers in C++.

std::vector< std::vector<object*> > data;

here object is a class and each entry of data carries a pointer to an object instance. I make it work in C++ but the memory management makes it hard to maintain when I apply it to other code. I did some research and someone suggests using a smart pointer instead. I try the following code

  #include <vector>
  #include <memory>
  using namespace std;
  
  int main(void) {
    vector< int > source = {1,2,3,4,5};
    vector< auto_ptr<int> > co;
    vector< vector< auto_ptr<int> > > all;

    co.push_back( auto_ptr<int>(&source[0]) );
    co.push_back( auto_ptr<int>(&source[2]) );
    co.push_back( auto_ptr<int>(&source[4]) ); // it works well up to here

    all.push_back(co); // but it crashs here
    return 0;
  }

One of the error messages is

C:/msys64/mingw64/include/c++/9.2.0/bits/stl_construct.h:75:7: error: no matching function for call to 'std::auto_ptr::auto_ptr(const std::auto_ptr&)' 75 | { ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); } | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

I wonder in what way I could add the vector< auto_ptr<int> > to another vector or list?

Converting a priority queue to vector of ints in C++

I am trying to convert a min-heap priority queue to return as a vector of ints. Is this type conversion is possible in C++;

Global variable with gtkmm

I created a gtkmm app and a custom c++ class. In this class i have a static member and I must initialize it first as a global variable but by initializing global variables I get the following runtime errors when the app starts:

(process:33366): Gtk-CRITICAL **: 23:12:00.041: _gtk_style_provider_private_get_settings: assertion 'GTK_IS_STYLE_PROVIDER_PRIVATE (provider)' failed

(process:33366): Gtk-CRITICAL **: 23:12:00.041: _gtk_style_provider_private_get_settings: assertion 'GTK_IS_STYLE_PROVIDER_PRIVATE (provider)' failed

(process:33366): Gtk-CRITICAL **: 23:12:00.041: _gtk_style_provider_private_get_settings: assertion 'GTK_IS_STYLE_PROVIDER_PRIVATE (provider)' failed
Segmentation fault (core dumped)

Any idea of how to tackle this?

Move constructor not called when constructing object in function parameter list

I have the following code to test the move constructor in C++. The class MovableArray is designed using the copy and swap idiom. I want to test that move semantics actually works.

However, it seems that the expression in main function with printSize(MovableArray(30)) doesn't invoke the move constructor.

I managed to get the line with 40 invoke move constructor by telling the compiler not to perform copy elision. So I am guessing the reason behind the call with 30 is also due to compiler optimization. However, I didn't find a flag from clang documentation.

Could anyone point out the reason? Thanks.

#include <algorithm>
#include <iostream>
#include <utility>

class MovableArray
{
public:
  MovableArray()
    : size_{ 0 }
    , data_{ nullptr }
  {}
  explicit MovableArray(int size) // ctor
    : size_(size)
    , data_{ new int[size]() } {};
  ~MovableArray() // dtor
  {
    delete[] data_;
    std::cout << "deleted array of size " << size_ << std::endl;
  };
  MovableArray(const MovableArray& other) // copy constructor
    : size_{ other.size_ }
    , data_{ new int[size_]() }
  {
    std::copy(other.data_, other.data_ + other.size_, this->data_);
    std::cout << "Array of size " << size_ << " is copied\n";
  }

  MovableArray(MovableArray&& other) // move constructor
    : MovableArray()
  {
    swap(*this, other);
    std::cout << "Array of size " << size_ << " is moved\n";
  }

  friend void swap(MovableArray& a, MovableArray& b) throw()
  {
    using std::swap;
    swap(a.data_, b.data_);
    swap(a.size_, b.size_);
  }
  int size() const { return this->size_; }
  int operator[](int i) const { return data_[i]; }
  int& operator[](int i) { return data_[i]; }

private:
  MovableArray& operator=(const MovableArray& rhs); // copy operator
  MovableArray& operator=(MovableArray&& rhs);      // move operator
  // MovableArray& operator=(MovableArray rhs);        // both
  int size_;
  int* data_;
};

void
printSize(MovableArray a)
{
  /* for (int i = 0; i < a.size(); ++i) */
  /*   std::cout << a[i] << "\t"; */
  /* std::cout << std::endl; */

  std::cout << "Size of array is " << a.size() << std::endl;
}

MovableArray
createArray(int size)
{
  auto ret = MovableArray(size);
  return ret;
}

int
main()
{
  MovableArray a{ 20 };
  // copied
  printSize(a);
  // explicitly moved
  printSize(std::move(a));
  // implicitly moved, why not working? TODO
  printSize(MovableArray(30));
  // implicitly moved
  // need to be compile with option 
  //     -fno-elide-constructors
  printSize(createArray(40));
}

The output I got is

Array of size 20 is copied
Size of array is 20
deleted array of size 20
Array of size 20 is moved
Size of array is 20
deleted array of size 20
Size of array is 30
deleted array of size 30
Array of size 40 is moved
deleted array of size 0
Size of array is 40
deleted array of size 40
deleted array of size 0

Write templated recursive integration method that accepts generic n-dimensional functions

I am working on a large C++ framework to do some particle physics computation and it would be nice to have a method to do N-dimensional integration of a generic function with N variables. The integration happens on the N-cube [0:1]^N. The integrand is unfortunately a member function and so I am passing an std::bind object to a templated function (lambdas work well too). When N > 1, the integration method binds again the function fixing one variable and passes the new function to the method for N-1.

I have the feeling that this can be done recursively by having N as a template parameter, but this is where I get stuck: is there a way to "templetize" the binding part such that it adds the right amount of placeholders with either the arity of the function or N? Then pass the new bound method to integral<N-1>, etc. I believe the problem lies in that an std::bind object has no signature. Maybe with lambdas one could exploit variadic pack expansions, but again the template has to resolve the signature somehow. Is there a way to make this work? If possible in c++11 and without boost libraries.

This is a very simplified version of what I have now without recursions, but instead different definitions of the integration method for each dimension (up to 3 now)

#include <iostream>
#include <functional>
#include <cmath>

// integrate between [0:1]
template <typename Functor>
double integral1D(Functor fn, size_t steps = 100) {
        double sum = 0.;
        double step = 1./steps;
        for (size_t s = 0; s < steps; ++s)
                sum += fn(s * step);

        return sum * step;
}

template <typename Functor>
double integral2D(Functor fn, size_t steps = 100) {
        auto subfn = [&](double v) ->double {
                auto subint = std::bind(fn, v, std::placeholders::_1);
                return integral1D(subint, steps);
        };

        return integral1D(subfn, steps);
}

template <typename Functor>
double integral3D(Functor fn, size_t steps = 100) {
        auto subfn = [&](double v) ->double {
                auto subint = std::bind(fn, v, std::placeholders::_1, std::placeholders::_2);
                return integral2D(subint, steps);
        };

        return integral1D(subfn, steps);
}
        
struct A
{
        double gaus1(double x, double range) { // computes jacobian on [-range:range]
                x = range * (2. * x - 1.);
                return 2 * range * std::exp(- x*x);
        }
    
        double gaus2(double x, double y, double range) {
                return gaus1(x, range) * gaus1(y, range);
        }

        double gaus3(double x, double y, double z, double range) {
                return gaus2(x, y, range) * gaus1(z, range);
        }

        double gaus1_integrate(double range) {
                auto func = std::bind(&A::gaus1, this, std::placeholders::_1, range);
                return integral1D(func);
        }

        double gaus2_integrate(double range) {
                auto func = std::bind(&A::gaus2, this, std::placeholders::_1,
                                                       std::placeholders::_2, range);
                return integral2D(func);
        }

        double gaus3_integrate(double range) {
                auto func = std::bind(&A::gaus3, this, std::placeholders::_1,
                                                       std::placeholders::_2,
                                                       std::placeholders::_3, range);
                return integral3D(func);
        }
};

int main() {
        A a;
        std::cout << "1D integral is " << a.gaus1_integrate(50) << "\n";
        std::cout << "2D integral is " << a.gaus2_integrate(50) << "\n";
        std::cout << "3D integral is " << a.gaus3_integrate(50) << "\n";
        return 0;
}

The above example works and gives expected results. I know it is not recommended to do Riemann sums (or equivalent) for more complicated functions with more dimensions, but it would be nice to see if something like described above can work.