samedi 30 novembre 2019

How to loop through the string by separating the file paths with space(' ') and store it into the vector/array in C++

I have a string that has multiple file paths like as shown below:

%programdata%\EMR\Registration\Registration_EMR.xml C:\ProgramData\EMR\Registration\RegistrationEMR.xml
%AppData%\EMR\EMR Setup\REGDATA\registration_EMR.xml %AppData%\EMR\EMR Setup\REGDATA\RegistrationEMR.xm

I wanted to loop through the string by separating the file paths with space(' ') and store it into the vector/array.

so that the vector/array contains the below path that is separated with space.

%programdata%\EMR\Registration\Registration_EMR.xml 
C:\ProgramData\EMR\Registration\RegistrationEMR.xml
%AppData%\EMR\EMR Setup\REGDATA\registration_EMR.xml 
%AppData%\EMR\EMR Setup\REGDATA\RegistrationEMR.xml

Could anyone please help me?

Custom hash for std::tuple doesn't work with unordered_set

I hope you help me to understand what's wrong with my code.

Basically I need an unordered_set of tuples, but every time I call the insert function, I see that even when the hash is the same, the tuple is being inserted which means that I have tuples with the same hash in an unordered_set. To be more clear, let me share a piece of code here.

So, this is how my example looks like:

#include <iostream>
#include <tuple>
#include <unordered_set>

using namespace std;
using namespace testing;

struct MyHash {
    size_t operator()(const tuple<int, int, int>& t) const
    {
        auto [num1, num2, num3] = t;
        vector<int> v(3);
        v[0] = num1;
        v[1] = num2;
        v[2] = num3;
        sort(v.begin(), v.end());
        string key = to_string(v[0]) + "|" + to_string(v[1]) + "|" + to_string(v[2]);
        auto hashValue = hash<string>()(key);
        cout << "Hash value for " << key << "= " << hashValue << endl;
        return hashValue;
    }
};

int main(int argc, char** argv)
{
    unordered_set<tuple<int, int, int>, MyHash> s;
    s.insert(make_tuple(1, 2, 3));
    s.insert(make_tuple(1, 3, 2));
    s.insert(make_tuple(3, 2, 1));

    cout << "Amount of items = " << s.size() << endl;
}

and this is the output I got:

Hash value for 1|2|3= 12066275531359578498
Hash value for 1|2|3= 12066275531359578498
Hash value for 1|2|3= 12066275531359578498
Amount of items = 3

Why if the hash value for each entry is the same the amount of item inserted is 3? I was expecting having only one.

Regards

Using threads to sort in parallel (C++11)

I am trying to sort an array (1,000,000 elements) in parallel using threads but I am getting the error <unresolved overloaded function type>. For the sort function I pass where I want it to start, where I want it to end, and my comparator function. Below is example code:

Thread calling:

thread th1(arraySort, array.begin(), array.begin() + 500000);
thread th2(arraySort, array.begin() + 500001, array.end());

Function:

template <typename ForwardIteratorType>
void arraySort(ForwardIteratorType  start, ForwardIteratorType end) {
    sort(start, end, compare);
}

Note that without threads it works, but I am trying to speed the sorting up.

I am new to multithreading, so let me know what you guys suggest.

C++11 sort() in parallel using threads

I am trying to sort an array (1,000,000 elements) in parallel using threads but I am getting the error error: invalid use of void expression. For the sort function I pass where I want it to start, where I want it to end, and my comparator function. Below is example code:

thread th1(sort(array.begin(), array.begin() + 500000, compare));
thread th2(sort(array.begin() + 500001, array.end(), compare));

Note that without threads it works, but I am trying to speed the sorting up:

sort(array.begin(), array.begin() + 500000, compare);

I am new to multithreading, so let me know what you guys suggest.

How to calculate number of calls per second of a function?

I'm using C++ on linux and I'd like to know how to calculate how many times a function has been called each second. I think analogous to how frame rates are done in video games. Unlike the other questions I saw, I'm not rate limiting the number of calls. Just looking for a way to report how many times a second it gets called.

c++ Multiple worker threads and promises

