jeudi 30 avril 2020

How to scale values according to a counter

I have five integer values

std::vector<int> vec(5, 0);

the value of each int will be based on a counter.

if counter is 0 than all the ints would be 0

if the counter is 100 than all the ints will have value of 20

so when the counter is 20 the first int will have a value of 20 and the rest will be 0.

when the counter is 30 the first int will be 20 and the second int will be 10

This is my code for this i am interested to see other logics to attain this,

std::vector<int> vec(5, 0);
    int counter = 50;
    for (int i = 0; i < 5; i++)
    {
        int startValue = (i) * 20;
        int finalValue = counter - startValue;

        if (finalValue > 20)
            finalValue = 20;

        if (finalValue < 0)
            finalValue = 0;

        vec[i] = finalValue;
    }


    for (auto &v : vec)
    {
        std::cout << v << std::endl;
    }

Compiler throws "ambiguous overload for operator"

I'm learning how to use std::chrono and I want to make a template class Timer easy to use (defined in timer.h). The testing program was successful and everything worked fine, until I tried to use my new Timer in a program with the definition of some template operators, which conflit with the operators used inside Timer.

Inside Timer I have to use operator- between two variables (start_time and end_time) of type std::chrono::time_point, in order to obtain the duration variable containing the elapsed time.

In another header (algebra.h) I implemented the overloading of the binary operator- to make the difference between two std::vector or two std::array, or also a user-defined container provided with operator[] and size() member function.

template<typename pointType>
pointType operator-(pointType a, const pointType & b){
    for(int i = 0; i < a.size(); ++i){
        a[i] = a[i] - b[i];
    }
    return a;
}

When I try to include both timer.h and algebra.h, the compiler throws an error saying "ambiguous overload for operator-" suggesting, as possible candidates, both the operator in algebra.h and the one implemented in <chrono>.

I don't understand why it is ambiguous, since pointType can't be deduced as std::chrono::time_point because it doesn't have operator[] and size() member function.

P.S. I tried something else to work it out, but I only got more confused testing a program which use std::valarray. When I include both <valarray> and "algebra.h", and try to make a difference between two valarrays, I expected the compiler to complain about ambiguous definition of operator-, since std::valarray already has implementation for binary operators. But this doesn't happen: it compiles using the <valarray> implementation. Why this doesn't throw an error?

How can I iterate over a vector of functions and call each of them in C++?

I am trying to loop through an array of functions stored in a vector, and i want to call each of them by the iterator pointer object, but something like this:

itr->funcs[i](5); // call the ith index function && pass int 5 as param

is not the solution i guess, what is the solution then ?

Below is my code, please check the last for loop in the code.

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

// to be able to take other functions as arguments in a function
#include <functional> 

using namespace std;

// receive other functions inside a function
// syntax: return_type function_name(std::function<return_type(parameter_lists)>func_name, parameter_lists)
double doMath(std::function<double(double)> someOtherFunction, double num){
    return someOtherFunction(num);
}

double multBy2(double d){ 
    // b'coz x is pointing to multBy2 the word 'someOtherFunction' in the 
    // above function behaves like an alias for this function 'multBy2'
    return d * 2;
}

double multBy3(double d){
    return d * 3;
}

int main (){
    // dec && init
    auto x = multBy2; // x pointing to multBy2 now
    std::cout << "2 * 5.1 : " << x(5.1) << "\n";
    std::cout << "multBy2 will be called: " << doMath(x, 6.1) << "\n";
    std::cout << "multBy2 will be called, again: " << doMath(x, 6.1) << "\n";

    // store different functions inside a vector

    // you must use the same signature type functions
    std::vector<function<double(double)>> funcs(2);
    funcs[0] = multBy2; // multBy2 stored at the zeroth index
    funcs[1] = multBy3; // multBy3 stored at the first index

    // check
    // funcs[0](10), pass value by index
    std::cout << "2 * 10 = " << funcs[0](10) << "\n";
    std::cout << "3 * 10 = " << funcs[1](10) << "\n";

    // loop through them
    for (auto itr = funcs.begin(); itr != funcs.end(); itr++){
        // iterate through the functions
        // itr->funcs[1](10); // I KNOW THIS IS WRONG, WHAT SHOULD I WRITE HERE?
    }

    return 0;
}

Evaluating the constructor equivalent of a variable

I have the constructor

class MyFrame : public wxFrame {  // defines the options on the top bar of the screen here we have:
    public:
        MyFrame();
    private:
        void OnHello(wxCommandEvent& event);  // hello option
        void OnExit(wxCommandEvent& event);  // exit option
        void OnAbout(wxCommandEvent& event);  // about option
        void OnHelp(wxCommandEvent& event); // event option

        // void OnCourseTextBoxClicked(wxCommandEvent &event);
        void OnOneHundredLevelDisplayGpButtonClicked(wxCommandEvent &event);
        void OnTwoHundredLevelDisplayGpButtonClicked(wxCommandEvent &event);
        void OnThreeHundredLevelDisplayGpButtonClicked(wxCommandEvent &event);
        void OnFourHundredLevelDisplayGpButtonClicked(wxCommandEvent &event);
        void OnFiveHundredLevelDisplayGpButtonClicked(wxCommandEvent &event);

        void OnDisplayCgpaButtonClicked(wxCommandEvent &event);

        // Common Courses equating their credit load
        /* 100 LEVEL FIRST SEMESTER */
        int CHM111 = 3;
        int CHM113 = 3;
        int MTH111 = 3;
        int MTH112 = 3;
        int PHY111 = 3;
        int PHY113 = 3;
        int GST111 = 2;
        int GST112 = 2;

        /* 100 LEVEL SECOND SEMESTER */
        int CHM122 = 3;
        int CHM124 = 3;
        int MTH123 = 3;
        int MTH125 = 3;
        int PHY109 = 2;
        int PHY124 = 4;
        int GST121 = 2;
        int GST122 = 2;
        int GST123 = 2;
        int LEVEL_TOTAL_100 = 47;
}

And somewhere else in the code base, some text is entered into a text box. The text box is supposed to contain one of the variables defined in the constructor which evaluate to their respective integers.

When the text box's content is evaluated e.g.:

course_one_text_box->GetValue();

evaluates CHM111

I want to grab the constructor integer value for the CHM111 which is 3. I want to employ this value in a mathematical formula.

How do I do this? Is there a particular syntax that grabs the constructor recorded version of the variable instead? Thanks.

How to make a QGrpahicsView background blinking in R - G - B every second

As the title says I am trying to have my QGraphicsView blinking 1 second in red, 1 second in green and 1 second in blue and after that the loop start over again. After doing a lot of research in the past couple of days I didn't have a lot of luck as the main problem is that I am not sure I need to subclass QGraphicsView to obtain the effect I am looking for. I came across some references that I inserted below saying that for this type of problems QPropertyAnimation seems to be the right direction. Although setting a QTimer could also be a choice.

Below the small verifiable example. I wrote minimal code:

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QPropertyAnimation>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
    QGraphicsView *mView;
    QGraphicsScene *mScene;
    QPropertyAnimation *mAnimation;
};
#endif // MAINWINDOW_H

**mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTimer>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    mView = new QGraphicsView();
    mScene = new QGraphicsScene();
    ui->graphicsView->setScene(mScene);
    // Starting with a gray background
    ui->graphicsView->setBackgroundBrush(QColor(Qt::gray));

    // Setting a timer that changes the color every second
    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(update()));
    timer->start(1000);

}

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

mygraphicsview.h

#ifndef MYGRAPHICSVIEW_H
#define MYGRAPHICSVIEW_H
#include <QGraphicsView>
class MyGraphicsView : public QGraphicsView
{
public:
    MyGraphicsView();
};

#endif // MYGRAPHICSVIEW_H

**mygraphicsview.cpp

#include "mygraphicsview.h"

MyGraphicsView::MyGraphicsView()
{}

main.cpp

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

In case you would like to see the .ui I am also sharing the file:

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>277</width>
    <height>228</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <layout class="QGridLayout" name="gridLayout">
    <item row="0" column="0">
     <widget class="QGraphicsView" name="graphicsView"/>
    </item>
   </layout>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>277</width>
     <height>22</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>

I have been researching the possibility to have a QGraphicsView blinking 1 second in red, 1 second in green and 1 second in blue and after that the loop start over again.

The only source I was able to find providing a complete example was in PyQt, for which I am not familiar with. The source is here and also this one.

The most important clue I got out of these examples is that, in particluar the last one, uses QState and QStateMachine. I am not familiar at all with these two features of Qt though and am struggling a little bit because of that.

Also I came across this partial example, and the good thing of this is that I learned how to set the QTimer useful for the 1s interval blinking.

Also because I am dealing with a QGraphicsView I have the feeling that void paintEvent(QPaintEvent *) override should be used.

Thank you very much for pointing in the right direction and solve this issue.

Strange behaviour of variable in c++

I am unable to understand how a variable defined in an outer scope can be redefined in an inner scope.

Here is my sample code. The code compiles successfully.

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

#define ll long long int

int main(int argc, char const *argv[])
{
    ll t;
    cin>>t;
    while(t--)
    {
        map<ll,ll> mp;
        map<ll,ll>::iterator t=mp.end();
    }
    return 0;
}

How should I pass a unique_ptr through 2 function calls with move semantics?

Simply, in some part of code, I create an object and assign to unique_ptr:

unique_ptr<Node> n ( CreateNode() );
container.place(id, std::move(n));

The definition of place is:

void place(int id, unique_ptr<Node> n)
{
    mappings_[id] = std::move(n);  // std::map<int, unique_ptr<Node>> mappings_;
}

I'm currently trying to hunt a bug where the alleged object that was retrieved from the map has some internal pointers completely twisted, which might have been a consequence of that the object was really deleted, but this fact was somewhat missed. Questions:

  1. Should this n be of unique_ptr<Node> type or unique_ptr<Node>&&?
  2. What are the consequences of both of the above?

Why is there no std:: equivalent to pthread_spinlock_t like there is for pthread_mutex_t & std::mutex?

I've used pthreads a fair bit for concurrent programs, mainly utilising spinlocks, mutexes, and condition variables.

I started looking into multithreading using std::thread and using std::mutex, and I noticed that there doesn't seem to be an equivalent to spinlock in pthreads.

Anyone know why this is?

Time difference when sorting vector of structs

I'm trying to sort vectors of 2 structs of different number of element:

    struct1 {
      int id1;
      int id2;
      string name;
      double ts1;
      double ts2;
    }

    struct2 {
      int id1;
      int id2;
      //string name; <-- this was left out
      double ts1;
      double ts2;
    }
std::vector<struct1> vec1;
std::vector<struct2> vec2;

When I tried to sort vec1 and vec2 based on ts1, there is a big difference in the sorting time. The sizes of vec1 and vec2 are large (>100k elements). Does the size of struct affect the sorting?

EDIT: my sorting function

inline bool sorting(const Type &lhs, const Type &rhs) {
    if (lhs.ts1 < rhs.ts2) {return true;}
    else {return false; }
}

std::sort(vec.begin(),vec.end(),
          [this] (Type lhs, Type rhs) { return sorting(lhs,rhs); });

guru meditation error when reading data from ESPAsyncWebServer request parameters

I am working on ESP32, New to this device.

I am currently facing the following error. when I try to read the data from request->value().c_str() the serial monitor shows me guru meditation error error SS of error: enter image description here

My code:

server.on("/register", HTTP_POST, [](AsyncWebServerRequest *request) {
request->send(200, "text/plain", Register(request->getParam("plain",true)).c_str());});

The function:

string Register(AsyncWebParameter *request){

const size_t bufferSize = JSON_OBJECT_SIZE(1) + 250;; StaticJsonDocument data; deserializeJson(data, request->value().c_str()); // facing issue here when request->value().c_str() is called const char* name = data["username"];

return String("Execution complete"); }

I have return simple javascript function to call the API:

function Register() {
const tosend={
      "username":"Mohit",
      "password":"Mohit10#",
      "lastname":"mhatre",
      "firstname":"Mohit"
  };
  const url="http://192.168.2.120/register";
  
  fetch(url, {
    method: 'post',
    headers: {
      // if you want to set
    },
    body: tosend
  })
    .then(
      function(response) {
        response.json().then(function(data) {
          console.log(data);
        });
      }
    )
    .catch(function(err) {
      console.log('Fetch Error :-S', err);
    });
}

Can someone please help me resolve the issue i am new to this and stuck here from yesterday

What do curly braces after a struct variable member mean?

During some maintenance (Valgrind'ing) I came across this code:

#pragma pack(push, 1)
struct somename
{
  uint16_t a{};
  uint16_t b{};
  uint32_t  c{};
};
#pragma pack(pop)

I would expect that the {} tell the compiler to always initialize the values to 0 (when allocating using new, or using a stack variable), but I cannot find any examples or documentation on that. Am I correct in this assumption? If not:

What do the curly braces {} after a struct member variable mean?

How to std::tie to unpack results of std::minmax_element?

I have a container v of elements of type T, to which I apply std::minmax_element, like so:

auto min_max = std::minmax_element(v.begin, v.end);
auto min = min_max.first;
auto max = min_max.second;

I would like to unpack the results of std::minmax_element with std::tie, but I can't figure the type for the declaration:

*type?* first_it, last_it;
std::tie(first_it, last_it) = std::minmax_element(v.begin, v.end);

What would be the type of first_it and last_it?

Not using constexpr in c++ template arguments

I am working with a variable of type itk::Image<OutputPixelType, Dimension>, where "itk" comes from the image processing library ITK.

The following code compiles:

constexpr unsigned int Dimension = 3;
using PixelType = float; 
using MyImageType = itk::Image<PixelType, Dimension>;

But now I need to define "Dimension" as something computed from a function.

unsigned int Dimension = get_dimension(...);

My compiler gives an error:

error: non-type template argument is not a constant expression
  using MyImageType = itk::Image<PixelType, Dimension>;
                                            ^~~~~~~~~

How could I work around this issue? I hope to use "Dimension" as something computed from a function.

constexpr array of constexpr function pointers

I'm trying to get my head around how constexpr work. And I need to convert a lot of code from const to constexpr. But I've hit a problem where I cant see the solution.

I have the following class:

class Control_base
{
public:

  static constexpr Control_base high_clock();

  static constexpr uint8_t size();

  static const Control_base from_index(uint8_t index_);

  Control_base& operator=(const Control_base& rhs) = default;

  constexpr Device_address value() const;
private:
  constexpr explicit Control_base(Device_address value_);

  Device_address value;


};

constexpr Control_base::Control_base(Device_address value_) :
  value(value_) {}

constexpr Device_address Control_base::value() const { return value; }

inline const Control_base Control_base::high_clock() { return Control_base(reinterpret_cast<Device_address>(0x10009000)); }

typedef const Control_base (*Control_base_func)(void);

const Control_base_func Control_base_arr[] = {&Control_base::high_clock};

inline const Control_base Control_base::from_index(uint8_t index_)
{
  return Control_base_arr[index_]();
}

constexpr uint8_t Control_base::size() { return 1; }

};

I wish to make the following changes:

From

inline const Control_base Control_base::high_clock() { return Control_base(reinterpret_cast<Device_address>(0x10009000)); }

typedef const Control_base (*Control_base_func)(void);

const Control_base_func Control_base_arr[] = {&Control_base::high_clock};

To

constexpr Control_base Control_base::high_clock() { return Control_base(reinterpret_cast<Device_address>(0x10009000)); }

typedef const Control_base (*Control_base_func)(void);

constexpr Control_base_func Control_base_arr[] = {&Control_base::high_clock};

However, I get the following error in

constexpr Control_base_func Control_base_arr[] = {&Control_base::high_clock};
                                                  ^

**value of type "ns::Control_base (*)()" cannot be used to initialize an entity of type "const ns::Control_base_func"**

I can't figure out what the best solution is here. And why it works with const but not constexpr

Regards

mercredi 29 avril 2020

How to read from a text file and put it into a map? c++

So I have a text file that I want to read and then put it into a map. Right now, I have written this, but I know this isn't correct.

   #include "headers.h"

   void SearchItem(string itemName);
   void SearchItem(double price);
   void SearchItem(int amount);
   void sort();

   struct ItemInfo{
      double Itemprice = 0;
      int Itemamount = 0;
   };

   struct storeName{
      string StoreName;
      map<string, ItemInfo> storeItem;
   };

   class inventory
   {

   public:
   //constructor to read frmo file
     inventory();
   //function to add items in map
     void updateInventory( int items);
  //function to iterate throught the list
     void iter();
  //last store item entered
     void viewInventory(string SName);
  //get list
     list<storeName> get_list();
  private:
     list<storeName> stores;
  };

I have written this class which has a list of type storeName which is a struct. I used a struct because I am trying to make an inventory list of all local grocery stores in my area and then have a map of their items like fruits and vegetables along with their prices and amount available in the store. The list is going to store the store name and the map, the map is going to store the item name, which will be the key and then two values- price and amount. I used a struct for map too so it can hold two values and then in the future, I could search by storename or throught the key. In the class, I am using the constructor as my read from file function which is this

  inventory::inventory(){
//read from file function
     ifstream read;
     vector<string> name;
     storeName input;
     ItemInfo enter;
     auto iter = stores.begin();
     auto mapIter = iter->storeItem.begin();
     iter->StoreName = "Walmart";
     read.open("/Users/vibhorsagar/Desktop/CovidProject/CovidProject/walmartList.txt");
     if(!read.is_open()){
        cout<<"Error"<<endl;
        return;
     }else {
         while(!read.eof()){
             string line;
             double price;
             int amount;
             getline(read, line, ' ');
             stringstream in(line);
             in>>line;
             name.push_back(line);
               while(in>> price >> amount){
                     //stuck here    
              }   
         }    
     }
 }

Now the in the text file I have this

Marketside Butter Lettuce Salad 2.98 200
Marketside Classic Iceberg Salad 2.64 400

so the name of the item is long and I want to store it as the key when I read it from the file. If it was just one name like "potato" or "tomato" then It would be kinda easier, but since the name is long and the price is double and the amount is int, I don't know how to store it in a map. Any suggestions would be helpful and if you have any suggestions on how I could implement it better in my code, or make my code better in general, it would be really helpful. Thank you

Mock for a concrete class using gmock in C++

I am stuck with creating a mock for a concrete class.

I know that is not a great idea to do this but I'm not not allowed to change production code.

My code is similar with:

Class A
{
public:
        A(B* b)
        {
                this->b = b;
        }
.........................
 void function_from_a_to_test(<arg>)
{
        if(!b)
                b->function_from_b();
        else
             //something to do
}
private:
        B * b;
};

class B
{
........
 public:       
        void function_from_b();
......
};
class MockB : public B , testing::Mock //i don't know why I can that, B is not virtual 
{

 MOCK_METHOD(function_from_b, void, (void));

};


A_Test :testing::Test{
 SetUp()
{
        b = new B();
        a = new A(b);
}

 TearDown()
{
        delete b ;
        delete a ;
}

void set_b(B * bb)
{
        a->b = bb;
}

.........................
}

In order to test I used Test_f

TEST_F(A_Test, Test_function_from_a_to_test)
{
//arrange

//act
 B * b_t = new MockB();
set_b(b_t);
EXPECT_CALL(*(static_cast<MockB> b_t), function_from_b))
        .Times(10);

function_from_a_to_test(arg);
}

It's seems that the test is passed but i got memory leak at static cast.

And If I store the result of static cast in another variable (in order to delete it), the expect call having that variable is failing.

I know that is not really a good practice, but I can not change the production code.

Has somebody a idea how to solve it? Or a better way to test this?

How to print an array that some values must be printed with a specific behaviour?

I'm trying to make a JVM. First, I have a vector with opcodes and the strings that represent them. It's initialised like this:

Opcodes::Opcodes():
opcodes(0xff + 1, "Not implemented")
{
    opcodes[0x2A] = "aload_0";
    opcodes[0x2B] = "aload_1";
    opcodes[0x2C] = "aload_2";
    opcodes[0x2D] = "aload_3";
    opcodes[0xB7] = "invokespecial";
}

Given an opcode, I want to print it, this is the code till now:

std::string Opcodes::getString(u1 opcode)
{
    try
    {
        return Opcodes::getInstance().opcodes.at(opcode);
    }
    catch (const std::out_of_range &e)
    {
        return "Opcode too large";
    }
}