I have a thread safe queue which is prepopulated with work by the main thread; when I launch my worker threads they pop a task from the work queue, but also, can push a new task back to the work queue (sometimes worker threads do push back more work, sometimes they don't). Brief glimpse into code:

auto work_queue = safe_queue{};

static void handle_task(T task) {
  // process the task
  // might push a new task to a work queue using work_queue.push()
}

int main() {
  //some work is done to prepopulate work_queue

  auto handle_work = [](){
    while (!work_queue.empty) {
      T task = work_queue.pop();
      handle_task(task);
    }
  };

  std::vector<std::thread> threads;
  for (int i = 0; i < NUM_OF_THREADS; i++) {
    threads.push_back(std::thread(processing));
  }

  std::for_each(threads.begin(), threads.end(), [](std::thread &t) {
    t.join();
  }
}

I understand that this code won't work correctly since in some cases, queue might be empty while some worker threads are processing work when another thread comes in, doesn't find work and exits (although threads processing tasks might push back new work to queue). My question is, how to prevent threads from exiting prematurely like that? Would that work using std::promise<void> to allow threads to communicate to other threads that they still might be working? If so, how would that work with multiple threads (I'm new to c++ and only used promises with single thread)?

Accessing to a private member of 'this' pointer in a static member function

I've just discovered something that was in contradiction to what I knew about the language. Let's start with following statemets:

  • this pointer of a class has type: Class* const
  • accessing private members of an object is not possible (except friend class objects)
  • a static method does not have access to object data

So the code below would not compile if not commented:

class Foo{
public:
    Foo* getPtr(){
        return this;
    }

private:
    int m_id;
};

int main(int argc, char **argv)
{
    Foo foo;
    Foo* fooPtr = foo.getPtr();
//    fooPtr->m_id; Won't compile
}

this pointer can be passed around to functions like a regular pointer, right?

So why it is possible to access private data through this pointer when it's passed to the static function callback as a parameter? What rule of the language allows it?

class Stomach{
public:
    using OnDigested = void (*)(void* userData);

    void StartEating(void* userData){
        timer(std::chrono::seconds(1), m_onDigested, userData);
    }

    void SetOnDigested(OnDigested onDigested) {
        m_onDigested = onDigested;
    }
private:
    OnDigested m_onDigested;
};

class Animal{
public:
    Animal(std::string specie){
        m_specie = specie;
    }

    void StartLeave(){
        m_stomach.SetOnDigested(OnDigested);
        m_stomach.StartEating(this);
    }
private:
    static void OnDigested(void* userData){
        Animal* animal = static_cast<Animal*>(userData);

        std::cout << "Every eaten tiger makes me wonder who I am.."
                     " I must be a: " << animal->m_specie << std::endl;

//        std::string specie = m_specie; //Won't compile
    }

    Stomach m_stomach;
    std::string m_specie;
};

int main(int argc, char **argv)
{
    Animal mammoth("Mammoth");
    mammoth.StartLeave();

    return 0;
}

The code above compiles and prints "Every eaten...".

I know that the call to the m_specie member is done from a Animal class, but not from an instance of animal class (static function). I assumed that when a this pointer is passed using userData it could be used as any other pointer (without access to private members)

variable value, after ternary operator

I have these lines of code:

int a = 10, b = 1;
a = --b ? b : (b = -99);
        cout << "a= " << a <<  "b= " <<b<< endl;

the output gives me b=-99 as a is not equal to 0(which makes senses) but it also changes the value of a to a=-99 how?

Initialization of map with a list as value

I am trying to initialize a map that contains a list

map<string, list<int>> firstNamesMap = name1;

I get the following error:

error: could not convert ‘name1’ from ‘<brace-enclosed initializer list>’ to ‘std::map<std::basic_string<char>, std::list<int> >’
 map<string, list<int>> firstNamesMap = name1;
                                                                 ^

I was originally trying to initialize a much larger map with list<Data *> instead of list<int>, in which "Data" is a simple class declared earlier. It produces the same error either way though.

Not sure if it matters, but I'm compiling with g++ in Cygwin.

vendredi 29 novembre 2019

Compilation on Linux - In function '_start': (.text+0x20): undefined reference to 'main'

I want to compile a series of cpp files on Linux. Using CentOS 7, in the Konsole, I type "g++ -std=c++11 main.cpp canvas.cpp patch.cpp utils.cpp", and I get an error:

/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status

Could anyone tell me how to solve this?

How to return an empty cvMat in a function for c++?

now I have a function:

cv::Mat func(int number){

cv::Mat img; ... if(number>=0)return img; else if(number<0) return xxx;

}

Here, when number<0 I want to return an empty cvMat, but return NULL; or return; are incorrect. So how to how to return an empty cvMat in a function?

Anyone can give some advises?

Extending base class and using the feature without altering the derived classes

I have a C++ Base class with some derived classes. If I later extend the base class by inheritance, it there way to reflect the changes in the already derived classes. To make my question more clear, consider the following code.

#include <iostream>

class FourWheelVehicle
{
    public:
        FourWheelVehicle()
        {std::cout<<"FourWheelVehicle created\n";}
};
class Car: public FourWheelVehicle
{
    public:
        Car()
        {std::cout<<"Car created\n";}
};
class Toyota: public Car
{
    public:
        Toyota()
        {std::cout<<"Toyota Car created\n";}
};
class Audi: public Car
{
    public:
        Audi()
        {std::cout<<"Audi Car created\n";}
};
int main()
{
    Toyota t;
    std::cout<<"..............................\n";
    Audi a;
    return 0;
}

How can I extend FourWheelVehicle to FourWheelVehicleWithSeatBelt so that all the cars I derived earlier will get the seat belt without altering their code? I have tried the following:

           FourWheelVehicle
               /      \
              /        \
             /          \
            Car          \
            /\            \
           /  \            \
      Toyota Audi    FourWheelVehicleWithSeatBelt

class FourWheelVehicleWithSeatBelt: public FourWheelVehicle
{
    public:
        FourWheelVehicleWithSeatBelt()
        {std::cout<<"FourWheelVehicleWithSeatBelt created\n";}
};

The above scheme does not seem to work!

Macro merge c++? [duplicate]

This question is an exact duplicate of:

I would like to know if it was possible to merge several macros in C++

Let me explain : I have an A macro that does not do anything at all. I want to add a macro B to A so that A = A + B, then I want to add a macro C to A so that A becomes A = A + C, and so that A contains B and C. I also want these operations to be done in different .h files and not in a single file like that :

// in Component.h
#define A
class Component
{

}
class myXmlParser
{
    template <class T>
    void addComponent<T>()
    {
        myComponents.push_back(new T);
    }

    std::vector<Component> myComponents;
}


// in PlayerScript.h
#include "Component.h"
class Player : public Component
{ 
#define A \
myParser.addComponent<Player>();
}

// in Enemy.h
#include "Component.h"
class Enemy : public Component
{
#define A \
myParser.addComponent<Enemy>();
}

// in main.cpp
void main()
{
    myXmlParser myParser;
    A
}

and the output is :
void main()
{
    myXmlParser myParser;
    myParser.addComponent<Player>();
    myParser.addComponent<Enemy>();
}

Now, if the user need to add another script, he dont need to touch the main, only his script.

Thank you ! Please !

C++ Fisher-Yates shuffle not working properly

I am attempting to implement the Fisher-Yates shuffle for a C++ Poker project.

I found this Code Review link that I used to implement my project.

My current code is below:

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

// Inspired by: https://codereview.stackexchange.com/questions/39001/fisher-yates-modern-shuffle-algorithm
void shuffleDeck(vector<Card> cards){
    random_device random;
    mt19937 mersenne_twister(random());
    uniform_int_distribution<uint8_t> distribution;
    for (auto i = cards.size() - 1; i > 0; i--){
        distribution.param(uniform_int_distribution<uint8_t>::param_type(0, i));
        swap(cards[i], cards[distribution(mersenne_twister)]);
    }

} //end shuffleDeck

int main(){
    Deck myDeck;
    vector<Card> theDeck = myDeck.getDeck();

    cout << "PRE SHUFFLE " << endl;

    for (unsigned int i = 0; i < theDeck.size(); i++){
        cout << theDeck[i].getRank() << theDeck[i].getSuit() << endl;
    }

    shuffleDeck(theDeck);

    cout << " POST SHUFFLE " << endl;

    for (unsigned int i = 0; i < theDeck.size(); i++){
        cout << theDeck[i].getRank() << theDeck[i].getSuit() << endl;
    }

}

I get the following for results:

PRE SHUFFLE
2C
3C
4C
5C
6C
7C
8C
9C
10C
2D
3D
4D
5D
6D
7D
8D
9D
10D
2H
3H
4H
5H
6H
7H
8H
9H
10H
2S
3S
4S
5S
6S
7S
8S
9S
10S
JC
KC
QC
AC
JH
KH
QH
AH
JS
KS
QS
AS
JD
KD
QD
AD
 POST SHUFFLE
2C
3C
4C
5C
6C
7C
8C
9C
10C
2D
3D
4D
5D
6D
7D
8D
9D
10D
2H
3H
4H
5H
6H
7H
8H
9H
10H
2S
3S
4S
5S
6S
7S
8S
9S
10S
JC
KC
QC
AC
JH
KH
QH
AH
JS
KS
QS
AS
JD
KD
QD
AD

I should note that the code compiles fine and there are no errors.

I would expect the POST SHUFFLE results to be different. I don't know what exactly, since it is a randomized shuffle, so I cannot post exact "expected results". But the shuffle isn't happening at all. What am I doing wrong that theDeck object is not shuffling?

How to show the default constructor in Doxygen generated documentation?

Having a class A:

class A {
public:
    /// @brief constructor taking no param
    A() {}
    /// @brief constructor taking 1 param
    A(int x){}
    /// @brief constructor taking 2 params
    A(int x, int y) {}
};

After generating documentation using Doxygen the "Constructor & Destructor Documentation" section will contain the documentation for constructors A(int x) and A(int x, int y). However not for A().

Is there any flag I can set to force Doxygen to include the constructor for A() in the relevant section of the class documentation?

Iterating over a vector containing pointers in c++

I got a function that accepts a pointer to a rapidjson::Value type and stores the item at that location into a rapidjson::Value of type kArrayType.

void addBlock(rapidjson::Value* block) {
    blocksArray.PushBack(*block, allocator);
}

This function works as expected.

To extend this I want to add a function that can take a vector of these pointers as an input. I tried this doing:

void addBlocks(std::vector<rapidjson::Value*> blocks) {
    for (const rapidjson::Value& block : blocks) {
        blocksArray.PushBack(*block, allocator);
    }
}

This does not work however. It gives me two red waves in Visual Studio.

The first one beneath block in the parameter declaration of the function, saying:

C++ no suitable constructor exists to convert from to...

And the second one beneath the * in the call to PushBack(), saying:

C++ no operator matches these operands operand types are: * const rapidjson::Value

My guess is that I am doing something very basic wrong that I am just missing.

moving smart pointers twice vs copying

Is there any significant difference in performance, memory, etc, between:

  • #1: moving a pointer to a temporary pointer, moving it back, then deleting the temporary pointer
  • #2: copying a pointer to a temporary pointer, then deleting the temporary pointer

I have the following code, two pointer of objects a Base and a Derived (which is derived from Base) are allowed to be stored inside a vector of pointers of Base objects, when reading the vector I need to check whether I need to dynamic_pointer_cast the pointer so data doesn't get sliced off.

#include "Base.h"
#include "Derived.h"

class Base
{
public:
    Base() {};
    ~Base() {};
};

class Derived: public Base
{
public:
    Derived() {};
    ~Derived() {};
};

int main()
{
    std::vector<std::shared_ptr<Base>> vectorOfBaseObjects;

    std::shared_ptr<Base> base = std::make_shared<Base>();
    std::shared_ptr<Derived> derived = std::make_shared<Derived>();

    myVec.push_back(base);
    myVec.push_back(derived);

    for (auto &it : vectorOfBaseObjects) {
        // #1: Move pointer to a temporary location and move it back when done
        if (std::shared_ptr<Derived> tmp_ptr = std::move(std::dynamic_pointer_cast<Derived>(it))) {
            // Do something with the derived object
            it = std::move(tmp_ptr);
        }

        // #2: Create a new temporary pointer
        if (std::shared_ptr<Derived> tmp_ptr = std::dynamic_pointer_cast<Derived>(it)) {
            // Do something with the derived object
        }
    }
}

Both statements work just fine, the only issues I could make of might be

  • #1: missing pointer locations in multi threaded appications in very rare cases, which could become a problem.
  • #2: an additional location assigned in the memory, which shoulnd't be an issue at all.

Create function with unknown number of std::array

I am trying to make a function that pass that test:

TEST(MyCat, CheckOn2Arrays){
    std::array<float, 3> vec1{1.0f, 2.0f, 3.0f};
    std::array<float, 3> vec2{4.0f, 5.0f, 6.0f};

    std::array<float, 6> r = MyCat(vec1, vec2);

    EXPECT_EQ(r[0], 1.0f);
    EXPECT_EQ(r[1], 2.0f);
    EXPECT_EQ(r[2], 3.0f);
    EXPECT_EQ(r[3], 4.0f);
    EXPECT_EQ(r[4], 5.0f);
    EXPECT_EQ(r[5], 6.0f);
}

I have writen that function:

template<class T, size_t N>
auto MyCat((std::array<T, N>) ... arrays) ->
decltype(std::array<T, N*sizeof...(arrays)>) {

    std::array<T, sizeof...(arrays)*N> retArray;

    int i = 0;
    for(std::array<T, N> array: arrays){
        T* = array.begin();
        while(!T){
            retArray[i] = &T;
            i++;
            T++;
        }
    }

    return retArray;
}

The function must take an arbitrary number of arguments and return an object of type std::array. All arguments are of type std::array (T and N are the same for all function arguments).

Im getting that errors and cant understand how to solve them..

../src/test/../myproject/MyCat.h:4:29: error: expected primary-expression before ‘)’ token
auto MyCat((std::array<T, N>) ... arrays) ->
                            ^
../src/test/../myproject/MyCat.h:4:6: warning: variable templates only available with     
std=c++14 or -std=gnu++14
auto MyCat((std::array<T, N>) ... arrays) ->
     ^
../src/test/../myproject/MyCat.h:4:43: error: expected ‘;’ before ‘->’ token
auto MyCat((std::array<T, N>) ... arrays) ->
                                          ^
../src/test/MyCat_test.cc: In member function ‘virtual void     
MyCat_CheckOn2Arrays_Test::TestBody()’:
../src/test/MyCat_test.cc:10:35: error: missing template arguments before ‘(’ token
std::array<float, 6> r = MyCat(vec1, vec2);

Calling a templated funtion using a thread object

#include<iostream>
#include<vector>
#include<thread>
#include<functional>
using namespace std;

typedef function<float(int)> lambda_t;

template<typename ty,typename funtor,typename res>
void traverse(ty &container,funtor lamda,res & out)
{
    int ind = 0;
    for(auto it=container.begin();it!=container.end();it++)
    {
        out[ind++] = lamda(*it);
    }
}



int main()
{
    vector<int> inp;

    for(int i=0;i<1000;i++)
        inp.push_back(rand()%1000);
    lambda_t lamda = [](int a){return (float)(a*2.5);};
    vector<float> outp(1000);
    thread t1(traverse<vector<int>,lambda_t,vector<float> >,inp,lamda,outp);
    int ind=0;
    for(auto i:outp) cout<<inp[ind++]<<" "<<i<<endl;
}

Above code is just for learning and I want to call the traverse function in a new thread. I think the issue is with the type of lambda parameter to traverse function and compiler says it cannot deduce type. Any help is appreciated. Also I'm new here so please let me know if I need to improve my question. Thanks

jeudi 28 novembre 2019

Get date time inC++ until milisconds [duplicate]

This question already has an answer here:

I used code below to get date time in c++.

    std::time_t t = std::time(0);
    std::tm* now = std::localtime(&t);

    int year = now->tm_year + 1900;
    int month = now->tm_mon + 1;
    int day = now->tm_mday;
    int hour = now->tm_hour;
    int min = now->tm_min;
    int sec = now->tm_sec;

    strstream tstamp_abs;
    tstamp_abs << year << "-" << month << "-" << day << " " << hour << ":" << min << ":" << sec;

My qustion is, how do I get the miliseconds?

I want result similar to python code:

from datetime import datetime
dateTimeObj = datetime.now()

The python code give result: 2019-11-29 11:15:39.192310

With c+ code, I only get the integer part of the seconds.I need to get more accurate milisecods.

How to make a TCP/IP sequencer

I have a OpenGL , QT application in which i am sending remote commands from a client , Based on the incoming commands the application is rendering.

The process works fine but i am not very proficient with networking and would like to know how i can improve the concept of the sequencer for the incoming commands that i have built.

This is the Main function.

int main(int argc, char *argv[])
{   
    QApplication a(argc, argv);
    cont.SetName("RootItem");
    TreeModel* model = new TreeModel("RootElement", &cont);
    WavefrontRenderer w(model);
    w.show();    // Show the QT GUI
    glfwInit();  // Initialioze the GLFW
    window = glfwCreateWindow(SCR_WIDTH , SCR_HEIGHT, "Renderer", nullptr, nullptr);   // Create the render window
    glfwMakeContextCurrent(window);
    GLenum GlewInitResult;
    glewExperimental = GL_TRUE;
    GlewInitResult = glewInit();    


          boost::asio::io_service io_service;
    server server1(io_service, 1980);
    boost::thread t(boost::bind(&io_service::run, &io_service)); // Start The service in a new thread so that it does not block the GUI

         while(!glfwWindowShouldClose(window))
    {
             // Process incoming commands
        processCommands()
             //Drawing Stuff here
                    Draw();

          }

    auto raii = makeCleaner( [&]() { io_service.stop(); });  // Stop the thread when the UI of QT closes
    return a.exec();
}

I create a server on a new thread so that the GUI is not blocked.

Than in my rendering loop i first collect the incoming commands , process them and than render the scene.

To collect the commands from the server i have a global extern std::vector , whenever a new message comes to the server i pushback the string into this vector.

To process these commands before drawing i have a class named CommandInterface in which i run a loop based on vector.size() of the same extern std::vector.

The server when receiving commands from telnet is not able to to receive all the incoming commands.

Also i have a question when i am running the std::vector loop in Command interface and at that time server receives a message and adds it to the the same vector would that cause a crash ?

This is the code for the server.

#include <cstdlib>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <qdebug.h>
#include <global.h>
using boost::asio::ip::tcp;
class session
{
public:
    session(boost::asio::io_service& io_service)
        : socket_(io_service)
    {
    }

    tcp::socket& socket()
    {
        return socket_;
    }

    void start()
    {       
        boost::asio::streambuf buf;
        boost::asio::read_until(socket_, buf, ";");
        std::string data = boost::asio::buffer_cast<const char*>(buf.data());
        incomingCommands.push_back(data); // Fill the the vector with incoming commands

    }

private:
    void handle_read(const boost::system::error_code& error,
        size_t bytes_transferred)
    {
        if (!error)
        {
            boost::asio::async_write(socket_,
                boost::asio::buffer("Wavefront_Hello", bytes_transferred),
                boost::bind(&session::handle_write, this,
                    boost::asio::placeholders::error));

        }
        else
        {
            delete this;
        }
    }

    void handle_write(const boost::system::error_code& error)
    {
        if (!error)
        {
            socket_.async_read_some(boost::asio::buffer(data_, max_length),
                boost::bind(&session::handle_read, this,
                    boost::asio::placeholders::error,
                    boost::asio::placeholders::bytes_transferred));
        }
        else
        {
            delete this;
        }
    }

    tcp::socket socket_;
    enum { max_length = 2048 };
    char data_[max_length];
};

class server
{
public:
    server(boost::asio::io_service& io_service, short port)
        : io_service_(io_service),
        acceptor_(io_service, tcp::endpoint(tcp::v4(), port))
    {
        start_accept();
    }

private:
    void start_accept()
    {
        session* new_session = new session(io_service_);
        acceptor_.async_accept(new_session->socket(),
            boost::bind(&server::handle_accept, this, new_session,
                boost::asio::placeholders::error));
    }

    void handle_accept(session* new_session,
        const boost::system::error_code& error)
    {
        if (!error)
        {
            new_session->start();
        }
        else
        {
            delete new_session;
        }

        start_accept();
    }

    boost::asio::io_service& io_service_;
    tcp::acceptor acceptor_;
};

Erasing all elements till the first occurrence of an element in a set in C++ STL

I need to delete all the elements from beginning to the first occurrence of the variable c in a set, But it's not working. What am I doing wrong? need some help.

#include<iostream>
#include<set>
using namespace std;
int main(){

    set<char> s;
    char c = 'y';

    s.insert('y');
    s.insert('n');
    s.insert('a');

    set<char>::iterator it = s.find(c);
    s.erase(s.begin(),it);
    s.insert(c);

    for(auto a : s){
        cout<<a<<" ";
    }

    return 0;
}

Output: 'y'

It is supposed to give : 'n' 'a' 'y' right?

C++ std::move and global variables

Is it useful and logical to use std::move for a global variable?

Example code:

const std::string gvar = "Global variables.......";
Print(const std::string&& str)
{
  std::cout << "Rvalue: " << str << std::endl;
}

int main( void )
{
  Print( std::move(gvar) );
  std::cout << gvar << std::endl;
  return 0;
}

Is this a good practice to replace 'const std::string &' with 'std::string_view' or just 'std::string'?

I was prefer const std::string & always when I need to play with std::strings. But recently, I suddenly noticed that there's no need to use const std::string & at all. The std::string_view will do better for read-only strings, and just std::string with move will do better for otherwise(setting string fields, etc).

// Read-only string example
bool foo(std::string_view bar) {
    return bar == "baz";
}
// Non read-only string example
void MyClass::foo(std::string bar) {
    this->baz = std::move(bar);
}

In above two cases, const std::string & is not optimal!

So I decided to remove all const std::string &s and replace these with one of them. So my question is :

  1. Will there any situation that const std::string & do better?
  2. If no, will I still need const std::string &?

Thank you.

std::atomic to what extent?

In the C++ Seasoning video by Sean Parent https://youtu.be/W2tWOdzgXHA at 1:17:12 when starting to talk about “no raw synchronization primitives”, he brings an example to show that with raw synchronization primitives we will get it wrong. The example is a bad copy on write class:

template <typename T>
class bad_cow {
    struct object_t {
        explicit object_t(const T& x) : data_m(x) { ++count_m; }
        atomic<int> count_m;
        T data_m;
    };

    object_t* object_m; public:
    explicit bad_cow(const T& x) : object_m(new object_t(x)) { }
    ~bad_cow() { if (0 == --object_m->count_m) delete object_m; }
    bad_cow(const bad_cow& x) : object_m(x.object_m) { ++object_m->count_m; }

    bad_cow& operator=(const T& x) {
        if (object_m->count_m == 1) {
            // label #2
            object_m->data_m = x; 
        } else {
            object_t* tmp = new object_t(x);
            --object_m->count_m; // bug #1
            // this solves bug #1:
            // if (0 == --object_m->count_m) delete object_m;
            object_m = tmp;
        }
        return *this;
    }
};

He then asks the audience to find the bug, which is the bug #1 as he confirms.

But a more obvious bug I guess, is when some thread is about to proceed to execute a line of code that I have denoted with label #2, while all of a sudden, some other thread just destroys the object and the destructor is called. So, the first thread will encounter a deleted memory location.

Am I right? I don’t seem so!

Templated member function access in other CPP files [duplicate]

This question already has an answer here:

I have a header file where I have below declaration:

A.hpp

class A
{
public:
    template <typename T1 = void, typename T2 = void>
        T2 set(T1* saddr, T2& sddrlen) const;
}

In a A.cpp I have the below code:

A.cpp

#include "A.hpp"

template <typename T1, typename T2>
T2 A::set(T1* saddr, T2& sddrlen) const
{
}

Now in another CPP file I have code like below:

B.cpp

#include "B.hpp"
#include "A.hpp

void B::set(const A& a)
{
 int y,x;
 a.set<int,int>(&y,x)
}

But while compiling the code I am getting B.ccp unresolved reference to A::set .. though I am liming A.cpp. I tried adding below line in A.hpp

template int A::set<int, int>(int*, int&) const;

But it did not help.

How can I solve the issue?

About end() function working and use in c++ [on hold]

"Please Elaborate me about the working of end() function how end() function work what it return. I am confused in working of end() Function. " I am talking about std::end() function. I need to know how end() function works.is it store only last no. Or it use as for() loop (from 1st no. To last no. Iteration)."

How do i get a user to pick a number in c++

i am trying to make the user pick a number thats leads to a another code in c++ how do i do that?

cout << "Choose a text: "
getline(????)

1:
code number one

2.
text number 2

Compare two different times that the user inputs thendisplay it back out C++ using chrono/ctime llibrary's

After I input the time I get very confused on how to display back out my time after it's compared to the system time. Since it gets converted to a double i want see how much remaining time is left, but it's in seconds and I need to convert back to hours minutes and seconds and display out the same date but I'm very lost how to get this done. I'm not very good with working with time in the ctime and chrono library's so a bit of help will go a long way for me.

#define _CRT_SECURE_NO_WARNINGS
#include <chrono>
#include <ctime>
#include <iomanip>
#include <iostream>

int main() {

std::tm now{};

    std::chrono::system_clock::time_point cc;

    std::cout << "enter\nyear month day\n";
    std::cout << "Enter in the hour, min, sec\n";

    std::cin >> now.tm_year >> now.tm_mon >> now.tm_mday >> now.tm_hour >> now.tm_min >> now.tm_sec;

    now.tm_year -= 1900;
    now.tm_mon -= 1;
    now.tm_mday;
    now.tm_hour;
    now.tm_min;
    now.tm_sec;

    std::time_t n = std::mktime(&now);
    cc = std::chrono::system_clock::from_time_t(n);
    n = std::chrono::system_clock::to_time_t(cc);

    std::cout << std::put_time(std::localtime(&n), "Date: %F Time: %T") << "\n";
    std::time_t system_time = time(nullptr);
    std::cout << asctime(localtime(&system_time));

    double fc = difftime(system_time, mktime(&now));
    std::cout << "time diff " << fc;

}

I want write next line with Async WriteFileEx

i want to write file(text) with WriteFileEx. but i don't know... how to offset the next line.

It is pointless adding the length of string. I'm so curious about how to get offset on the next line, not behind the written.

I'll ask for your advice.

ex) abcde, fghij <- i want write next line this string (fghij)

OVERLAPPED  ov { 0 };
LARGE_INTEGER   nLarge { 0 };
WriteFileEx(m_handle, str.c_str(), str.lenght(), &ov, nullptr);

nLarge.QuadPart += ???(How can I get the location of the next line?)
ov.Offset = nLarge.LowPart; 
ov.OffsetHigh = nLarge.HighPart;

unordered_map vs vector with int keys

What is the difference in performance between using an unordered_map or a vector when the keys are integers. I have around 100-1000 elements which have continuous id that I can use to access a vector. The reason to use a hash table is that is more convenient to index by the objects themselves.

Note that I ask it as a general question, no as a code specific one.

Finding of specific values in an array C++

I want to find the position of an element in an array, the thing is that when I create the function to return the index of the desired element the if statement does not work. However, if I do it in the main function it works perfectly. I would appreciate if someone could explain me why this is happening.

#include <iostream>
#include <algorithm>
int find_index(double vector, double *value, int size_vector);


int main() {
    double vec_eye_x[2]={2323,1}; // center position x two eyes.
    double vec_eye_y[2]={33,2}; // center position y two eyes.
    int index_val=1;
    double *yc_max=std::max_element(vec_eye_y,vec_eye_y+2); // Creating a pointer
    double *yc_min=std::min_element(vec_eye_y, vec_eye_y+2);
    double *xc_max=std::max_element(vec_eye_x,vec_eye_x+2);
    double *xc_min=std::min_element(vec_eye_x, vec_eye_x+2);

    int index=0;
    for(int i=0; i<2; i++){
        if(*xc_min==vec_eye_x[i]){std::cout<<"Works in the main function"<<std::endl;}
    }
    std::cout << "index val: " <<find_index(vec_eye_x, &xc_max,2)<<std::endl;
    return 0;
}


int find_index(double vector_x, double *value, int size_vector){
    int index=0;
    for(int i=0; i<size_vector; i++){
        if(*value==vector_x[i]){index=i;}
    }
    return index;
}

What happens to the return values while using Google Benchmark?

Below is an example from the Google benchmark repository. The same can also be found on the quick-bench

1 static void BM_StringCopy(benchmark::State& state) {
2 std::string x = "hello";
3 for (auto _ : state)
4  std::string copy(x);
5 }
6 
7 BENCHMARK(BM_StringCopy);

I am trying to understand 2 things here.

  1. Which function does copy in line 4 call? and How do I know this? The call does not look like the one from the C++ standard. Rather, looks like a free function.

  2. What happens to the return values of the function being benchmarked? I have functions that return std::map. Should I ignore these return values?

Class templates alias should not be visible in generated symbols, do they?

When compiling this snipet in godbolt, most compilers generate two different get methods (different symbol in the assembly window):

template<typename  T> 
struct Field { T impl; };

template<typename  T> 
using CurrentField = Field<T>;

template<template <typename> class F> 
struct Encompassing { F<int> member; };


auto get(Encompassing<Field> const& instance)
{
    return instance.member.impl;
}
auto get(Encompassing<CurrentField> const& instance)
{
    return instance.member.impl;
}

I see CurrentField in symbols even if it is an alias. Only gcc complains about redefinition (as expected).

C++ reference on type_alias says

It does not introduce a new type

so I think it is not supposed to behave like this, am I wrong?

Actually most compiler seems behave like the alias template was substituted with class Trait like

template<typename T>
struct CurrentField
{
 alias type = Field<T> ;
};

How to constraint the parameter package type in c++11? And How to implement the template in cpp?

For the first quesion:

I want to write a function to concatenation the strings, and it can receive multiple strings;

#include <string>
#include <vector>
#include <type_traits>

template <class... Args, typename std::enable_if<std::is_same<typename std::decay<Args...>::type, std::string>::type>::type>
std::string foo(const std::string &first, const Args &... senconds) {
    std::string delimiter = "$$";
    std::string ret = first;
    std::vector<std::string> vec{senconds...};
    for (auto second = vec.rbegin(); second != vec.rend(); second++) {
        ret = delimiter + *second + delimiter + ret;
    }
    return ret;
}

but when I invoke it like:

std::string name = "x";
name = foo(name, "xxx");

the compiler will throw an error:

error: no matching function for call to ‘foo(std::__cxx11::string&, const char [4])’

and there will be some note:

note: couldn't deduce template parameter ‘<anonymous>’

I think I should modify the constraint in the template, and I've tried all the related methods in the type_traits, but none of them works.

For the second question:

I want to hide the implementation of some function, but for the template function, it's unable to put the definition in the .hpp, and put the implementation in the .cpp, the compiler will throw a undefined reference error. Is there any elegant way to solve this?

Thanks.

mercredi 27 novembre 2019

"terminate called without an active exception" after pthread_cancel

In probing the conditions of this question, a problem arose, exemplified by the code below.

#include <iostream>
#include <thread>
#include <chrono>
#include <stdexcept>
#include <cxxabi.h>

using namespace std;

// mocking external library call stuck in an infinite loop
int buggy_function_simulation()
{
    // cout << "In buggy function" << endl; // (1)
    int counter = 0;
    while (true)
    {
        if ( ++counter == 1000000 ) { counter = 0; }
    }
}

int main(int argc, char **argv) {
    cout << "Hello, world!" << endl;

    auto lambda = []() {
        pthread_setcanceltype( PTHREAD_CANCEL_ASYNCHRONOUS, nullptr );
        // cout << "ID: "<<pthread_self() <<endl; // (2)
        try
        {
            cout << "ID: "<<pthread_self() <<endl; // (3)
            buggy_function_simulation();
        }
        catch ( abi::__forced_unwind& )
        {
            cout << "thread cancelled!" << endl; // (4)
            throw;
        }
    };

    std::thread th(lambda);

    pthread_t id = th.native_handle();
    cout << id << endl;

    this_thread::sleep_for(chrono::seconds(1));
    cout << "cancelling ID: "<< id << endl;

    pthread_cancel(id);
    th.join();

    cout << "cancelled: "<< id << endl;

    return 0;
}

Compiling and running results in an abort:

$ g++ -g -Og -std=c++11 -pthread -o test test.cpp -lpthread
$ ./test
Hello, world!
139841296869120
ID: 139841296869120
cancelling ID: 139841296869120
terminate called without an active exception
Aborted (core dumped)
$

Note that the diagnostic output (4) does not appear.

If I comment out (3) and uncomment (2), the result is:

$ ./test
Hello, world!
139933357348608
ID: 139933357348608
cancelling ID: 139933357348608
cancelled: 139933357348608
$

Again, the output at (4) does not appear (why?), but the abort has been obviated.

If, alternately, I retain (3), leave (2) commented out, and uncomment (1), the result is finally as expected:

$ ./test
Hello, world!
139998901511936
ID: 139998901511936
In buggy function
cancelling ID: 139998901511936
thread cancelled!
cancelled: 139998901511936
$

So, the questions are:

  • what is the reason for the "terminate called without an active exception" abort in the first case?
  • why is the catch block not activated in the second case?
  • why did uncommenting (1) in the third case make such a difference?

For completeness, here is the stack trace from gdb for the first case:

Program terminated with signal SIGABRT, Aborted.
#0  __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:51
51      ../sysdeps/unix/sysv/linux/raise.c: No such file or directory.
[Current thread is 1 (Thread 0x7f5d9b49a700 (LWP 12130))]
(gdb) where
#0  __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:51
#1  0x00007f5d9b879801 in __GI_abort () at abort.c:79
#2  0x00007f5d9bece957 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#3  0x00007f5d9bed4ab6 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#4  0x00007f5d9bed4af1 in std::terminate() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#5  0x00007f5d9bed44ba in __gxx_personality_v0 () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#6  0x00007f5d9bc3a708 in ?? () from /lib/x86_64-linux-gnu/libgcc_s.so.1
#7  0x00007f5d9bc3acfc in _Unwind_ForcedUnwind () from /lib/x86_64-linux-gnu/libgcc_s.so.1
#8  0x00007f5d9c1dbf10 in __GI___pthread_unwind (buf=<optimized out>) at unwind.c:121
#9  0x00007f5d9c1d0d42 in __do_cancel () at ./pthreadP.h:297
#10 sigcancel_handler (sig=<optimized out>, si=0x7f5d9b499bb0, ctx=<optimized out>) at nptl-init.c:215
#11 <signal handler called>
#12 buggy_function_simulation () at test.cpp:15
#13 0x0000558865838227 in <lambda()>::operator() (__closure=<optimized out>) at test.cpp:28
#14 std::__invoke_impl<void, main(int, char**)::<lambda()> > (__f=...) at /usr/include/c++/7/bits/invoke.h:60
#15 std::__invoke<main(int, char**)::<lambda()> > (__fn=...) at /usr/include/c++/7/bits/invoke.h:95
#16 std::thread::_Invoker<std::tuple<main(int, char**)::<lambda()> > >::_M_invoke<0> (this=<optimized out>)
    at /usr/include/c++/7/thread:234
#17 std::thread::_Invoker<std::tuple<main(int, char**)::<lambda()> > >::operator() (this=<optimized out>)
    at /usr/include/c++/7/thread:243
#18 std::thread::_State_impl<std::thread::_Invoker<std::tuple<main(int, char**)::<lambda()> > > >::_M_run(void) (
    this=<optimized out>) at /usr/include/c++/7/thread:186
#19 0x00007f5d9beff66f in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#20 0x00007f5d9c1d26db in start_thread (arg=0x7f5d9b49a700) at pthread_create.c:463
#21 0x00007f5d9b95a88f in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:95

string to long int in C++

I am trying to input lines from a file. Each line is a word. I am taking the word and splitting it up, then based on the split, then putting it to a long int. For instance, i read in the word "Raindrops". I would then use substr to create a seperate string "ai". Im needing to then make "ai" into an interger based on ascii code. I have tried to cast, use stoi, stol, strtol, strtoi, and they have all failed at runtime do to invalid arguments. I feel as though this should be simple.

My next thought would be to go from a string to a string array in c++ and then each field in the string array it would individually assign ints to it. Is this the best way?

Thanks!

long int foo(int inWord){
string slice1 = inWord;
slice1 = slice1.substr(2,2);
//make the new substring into a char array?
//trying to convert to ascii
return ascii code
}

Any suggestions on how to read in a word using getline() using a char array then getting specific characters out based on their position would be helpful. thank you!

Cant Access Variables Or Types From Project Headers Xcode 11

I am not completely sure what is going on. I logged onto my computer today and tried to compile my game code, but for some reason everything had stopped working despite having worked the day before. I didn't touch it and all the errors seem to be related to indexing my header files. I have provided all the images I can to help provide some context for my issue.

main.hpp player.cpp block.hpp

C++ compile errors when using template in unordered_map

I am trying to use unordered_map in my project. The code related to my problem is

struct Node

struct Node_IB

struct Grid
{
    std::unordered_map< std::bitset<64>, Node> grid;
};

struct Grid_IB
{
    std::unordered_map< std::bitset<64>, Node_IB> grid;
};


template <class T_grid, class T_node>
void func1(T_grid &grid_ptr, T_node node_temp);

int main()
{
       ilevel = 1 ;
       if (ilevel == C_max_level)
    {
        Node_IB node_temp;
        func1(grid_ptr, node_temp);
    }
    else
    {
        Node node_temp;
        func1(grid_ptr, node_temp);
    }
}

template <class T_grid, class T_node>
voidfunc1(T_grid &grid_ptr, T_node node_temp)
{
      std::bitset<64> key = 0;
      grid_ptr.grid.insert(make_pair( key, node_temp));
} 

The error is "error C2664: 'std::_List_iterator>> std::_Hash,_Alloc,false>>::insert(std::_List_const_iterator>>,const std::pair &)': cannot convert argument 1 from 'std::pair,Node>' to 'std::pair &&'"

I am new to code development. Sorry for any confusing information.

Could anyone help me with this?

Thank you

How do we store a reference to an object in the pointer?

I am thinking of this solution, but not sure if it is correct.

Type* myObjP;

void setSmth(Type& toBePassed) {
  myObjP = *toBePassed;
};

std::list push_back() and pop_front() giving a const error

I am working on a coding project and have hit a bit of a snag. When I try to make it, I get these errors:

src/mean.cc:26:12: error: passing ‘const csce240::Mean’ as ‘this’ argument discards qualifiers [-fpermissive]
   pop_back();
            ^
In file included from /usr/include/c++/7/list:63:0,
                 from inc/mean.h:9,
                 from src/mean.cc:2:
/usr/include/c++/7/bits/stl_list.h:1152:7: note:   in call to ‘void std::__cxx11::list<_Tp, _Alloc>::pop_back() [with _Tp = double; _Alloc = std::allocator<double>]’
       pop_back() _GLIBCXX_NOEXCEPT
       ^~~~~~~~
src/mean.cc:33:29: error: passing ‘const csce240::Mean’ as ‘this’ argument discards qualifiers [-fpermissive]
   push_front(tempList.back());
                             ^
In file included from /usr/include/c++/7/list:63:0,
                 from inc/mean.h:9,
                 from src/mean.cc:2:
/usr/include/c++/7/bits/stl_list.h:1067:7: note:   in call to ‘void std::__cxx11::list<_Tp, _Alloc>::push_front(const value_type&) [with _Tp = double; _Alloc = std::allocator<double>; std::__cxx11::list<_Tp, _Alloc>::value_type = double]’
       push_front(const value_type& __x)
       ^~~~~~~~~~

The closest solution I could find was to add const to the end of the function definition, however that was already in the definition to start with. Here is are the .h and .cc files:

https://pastebin.com/rw8hTHvH

Why std::string does not have const char* cast (STL architecture question)?

I like to know pro's and con's for having and not-having such cast. At several places including here on Stackoverflow I can see that the const char* cast is considered bad idea but I am not sure why?

Lack of the (const char*) and forcing to always use c_str() cast creates some problems when writing generic routines and templates.

void CheckStr(const char* s)
{
}

int main()
{
    std::string s = "Hello World!";

    // all below will not compile with 
    // Error: No suitable conversion function from "std::string" to "const char *" exists!
    //CheckStr(s);             
    //CheckStr((const char*)s);  
    // strlen(s);

    // the only way that works
    CheckStr(s.c_str());
    size_t n = strlen(s.c_str());
    return 0;
}

For example, if I have a large number of text processing functions that accept const char* as input and I want to be able to use std::string each time I have to use c_str(). But in this way a template function can't be used for both std::string and const char* without additional efforts.

As a problem I can see some operator overloading issues but these are possible to solve.

template argument was not declared in this scope

Why am I having issues compiling this in g++ 4.8.5, -std=c++11 -O2 -lm?

#include <algorithm>
#include <array>
#include <iostream>
#include <iterator>
#include <numeric>
#include <sstream>
#include <utility>

template<uint_fast32_t N>
class Jollo
{
private:
    template<uint_fast32_t c>
    struct Player
    {
        int_fast32_t cards[c]; // This line is OK!
        uint_fast32_t nsize = c; // error 'c' was not declared in this scope
        friend std::istream& operator>>(std::istream& is, Player& p)
        {
            for(auto& i : p.cards){
                is >> i;
            }
            return is;
        }

    };
private:
    enum JP_ID{ JPID_PRINCE = N+1, JPID_PRINCESS, JPID_NONE };
    Player<2> m_Prince;
    Player<3> m_Princess;
    int_fast32_t deck[N];
    constexpr static int_fast32_t RoundsToWin {2};
    int_fast32_t NextAvailableCard(const JP_ID& idPlayer, int_fast32_t lastPlayedCard = 0);
public:
    Jollo<N>(){
        static_assert( N>4, "Invalid deck size - JolloManager");
    }

    bool Read();
    int_fast32_t GetWinningCard();
};

template<uint_fast32_t N>
bool Jollo<N>::Read()
{
    static std::string line;
    std::getline(std::cin, line);
    std::istringstream issline(line);
    issline >> m_Princess;
    issline >> m_Prince;
    return (m_Princess.cards[0] != 0);
}

template<uint_fast32_t N>
int_fast32_t Jollo<N>::NextAvailableCard(const JP_ID& idPlayer, int_fast32_t lastPlayedCard)
{
    if(idPlayer == JPID_PRINCE)
    {
        for(int_fast32_t i{0}; i<m_Prince.nsize; ++i) {

            if(deck[m_Prince.cards[i] - 1] != JPID_PRINCE){
               deck[m_Prince.cards[i] - 1] =  JPID_PRINCE;
               return m_Prince.cards[i];
            }
        }
    } else
    if(idPlayer == JPID_PRINCESS)
    {
        for(int_fast32_t i{0}; i<m_Princess.nsize; ++i) {
            if(deck[m_Princess.cards[i] - 1] != JPID_PRINCESS && deck[m_Princess.cards[i] - 1] > lastPlayedCard) {
               deck[m_Princess.cards[i] - 1] =  JPID_PRINCESS;
               return m_Princess.cards[i];
            }
        }
        //no card was higher, return lowest available card
        for(int_fast32_t i{0}; i<m_Princess.nsize; ++i) {
            if(deck[m_Princess.cards[i] - 1] != JPID_PRINCESS) {
               deck[m_Princess.cards[i] - 1] =  JPID_PRINCESS;
               return m_Princess.cards[i];
            }
        }
    }

    for(uint_fast32_t i{0}; i<N; i++)
    {
        if(deck[i] != JPID_PRINCE && deck[i] != JPID_PRINCESS && deck[i] > lastPlayedCard ) {
            return deck[i];
        }
    }
    return -1;
}

template<uint_fast32_t N>
int_fast32_t Jollo<N>::GetWinningCard()
{
    std::iota(deck, deck + N, 1);
    std::sort(m_Prince.cards, m_Prince.cards + m_Prince.nsize, std::greater<int_fast32_t>());
    std::sort(m_Princess.cards, m_Princess.cards + m_Princess.nsize);

    int_fast32_t princeWins {0};
    int_fast32_t princessWins {0};

    for(int_fast32_t round {0}; round < RoundsToWin; ++round) //play two first rounds
    {
        int_fast32_t princeCard = NextAvailableCard(JPID_PRINCE);
        int_fast32_t princessCard = NextAvailableCard(JPID_PRINCESS, princeCard);

        if(princessCard > princeCard){
            ++princessWins;
        } else {
            ++princeWins;
        }
    }
    int_fast32_t lastPrincessCard = NextAvailableCard(JPID_PRINCESS); //important to flip the last card on the deck before continuing
    if(princessWins == RoundsToWin){
        return -1;
    }
    if(princeWins == RoundsToWin){
        return NextAvailableCard(JPID_NONE);
    }
    return NextAvailableCard(JPID_NONE, lastPrincessCard);
}

int main()
{
    Jollo<52u> jollo;
    while(true)
    {
        if(!jollo.Read()) {
            break;
        }
        std::cout << jollo.GetWinningCard() << '\n';
    }
    return 0;
}

I can compile it on almost any other g++ version with c++11 flags.

Best practice on where to define doxygen c++ documentations mainpage [duplicate]

This question already has an answer here:

When having a C++ project that only defines some classes and namespaces. Where should I put the mainpage documentation according to best practices for writing doxygen documentation? Placing it inside one of the header files in which the classes reside feels strange. Should I create a dedicated file that only contains this documentation?

generic-template function always returning integer values

I am writing the below linear interpolation function, which is meant to be generic, but current result is not.

The function finds desired quantity of equally distant points linear in between two given boundary points. Both desired quantity and boundaries are given as parameters. As return, a vector of linear interpolated values is returned.

The issue I have concerns to return type, which always appear to be integer, even when it should have some mantissa, for example:

lower_limit = 5;
high_limit = 1;
quantity = 3;
return std::vector<int>({4, 3, 2}); // CORRECT

but:

lower_limit = 5;
high_limit = 1;
quantity = 4;
return std::vector<int>({4, 3, 2, 1}); // Not CORRECT
// it should be:
return std::vector<float>({4.2, 3.4, 2.6, 1.8});

What should I do to make it generic and have correct return values?

code:

template <class T>
std::vector<T> interpolatePoints(T lower_limit, T high_limit, const unsigned int quantity) {
    auto distance = abs(std::max(high_limit, lower_limit) - std::min(high_limit, lower_limit));

    auto step = ((1/(double)(quantity+1)) * distance);

    std::vector<T> interpolated_points;
    for(unsigned int i = 1; i <= quantity; i++) {
        if(lower_limit < high_limit) {
            interpolated_points.push_back((std::min(lower_limit, high_limit) + (step*i)));
        } else {
            interpolated_points.push_back((std::max(high_limit, lower_limit) - (step*i)));
        }
    }
    return interpolated_points;
}

Getting Error : redifinition of bool queue

I am trying to do load balancing in c++. But getting error. I have copied the code from youtube and it works fine there. code is

//arrayqueue.h

#define QUEUE_H
#pragma once
template <class T>
class queue
{
    public:
        queue()
        {
            size = 5;
            data = new T[size];
            head = 0;
            tail = 0;
        }
        void enqueue (T data);
        T dequeue ();
        T peek ();
        bool isEmpty();

    private:
        T* data;
        int head, tail, size;
        bool needToResize();
        void resize();
};

#include "arrayqueue.cpp"
//arrayqueue.cpp

#ifndef QUEUE_H
#include "arrayqueue.h"
#endif

#include <stdexcept>
using namespace std;

template <class T>
bool queue<T>::needToResize()
{
  return (tail == size);   
}

template <class T>
void queue<T>::resize()
{
    T* temp = new T[2*size];
    for (int i = 0; i < tail - head; i ++)
        temp[i] = data[i+head];
    data = temp;
    tail = tail - head;
    head = 0;
    size *= 2;
}

template <class T>
void queue<T>::enqueue(T obj)
{
    if (needToResize())
        resize();
    data[tail++] = obj;
}

template <class T>
T queue<T>::dequeue()
{
    if (head == tail)
        throw std::out_of_range("Attempt to dequeue from empty queue");
    return data[head++];
}

template <class T>
T queue<T>::peek()
{
    if (head == tail)
        throw std::out_of_range("Attempt to peek from empty queue");
    return data[head];
}

template <class T>
bool queue<T>::isEmpty()
{
    return head == tail;
}

//loadbalancer.h

#define LOADBALANCER_H

#ifndef REQUEST_CPP
#include "request.cpp"
#endif

#include "arrayqueue.h"

class loadbalancer
{
    public:
        loadbalancer()
        {
            systemTime = 0;
        }
        int getTime();
        void incTime();
        void addRequest (request r);
        request getRequest();
        bool isRequestQueueEmpty();
    private:
        int systemTime;
        queue <request> requestQueue;
};
#include "loadbalancer.cpp"
//loadbalancer.cpp

#ifndef LOADBALANCER_H
#include "loadbalancer.h"
#endif

int loadbalancer::getTime()
{
    return systemTime;
}

void loadbalancer::incTime()
{
    systemTime ++;
}

void loadbalancer::addRequest(request r)
{
    requestQueue.enqueue(r);
    incTime();
}

request loadbalancer::getRequest()
{
    incTime();
    if (!requestQueue.isEmpty())
    {
        request r = requestQueue.dequeue();
        return r;
    }
}

bool loadbalancer::isRequestQueueEmpty()
{
    return requestQueue.isEmpty();
}
//request.cpp

#include <string>

#define REQUEST_CPP

using namespace std;

struct request
{
    string source;
    string destination;
    int processTime;
};
//webserver.cpp

#ifndef REQUEST_CPP
#include "request.cpp"
#endif

class webserver
{
    public:
        webserver()
        {
            requestStartTime = 0;
            servername = ' ';
        }
        webserver (char c)
        {
            requestStartTime = 0;
            servername = c;
        }
        void addRequest(request req, int currTime)
        {
            r = req;
            requestStartTime = currTime;
        }
        request getRequest()
        {
            return r;
        }
        char getName()
        {
            return servername;
        }
        bool isRequestDone(int currTime)
        {
            return (currTime >= (requestStartTime + r.processTime));
        }
    private:
        request r;
        int requestStartTime;
        char servername;
};
//loadbalancermain.cpp

#include "request.cpp"
#include "webserver.cpp"
#include "loadbalancer.h"

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <sstream>

using namespace std;

const int NUMWEBSERVERS = 8;

//create a request
request createRandomRequest()
{
    stringstream ips, ipd;
    request r;
    ips << (rand() % 256) << "." << (rand() % 256) << "." << (rand() % 256) << "." << (rand() % 256);
    ipd << (rand() % 256) << "." << (rand() % 256) << "." << (rand() % 256) << "." << (rand() % 256);
    r.source = ips.str();
    r.destination = ipd.str();
    r.processTime = rand()%500;
    return r;
}

int main()
{
    //random number generator
    srand(time(0));
    //create a loadbalancer
    loadbalancer lb;
    //start off with a "full" queue
    for (int i = 0; i < 10; i ++)
    {
        request r = (createRandomRequest());
        lb.addRequest(r);
    }
    //an array of webservers
    webserver webarray[NUMWEBSERVERS];
    for (int i = 0; i < NUMWEBSERVERS; i ++)
    {
        webserver w((char)(i + 65));
        webarray[i] = w;
        webarray[i].addRequest(lb.getRequest(), lb.getTime());
    }
    //loop
    while (lb.getTime() < 10000)
    {
        int currTime = lb.getTime();
        //check each webserver if it's done
        if (webarray[currTime % NUMWEBSERVERS].isRequestDone(currTime))
        {
            request r = webarray[currTime % NUMWEBSERVERS].getRequest();
            cout << "At " << currTime << " " << webarray[currTime % NUMWEBSERVERS].getName() << " processed request from "<< r.source << " to " << r.destination << endl;
            //then give it a new request
            webarray[currTime % NUMWEBSERVERS].addRequest(lb.getRequest(),currTime);
        }

        //every random amt of time, we get a new request
        if (rand() % 20 == 0)
        {
            request r = (createRandomRequest());
            lb.addRequest(r);
        }
        lb.incTime();
    }
}

The error log is as follows :


- Filename: C:\Users\Manish Anhal\Desktop\Makefile.win

Processing makefile...
--------
- Makefile Processor: C:\Program Files (x86)\Dev-Cpp\MinGW64\bin\mingw32-make.exe
- Command: mingw32-make.exe -f "C:\Users\Manish Anhal\Desktop\Makefile.win" all

g++.exe -c Pdc/arrayqueue.cpp -o Pdc/arrayqueue.o -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include/c++" 

Pdc/arrayqueue.cpp:11:6: error: redefinition of 'bool queue<T>::needToResize()'
 bool queue<T>::needToResize()
      ^

In file included from C:\Users\Manish Anhal\Desktop\Pdc\arrayqueue.h:28:0:
C:\Users\Manish Anhal\Desktop\Pdc\arrayqueue.cpp:11:6: note: 'bool queue<T>::needToResize()' previously declared here
 bool queue<T>::needToResize()
      ^
Pdc/arrayqueue.cpp:17:6: error: redefinition of 'void queue<T>::resize()'
 void queue<T>::resize()
      ^
In file included from C:\Users\Manish Anhal\Desktop\Pdc\arrayqueue.h:28:0:
C:\Users\Manish Anhal\Desktop\Pdc\arrayqueue.cpp:17:6: note: 'void queue<T>::resize()' previously declared here
 void queue<T>::resize()
      ^
Pdc/arrayqueue.cpp:29:6: error: redefinition of 'void queue<T>::enqueue(T)'
 void queue<T>::enqueue(T obj)
      ^
In file included from C:\Users\Manish Anhal\Desktop\Pdc\arrayqueue.h:28:0:
C:\Users\Manish Anhal\Desktop\Pdc\arrayqueue.cpp:29:6: note: 'void queue<T>::enqueue(T)' previously declared here
 void queue<T>::enqueue(T obj)
      ^
Pdc/arrayqueue.cpp:37:3: error: redefinition of 'T queue<T>::dequeue()'
 T queue<T>::dequeue()
   ^
In file included from C:\Users\Manish Anhal\Desktop\Pdc\arrayqueue.h:28:0:
C:\Users\Manish Anhal\Desktop\Pdc\arrayqueue.cpp:37:3: note: 'T queue<T>::dequeue()' previously declared here
 T queue<T>::dequeue()
   ^
Pdc/arrayqueue.cpp:45:3: error: redefinition of 'T queue<T>::peek()'
 T queue<T>::peek()
   ^
In file included from C:\Users\Manish Anhal\Desktop\Pdc\arrayqueue.h:28:0:
C:\Users\Manish Anhal\Desktop\Pdc\arrayqueue.cpp:45:3: note: 'T queue<T>::peek()' previously declared here
 T queue<T>::peek()
   ^
Pdc/arrayqueue.cpp:53:6: error: redefinition of 'bool queue<T>::isEmpty()'
 bool queue<T>::isEmpty()
      ^
In file included from C:\Users\Manish Anhal\Desktop\Pdc\arrayqueue.h:28:0:
C:\Users\Manish Anhal\Desktop\Pdc\arrayqueue.cpp:53:6: note: 'bool queue<T>::isEmpty()' previously declared here
 bool queue<T>::isEmpty()
      ^

C:\Users\Manish Anhal\Desktop\Makefile.win:40: recipe for target 'Pdc/arrayqueue.o' failed
mingw32-make.exe: *** [Pdc/arrayqueue.o] Error 1

I did the exact same copy of code as given in this repository but am unable to run: https://github.com/mistapotta/C-Code/tree/master/C%2B%2B%20Stuff/Unit%206%20-%20arrayqueue/Day%203%264%20-%20Complicated%20Problem

Please help me find the solution.

Which is a better way of handling virtual destructor?

I have a few classes (around 10 in my project) that needs a virtual destructor while also requiring support for std:move and std::copy calls. To keep both copy and move semantics in these classes, I added another class to serve as a base class for these classes:

/*
This class should be inherited by any class that:
- needs a virtual destructor,
- doesn't require explicit definitions of destructor, copy/move constructor/assignment
- needs to support copy and move semantics.

Such classes can inherit from the class defined below to make their destructor virtual,
and keeping copy and move semantics intact.

INFO: This class won't be able to serve it's purpose if any of the 5 mentioned member
functions are explicitly defined in the derived class.
*/

class VirtualDtor
{
protected:
   virtual ~VirtualDtor() = default;
};

This class drew some concerns such as - A derived class may (by mistake or design) explicitly define one or few of the 5 member functions, even after inheriting from VirtualDtor. That would lead to the removal of copy/move semantics defeating the purpose of VirtualDtor. To avoid such scenarios, maintaining rule of 5 by declaring the 5 functions as default in each class individually could bring some clarity about what to expect.

But inheriting from this class will make the code more readable and if we understand it's requirements and usage before inheriting, it will not cause any unexpected behavior.

So I would like to know which is a better way of handling virtual destructors and the rule of 5.

Note: I could have added copy and move member functions too in the VirtualDtor class like it's suggested here. I didn't keep them to avoid the mistaken impression that any class that derives from VirtualDtor will inherit copy and move-semantics which it won't. It will only make the destructor in derived classes virtual. So I skipped the rule of 5 in VirtualDtor.

mardi 26 novembre 2019

How do I put extra-statements in list-initialization?

Given I have a class with a constructor which looks as follows:

MClass(const char *t_source);

In fact there are a lot of places where t_source is obtained from a file, so I'm considering making another constructor which takes FILE pointer instead and put most of the boilerplate inside of it. At the same time existing constructor also has a lot of use by itself and contains logic which i don't want to repeat more than once in the code. I was thinking about delegating constructor but can't see any way how i can leverage this feature as i need more than one statement to extract data from a FILE instance (like allocating a char array and reading from the FILE and deleting afterward). So essentially I want to do something like this:

MClass(FILE *t_file) : MClass(MNameSpace::readFile(t_file)) {}

But with some preliminary and post-call actions. Any idea?

how do i fix my for loop issue im having?

last quarter in school i passed intro to c++. to get better at writing c++, i decided to take on an intermediate project especially since i'm now going to be in intermediate c++ class soon. This project i decided to take on as a challenge is a mock-up banking system which allows you to open checking and savings account as well as being able to see your balance. a text file will also be used but much later on. right now i have 3 functions in my getdata function im using pass-by-reference to some string and int variables that were declared in the int main function. the for loop inside the getdata function is supposed to read print the question array and use j as the index. it does that all fine, but for some reason i have to put a mock name and hit enter it goes to the next blank line. i figured out that if you enter the same user input 2 more times it takes you to the next question. also am not able to cout data that is collected as user input the arguments in the for loop. How can i fix the that printing problem and how to cout the variables data.

#include <iostream> //input out stream 
#include <fstream>  //used for writing getdata functions arguments into a .txt file which stores mock clients data 
#include <iomanip>  //used for setting width of titles
#include <algorithm> //used later for sort algorithm 
#include <cmath>    //used for getting random number
#include <ctime>    //used for generating a new number  
#inlcude <cstdlib>  
#include <bits/stdc++.h>

using namespace std;

void menu() {
    string titleArr[2] = {"Cookies Banking Management System","Federal Banking Member FDA." };
    cout<<setw(50)<<titleArr[0]<<'\n'<<setw(50)<<titleArr[1]<<'\n'<<endl;
    string menuArr[3] = { "1. Open Checking Account","2. Open Savings Account", "3. Check Balance" };
    for(int i = 0; i<3; ++i) {
        cout<<menuArr[i]<<endl;
    }
}
/*The get data function is supposed to take in 4 variables from an int main function and pass it as reference 
we initialize those variables by asking questions which are stored in an array. then we also use a for loop 
to access the array and print the questions to the compiler the other part is that we also ask for user input. the for 
loop is supposed to print this to the compiler after pressing 1`in the main menu: 

Enter Your First Name: John
Enter Your last Name: Doe
Enter Your Phone Number: 000-000-0000

John Doe 000-000-0000
*/
string getdata(int&menuOption, string&firstName, string&lastName, string&phoneNumber) {
    //using the menuOption as pass-by-reference and giving it value with user input
    cin>>menuOption;
    //the if condition which takes in the var menuOption and see what integer you choose to access the menu.
    if(menuOption == 1) {
        //title description string array with 2 elements
        string desArr[2] = {"Welcome to Cookies Banking Management System"," To open an account please enter info"};
        //prints out title array with each title on its own line.
        cout<<desArr[0]<<'\n'<<desArr[1]<<'\n'<<endl;
        //string array for questions to ask before opening mock bank account
        string Questions[3] = {"Enter your first name: ","Enter last name: ","\n Enter your phone no.: "};
        //the for loop that prints out questions array and reads in user input.
        for(int j = 0; j < 3; ++j) {
            cout<<Questions[j];
            cin>>firstName>>lastName>>phoneNumber

        }

    }
}


//----------------------------------------------------------------------------------------------------
int main(){

   int menuOption; // this variable stores integral values of 1-3.
   string firstName, lastName, phoneNumber; // these variables store mock clients data with pass-by-reference
   menu();//calls to the menu function 
   getdata(menuOption,firstName, lastName, phoneNumber);//calls to the getdata function and it passes-by-reference the variables above
}

Implement hash for custom class C++

I have a circle defined like so:


class Circle {
public:
    int x;
    int y;
    int r;

    Circle() : x(0), y(0), r(0) {}

    Circle(int x, int y, int r) {
        this->x = x;
        this->y = y;
        this->r = r;
    }

    double area() {
        return PI * pow(r, 2);
    }
};

I want to be able to add it to a set, based on the hash of its center (x and y)

What's the correct and idiomatic way of doing this in C++ 11?

Does "code bloat" occur in C++ due to inline functions?

I have an interview question about C++, Does "code bloat" occur in C++ due to inline functions?

I know that this is true for templates, but what about inline functions? if yes, why.

Thanks.

I am not able to get the data from node server to c++ client using socket io

Node server

socket.broadcast.emit('JogJointButton', data)
data = {
            name: Suneeth,
            age: 27
       }

now im accepting this data from server in c++ client. right now my code looks like this.

        sio::client io;
        io.set_open_listener([&]() {
            std::string nickName = "asdad";
            io.socket()->emit("key", nickName);
            io.socket()->on("JogJointButton", [&](sio::event& ev)
                    {
                       //Here how do i get the **data** from server
                    });
        });
        io.connect("http://localhost:8081/");

How do i accept that data inside c++. i tried ev.get_messages() but im getting some reference.

Recursive function for Fibonacci number

I have to write a simple program as follows: "Given a non-negative integer n, find the nth Fibonacci number using recursion". I think what this means is that, for any value entered by the user, I have to get the Fibonacci number. For example, if the user entered 4, I would have to get the 4th value in the list of Fibonacci numbers (which is 2). Below is what I have written, but there is something wrong with my recursion as it crashes when I run it. Appreciate any help...

int userValue;
int fibo;
int fib(int n);
int fibValue;


int main() {
    cout << "Please provide your value" << endl;
    cin >> userValue;

    while (userValue < 0) {
        cout << "Fibonacci numbers only start at 0, please try again: " << endl;
        cin >> userValue;
    }

    if (userValue == 1 || userValue == 0) {
        cout << "Fibonacci result is: " << userValue << endl;
        return 0;
    }
    else {
        fib(userValue);
        cout << "Fibonacci result is: " << fibValue << endl;
        //return 0;
    }
}

int fib(int n)
{
    fibValue = fib(n - 1) + fib(n - 2);
    return fibValue;
}

How to find the max element using a list with lambda funcion in C++?

How can I get the max value using a list in C++?

I haven't found solutions for this on Google :(

That Point will be the greatest which coordinates sum is the highest.

Here's the main.cpp where i have to call the lambda function:

PointList plist{Point(1,2,3),
                Point(5.5,4.2,-6.6),
                Point(-2.2,9.7,7),
                Point(7,6.4,9.5),
                Point(8.3,-3,2.4),
                Point(-7.5,-7,1.3),
                Point(5.4,8,3)};
cout << "listsize: " << plist.size() << endl; // listsize: 7

PointList::const_iterator iter1=plist.findMax([](){});

cout << "--Max--  x: " << iter1->getX() << " y: " << iter1->getY() << " z: " << iter1->getZ() << endl; // --Max--  x: 7 y: 6.4 z: 9.5

And here is the findMax function:

PointList::const_iterator PointList::findMax(function<double (const Point &)> func) const
{
    if (size()==0) return cend();
    const_iterator maxit=cbegin();
    double maxval=func(*maxit);
    for (const_iterator temp_it=cbegin(); temp_it!=cend(); ++temp_it)
    {
        double temp_val=func(*temp_it);
        if (temp_val > maxval)
        {
            maxval=temp_val;
            maxit=temp_it;
        }
    }
    return maxit;
}

Here's the full code: https://www.codepile.net/pile/b9e16D9P

Combine istream_iterator with regex_token_iterator

Is it possible to combine an istream_iterator with an regex_token_iterator similar like this:

std::copy(std::sregex_token_iterator(std::istreambuf_iterator<char>{ifs}, std::istreambuf_iterator<char>{}, r, 1), std::sregex_token_iterator{}, std::ostream_iterator<std::string>(std::cout));

To give this a little bit of context. Im new to programming and im trying to solve a problem where i want to delete everything in an ifstream, except digits. Im doing this for practice and learning.

The input file is looking like this:

aoisdnf 2 aopsjmdf 4 anpoidsnian 5 ainsdf 12 paalknshndf 43 aoksjhndfal 4 aslkdfoo 9 hjalkgshgdfk 4

The solution should look like this:

2 4 5 12 43 4 9 4

My first approach was this:

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <ctype.h>

int main()
{
   std::ifstream ifs ("C:/Users/../whitespace_seperated_integers.txt", std::ifstream::in);
   std::string tmp;
   std::vector<int> vector;

   for (auto it = std::istreambuf_iterator<char>{ifs}; it != std::istreambuf_iterator<char>{}; ++it) {
      if (*it >= '0' && *it <= '9') tmp.append(1, *it);
      else if (!tmp.empty()){
         vector.push_back(std::stoi(tmp));
         tmp.clear();
      }
   }
   if (!tmp.empty()) vector.push_back(std::stoi(tmp));

   for(const auto i : vector){
      std::cout << i << " ";
   }

Which worked fine, but then i had the idea to solve this problem with regex, which lead to this solution:

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <ctype.h>
#include <regex>

int main()
{
   std::ifstream ifs ("C:/Users/../whitespace_seperated_integers.txt", std::ifstream::in);
   std::string puf;
   std::vector<std::string> vector;
   std::string line;
   char wts = ' ';
   while(getline(ifs ,line, wts)){
      puf += line;
   }
   std::regex r(R"([^\d]*(\d+))");
   std::copy(std::sregex_token_iterator(puf.begin(), puf.end(), r, 1), std::sregex_token_iterator(), std::back_inserter(vector));

   std::vector<int> vec;
   std::smatch sm;
   while(std::regex_search(puf, sm, r))
   {
      vec.push_back(std::stoi(sm[1]));
      /* std::cout << sm[1] << '\n';*/
      puf = sm.suffix();
   }
   for(const auto i : vec){
      std::cout << i << " ";
   }
}

But im not really happy with this code, so i was trying to figure out how to improve it. I tried to combine the istream_iterator with the regex_token_iterator, but im not able to figure out how it works.

the problem of "using Shared = std::shared_ptr<>" in base class and child class

I just solve a bug caused by "using Shared" in base class and child class. Like this:

class B: public A{
public:
    /**
     * Attention! This "using Shared" should be located before "using ResCallback " because
     * in class A, there is also a "using Shared".
     */
    using Shared = std::shared_ptr<B>;

    using ResCallback = std::function<void(const C& c, const char* data, size_t size, Shared b)>;

In the other file, there is class A:

class A{
public:
    using Shared = std::shared_ptr<A>;

In the past, I put "using ResCallback" before "using Shared" then it caused problem. This makes me doubt the "using Shared". Is there a better design style to avoid this stupid bug source?

terminate called after throwing an instance of 'std::__cxx11::basic_string

I tried to write a sample project to use sqlite. Everytime I enter the ID i get the following error message: terminate called after throwing an instance of 'std::__cxx11::basic_string, std::allocator >'

Can anyone please help me?

Header Database.h

...
private:
void showMenu();
void addRecord();
void showRecord();
void openDB();

int nSelection;

sqlite3* db;
int rc;
std::string sql;

const unsigned char* uc_result_firstName;
const unsigned char* uc_result_lastName;

int nRowID;
std::string strFirstName;
std::string strLastName;
int nAge;

}; ...

cpp File Database.cpp

...
void Database::showRecord(){

std::cout << "Select ID -> ";
int nID;
std::string strBuffer = "";
std::cin >> strBuffer;
nID = std::stoi(strBuffer.c_str());

sqlite3_stmt* stmt;
rc = sqlite3_prepare_v2(db, "SELECT FirstName, LastName, Age"
                                " FROM customerTable"
                                " WHERE id = ?", -1, &stmt, NULL);

if (rc != SQLITE_OK)
    throw std::string(sqlite3_errmsg(db));

rc = sqlite3_bind_int(stmt, 1, nID);            // Using parameters ("?") is not
if (rc != SQLITE_OK) {                          // really necessary, but recommended
    std::string errmsg(sqlite3_errmsg(db));     // (especially for strings) to avoid
    sqlite3_finalize(stmt);                     // formatting problems and SQL
    throw errmsg;                               // injection attacks.
}

rc = sqlite3_step(stmt);
if (rc != SQLITE_ROW && rc != SQLITE_DONE) {
    std::string errmsg(sqlite3_errmsg(db));
    sqlite3_finalize(stmt);
    throw errmsg;
}
if (rc == SQLITE_DONE) {
    sqlite3_finalize(stmt);
    throw std::string("customer not found");
}

uc_result_firstName = sqlite3_column_text(stmt, 0);
uc_result_lastName = sqlite3_column_text(stmt, 1);

this->nRowID     = nID;
this->strFirstName = std::string(reinterpret_cast<char const*>(uc_result_firstName));
this->strLastName  = std::string(reinterpret_cast<char const*>(uc_result_lastName));
this->nAge         = sqlite3_column_int(stmt, 2);

sqlite3_finalize(stmt);

std::cout << "\nLastname: " << strLastName << std::endl;

}

C++ std::atomic - impossibility of synchronizing 2 threads based on a shared atomic variable

In my program, 2 threads sort a simple array in a contradictory (for test) way. The single idea is to prevent both threads to sort the array at the same time using std::atomic. The expected result is that the array will be sorted, either descending or ascending depending on "the winner thread". I know that this can easily be solved with mutexes, but I just here try to understand the benefit of std::atomic. My program fails in 10% of all execution cases: failure is when both sorts intertwine... Thanks in advance for any highlighting...

std::array my_array{ 1, 4, 3, 2, 5 }; std::atomic< std::array* > my_array_{ &my_array };

std::thread my_thread(
    [&my_array_]() {
        std::array<int, 5>* my_array = nullptr;
        do { my_array = my_array_.load(std::memory_order_acquire); } while (my_array == nullptr);
        my_array_.store(nullptr, std::memory_order_release);

        std::sort(my_array->begin(), my_array->end(),
            [](const int a, const  int b) {
                // std::cout << "\tascending a: " << a << " b: " << b << std::endl;
                return a > b;
            });
        my_array_.store(my_array, std::memory_order_release);
    });

std::thread my_thread_(
    [&my_array_]() {
        std::array<int, 5>* my_array = nullptr;
        do { my_array = my_array_.load(std::memory_order_acquire); } while (my_array == nullptr);
        my_array_.store(nullptr, std::memory_order_release);

        std::sort(my_array->begin(), my_array->end(),
            [](const int a, const int b) {
                // std::cout << "\tdescending a: " << a << " b: " << b << std::endl;
                return a < b;
            });
        my_array_.store(my_array, std::memory_order_release);
    });

my_thread_.join();
my_thread.join();

for (const int i : my_array)
    std::cout << "\t" << i;

Boost TCP Server not reading all incoming data

I am making a Boost TCP Server and following this example.

https://www.boost.org/doc/libs/1_58_0/doc/html/boost_asio/example/cpp11/echo/async_tcp_echo_server.cpp

I realised that not all the messages sent by client are received by the server and after further reading i realised the problem lies with this function.

void do_read()
  {
    auto self(shared_from_this());
    socket_.async_read_some(boost::asio::buffer(data_, max_length),
        [this, self](boost::system::error_code ec, std::size_t length)
        {
          if (!ec)
          {
            do_write(length);
          }
        });
  }

Since we are using socket_.async_read_some this function can exit before reading all the messages.

Can this function be modified or how should i make a server which will read all the incoming messages.

How to share the struct in inheritance classes?

I would like to share a struct with multiple inheritance classes. But I am not sure how to write such codes.

This is a code I tried to write. I would like to share Info with Parent and ChildA

#include <memory>
#include <iostream>
#include <vector>

struct Info
{
    Info(int num) : 
        memberNum(num)
    {

    }

    const std::string surName = "foge";
    const int memberNum;
};


class Parent
{
public:
    Parent(std::shared_ptr<Info> info) : 
        info(info)
    {};
    virtual ~Parent() {};

protected:
    std::shared_ptr<Info> info = nullptr;
};


class ChildA : public Parent
{
public:
    ChildA(std::shared_ptr<Info> info) : 
        info(info) // error : C++ is not a nonstatic data member or base class of class
    { // error : C++ no default constructor exists for class

    };

    ~ChildA() {};

};


int main(int argc, char** argv)
{
    int num = 4;
    std::shared_ptr<Info> info = std::make_shared<Info>(num);

    std::unique_ptr<Parent> pa = std::make_unique<Parent>(info);
    std::unique_ptr<Parent> chA = std::make_unique<ChildA>(info);

    return 0;
}

I am not sure this is a good manner of writing. Does anyone have any idea? Thank you!

pointer-to-method callbacks in C++11/14/17?

(A previous question of mine has similar wording and examples, but is asking something quite different. Before I was asking for ideas for approaches. Now I'm asking how to get a specific approach to work.)

I have some subscription function that will call my callback when something happens. (Let's say it's a timer, and will pass me an object when a certain number of milliseconds elapses.) After looking at lambdas, std:function and std:bind I think the solution of pointers-to-methods is higher performance and simpler to write (especially for the subscriber) but I can't quite figure out the last bit.

This example mirrors my project a bit: we have a framework, represented by Foo, which is written once, and we'll have many subclasses represented here by Bar that will be written by people with more domain knowledge but less C++ knowledge. So, we want that call to SubscribeTimer() to be as simple as possible. Finally the application is high performance and we'd like to eliminate heap usage, including creating implicit std::bind objects and so on.

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

class Data { int i; };

class Foo {
public:
    typedef void (Foo::*Timer_T)( Data* pd );
    virtual void SubscribeTimer( int iMilliseconds, Timer_T pmethod );
    virtual void SubscribeTimer( int iMilliseconds, std::function<void(Data*)> pfn ); // undesired

    virtual void OnTimerA( Data* pd ) { cout << "Foo::OnTimerA called" << endl; };
};

void Foo::SubscribeTimer( int iMilliseconds, Timer_T pmethod ) {
    Data d;
    (this->*pmethod)( &d );
}

void Foo::SubscribeTimer( int iMilliseconds, std::function<void(Data*)> pfn ) { // undesired
    Data d;
    pfn( &d );
}

class Bar: public Foo {
    public:
    void Init();
    virtual void OnTimerA( Data* pd ) { cout << "Bar::OnTimerA called" << endl; };
    virtual void OnTimerB( Data* pd ) { cout << "Bar::OnTimerB called" << endl; };
};

void Bar::Init() {
    // Works like I want it to: easy to subscribe, and high performance.
    SubscribeTimer( 1000, &Foo::OnTimerA );
    // What I'd like to do, but doesn't work.
    //SubscribeTimer( 1000, &Bar::OnTimerB );
    // Does exactly what I want except more complicated to write and I believe slower to run.
    SubscribeTimer( 1000, std::bind( &Bar::OnTimerB, this, std::placeholders::_1 ) );
}


int main( int nArg, const char* apszArg[] ) {
    Bar bar;
    bar.Init();
}

As expected (if you overlook the requirement to write Foo::, not Bar:: in Init()'s call to SubscribeTimer()) the program outputs:

Bar::OnTimerA called  (from the version of SubscribeTimer() I like)
Bar::OnTimerB called  (from the version of SubscribeTimer() I think is too verbose/slow)

So this example works perfectly and does what I need... except that the subclass can only register handlers for method names the superclass has thought to define, whether or not they are defined or not. In reality, though, the subclass may wish to register many handlers for different events, with names tha superclass wouldn't know.

So in a sentence: how can I pass OnTimerB() into the method-pointer version of SubscribeTimer()? I'm happy to change Timer_T definition, SubscribeTimer() or whatever. As a floor though, there is no point in a member-pointer solution more complicated for the subclass than the std::function implementation, and no point in a solution slower than thestd::function implementation either. On the other hand, added complexity in the superclass isn't a problem, as it's write-once code.

Node js server and c++ client socket io connection , not able to emit or read the data

I cannot get this simple test work. I wrote the client in C++ and the server in NodeJS, both running on my computer. When I execute the client application, the console outputs this text...but the event 'key' is never fired on the server!

Client console output:

Error: No active session [2019-11-21 17:30:11] [connect] Successful connection [2019-11-21 17:30:11] [connect] WebSocket Connection 127.0.0.1:8081 v-2 "WebSocket++/0.8.1" /socket.io/?EIO=4&transport=websocket&t=1574353811 101

C++ client

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

#include <sio_client.h>

using namespace sio;
using namespace std;

int main()
{
    sio::client io;
    io.connect("http://127.0.0.1:8081");

    string command = "w";

    io.socket()->emit("key", command );

}

NodeJS server

'use strict';

const express     = require('express');
const app         = express();
const serverHttp  = require('http').Server(app); 
const io = require('socket.io')(serverHttp);

const port = 9876;

io.on('connection', function (socket) {   
    // Never fired :(
    socket.on('key', function (data) {
        console.log("key received!!!");
    });
});

serverHttp.listen(port, function() {  
    console.log("init!!!");    
});

could you please fix this , i saw someone asking the same question in github issues section for socket io c++ client, no one has answered yet. please help out

if i am missing some codes in client please let me know . i just followed what they have mentioned in here. https://github.com/socketio/socket.io-client-cpp

lundi 25 novembre 2019

Why make_shared slower than sharet_ptr

In each article it is written that make_shared is more efficient, than shared_ptr(new T), because of one memory allocation not two. But i try this code:

#include <cstdio>
#include <ctime>

#include <memory>
#include <vector>

static const size_t N = 1L << 25;

int main(void) {

    clock_t start = clock();
        for ( size_t rcx = 0; rcx < N; rcx++ ) {
            auto tmp = std::shared_ptr<std::vector<size_t>>( new std::vector<size_t>( 1024 ) );
        }
    clock_t end = clock();
    printf("shared_ptr with new: %lf\n", ((double)end - start) / CLOCKS_PER_SEC);

    start = clock();
        for ( size_t rcx = 0; rcx < N; rcx++ ) {
            auto tmp = std::make_shared<std::vector<size_t>>( 1024 );
        }
    end = clock();
    printf("make_shared: %lf\n", ((double)end - start) / CLOCKS_PER_SEC);

    return 0;
}

compile with:

g++ --std=c++14 -O2 test.cpp -o test

and got this result:

shared_ptr with new: 10.502945

make_shared: 18.581738

Same for boost::shared_ptr:

shared_ptr with new: 10.778537

make_shared: 18.962444

This have answer about LLVM's libc++ is broken, but i use libstdc++ from GNU. So, why make_shared is slower?

P.S. With -O3 optimization got this result:

shared_ptr with new: 5.482464

make_shared: 4.249722

same for boost::shared_ptr.

i cant understanad the problem ,can someone explain it to me

one of the most efficient uses of binary search is to find a range that satisfies a certain condition we want you to do something like that given an array A for each index find the Largest element in the Array A such that that element named x - ai  ≤  v.

where v is a given integer.

Input on the first line you are given two integers n and v where (1  ≤  n  ≤  105) and (0  ≤  v  ≤  109).

then you will be given n integers the array A where (1  ≤  ai  ≤  109).

Output Output n integers where for each i output xi where xi is the largest element in the array where xi - ai  ≤  v.

Examples

input

5 2

5 4 2 1 3

output

5 5 4 3 5

Why the object is still exists after std::move function

I have a question regarding std::move function. Please refer to the code below:

#include <iostream>
#include <memory>

using namespace std;

class CPointer {
public:
    CPointer(double a, double b)
    {
        m_dX = a;
        m_dY = b;
    }

    ~CPointer()
    {
        m_dX = m_dY = 0;
    }


    double getX() const
    {return m_dX;}

    double getY() const
    {return m_dY;}

private:
    double m_dX;
    double m_dY;
};

class CContainer 
{
public:
    CContainer(CPointer* p)
    {
        m_p = p;
    }

    ~CContainer()
    {
        m_p = nullptr;
    }

    CPointer* getP() const
    {return m_p;}

private:
    CPointer* m_p;

};


class CBigContainer
{
public:
    CBigContainer(CContainer* p)
    {
        m_p = p;
    }
    ~CBigContainer()
    {
        m_p = nullptr;
    }
    CContainer* getP() const
    {return m_p;}

private:
    CContainer* m_p;
};

int main()
{
    CPointer* pPointer = new CPointer(150,360);

    cout << "1.) " << pPointer->getX() << " , " << pPointer->getY() << "\n";

    std::shared_ptr<CContainer> spContainer = std::make_shared<CContainer>(pPointer);

    cout << "2.) " << pPointer->getX() << " , " << pPointer->getY() << "\n";

    std::shared_ptr<CBigContainer> spBigContainer = std::make_shared<CBigContainer>(std::move(spContainer.get())); //<--- std::move here

    cout << "3.) " << spBigContainer->getP()->getP()->getX() << " , " << spBigContainer->getP()->getP()->getY() << "\n";
    cout << "4.) " << spContainer->getP()->getX() << " , " << spContainer->getP()->getY() << "\n";
    cout << "5.) " << pPointer->getX() << " , " << pPointer->getY() << "\n";

    return 0;
}

And this is the result :

enter image description here

My question is , I am using a std::move

std::shared_ptr<CBigContainer> spBigContainer = std::make_shared<CBigContainer>(std::move(spContainer.get()));

So I am expecting the spContainer cannot be used after the line of code, because the object inside smart pointer is removed. But it still work fine. It seems like has no different with not using std::move in this case.

Can you explain to me in details ? Thank you very much.