void Opcodes::printCode(std::ostream& out, u1 code[], u4 codeLength)
{
    for (u4 i = 0; i < codeLength; i++)
    {
        out << Opcodes::getString(code[i]) << std::endl;
    }
}

There will be a lot more of opcodes. For a lot of opcodes I just have to get the opcode and print it. But for the others I have to take a different approach, for example, in the method printCode() if I read the invokespecial opcode I have to print the two next opcodes in the code array (code[]) in another way than just take it from the opcodes vector, or just ignore them (don't print).

How can I do it in a good way? Which could be a good approach for that?

I could just use if or switch but it'll be really a lot of if's, I don't think that's good, sounds messy. I thought of using lambda someway. I've heard about a pattern called command, maybe it could be helpful. What do you think?

Does anybody know what i am doing wrong? getting retail price c++

Description: Write a complete C++ program that asks the user to enter an item’s wholesale cost and its markup percentage (not per dollar). It should display the item’s retail price. That’s the over all description of this problem.

*/

include

using namespace std;

// function1. ask user for wholesale value.

double getWholesaleCost(){
    double WholesaleCost;
    cout << " Enter the products Wholesale cost: ";
    cin >> WholesaleCost;
    return WholesaleCost;

}

// function2, ask for markup percentage for the wholesalecost.

double getMarkup(){
    double markup_percentage;
    cout << " Enetr markup percentage of the item’s wholesale price: ";
    cin >> markup_percentage;
    return markup_percentage;

}

double calculateRetail(double wholesalePrice, double markup_percentage){
    double retailPrice = wholesalePrice * (markup_percentage / 100);
    retailPrice = wholesalePrice + retailPrice;
    return retailPrice;

}

// display function

void dispaly( double retailPrice){
    cout << " The retail price is: " << retailPrice;
    return;
}

//main function

int main(){


double wholesalePrice = getWholesaleCost();
    double markupPercent = getMarkup();
    double retailPrice = calculateRetail(wholesale, markupPercent);
    display(retailPrice);

return 0;

}

Same performance with two threads as with one?

I'm playing around with multithreading to try and get a better understanding of how to implement it in another project and have put together a small example. The code first generates 1000 strings. There is a function foo which loops through each string between two given start and end indexes, checking to see if the character "a" is present (simply for some synthetic load).

When calling foo on the main thread and looping through all 1000 strings, the execution time is ~72ms. When using two separate threads th1 and th2 and passing the foo function pointer along with a start and end index (effectively each thread processes half of the 1000 strings), I was expecting the execution time to be less than ~72ms as it was my understanding that each thread would execute simultaneously, producing an execution time of ~36ms.

However, the execution time is the same as the loop running through all 1000 strings on the main thread. Could someone explain to me why this is the case?

#include <iostream>
#include <vector>
#include <memory>
#include <map>
#include <optional>
#include <string>
#include <algorithm>
#include <chrono>
#include <thread>
#include <iomanip>
#include <cmath>
#include <limits>
#include <ratio>
#include <thread> 

std::chrono::high_resolution_clock::time_point startTime;

std::vector<std::string> strings;

bool string_contains(std::string needle, std::string haystack)
{
    if (haystack.find(needle) != std::string::npos)
    {
        return true;
    }
    return false;
}

std::string random_string(int len)
{
    std::string str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    std::string newstr;
    int pos;
    while (newstr.size() != len) {
        pos = ((rand() % (str.size() - 1)));
        newstr += str.substr(pos, 1);
    }
    return newstr;
}

const double now()
{
    std::chrono::duration<double> t = std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::high_resolution_clock::now() - startTime);
    return t.count();
}

void build_strings()
{
    for (size_t i = 0; i < 10000; i++)
    {
        strings.push_back(random_string(20));
    }
}

void foo(size_t start, size_t end, size_t thread)
{
    for (size_t i = start; i < end; i++)
    {
        std::cout << thread << "\n";

        if (string_contains("a", strings[i]))
        {

        }
    }
}

int main()
{
    build_strings();

    auto time_a = now();
    std::thread th1(foo, 0, strings.size() / 2, 1);
    std::thread th2(foo, strings.size() / 2, strings.size(), 2);

    //foo(0, strings.size(), 0);

    th1.join();
    th2.join();

    auto time_b = now();

    std::cout << std::setprecision(10) << std::fixed << time_b - time_a << "\n";


    std::cin.get();
}

How to force std::vector to use move constructor instead of the copy one?

I want to use move semantics in my application, not to copy the data. Here is the code:

using namespace std;

struct TestData
{
    TestData(const TestData&) = delete;
    TestData& operator=(const TestData&) = delete;
    TestData(TestData &&other) = default;
    TestData& operator=(TestData &&other) = default;

    TestData() { std::cout << "TestData()" << std::endl; }
    ~TestData() noexcept {
        if(ptr != null) delete []ptr;
        std::cout << "~TestData(), ptr = " << (ptr == nullptr ? "nullptr" : "not null") << std::endl; 
    }
    int x;
    char *ptr = nullptr;
};

void add(std::vector<TestData> &vector)
{
    TestData d;
    d.x = 1;
    d.ptr = new char[12];
    memcpy(d.ptr, "Test string", 11);
    vector.push_back(d);
}


int main()
{
    std::vector<TestData> v;
    add(v);
    add(v);

    return 0;
}

But the GCC compiler fails with the error:

error: use of deleted function ‘TestData::TestData(const TestData&)’

But I don't want to copy the data, I want to move that. The reason is that copying data cause to copy the pointer (ptr) and so attempt to delete it in the destructor cause to double free corruption.

So the question - how to force that GCC will use move constructor?

  • GCC v. 9.3.0
  • Ubuntu 20.04

Exclude first matched character in regex string [duplicate]

I have some code that manually parses a string for a specific character and then makes a copy of the following characters as long as they are a specific range of characters. This is ideal to replace with regex.

The regex that works is a[0-9]{4} matches this but also includes the first character a. Simply removing the first letter of the resulting string with str.erase(str.begin()) is a no go as the resulting copy to the temporary is 140x slower than the manual parse (over 1 million items)

So I tried to exclude the a from the resulting block. (?<=a)[0-9]{4} works in online regex testers but throws in C++ (gcc 6.3) with an "Invalid special open parenthesis."

What expression will return the result I want in C++?

Find the no of pairs with gcd 1 efficiently

Given 2 arrays of length n, a and b, I want to find the number of pairs such that gcd(a[i], b[j]) == 1 in less than O(n^2).

Need help to debug Run-Time Check Failure #2 - Stack around the variable 'newString' was corrupted

This is a function to convert a long string (sentence) into a vector of strings. From the error, it seems obvious that the char ptr newString is causing some access violation, run-time issues. Probably it's length is the root cause? Any help on how to debug/ fix this issue will be appreciated! Also, please note that the output of the function is just coming as expected, but with the run-time error occurring.

vector<string> convertStrgToStrVect(char *inString)
{
    unsigned int end = 0, start = 0, i = 0, len = 0, j = 0;
    char *inStr = inString, *s;
    char newString[] = "";
    vector<unsigned int> startLenVect, endLenVect, strLenVect;
    vector<unsigned int> :: iterator itr1, itr2;
    vector<string> stringVect;
    vector<string> :: iterator itr3;

    s = inStr;

    // Add an extra space an the end of the string
    for( i = 0; i < strlen(s); i++)
    {
    }
    s[i] = ' ';
    i++;
    s[i] = '\0';

    cout << s << endl;
    cout << strlen(s) << endl;

    // Create vectors for start and end indexes to split the words separated by a space
    for( i = 0; i < strlen(s); i++)
    {
        if(s[i] != ' ')
        {
            end++;
            len = end - start;
        }
        else
        {
            endLenVect.push_back(end);
            startLenVect.push_back(start);
            strLenVect.push_back(len);
            end = i+1;
            start = i+1;
        }
    }
    cout << "startLenVect: ";
    for(itr1 = startLenVect.begin(); itr1 != startLenVect.end(); itr1++)
    {
        cout << *itr1 << " ";
    }

    cout << "endLenVect: ";
    for(itr1 = endLenVect.begin(); itr1 != endLenVect.end(); itr1++)
    {
        cout << *itr1 << " " << endl;
    }

    for(itr1 = startLenVect.begin(), itr2 = endLenVect.begin(); itr1 != startLenVect.end(); itr1++, itr2++)
    {
        strcpy(newString, "");
        for(i = *itr1, j = 0; i < *itr2; i++, j++)
        {
            newString[j] = s[i];
        }
        newString[j] = '\0';

        stringVect.push_back(newString);
    }

    for(itr3 = stringVect.begin(); itr3 != stringVect.end(); itr3++)
    {
        cout << "stringVect: " << *itr3 << endl;
    }
    return stringVect;
}

Is it allowed to pass a pointer to a template function to C library? (as a callback)

Consider the following code:

#include <iostream>

struct Foo {
  void work() { std::cout << "foo" << std::endl; }  
};

typedef void function_type(void *arg);

template <typename T>
void function(void *arg)
{
    auto &t = *reinterpret_cast<T*>(arg);
    t.work();
}

void call_function(function_type *fn, void *arg)
{
    fn(arg);
}

int main()
{
    Foo foo;

    call_function(&function<Foo>, &foo);

    return 0;
}

If call_function() would be an interface of some C library (which is linked dynamically to my program), is it OK to pass a pointer to some specific instance of a template function? Are there any differences between pointers to (a instantiation of) a template function and regular functions?

How to create a unix socket file with read/write permissions for different users C++?

I have 2 different aplications running in 2 different users in linux. I want them to be connected by unix sockets and, as a unix domain socket is known by a pathname, the 2 applications need to share the same path and same the socket file that is created. The problem here is that when binding the socket in the Server, everything is fine but, when trying to connect from the 2nd application the error "access denied" appears.

Here is the code I am using for the server, who does create the socket file.

  int main() {
    struct sockaddr_un addr;
    char buf[100];
    int fd,cl,rc;

    if (argc > 1) socket_path=argv[1];

    if ( (fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
      perror("socket error");
      exit(-1);
    }

    memset(&addr, 0, sizeof(addr));
    addr.sun_family = AF_UNIX;
    if (*socket_path.c_str() == '\0') {
      *addr.sun_path = '\0';
      strncpy(addr.sun_path+1, socket_path.c_str()+1, sizeof(addr.sun_path)-2);
    } else {
      strncpy(addr.sun_path, socket_path.c_str(), sizeof(addr.sun_path)-1);
      unlink(socket_path.c_str());
    }

    if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
      perror("bind error");
      exit(-1);
    }

    if (listen(fd, 5) == -1) {
      perror("listen error");
      exit(-1);
    }

     return 0;
}

Mocking classes with template methods

Is there any pattern for testing classes that use classes containing template methods in public api? I know that in dynamic polymorphism mocking interface is the solution like this:

struct Interface {
 virtual void foo() = 0; 
 virtual ~Interface() = default;
};

class TestedClass {
public:
  TestedClass(Interface& i) {}
  // ... rest of the class
};

struct IMock : public Interface {
 void foo() override {} 
};

void test() {
  IMock bar;
  TestedClass baz(bar);
}

But what can I do with something like below? Is there an idiomatic way to test this?

struct Interface {
 template<class T>
 void foo() {
   // do stuff depending on type
 }
};

class TestedClass {
public:
  TestedClass(Interface& i) {}
  // ... rest of the class
  // uses Interface foo with multiple types
};

C++ program to simulate FIFO with class templates, returns value 3221225477 when dequeuing

I'm currently studying my second course of C++ object oriented programming at university, so I'll probably have bad programming practices and general errors in my code, so, please, point them out if you see any. I'm always open to learn.

I currently have an assignment on C++ templates, where I have to create a program with a class that simulates FIFO(First in First out) queue using a different class as the template type (Queue< Human >HumanQueue).

Queue.h

#ifndef QUEUE_H
#define QUEUE_H
#include "human.h"


template<class T>
class Queue : public Human{
    public:
        Queue(int = 5);
        ~Queue();
        void enqueue(T);
        T dequeue();
        void PrintQueue();

    private:
        T* array;
        int size, index;
};

#endif

Queue.cpp

#include <iostream>
#include "queue.h"
using namespace std;


template<class T>
Queue<T>::Queue(int s){
    array = new T[s];
    size = s;
    index = 0;
}


template<class T>
Queue<T>::~Queue(){
    delete [] array;
}


// Add object to end of array
template<class T>
void Queue<T>::enqueue(T obj){
    if(index == size){
        cout << "Rinda ir pilna, nevar pievienot elementu!" << endl; // Array full, can't add any more objects
        return;}

    else{
        array[index] = obj;
        index++;}
}


// Remove object from start of array and shift the whole array by 1 position
template<class T>
T Queue<T>::dequeue(){
    for(int i = 0; i < size; i++){
        array[i] = array[i + 1];
    }

    index--;
}


template<class T>
void Queue<T>::PrintQueue(){
    for(int i = 0; i < index; i++){
        cout << i + 1 << ". ";
        array[i].PrintHuman();
    }
}

main.cpp

#include <iostream>
#include "human.h"
#include "queue.h"
#include "queue.cpp"
using namespace std;


int main(){
    Queue<Human> HumanQueue(3);
    Human a("Janis", 1.86, 76);
    Human b("Peteris", 1.76, 69);
    Human c("Arturs", 1.79, 75);
    Human d("Aleksis", 1.81, 78);


    cout << "Elementu rinda" << endl; // Element queue
    HumanQueue.enqueue(a);
    HumanQueue.enqueue(b);
    HumanQueue.PrintQueue();
    cout << "\n//Pievienojam elementu rindai//" << endl; // Add element to queue
    HumanQueue.enqueue(c);
    HumanQueue.PrintQueue();
    cout << "\n//Meginam pievienot vel 1 elementu rindai//" << endl; // Trying to add one more element to queue, should return, that queue is full
    HumanQueue.enqueue(d);
    HumanQueue.PrintQueue();
    cout << "\n//Iznemam 2 elementus no rindas//" << endl; // Dequeue 2 elements from queue
    HumanQueue.dequeue();
    HumanQueue.dequeue();
    HumanQueue.PrintQueue();


    system("pause");
    return 0;
}

The class "Human" is open to interpretation with any variables and functions of my choosing so I'm not including it in this thread.

The constructor, enqueue and print work fine, but when trying to dequeue I get a return value of 3221225477. From what I have gathered, it means it's some kind of problem with the way the program is using the memory. I used this same template for a previous project, where the types were int, char, float and it worked fine, but it doesn't like to work with objects.

Wait for thread queue to be empty

I am new to C++ and multithreading applications. I want to process a long list of data (potentially several thousands of entries) by dividing its entries among a few threads. I have retrieved a ThreadPool class and a Queue class from the web (it is my first time tackling the subject). I construct the threads and populate the queue in the following way (definitions at the end of the post):

ThreadPool *pool = new ThreadPool(8);
std::vector<std::function<void(int)>> *caller = 
    new std::vector<std::function<void(int)>>;
for (size_t i = 0; i < Nentries; ++i)
{
    caller->push_back( 
        [=](int j){func(entries[i], j);});
    pool->PushTask((*caller)[i]);
}
delete pool;

The problem is that only a number of entries equaling the number of created threads are processed, as if the program does not wait for the queue to be empty. Indeed, if I put

while (pool->GetWorkQueueLength()) {}

just before the pool destructor, the whole list is correctly processed. However, I am afraid I am consuming too many resources by using a while loop. Moreover, I have not found anyone doing anything like it, so I think this is the wrong approach and the classes I use have some error. Can anyone find the error (if present) or suggest another solution?

Here are the classes I use. I suppose the problem is in the implementation of the destructor, but I am not sure.

SynchronizeQueue.hh

#ifndef SYNCQUEUE_H
#define SYNCQUEUE_H
#include <list>
#include <mutex>
#include <condition_variable>

template<typename T>
class SynchronizedQueue
{
    public:
        SynchronizedQueue();

        void Put(T const & data);
        T Get();
        size_t Size();

    private:
        SynchronizedQueue(SynchronizedQueue const &)=delete;
        SynchronizedQueue & operator=(SynchronizedQueue const &)=delete;

        std::list<T> queue;
        std::mutex mut;
        std::condition_variable condvar;
};

template<typename T>
SynchronizedQueue<T>::SynchronizedQueue()
{}


template<typename T>
void SynchronizedQueue<T>::Put(T const & data)
{
    std::unique_lock<std::mutex> lck(mut);
    queue.push_back(data);
    condvar.notify_one();
}

template<typename T>
T SynchronizedQueue<T>::Get()
{
    std::unique_lock<std::mutex> lck(mut);
    while (queue.empty())
    {
        condvar.wait(lck);
    }
    T result = queue.front();
    queue.pop_front();
    return result;
}

template<typename T>
size_t SynchronizedQueue<T>::Size()
{
    std::unique_lock<std::mutex> lck(mut);
    return queue.size();
}

#endif

ThreadPool.hh

#ifndef THREADPOOL_H
#define THREADPOOL_H    
#include "SynchronizedQueue.hh"
#include <atomic>
#include <functional>
#include <mutex>
#include <thread>
#include <vector>

class ThreadPool
{
    public:
        ThreadPool(int nThreads = 0);
        virtual ~ThreadPool();

        void PushTask(std::function<void(int)> func);

        size_t GetWorkQueueLength();

    private:
        void WorkerThread(int i);

        std::atomic<bool> done;
        unsigned int threadCount;
        SynchronizedQueue<std::function<void(int)>> workQueue;
        std::vector<std::thread> threads;
};

#endif

ThreadPool.cc

#include "ThreadPool.hh"
#include "SynchronizedQueue.hh"

void doNothing(int i)
{}

ThreadPool::ThreadPool(int nThreads)
    : done(false)
{
    if (nThreads <= 0)
    {
        threadCount = std::thread::hardware_concurrency();
    } 
    else
    {
        threadCount = nThreads;
    }

    for (unsigned int i = 0; i < threadCount; ++i)
    {
        threads.push_back(std::thread(&ThreadPool::WorkerThread, this, i));
    }
}

ThreadPool::~ThreadPool()
{
    done = true;
    for (unsigned int i = 0; i < threadCount; ++i)
    {
        PushTask(&doNothing);
    }
    for (auto& th : threads)
    {
        if (th.joinable())
        {
            th.join();
        }
    }
}

void ThreadPool::PushTask(std::function<void(int)> func)
{
    workQueue.Put(func);
}

void ThreadPool::WorkerThread(int i)
{
    while (!done)
    {
        workQueue.Get()(i);
    }
}

size_t ThreadPool::GetWorkQueueLength()
{
    return workQueue.Size();
}

class std::set

I used to make a function which stores a json object into a map of strings (key) and a vector of strings (value) using this code :

#include <vector>
#include <map>
using VMap = std::map<std::string, std::vector<std::string> >;

VMap fileMapper (ptree const& config) 

{ 
    VMap mymap ; 
    for (auto& entry : config) {
        std::vector<std::string> val; 
        for (auto& element : boost::make_iterator_range(entry.second.equal_range(""))) {
            val.push_back(element.second.get_value<std::string>()); 
        } 
        mymap.insert(std::pair<std::string, std::vector<std::string>>(entry.first,val));
        } 
    return mymap;
} 

I'm looking to make the same action using a set of strings instead of a vector of strings, I've tried to make a small modification to the code :

#include <map>
#include <set>

using VMap = std::map<std::string, std::set<std::string> >;

VMap fileMapper (ptree const& config) 

{ 
    VMap mymap ; 
    for (auto& entry : config) {
        std::set<std::string> val; 
        for (auto& element : boost::make_iterator_range(entry.second.equal_range(""))) {
            val.push(element.second.get_value<std::string>()); 
        } 
        mymap.insert(std::pair<std::string, std::set<std::string>>(entry.first,val));
        } 
    return mymap;
} 

And I've got this error : class std::set > ' has no member named 'push'

Any idea ?

Test Results exersise

Exercise: Test results are saved in a text file as below. The first line indicates the maximum scoring for individual tasks. Each subsequent line contains the student's one-part surname and points gained by him for subsequent tasks. The number of assignments or students is not known in advance. Write program "Test" , which takes the name of such a file as an argument and prints to standard output the combined results of each student and the average results of each assignment as in the example below. The program only includes the fstream, iostream, sstream, string and vector header files.


Sample input file input.txt
                 5.0 5.0 5.0
Einstein         1.5 3.0 0.5
Chopin           0.5 3.5 2.5
Sklodowska-Curie 5.0 5.0 5.0


Sample implementation:

Linux: ./colloquium input.txt
Windows: colloquium.exe input.txt
Out: Einstein 5
Out: Chopin 6.5
Out: Sklodowska-Curie 15
Out: 1 2.33333
Out: 2 3.83333
Out: 3 2.66667

This is what I have done so far :

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


int main(int argc, char *argv[])
{
std::ifstream input(argv[1]);
double sum = 0.;
for (std::string line; std::getline(input, line);)
    {
    std::string word;
    for (std::istringstream stream(line); stream >> word;);
    double grade;
    std::cout<<line<<std::endl;
        if (std::istringstream(word) >> grade)
        {
        sum += grade; 
        }
    }
std::cout << sum << std::endl;

input.close(); 
}

And I'm kind of stuck because it's only reads numbers from last column. And I dont know what to do further

Is there a way to transparently use move or copy constructor in a template?

I am trying to implement a generic thread safe queue in a way that can work both with move-only objects or copy-only objects. Here is what I tried (I removed all the irrelevant code (locks) for the sake of simplicity):

struct MoveOnly
{
  MoveOnly() = default;
  MoveOnly(const MoveOnly& a) = delete;
  MoveOnly& operator=(const MoveOnly& a) = delete;
  MoveOnly(MoveOnly&& a) = default;
  MoveOnly& operator=(MoveOnly&& a) = default;

  std::vector<int> v;

};

struct CopyOnly
{
  CopyOnly() = default;
  CopyOnly(const CopyOnly &a) = default;
  CopyOnly &operator=(const CopyOnly &a) = default;
  CopyOnly(CopyOnly &&a) = delete;
  CopyOnly &operator=(CopyOnly &&a) = delete;

  std::vector<int> v;
};

template <typename T>
class Queue
{
  std::queue<T> q;

public:
  T pop()
  {
    T t = q.front();
    return t;
  }

  void push(T&& t)
  {
    q.push(std::forward<T>(t));
  }
};

int main()
{
  Queue<MoveOnly> qm;
  qm.push(MoveOnly());
  MoveOnly mo = qm.pop();

  Queue<CopyOnly> qc;
  CopyOnly c;
  qc.push(c);
  CopyOnly&& co = qc.pop();
}

There are several compile errors due to pop: T t = q.front() cannot work with move semantics as the function returns a lvalue reference. T t = std::move(q.front()) would not work with an explicitly deleted move constructor as operator overloading will resolve to the deleted constructor. The same kind of problem used to appear in the push function but it is resolved with perfect forwarding.

Another problem is apparently that return t binds to the move constructor for CopyOnly, and I have difficulties to understand why it does so.

Is there a way to make pop work with both MoveOnlyand CopyOnly objects?


Side question: does it make sense to define an object like CopyOnlywith explicitly deleted move constructors? In which case would it be useful to do that? Because it works if the constructors are implicitly deleted.

Type conversion from std::complex

I have a class MyType that implements a user-defined arithmetic type. This class provides the following conversion operator

struct MyType 
{ ...
  operator double()
  { 
    return to_double(); // This converts my type to a double value
  }
... };

Using this class as follows works fine:

double d = MyType(1);

However, using this class as type within std::complex, e.g.

#include <complex>
std::complex<double> c = std::complex<MyType>(1,1);

fails with the following compiler error:

error: conversion from 'std::complex<MyType>' to non-scalar type 'std::complex<double>' requested

Any help to solve this problem is appreciated.

Matthias

Why does this c++ template scenario unable to compile:

struct stream_type1 {
  template<typename T>
  const T& read() const;
};

struct stream_type2 {
  template<typename T>
  const T& read() const;
};

template<typename S, typename T>
const T& stream_read(const S& stream)
{
  return stream.read<T>();
}

// example:
stream_type1 stream1;
stream_type1 stream2;

int value1 = stream_read<int>(stream1);
int value2 = stream_read<int>(stream2);

error: C2665: 'stream_read': none of the 2 overloads could convert all the argument types

so, I have to specialize the template witch makes it redundant

template<typename T>
const T& stream_read(const stream_type1 & stream)
{
  return stream.read<T>();
}

template<typename T>
const T& stream_read(const stream_type2 & stream)
{
  return stream.read<T>();
}

mardi 28 avril 2020

Is a for-loop or iterator a faster way to traverse a string?

I have a string.

std::string strLine;

I can traverse the string chars using a if loop

for (int i = 0; strLine[i]; i++)

Another way i can do is using string iterator

string::iterator it;
for (it = strLine.begin(); it < strLine.end(); it++) 

Which is a faster and flexible way to iterate ?

g++: undefined reference to `_imp___ZN5pluma13Plxxxx

I want to compile project "pluma".I use mingw,and open this project with codeblock with default cbp. The first two project go well, with following log:

mingw32-g++.exe -std=c++0x -Wall -DPLUMA_EXPORTS -g -O0 -I..\..\include -I..\..\src -c F:\workspace\mec\Pluma-1.1\src\Pluma\Dir.cpp -o ..\..\ztemp\mingw\debug\src\Pluma\Dir.o
mingw32-g++.exe -std=c++0x -Wall -DPLUMA_EXPORTS -g -O0 -I..\..\include -I..\..\src -c F:\workspace\mec\Pluma-1.1\src\Pluma\DLibrary.cpp -o ..\..\ztemp\mingw\debug\src\Pluma\DLibrary.o
mingw32-g++.exe -std=c++0x -Wall -DPLUMA_EXPORTS -g -O0 -I..\..\include -I..\..\src -c F:\workspace\mec\Pluma-1.1\src\Pluma\Host.cpp -o ..\..\ztemp\mingw\debug\src\Pluma\Host.o
mingw32-g++.exe -std=c++0x -Wall -DPLUMA_EXPORTS -g -O0 -I..\..\include -I..\..\src -c F:\workspace\mec\Pluma-1.1\src\Pluma\PluginManager.cpp -o ..\..\ztemp\mingw\debug\src\Pluma\PluginManager.o
mingw32-g++.exe -std=c++0x -Wall -DPLUMA_EXPORTS -g -O0 -I..\..\include -I..\..\src -c F:\workspace\mec\Pluma-1.1\src\Pluma\Provider.cpp -o ..\..\ztemp\mingw\debug\src\Pluma\Provider.o
mingw32-g++.exe -shared  -Wl,--out-implib=..\..\lib\libpluma-d.a -Wl,--dll  ..\..\ztemp\mingw\debug\src\Pluma\Dir.o ..\..\ztemp\mingw\debug\src\Pluma\DLibrary.o ..\..\ztemp\mingw\debug\src\Pluma\Host.o ..\..\ztemp\mingw\debug\src\Pluma\PluginManager.o ..\..\ztemp\mingw\debug\src\Pluma\Provider.o  -o ..\..\lib\pluma-d.dll  
Output file is ..\..\lib\pluma-d.dll with size 1.36 MB
Process terminated with status 0 (0 minute(s), 1 second(s))
0 error(s), 0 warning(s) (0 minute(s), 1 second(s))

mingw32-g++.exe -Wall -DPLUGIN_EXPORTS -g -O0 -I..\..\..\include -I..\..\src\interface -I..\..\src\plugin -c F:\workspace\mec\Pluma-1.1\example\src\interface\Warrior.cpp -o ..\..\..\ztemp\mingw\elite-warriors\debug\src\interface\Warrior.o
mingw32-g++.exe -Wall -DPLUGIN_EXPORTS -g -O0 -I..\..\..\include -I..\..\src\interface -I..\..\src\plugin -c F:\workspace\mec\Pluma-1.1\example\src\plugin\Connector.cpp -o ..\..\..\ztemp\mingw\elite-warriors\debug\src\plugin\Connector.o
mingw32-g++.exe -shared   -Wl,--dll -L..\..\..\lib ..\..\..\ztemp\mingw\elite-warriors\debug\src\interface\Warrior.o ..\..\..\ztemp\mingw\elite-warriors\debug\src\plugin\Connector.o  -o ..\..\bin\plugins\elite-warriors-d.dll -lpluma-d  
Output file is ..\..\bin\plugins\elite-warriors-d.dll with size 269.04 KB
Process terminated with status 0 (0 minute(s), 1 second(s))
0 error(s), 0 warning(s) (0 minute(s), 1 second(s))

But when I compile the third project and link with the lib generated before.I get following log:

mingw32-g++.exe -Wall -g -O0 -I..\..\..\include -I..\..\src\interface -I..\..\src\host -c F:\workspace\mec\Pluma-1.1\example\src\host\Main.cpp -o ..\..\..\ztemp\mingw\aztec-warfare\debug\src\host\Main.o
mingw32-g++.exe -Wall -g -O0 -I..\..\..\include -I..\..\src\interface -I..\..\src\host -c F:\workspace\mec\Pluma-1.1\example\src\interface\Warrior.cpp -o ..\..\..\ztemp\mingw\aztec-warfare\debug\src\interface\Warrior.o
mingw32-g++.exe -L..\..\..\lib -L..\..\..\lib -o ..\..\bin\aztecs-d.exe ..\..\..\ztemp\mingw\aztec-warfare\debug\src\host\Main.o ..\..\..\ztemp\mingw\aztec-warfare\debug\src\interface\Warrior.o  -lpluma-d  
F:\workspace\mec\Pluma-1.1\example\src\host\Main.cpp: In function 'int main()':
F:\workspace\mec\Pluma-1.1\example\src\host\Main.cpp:30:16: warning: deleting object of abstract class type 'Warrior' which has non-virtual destructor will cause undefined behavior [-Wdelete-non-virtual-dtor]
   30 |         delete warrior;
      |                ^~~~~~~
d:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: ..\..\..\ztemp\mingw\aztec-warfare\debug\src\host\Main.o: in function `main':
F:/workspace/mec/Pluma-1.1/example/src/host/Main.cpp:15: undefined reference to `_imp___ZN5pluma13PluginManager14loadFromFolderERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEb'
d:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: ..\..\..\ztemp\mingw\aztec-warfare\debug\src\host\Main.o: in function `ZN5pluma5Pluma18acceptProviderTypeI15WarriorProviderEEvv':
F:\workspace\mec\Pluma-1.1\example\build\mingw/../../../include/Pluma/Pluma.inl:35: undefined reference to `_imp___ZN5pluma13PluginManager12registerTypeERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEjj'
d:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: ..\..\..\ztemp\mingw\aztec-warfare\debug\src\host\Main.o: in function `ZN5pluma5Pluma12getProvidersI15WarriorProviderEEvRSt6vectorIPT_SaIS5_EE':
F:\workspace\mec\Pluma-1.1\example\build\mingw/../../../include/Pluma/Pluma.inl:46: undefined reference to `_imp___ZNK5pluma13PluginManager12getProvidersERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE'
collect2.exe: error: ld returned 1 exit status

However,I use "nm libpluma-d.a" to check out the symbols,I see:

00000000 I __imp___ZN5pluma13PluginManager14loadFromFolderERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEb
00000000 I __imp___ZN5pluma13PluginManager12registerTypeERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEjj
00000000 I __imp___ZNK5pluma13PluginManager12getProvidersERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE

These symbols are existed, but only they are prefixed with "__imp".There is another "_" in the prefix.Is this the problem?How can I fix it?

When can memory_order_acquire or memory_order_release be safely removed from compare_exchange?

I refer to the code in Lewiss Baker's coroutine tutorial.

https://lewissbaker.github.io/2017/11/17/understanding-operator-co-await

bool async_manual_reset_event::awaiter::await_suspend(
  std::experimental::coroutine_handle<> awaitingCoroutine) noexcept
{
  // Special m_state value that indicates the event is in the 'set' state.
  const void* const setState = &m_event;

  // Remember the handle of the awaiting coroutine.
  m_awaitingCoroutine = awaitingCoroutine;

  // Try to atomically push this awaiter onto the front of the list.
  void* oldValue = m_event.m_state.load(std::memory_order_acquire);
  do
  {
    // Resume immediately if already in 'set' state.
    if (oldValue == setState) return false; 

    // Update linked list to point at current head.
    m_next = static_cast<awaiter*>(oldValue);

    // Finally, try to swap the old list head, inserting this awaiter
    // as the new list head.
  } while (!m_event.m_state.compare_exchange_weak(
             oldValue,
             this,
             std::memory_order_release,
             std::memory_order_acquire));

  // Successfully enqueued. Remain suspended.
  return true;
}

where m_state is just a std::atomic<void *>.

bool async_manual_reset_event::is_set() const noexcept
{
  return m_state.load(std::memory_order_acquire) == this;
}
void async_manual_reset_event::reset() noexcept
{
  void* oldValue = this;
  m_state.compare_exchange_strong(oldValue, nullptr, std::memory_order_acquire);
}
void async_manual_reset_event::set() noexcept
{
  // Needs to be 'release' so that subsequent 'co_await' has
  // visibility of our prior writes.
  // Needs to be 'acquire' so that we have visibility of prior
  // writes by awaiting coroutines.
  void* oldValue = m_state.exchange(this, std::memory_order_acq_rel);
  if (oldValue != this)
  {
    // Wasn't already in 'set' state.
    // Treat old value as head of a linked-list of waiters
    // which we have now acquired and need to resume.
    auto* waiters = static_cast<awaiter*>(oldValue);
    while (waiters != nullptr)
    {
      // Read m_next before resuming the coroutine as resuming
      // the coroutine will likely destroy the awaiter object.
      auto* next = waiters->m_next;
      waiters->m_awaitingCoroutine.resume();
      waiters = next;
    }
  }
}

Note in m_state.exchange of the set() method, the comment above shows clearly why the call to exchange requires both acquire and release.

I wonder why in the m_state.compare_exchange_weak of the await_suspend() method, the third parameter is a std::memory_order_release but not a memory_order_acq_rel (the acquire is removed).

The author (Lewis) did explain that we need release in the compare_exchange_weak because we need to let later set() see the writes in compare_exchange_weak. But why don't we require other compare_exchange_weak in other threads to see the writes in the current compare_exchange_weak?

Is it because of release sequence? I.e., in a release chain (write release at first, and all the middle operations are "read acquire then write release" operations, and the final operation is read acquire), then you don't need to tell them to acquire in the middle?

In the following code, I tried to implement a shared lock,

    struct lock {
        uint64_t exclusive : 1;
        uint64_t id : 48;
        uint64_t shared_count : 15;
    };
    std::atomic<lock> lock_ { {0, 0, 0} };
    bool try_lock_shared() noexcept {
        lock currentlock = lock_.load(std::memory_order_acquire);
        if (currentlock.exclusive == 1) {
            return false;
        }
        lock newlock;
        do {
            newlock = currentlock;
            newlock.shared_count++;
        }
        while(!lock_.compare_exchange_weak(currentlock, newlock, std::memory_order_acq_rel) && currentlock.exclusive == 0);

        return currentlock.exclusive == 0;
    }
    bool try_lock() noexcept {
        uint64_t id = utils::get_thread_id();
        lock currentlock = lock_.load(std::memory_order_acquire);
        if (currentlock.exclusive == 1) {
            assert(currentlock.id != id);
            return false;
        }

        bool result = false;
        lock newlock { 1, id, 0 };
        do {
            newlock.shared_count = currentlock.shared_count;
        }
        while(!(result = lock_.compare_exchange_weak(currentlock, newlock, std::memory_order_acq_rel)) && currentlock.exclusive == 0);

        return result;
    }

I used lock_.compare_exchange_weak(currentlock, newlock, std::memory_order_acq_rel) everywhere, can I safely replace them to compare_exchange_weak(currentlock, newlock, std::memory_order_release, std::memory_order_acquire) ?

I could also see examples that memory_order_release is removed from compare_exchange_strong (see the compare_exchange_strong in reset() function of Lewis code), where you only need std::memory_order_acquire for compare_exchange_strong (but not release). I didn't really see memory_order_release is removed from weak nor memory_order_acquire is removed from strong.

This made me wonder whether there's deeper rule that I didn't understand or not.

Thanks.

How to overload dereference operator of std::list for range-based for?

I am trying to handle std::list of pointer type, like this:

std::list<int*> pNums;

Originally, iterating this container with range-based for loop will look like this :

for(int* pNum : pNums)
{
    std::cout << (*pNum) << std::endl;
}

However, I want to iterate this container with a value, not a pointer, like below:

for(int num : Range(pNums))
{
    std::cout << num << std::endl;
}

| Here, Range is a custom wrapping-class of std::list<int*>, something should be defined in this manner, I guess:

class Range
{
    Range(std::list<int*>& _list) : list(_list) {}
    std::list<int*>& list;

    // Basically inherit the original iterator
    class custom_const_iterator : std::list<int*>::const_iterator
    {
        // Define an overloaded dereference operator
        const int& operator*() const
        {
            ...
        }
        ...
    };

public:
    custom_const_iterator begin() { return ...; }
    custom_const_iterator end()   { return ...; }
};

So, my question is, what should I write down for class Range?

Is it possible to create a vector of a template class and call its functions?

I created a template class with some methods that use as parameter template type like this:

template <class T>
class vector{
... 
void new(const T&new_value)
...
}

I want to use it inside another class but since it's not allowed to declare it like this:

class matrix{
vector _ptr_to_vect;
}

I created a base class BaseVector.

But in BaseVector I cannot define a virtual function like new(const T&new_value) to override it (because I don't want to use template again). Since I cannot define it then is not possible to call it like:

BaseVector _ptr_to_vect;
BaseVector[0].new("new value")

Storing the iterator of a set to user-defined type in a std::deque in C++

I have a std::set of user-defined type which contains sorted-values based on some criteria[overloaded < operator]. I want to store the iterator from this set into a std::deque which I can use later to update/delete entries from set. Here's what I am doing :

.h file

static std::set<SpanStruct_X> spanXRange;
std::map<uint16_t, std::deque<SpanStruct_X>::iterator> mMap;

.cpp

SpanStruct_X sX;
spanXRange.insert(sX);
mMap[id].push_back(spanXRange.find(sX));

I assume ::iterator is available only for std types and not for user defined and hence I get this compilation error.

Compilation Error :

error: ‘std::map<short unsigned int, std::_Deque_iterator<SpanStruct_X, SpanStruct_X&, SpanStruct_X*> >::mapped_type’ has no member named ‘push_back’
                         mMap[id].push_back(spanXRange.find(sX));

How should I get this done?

Thanks!

C++: Is memcpy to POD based sub-object UB?

Let's go to the code:

extern "C" {
#include "pod-struct-T.h"
#include "malloc-and-initialize-one-T.h"
}

struct TCpp : T
{
   TCpp()
   {
      T* ptr_t = malloc_and_initialize_one_T();
      T* this_t = static_cast<T*>(this);
      std::memcpy(this_t, ptr_t, sizeof(T));
      free(ptr_t);
   }
};

How many UBs is there in this piece of code (for both C++03 and C++11; or for C++20 if something has change after its revisited memory model) or doing that memcpy is just fine? In case it is UB, is it at least portable among major compilers? (gcc, clang, intel, etc).

DISCLAIMER: Yes I know..., it's ugly, but don't ask why I need to do this.

Change QFrame Box color and border when pressed

I'm trying to change a QFrame with a Box style color and border when the mouse pressed down on it. The style is within an external style sheet file. I have the :hover pseudo state working for this but trying the :pressed or :selected doesn't seem to work or show the style changes I want.

How to show latest entry on a QListView always on top

As is possible to see from the print screen below I have the following problem: as I add the entry via QPushButton I don't want the last entry to be the last of the QListView but instead I want it to be at the top of the QListView. How do I make the QListView always showing from the latest entry to the last entry?

view_wrong

The desired behavior is with the latest entry on top:

correct

Below the code:

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    mView = new QGraphicsView();
    mScene = new QGraphicsScene();
    ui->graphicsView->setScene(mScene);

    QFont font;
    font.setPixelSize(10);
    font.setBold(false);
    font.setFamily("Calibri");

    mText = new QGraphicsTextItem;
    mText->setPos(150,70);
    mScene->addText(tr("Boat outside alarm area"))->setDefaultTextColor(Qt::black);

    model = new QStringListModel();
    ui->listView->setModel(model);
    ui->listView->setEditTriggers(QAbstractItemView::NoEditTriggers);

    connect(ui->listView, SIGNAL(loggingUpdated()), this, SLOT(updateListView(const QString &)));
}


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

void MainWindow::updateListView(const QString & message)
{
    if(model->insertRow(model->rowCount())) {
        QModelIndex index = model->index(model->rowCount() - 1, 0);
        model->setData(index, message);
        ui->listView->scrollTo(index);
    }
}

void MainWindow::on_pushButton_clicked()
{
    QString str = ui->lineEdit->text();
    model->insertRow(model->rowCount());
    QModelIndex index = model->index(model->rowCount()-1);
    model->setData(index, str);
}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsTextItem>
#include <QStringListModel>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
    void updateListView();
    void updateListView(const QString & message);

signals:
    void loggingUpdated();

private slots:
    void on_pushButton_clicked();

private:
    Ui::MainWindow *ui;
    QGraphicsView *mView;
    QGraphicsScene *mScene;
    QGraphicsTextItem *mText;
    QStringListModel *model;

};
#endif // MAINWINDOW_H

I wonder if there is some missing signals I didn't catch or if at this point I should use a Q_PROPERTY but I am not sure if that is actually the right route. I am running out of ideas on how to solve this issue.

What I have done so far:

I researched the problem and came across this source that helped me set the proper index. However it did not help to completely solve the problem.

I also consulted the official documentation however my problem is not related to how scolling should be, but how to determine the latest entry and put it as first item of the QListView.

I didn't stop there and dug more and arrived to this command but I am not sure it applies coorectly to the problem I am solving.

Thanks for pointing to the right direction on how to solve this problem

How to change QGraphicsView background color based on specific QString content inside a QListView

In order to shrink the problem I made a small verifiable example of a small gui. If you would like to take a glance at the code you can see it here.

I have a specific string on a QLineEdit, this string is passed to a QListView via QPushButton as shown below. Those strings are choices of a QComboBox and they are very specific: 1) "[ INFO] Minimum Distance: 5", 2) "[ INFO] Minimum Distance: 10" and 3) "[ INFO] Minimum Distance: 15"

The problem: How can I detect the specific QString content inside a QListView in order to change the background color of a QGraphicsView?

For example if inside the QListView there is "[ INFO] Minimum Distance: 5", the color of the QGraphicsView should be red or if inside the QListView there is "[ INFO] Minimum Distance: 10", the color of the QGraphicsView should be yellow etc.

string

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    mView = new QGraphicsView();
    mScene = new QGraphicsScene();
    ui->graphicsView->setScene(mScene);

    mText = new QGraphicsTextItem;
    mText->setPos(150,70);
    mScene->addText(tr("Boat outside alarm area"))->setDefaultTextColor(Qt::black);

    model = new QStringListModel();
    ui->listView->setModel(model);
    ui->listView->setEditTriggers(QAbstractItemView::NoEditTriggers);

    changeColorDetection();

}

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

void MainWindow::changeColorDetection()
{
    QColor red;
    QColor yellow;
    QColor green;

    // if [ INFO] Minimum Distance: 5 inside QListView
    // Than change color of the QGraphicsView background to red

    // if [ INFO] Minimum Distance: 10 inside QListView
    // Than change color of the QGraphicsView background to yellow

    QModelIndex index = ui->listView->currentIndex();
    QString itemText = index.data(Qt::DisplayRole).toString();
    if(itemText.startsWith("[ INFO] Minimum Distance: 10"))
    {
        ui->graphicsView->setStyleSheet("QGraphicsView {background-color: red}");
    }
}

void MainWindow::on_pushButton_clicked()
{
    QString str = ui->lineEdit->text();
    model->insertRow(model->rowCount());
    QModelIndex index = model->index(model->rowCount()-1);
    model->setData(index, str);
}


void MainWindow::on_comboBox_currentIndexChanged(const QString &arg1)
{
    QString list = ui->comboBox->currentText();
    ui->lineEdit->setText(list);
    Q_UNUSED(arg1)
}

mainwindow.h

#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsTextItem>
#include <QStringListModel>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
    void changeColorDetection();

private slots:
    void on_pushButton_clicked();
    void on_comboBox_currentIndexChanged(const QString &arg1);

private:
    Ui::MainWindow *ui;
    QGraphicsView *mView;
    QGraphicsScene *mScene;
    QGraphicsTextItem *mText;
    QStringListModel *model;

};
#endif // MAINWINDOW_H

main.cpp

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

In case you also would like to see the small .ui the code is below:

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>555</width>
    <height>382</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <layout class="QGridLayout" name="gridLayout_2">
    <item row="0" column="0">
     <layout class="QVBoxLayout" name="verticalLayout">
      <item>
       <widget class="QGroupBox" name="groupBox">
        <property name="title">
         <string>Area</string>
        </property>
        <layout class="QGridLayout" name="gridLayout">
         <item row="0" column="0">
          <layout class="QHBoxLayout" name="horizontalLayout">
           <item>
            <widget class="QCheckBox" name="checkBoxRedArea">
             <property name="text">
              <string>Red area</string>
             </property>
            </widget>
           </item>
           <item>
            <widget class="QCheckBox" name="checkBoxYellowArea">
             <property name="text">
              <string>Yellow Area</string>
             </property>
            </widget>
           </item>
           <item>
            <widget class="QCheckBox" name="checkBoxGreenArea">
             <property name="text">
              <string>Green Area</string>
             </property>
            </widget>
           </item>
          </layout>
         </item>
         <item row="1" column="0">
          <layout class="QHBoxLayout" name="horizontalLayout_3">
           <item>
            <widget class="QPushButton" name="pushButton">
             <property name="text">
              <string>Add Message</string>
             </property>
            </widget>
           </item>
           <item>
            <widget class="QLineEdit" name="lineEdit"/>
           </item>
           <item>
            <widget class="QComboBox" name="comboBox">
             <item>
              <property name="text">
               <string>Select Option Distance</string>
              </property>
             </item>
             <item>
              <property name="text">
               <string>[ INFO] Minimum Distance: 5</string>
              </property>
             </item>
             <item>
              <property name="text">
               <string>[ INFO] Minimum Distance: 10</string>
              </property>
             </item>
             <item>
              <property name="text">
               <string>[ INFO] Minimum Distance: 15</string>
              </property>
             </item>
             <item>
              <property name="text">
               <string>[ INFO] Minimum Distance: 20</string>
              </property>
             </item>
            </widget>
           </item>
          </layout>
         </item>
        </layout>
       </widget>
      </item>
      <item>
       <layout class="QHBoxLayout" name="horizontalLayout_2">
        <item>
         <widget class="QListView" name="listView"/>
        </item>
        <item>
         <widget class="QGraphicsView" name="graphicsView">
          <property name="styleSheet">
           <string notr="true">background-color: rgb(211, 215, 207);</string>
          </property>
         </widget>
        </item>
       </layout>
      </item>
     </layout>
    </item>
   </layout>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>555</width>
     <height>22</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>

What I have done so far:

I have been doinf a lot of research about this problem and came across this source which was useful but could not solve the problem, but in addition it seems to use a QModelIndex and I am not sure this is exactly what I need for this small project.

Also I read this source which was useful to establish and capture the specific and unique string but in terms of changing colors I could not solve that.

I also came across this which led me to give a try to the following:

void MainWindow::changeColorDetection()
{
    // if [ INFO] Minimum Distance: 5 inside QListView
    // Than change color of the QGraphicsView background
    QModelIndex index = ui->listView->currentIndex();
    QString itemText = index.data(Qt::DisplayRole).toString();
    if(itemText.startsWith("[ INFO] Minimum Distance: 10"))
    {
        QColor bg = ui->graphicsView->palette().background().color();
        ui->graphicsView->setStyleSheet(QString("background-color:") + bg.name(QColor::HexArgb));
    }
}

But also this last one did not result in any change in the background.

What am I missing? Thank you very much for pointing to the right direction for solving this issue.

I have 3 errors and 1 warning. Need help to fix them

enter image description here

enter image description herem/RZxvi.png

enter image description here

enter image description hereenter image description here

how to read a whole vector?

#include"std_lib_facilities.h"
int main()
{
  vector<int>test = {1,2,3,4,5,6,7,8,9};
    cout<<test[0,8]<<'\n';
}

I want this code to print from 0 to 9 but it is only printing 9 and I also tried

cout<<test[0,test.size()] 

but it is showing an "range error 9".... Also please don't recommend me this code:

for(int x : test)
  cout<<x<<'\n';

because I don't know how to use that x effectively....please help me this...

Sorting numbers digit wise

I have N numbers and I want to sort each number by digit. ( In my original problem I want to make the largest number by these (greedy approach)) For ex - If we have 5 numbers 9 1000 845 8000 56 In first step I will pick 9 as 9 is the highest of all 1st digit of numbers

In second step ( as 9 is already picked), next highest first digit is 8, but when 2 or more numbers have same digit I will compare their next digit so I will pick 845.

In this if I sort I will get the following result 9 845 8000 56 1000.

My question is how can implement this in c++ ?

Thanks in advance

Name (or refer) a specialized template parameter

I decided to use the following pattern to combine various types of objects and their configs automatically:

enum class Type { Car, Person };

template< Type TYPE >
struct Object;

template< Type TYPE >
struct ObjectConfig;

template<>
struct ObjectConfig< Type::Car >
{
};

// Version 1
template<>
struct Object< Type::Car >: public ObjectConfig< Type::Car > // How could I avoid this duplication???
{
};

// Version 2
template<>
struct Object< Type::Car >
{
    static constexpr Type myType{ Type::Car }; // How could I avoid this duplication???
    ObjectConfig< myType > m_params;
};

It is intended to be error-proof and automatic, but I can not avoid writing the enum value twice (which is error prone and non-automatic at all). I would like to write something similar (so I would like to refer the specialized parameter somehow):

template< Type TYPE >
struct Object;

template<>
struct Object< Type::Car >: public ObjectConfig< TYPE >
{
};

Is there any trick I could use to achieve something similar?

Thank you in advance!

std::shared_ptr which is empty but not null

http://www.cplusplus.com/reference/memory/shared_ptr/ says

A shared_ptr that does not own any pointer is called an empty shared_ptr. A shared_ptr that points to no object is called a null shared_ptr and shall not be dereferenced. Notice though that an empty shared_ptr is not necessarily a null shared_ptr, and a null shared_ptr is not necessarily an empty shared_ptr.

Am I able to create an empty std::shared_ptr, i.e. one which does not own anything but which is not null, i.e. contains payload?

The usecase is to marry "legacy" code with the modern pointers: Given that foo's call syntax is not to be changed,

void foo(const MyClass* p) {
   if (p == nullptr) {
       auto defaultObject = std::make_shared<MyClass>("some", "parameters");
       defaultObject->doSomething();
       ...
       defaultObject->doSomethingElse();
       // The default object must be destroyed again
   } else {
       p->doSomething();
       ...
       p->doSomethingElse();
       // p must not be destroyed, its memory is managed somewhere else
   }
}

is there an implementation for doNotOwnButStillPointTo() which allows this:

void foo(const MyClass* p) {
    std::shared_ptr<MyClass> wrapper;
    if (p == nullptr) {
        // Create a default object
        wrapper = std::make_shared<MyClass>("some", "parameters");
    } else {
        wrapper = doNotOwnButStillPointTo(p);
    }

    wrapper->doSomething();
    ...
    wrapper->doSomethingElse();
    // p mus not be destroyed, the default object (if created) shall be
}

Or, to not fall for the XY-Problem, is there a different smart pointer available or none at all?

  • However, I want to add, that the line std::make_shared<MyClass>("some", "parameters") is actually a call to a more complex function which creates a shared_ptr. I'd like to retain this function and use its result

Elegant way to parse json to C struct using latest C++ features

I'm using nlohmann json parse lib but i'm trying to make good use of the latest C++ extensions in order to make the parsing as generic and elegant as possible. Of course, some corner case specialization will be neded.

I've found visit_struct lib, but it uses boost.

Any suggestions ?

Terminate called after throwing an instance of 'range error' what(): 'Range Error' -1?

#include"std_lib_facilities.h"
int main()
{
  vector<double>numbers;
  cout<<"Enter any two numbers:\n";
  double two_numbers;
  //loop
  while(cin>>two_numbers){
    numbers.push_back(two_numbers);
    double vector_size = numbers.size();
    double two = 2;
    double formula_equal = 1.0/100;
    double od_ev = fmod(vector_size , two);
    //checking the conditions
    if(od_ev == 0)
      if(numbers[vector_size-1] > numbers[vector_size - 2])
        cout<<"The larger value is: "<<numbers[vector_size - 1]<<'\n'
            <<"The smaller value is: "<<numbers[vector_size - 2]<<'\n';
        if(numbers[vector_size-1] - numbers[vector_size - 2] < formula_equal)
          cout<<"These numbers are almost equal.";

      else if(numbers[vector_size-1] < numbers[vector_size - 2])
        cout<<"The larger value is: "<<numbers[vector_size - 2]<<'\n'
            <<"The smaller value is: "<<numbers[vector_size - 1]<<'\n';
        if(numbers[vector_size-2] - numbers[vector_size - 1] < formula_equal)
          cout<<"these numbers are almost equal.";

      else if(numbers[vector_size-1] == numbers[vector_size - 2])
        cout<<numbers[vector_size-1]<<" is equal to  "<<numbers[vector_size - 2]<<'\n';

      }
  }

I don't know why the compiler is showing such error I have searched a lot in google but I don't find anything related to this code please help me with this code.....I don't find any error but I am just a beginner....

OpenCL2 work_group_reduce_add float incorrect output

I'm learning opencl, but in one of my tests I tried to use work_group_reduce_add to add 3 floating values of an array (1.5f, 1.5f, 1.5f), the result I expected was 4.5f the most was 4.0f. And when I try a matrix with 2 values (1.5f, 1.0f), the result is the expected 2.5f, but when I try with more values from the third element of the matrix, the floating values start to be treated as integers. My code is just below.

std::vector<cl::Platform> plataforms;
cl::Platform::get(&plataforms);
std::vector<cl::Device> devices;
plataforms.front().getDevices(CL_DEVICE_TYPE_GPU, &devices);

cl::Context context(devices.front());

const char* code = "\
    __kernel void test(__global float* a, __global float* b) {\
        b[0] = work_group_reduce_add(a[get_global_id(0)]);\
    }\
";

cl::Program::Sources src(1, std::make_pair(code, strlen(code)));
cl::Program program(context, src);
program.build("-cl-std=CL2.0");
cl::CommandQueue queue_default(context, devices.front(), CL_QUEUE_ON_DEVICE | CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE | CL_QUEUE_ON_DEVICE_DEFAULT);
cl::CommandQueue queue(context, devices.front());

cl::Kernel kernel_test(program, "test");

float a[3] = { 1.5f, 1.5f, 1.5f };
float b[1] = { 0.0f };

cl::Buffer _a(context, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, sizeof(float) * 3, a);
cl::Buffer _b(context, CL_MEM_READ_WRITE | CL_MEM_USE_HOST_PTR, sizeof(float), b);

kernel_test.setArg(0, _a);
kernel_test.setArg(1, _b);

queue.enqueueNDRangeKernel(kernel_test, cl::NDRange(), cl::NDRange(3), cl::NDRange(3));
queue.finish();

Using `extern template` with third-party header-only library

I am using the glm library, which is a header-only collection of math utilities intended for 3D graphics. By using -ftime-trace on Clang and ClangBuildAnalyzer, I've noticed that a lot of time is being spent instantiating glm types:

**** Templates that took longest to instantiate:
 16872 ms: glm::vec<4, signed char, glm::packed_highp> (78 times, avg 216 ms)
 15675 ms: glm::vec<4, unsigned char, glm::packed_highp> (78 times, avg 200 ms)
 15578 ms: glm::vec<4, float, glm::packed_highp> (78 times, avg 199 ms)

...

So, I decided to create a wrapper header/source pair for glm, and use extern template to avoid unnecessary instantiations:

// glmwrapper.h

#pragma once

#include <glm.hpp>

extern template struct glm::vec<4, signed char, glm::packed_highp>;
extern template struct glm::vec<4, unsigned char, glm::packed_highp>;
extern template struct glm::vec<4, float, glm::packed_highp>;
// glmwrapper.cpp

template struct glm::vec<4, signed char, glm::packed_highp>;
template struct glm::vec<4, unsigned char, glm::packed_highp>;
template struct glm::vec<4, float, glm::packed_highp>;

Now, in my project, instead of including <glm.hpp>, I include "glmwrapper.h" instead. Unfortunately, that did not change anything. Using -ftime-trace and ClangBuildAnalyzer again reports the same number of instantiations.

I suspect that this is because #include <glm.hpp> does actually end up including the template definition, and at that point the subsequent extern template declarations are just redundant.

Is there a way to achieve what I want without modifying the glm library?


In pseudocode, I kinda want something like this:

// glmwrapper.h (psuedocode)

#pragma once

#include <glm.hpp>

// Make definition of the templates unavailable:
undefine template struct glm::vec<4, signed char, glm::packed_highp>;
undefine template struct glm::vec<4, unsigned char, glm::packed_highp>;
undefine template struct glm::vec<4, float, glm::packed_highp>;

// Make declaration of the templates available:
extern template struct glm::vec<4, signed char, glm::packed_highp>;
extern template struct glm::vec<4, unsigned char, glm::packed_highp>;
extern template struct glm::vec<4, float, glm::packed_highp>;
// glmwrapper.cpp (psuedocode)

// Define templates only in the `.cpp`, not in the header:
template struct glm::vec<4, signed char, glm::packed_highp>;
template struct glm::vec<4, unsigned char, glm::packed_highp>;
template struct glm::vec<4, float, glm::packed_highp>;

User defined call back functions as parameter in ALT COM dll

I have created a c++ console application. Now I want to build a ALT COM object so that I can use the C++ code in other platforms(eg. C#). One of the functions RegisterListener(parameter1, parameter2) takes two call back (out) functions as parameters. I have seen videos/documentations but all of them build COM dll where parameters are built in data types(int, long, bool, HRESULT, etc). How can I use user defined callback(out) functions as parameter.
Example:

sigin(int,string);
signout(string);
RegisterListener( (sigin)(int,string), signout(string) );

I want to allow the function RegisterListener to be called by other programs using the COM dll How can I do this/Are there any tutorials regarding this? Note: I have never wrote any COM objectsdll before.

Getting error can not inherit constructors from indirect base in c++17 compiler

#include <iostream> 
#include <chrono>    

class A{
    public:
        A(){} // default constr

};

class B:public A{
    public:
    using A::A;
    protected:

};

class C:public B{
    public:
        using A::A; //scope resolution 

        int f1(A a);// dummy function

};

int main () 
{ 
    return 0; 
} 

// Above program is working fine with C++ and C++14 but its giving error with C++17 // why and how can it be resolved?

Debugger does not stop at breakpoint and displays "Frames are not available" and "Variables are not available" (CLion)

System

Latest macOS, CLion (2018)

Problem

I'm trying to solve an exercise for uni and once I download the project I put it into my HDD I always used and once opened a message from IDE (never saw it before) shows up saying something related to case sensitive problems. Clicking on it the website says it is not really a problem so I decide to ignore it, until now. I need to debug the project as a part of the exercise and when I try nothing shows up on the debugger even if there are 3 breakpoints.

What I tried

I tried to download a fresh project and the problem does not go away, on the IDE site there are not direct solutions and the documentation for "Debugger" is generic. I tried to debug other project and it doesn't work anywhere.

What should I do?

Now, the project is due to next Monday, what should I do? Keep in mind that I'm a complete noob, it was kinda the first time for me working with the debugger, the real first time in class everything worked fine (a couple months ago). The problem seems to be related to the HDD (file system: NTFS, I use it via Tuxera) but that doesn't make sense... I had projects there in the past.

Thanks to everyone will try to help!

How switch char* on std::string in my implementation of func?

How convert my function from const char* to string? I need it withot templates. Just rebuild my function pattern_founder(const char*, const char*) on pattern_founder(std::string, std::string). I trying to do it with iterators, but something went wrong. Thank you.

 static bool pattern_founder(const char* file_path_ptr, const char* pattern) noexcept
    {
        const char* supp_file_path_ptr = nullptr;
        const char* supp_pattern = nullptr;
        while (true) 
            if (*pattern == '*') {
                supp_file_path_ptr = file_path_ptr;
                supp_pattern = ++pattern;
            }
            else if (!*file_path_ptr)
                return !*pattern;
            else if (*file_path_ptr == *pattern || *pattern == '?') {
                ++file_path_ptr;
                ++pattern;
            }
            else if (supp_file_path_ptr) {
                file_path_ptr = ++supp_file_path_ptr;
                pattern = supp_pattern;
            }
            else 
                return false;
    }