dimanche 30 avril 2017

C++ regex_search() does not work with star-quantifier

I'm compiling this on Linux with g++ 5.4.0

string s = "ans42";
smatch result;

if (regex_search(s, result, regex("\\d*")))
    cout << result.str() << endl;

Above does match 42 if I change \\d* to \\d+. But AFAIK both are greedy so both should work! What gives?

Efficient way of assigning variables from cin

So in the past I have had to take in a single line of input with different numbers or letters separated by spaces ( e.g. "1100 2 100 1" ) and assign each set of numbers or letters to it's own respective variable. For example, if user enters "1100 2 100 1" the program needs to add the first line of numbers "1100" to a string array called 'string1', "2" to an int called 'num', "100" to a string array called 'string2', etc..

The way I have always handled this problem is with a series of for-loops, if-statements and counters to remember where in the cin input we are up to:

// Takes in an input from the user and adds them to the required strings and chars to be used in main.

void addToList()
{
std::string temp;

std::getline( std::cin, temp );

// Takes each element from cin and stores them in variables accordingly.
int length = temp.length();

int i;
int j;
int k;
int l;

// Adds the first set of numbers from cin into the string array 'binarystr1'
for ( i = 0; i < length; i++ )
{
    if ( temp[i] == ' ' )
    {
        break;
    }

    if ( temp[i] >= 0 )
    {
        binarystr1 += temp[i];
    }

}

int bs1Length = binarystr1.length();

// Sets the char 'k1' to the second number in cin.
for ( j = bs1Length+1; j < length; j++ )
{

    if ( temp[j] == ' ' )
    {
        break;
    }

    if ( temp[j] >= 0 )
    {
        k1 = temp[j];
    }

}

int newLength = bs1Length + 3;

// Adds the 3rd line of numbers entered in cin to the string 'binarystr2'.
for ( k = newLength; k < length; k++ )
{
    if ( temp[k] == ' ' )
    {
        break;
    }
    if ( temp[k] >= 0 )
    {
        binarystr2 += temp[k];
    }
}

int bs2Length = binarystr2.length();
int lastLength = newLength + bs2Length+1;

// Sets char 'k2' to the last number entered in cin.
for ( l = lastLength; l < length; l++ )
{
    if ( temp[l] == ' ' )
    {
        break;
    }
    if ( temp[l] >= 0 )
    {
        k2 = temp[l];
    }
}
}

As you can see this is a very ugly and lengthy process, so if someone could show me a better way of splitting up input and storing them in the future, it would be greatly appreciated. Thanks!

error: no matching function for call to 'std::basic_ifstream

I am trying to write a program that opens a file and counts the whitespace-separated words in that file.

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

int main() {
    string filepath;
    cout << "Enter the file path including the file name:" << endl;
    cin >> filepath; 
    ifstream f(filepath);
    int nwords = 0;
    string word;
    while (f >> word)
        ++nwords;
    cout << "Number of words = " << nwords << endl;
}

This is the error when I try to compile it.

g++ Assignment1.cpp
Assignment1.cpp: In function 'int main()':
Assignment1.cpp:10:21: error: no matching function for call to 'std::basic_ifstream<char>::basic_ifstream(std::__cxx11::string&)'
  ifstream f(filepath);
                     ^
In file included from Assignment1.cpp:2:0:
c:\mingw\lib\gcc\mingw32\5.3.0\include\c++\fstream:495:7: note: candidate: std::basic_ifstream<_CharT, _Traits>::basic_ifstream(const char*, std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits<char>; std::ios_base::openmode = std::_Ios_Openmode]
       basic_ifstream(const char* __s, ios_base::openmode __mode = ios_base::in)
       ^
c:\mingw\lib\gcc\mingw32\5.3.0\include\c++\fstream:495:7: note:   no known conversion for argument 1 from 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' to 'const char*'
c:\mingw\lib\gcc\mingw32\5.3.0\include\c++\fstream:481:7: note: candidate: std::basic_ifstream<_CharT, _Traits>::basic_ifstream() [with _CharT = char; _Traits = std::char_traits<char>]
       basic_ifstream() : __istream_type(), _M_filebuf()
       ^
c:\mingw\lib\gcc\mingw32\5.3.0\include\c++\fstream:481:7: note:   candidate expects 0 arguments, 1 provided
c:\mingw\lib\gcc\mingw32\5.3.0\include\c++\fstream:455:11: note: candidate: std::basic_ifstream<char>::basic_ifstream(const std::basic_ifstream<char>&)
     class basic_ifstream : public basic_istream<_CharT, _Traits>
           ^
c:\mingw\lib\gcc\mingw32\5.3.0\include\c++\fstream:455:11: note:   no known conversion for argument 1 from 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' to 'const std::basic_ifstream<char>&'

Compiler Error When Calling Base Constructor when both Base and Derived are Templated With Derived Type Parameter

I am struggling to understand why the following code does not compile:

template <class T>
class Base {
    public:
        Base(int a){}
};
template <class T>
class Derived: public Base<T>  {
    public:
        Derived(int a): Base(a){}
};
int main(){}

On my compiler (gcc 5.4.0 with C++ 11) this outputs the error message

error: class 'Derived<T>' does not have any field named 'Base'
         Derived(int a): Base(a){}

I see that this is somewhat similar to Template base constructor call in member initialization list error, though that test case actually compiles for me while this one does not: The main difference seems to be that both Base and Derived use the same type parameter. Additionally, it compiles fine if I explicitly add the type parameters or I give an explicit scope for base, as in

template <class T>
class Base {
    public:
        Base(int a){}
};

template <class T>
class Derived: public Base<T>  {
    public:
        Derived(int a): Derived::Base(a){}
};

int main(){}

What's going on? Am I misunderstanding when injected class names may be used?

How to set all expect one element in a vector of bools to true?

Makes a a vector in C++.

 vector<bool> trumpIsGoodFor(42);

Needs to set all the elements expect the 24th element to true.

Wants to do it using a one/two line or elegant assignment using C++11/14.

Is there a way to partially match a variadic template parameter pack?

I currently have a system to "connect" signals to functions. This signal is a variadic template that has as template parameters the arguments of the functions if can connect to.

In the current implementation, I obviously cannot connect to functions whose arguments aren't exactly the same (or those that can be converted to) as the signal's parameters. Now, as I'm trying to mimic Qt's signal/slot/connect, I'd also like to connect a signal of N parameters to a slot of M<N parameters, which is perfectly well-defined (i.e. ignore the >M parameters of the signal and just pass the first M to the connected function). For an example of the code I have in its most simplistic form, see Coliru.

So the question is two-fold:

  1. How do I make the connect call work for a function void g(int);?
  2. How do I make the emit call work for a function void g(int);?

I'm guessing I'll have to make some "magic" parameter pack reducer for both the slot and the , but I can't see how it all should fit together so it's quite hard to actually start trying to code a solution. I'm OK with a C++17-only solution, if at least Clang/GCC and Visual Studio 2017 can compile it.

The code linked above for completeness:

#include <memory>
#include <vector>

template<typename... ArgTypes>
struct slot
{
    virtual ~slot() = default;

    virtual void call(ArgTypes...) const = 0;
};

template<typename Callable, typename... ArgTypes>
struct callable_slot : slot<ArgTypes...>
{
    callable_slot(Callable callable) : callable(callable) {}

    void call(ArgTypes... args) const override { callable(args...); }

    Callable callable;
};

template<typename... ArgTypes>
struct signal
{
    template<typename Callable>
    void connect(Callable callable)
    {
        slots.emplace_back(std::make_unique<callable_slot<Callable, ArgTypes...>>(callable));
    }

    void emit(ArgTypes... args)
    {
        for(const auto& slot : slots)
        {
            slot->call(args...);
        }
    }

    std::vector<std::unique_ptr<slot<ArgTypes...>>> slots;
};

void f(int, char) {}

int main()
{
    signal<int, char> s;
    s.connect(&f);

    s.emit(42, 'c');
}

How to correct match the object type and return it using factory pattern?

I'm trying to solve this error :

No suitable user-defined conversion from
"std::unique_ptr<< error_type >>, std::default_delete<< error_type >>" to
"std::unique_ptr< NPC, std::default_delete< NPC >>" exists.

This is my base class

NPC.h

class NPC
{

public:
    virtual void Talk() = 0;
    virtual void Act() = 0;
};

Then I have the current NPC objects

GoldenNpc.h

class GoldenNpc : public NPC
{
public:
    GoldenNpc(int npcIndex) { this->npcIndex = npcIndex };

    void Talk() override;

private:
    void Act() override;

private:
    int npcIndex;
};

SilverNpc.h

class SilverNPC : public NPC
{
public:
    SilverNPC(int npcIndex) { this->npcIndex = npcIndex };

    void Talk() override;

private:
    void Act() override;

private:
    int npcIndex;
};

The compiler error happens here:

NPCFactory npcFactory = NPCFactory();
std::unique_ptr<NPC> npc = npcFactory.MakeNpc(npcIndex, NPC_CONSTANT);
//npc.talk();

My Factory is defined as follow :

NPCFactory.h

class NPCFactory
{

public:
    std::unique_ptr<NPC> MakeNpc(int npcIndex, int npc_code) const;
};

NPCFactory.cpp

std::unique_ptr<NPC> NPCFactory::MakeNpc(int npcIndex, int npc_code) const
{
    switch (npc_code)
    {
    case GOLD:
        return std::make_unique<GoldNpc>(npcIndex);
    case Silver:
        return std::make_unique<SilverNpc>(npcIndex);
    default:
        return nullptr;
    }
}

I did not understand the reason for this compiler error.

Could someone explain to me? Thanks!

c++ static_assert and compile-time

I want to write for ARM 32-bit microcontroller and I want to use modern C++ for education. My goals is: readable code, configurable in compile-time and help compiler to generate maximum optimizations for size and speed. What language tools should I use to archive my goals? I write some code and static assertions does not work... Please help me to fix this code (add assertions and no overhead).

#include <initializer_list>
#include <vector>

typedef uint port_type;
typedef uint pin_type;

class Pin {
private:
    const port_type _port;
    const pin_type _pin;
public:
    Pin(const port_type port, const pin_type pin) :
            _port(port), _pin(pin) {
    }
};

class Actuator {
private:
    const Pin _enable_pin;
    const Pin _dir_pin;
    const Pin _step_pin;
public:
    Actuator(const Pin enable_pin, const Pin dir_pin, const Pin step_pin) :
            _enable_pin(enable_pin), _dir_pin(dir_pin), _step_pin(step_pin) {
    }

};

class Machine {
private:
    const std::vector<Actuator> _actuators;
public:
    Machine(const std::initializer_list<Actuator> actuators) :
            _actuators(actuators) {
        /*check: all actuators _enable_pin ports are same*/
        /*check: all actuators _dir_pin ports are same*/
        /*check: all actuators _step_pin ports are same*/
        /*check: all port/pin pairs are unique*/
    }
};

int main() {
    /*example: good sequence*/
    Actuator act1(Pin(1, 1), Pin(1, 2), Pin(1, 3));
    Actuator act2(Pin(1, 4), Pin(1, 5), Pin(1, 6));
    Machine machine1( { act1, act2 });
    /*example: bad sequence*/
    Actuator act3(Pin(2, 1), Pin(2, 2), Pin(2, 2)); // NOK! Pin(2,2) already used!
    Actuator act4(Pin(2, 1), Pin(2, 3), Pin(2, 4)); // NOK! Pin(2,1) already used in act3!
    Machine machine2( { act3, act4 });
} 

Setting opengl vertex array object in seperate class breaks drawing

I'm new to c++ and OpenGL and my code now that I changed it to be more object oriented doas not draw anymore. I don't get an error message.

I tried to bugfix this for a while now and I have still no Idea what the problem could be. Hopefully you can help me :D

Here is the main Program I left out all the includes and some basic stuff:

// Game variables
TestEntity *testEntity;

int main()
{
glfwInit(); 
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "TopDown-Shooter", nullptr, nullptr); // Create a GLFWwindow object that we can use for GLFW's functions
glfwMakeContextCurrent(window);

// Set the required callback functions
glfwSetKeyCallback(window, key_callback);
glewExperimental = GL_TRUE; // Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions
glewInit(); // Initialize GLEW to setup the OpenGL Function pointers

int width, height; // Define the viewport dimensions
glfwGetFramebufferSize(window, &width, &height);
glViewport(0, 0, width, height);

Shader myShader("shader.vs", "shader.frag");

testEntity = new TestEntity; // creating world object. Always create game objectrs after seeting up OpenGl context

// Game loop
while (!glfwWindowShouldClose(window))
{
    // Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions
    glfwPollEvents();

    // Render
    glClearColor(0.1796875f, 0.5078125f, 0.796875f, 1.0f); // Clear the colorbuffer
    glClear(GL_COLOR_BUFFER_BIT);

    // Drawing
    myShader.Use(); // Activates Shaders

    // Draw first triangle
    glBindTexture(GL_TEXTURE_2D, testEntity->getTex());
    GLuint drawSize = testEntity->getIndices().size();
    glBindVertexArray(testEntity->getVAO());
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
    glBindVertexArray(0);

    // Swap the screen buffers
    glfwSwapBuffers(window);
}

// Properly de-allocate all resources once they've outlived their purpose
    //testEntity->disallocateRecources();

// Terminate GLFW, clearing any resources allocated by GLFW.
glfwTerminate();
return 0;

}

and my TestEntity object:

class TestEntity {
public:
TestEntity() {
    vertices = {
        // Positions          // Colors           // Texture Coords
        0.5f,  0.5f, 0.0f,   1.0f, 0.0f, 0.0f,   1.0f, 1.0f,   // Top Right
        0.5f, -0.5f, 0.0f,   0.0f, 1.0f, 0.0f,   1.0f, 0.0f,   // Bottom Right
        -0.5f, -0.5f, 0.0f,   0.0f, 0.0f, 1.0f,   0.0f, 0.0f,   // Bottom Left
        -0.5f,  0.5f, 0.0f,   1.0f, 1.0f, 0.0f,   0.0f, 1.0f    // Top Left 
    };
    indices = {
        0, 1, 3, // First Triangle
        1, 2, 3 // Second Triangle
    };

    // VertexArray;
    glGenVertexArrays(1, &VAO); 
    glGenBuffers(1, &EBO); // generates element buffer object
    glGenBuffers(1, &VBO); // generates vertex buffer object
    glBindVertexArray(VAO); // Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s).
    glBindBuffer(GL_ARRAY_BUFFER, VBO); 
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), &vertices[0], GL_DYNAMIC_DRAW); // Writes vertices to the VBO
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), &indices[0], GL_DYNAMIC_DRAW); // writes indices to the EBO
    // Specifying vertexAttribPointers (connection to the vertex shader)
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0); // Vertices
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); // Colors
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat))); // Texture Coordinates
    glEnableVertexAttribArray(2);
    glBindVertexArray(0);

    glGenTextures(1, &tex); // generating textures
    glBindTexture(GL_TEXTURE_2D, tex);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // Specifies wrapping settings for T and S axis
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // Specifies Pixleinterpolation
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    int imgWidth, imgHeight;
    unsigned char* myImage;
    myImage = SOIL_load_image("Textures\\Test_IMG_container.jpg", &imgWidth, &imgHeight, 0, SOIL_LOAD_RGB); // loads texture image
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, imgWidth, imgHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, myImage); // converts image to texture
    glGenerateMipmap(GL_TEXTURE_2D); // generates Mipmap
    SOIL_free_image_data(myImage);
    glBindTexture(GL_TEXTURE_2D, 0);
}

pulling out unique_ptr from unique_ptr

Can someone please advise on how to return the unique pointer from a templatised unique pointer pool with a custom deletor.

In the code snippet below i am using ObjectPool.h as my template class to get a stack of unique pointers . I am using ObjectPool to create a sharedpool object in DBConnection.h and later in DBConnection.cpp i am simply returning the object to DBExec .

I get compile errors in DBConnection.cpp related to conversion of pointer with deleter to normal unique pointer.

> Class that will manage connection objects. 
**DBConnectionPool.h**
#ifndef DBCONNECTIONPOOL_H
#define DBCONNECTIONPOOL_H
#include "DBExec.h"
#include "ObjectPool.h"
class DBConnectionPool {
    static SharedPool<DBExec> pool;
    static DBConnectionPool* instance;
    DBConnectionPool& operator=(const DBConnectionPool&);
    DBConnectionPool(const DBConnectionPool&);;
    DBConnectionPool(){};
public:
    ...
    **static std::unique_ptr<DBExec> getQueryObject();**
};



#endif /* DBCONNECTIONPOOL_H */

**DBConnection.cpp**
>implementation of getQueryObject 
 **std::unique_ptr<DBExec>  DBConnectionPool::getQueryObject() {
    return std::move(pool.acquire());
}**

/* Class that manages the unique pointer */ 
**ObjectPool.h**
#ifndef OBJECTPOOL_H
#define OBJECTPOOL_H
#include <memory>
#include <stack>
#include <mutex>
#include <assert.h>
template <class T>
class SharedPool {

/* Class that manages the unique pointer */ public: using ptr_type = std::unique_ptr >;

    SharedPool() {
    }

    virtual ~SharedPool() {
    }

    void add(std::unique_ptr<T> t) {
        std::lock_guard<std::mutex>  lck (mt);
        pool_.push(std::move(t));
    }

    ptr_type acquire() {
        std::lock_guard<std::mutex>  lck (mt);
        assert(!pool_.empty());
        ptr_type tmp(pool_.top().release(),
                [this](T * ptr) {
                    this->add(std::unique_ptr<T>(ptr));
                });
        pool_.pop();
        return std::move(tmp);
    }

    bool empty() const {
        std::lock_guard<std::mutex>  lck (mt);
        return pool_.empty();
    }

    size_t size() const {
        std::lock_guard<std::mutex>  lck (mt);
        return pool_.size();
    }
    std::stack<std::unique_ptr<T>>& getPoolStack () {
        return pool_;
    }
private:
> thread safe 
    std::mutex mt;
    std::stack<std::unique_ptr<T> > pool_;
};

#endif /* OBJECTPOOL_H */

Can't read whole file into string

I have a code:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(int argc, char *argv[]) {
    ifstream file;

    do {
        string filename;
        cout << "Input file name:" << endl;
        cin >> filename;
        file.open(filename, ios::in);
    } while (!file.is_open());

    string content(istreambuf_iterator<char>(file),
                   istreambuf_iterator<char>());

    cout << "Content:\n" << content << endl;

    if (file.is_open()) {
        file.close();
    }

    return 0;
}

To read this file content:

 1 -1  0 -3  0
-2  5  0  0  0
 0  0  4  6  4
-4  0  2  7  0
 0  8  0  0 -5

But it outputs 1 only and a new line.
P.S. I am a nobie and just learn C++ by samples. What do I doing wrong?

Why is constructing std::string from mmaped file blocking threads?

I'm trying to read and process multiple files, in parallel, right now I have two file and two parsing functions which I call in 2 threads:

In the first case, I'm constructing string from parts of the file (reading headers of csv), the first function:

void csv_parse_items_file(const char* file, size_t fsize,
    //void(*deal)(const string&, const size_t&, const int&), 
size_t arrstart_counter = 0) {
size_t idx = 0;
int line = 0;
size_t last_idx = 0;
int counter = 0;

cout<<"items_header before loop, thread_id="+std::to_string(thread_index())<<endl;
map<string, int> headers;
{
    int counter = 0;
    while (file[idx] && file[idx] != '\n') {
        if (file[idx] == '\t' || file[idx] == '\n') {
            string key(file, last_idx, idx - last_idx);
            headers[key] = counter++;
            last_idx = idx + 1;
        }

        ++idx;
    }
}
cout<<"items_header after loop, thread_id="+std::to_string(thread_index())<<endl;
... then the processing continues in a loop

the second function:

void csv_parse_users_file(const char* file, size_t fsize,
    //void(*deal)(const string&, const size_t&, const int&), 
    size_t arrstart_counter = 0) {
size_t idx = 0;
int line = 0;
size_t last_idx = 0;
int counter = 0;
map<string, int> headers;
{
    int counter = 0;
    while (file[idx] && file[idx] != '\n') {
        if (file[idx] == '\t' || file[idx] == '\n') {
            string key(file, last_idx, idx - last_idx);
            headers[key] = counter++;
            last_idx = idx + 1;
        }

        ++idx;
    }
}

when I run in this config, the output is:

users_mapped 86431022
items_mapped237179072
1497021
1306055
items_header before loop, thread_id=0
processed 100000users thread_id:1 
processed 200000users thread_id:1 
processed 300000users thread_id:1 
processed 400000users thread_id:1 
processed 500000users thread_id:1 
processed 600000users thread_id:1 
processed 700000users thread_id:1 
processed 800000users thread_id:1 
processed 900000users thread_id:1 
processed 1000000users thread_id:1 
processed 1100000users thread_id:1 
processed 1200000users thread_id:1 
processed 1300000users thread_id:1 
processed 1400000users thread_id:1 
finished_processing_users:1497020
0x700008d52c80 finished
items_header after loop, thread_id=0
processed 100000items, thread_id:0 
processed 200000items, thread_id:0 
processed 300000items, thread_id:0 
processed 400000items, thread_id:0 
processed 500000items, thread_id:0 
processed 600000items, thread_id:0 
processed 700000items, thread_id:0 
processed 800000items, thread_id:0 
processed 900000items, thread_id:0 
processed 1000000items, thread_id:0 
processed 1100000items, thread_id:0 
processed 1200000items, thread_id:0 
processed 1300000items, thread_id:0 
finished_p

Now, if I edited the first function, and commented out this line string key(file, last_idx, idx - last_idx); so the first function will start like this:

void csv_parse_items_file(const char* file, size_t fsize,
    //void(*deal)(const string&, const size_t&, const int&), 
size_t arrstart_counter = 0) {
size_t idx = 0;
int line = 0;
size_t last_idx = 0;
int counter = 0;

cout<<"items_header before loop, thread_id="+std::to_string(thread_index())<<endl;
map<string, int> headers;
{
    int counter = 0;
    while (file[idx] && file[idx] != '\n') {
        if (file[idx] == '\t' || file[idx] == '\n') {
            //string key(file, last_idx, idx - last_idx);
            headers["ok"] = counter++;
            last_idx = idx + 1;
        }

The output is:

    users_mapped 86431022
items_mapped237179072
1497021
1306055
items_header before loop, thread_id=0
items_header after loop, thread_id=0
processed 100000users thread_id:1 
processed 200000users thread_id:1 
processed 300000users thread_id:1 
processed 100000items, thread_id:0 
processed 400000users thread_id:1 
processed 500000users thread_id:1 
processed 200000items, thread_id:0 
processed 600000users thread_id:1 
processed 700000users thread_id:1 
processed 300000items, thread_id:0 
processed 800000users thread_id:1 
processed 900000users thread_id:1 
processed 1000000users thread_id:1 
processed 400000items, thread_id:0 
processed 1100000users thread_id:1 
processed 1200000users thread_id:1 
processed 500000items, thread_id:0 
processed 1300000users thread_id:1 
processed 1400000users thread_id:1 
finished_processing_users:1497020
0x700001870c80 finished
processed 600000items, thread_id:0 
processed 700000items, thread_id:0 
processed 800000items, thread_id:0 
processed 900000items, thread_id:0 
processed 1000000items, thread_id:0 
processed 1100000items, thread_id:0 
processed 1200000items, thread_id:0 
processed 1300000items, thread_id:0 
finished_processing_items:1306054

The header file is less then 1000 chars compared with the size of the files (86431022 and 237179072).

    $g++ -v
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 8.0.0 (clang-800.0.42.1)
Target: x86_64-apple-darwin16.1.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/binrocessing_items:1306054

compiled with g++ -pthread -c -g -std=c++11

files mmaped with mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);

I can't figure out why having the string construction in both thread from two different mmaped files, with no common variables other then cout, cause one thread to wait for the other! is there any locks when construction std::string?

std::remove_if polymorphic std::unique_ptr from std::vector

I have a hierarchy of three classes where Derived derives from Selectable and Drawable. Then I have a vector of unique_ptr<Drawable> which I fill with Derived objects.

I am certain that the vector will be filled only by objects which derive from both bases simultaneously.

The problem comes when I try to remove a certain element from the vector by using a pointer to Selected.

#include <vector>
#include <memory>
#include <algorithm>

struct Selectable {
    virtual ~Selectable() = 0;
};
Selectable::~Selectable() = default;

struct Drawable {
    virtual ~Drawable() = 0;
};
Drawable::~Drawable() = default;

struct Derived : Selectable, Drawable {};

int main()
{
    std::vector<std::unique_ptr<Drawable>> vec;
    for (int i = 0; i < 5; ++i) {
        vec.push_back(std::make_unique<Derived>());
    }
    Selectable* selected = dynamic_cast<Selectable*>(vec[2].get());

    vec.erase(std::remove_if(vec.begin(), vec.end(), 
        [selected](auto&& ptr) { 
            return ptr.get() == dynamic_cast<Drawable*>(selected); 
    }), vec.end());
}

Obviously if I make selected to be a pointer to Drawable, everything is fine, but that is not my intention.

I am getting a run-time error which causes the program to crash. Why is this happening and how would I fix it?

std::future in c++ with raspberry e sysroot

I'm writing a sample code to learn the asynchronos function with std::async.

My code it's very simple:

#include <iostream>
#include <future>

void error(char *msg)
{
    std::cout << msg;
}


int main(int argc, char * argv[])
{
    std::future<void> asyncr = std::async(errore,"start async");

    std::cout << "finish";
}

i think this is all correct, but my VisualStudio with VisualGDB throw an error in "asyncr":

[Clang IntelliSense] Error: implicit instantiation of undefined template 'std::future'

I lost several hours, and i want to find a solution.

I will be very grateful to those who will help me

uint8_t need uint16_t to store values from stringstream

reading an IP address from argv forces me to convert it to uint32_t

this function will do so:

uint32_t convert_string_ip_to_uint32_t (const string & string_ip) { stringstream s(string_ip) ; uint16_t a,b,c,d; //to store the 4 ints char ch; //to temporarily store the '.' s >> a >> ch >> b >> ch >> c >> ch >> d ; std::cout << a << " " << b << " " << c << " "<< d << std::flush;; return ((uint32_t) a << 24 | b << 16 | c << 8 | d); }

But when I change the data type of a,b,c and d to uint8_t, the result will be rubish. Why? e.g. string_ip = '192.168.1.10'

How to set build and run C++ code in Sublime Text with allowing cin>> inputs?

I use Sublime Text 3 editor in Ubuntu and I hate to use the command line g++ program.cpp -o program in order to compile and run my programs. Because of this reason I used sublime script builder

{
    "shell_cmd": "g++ -std=c++11 \"${file}\" -o \"${file_path}/${file_base_name}\"",
    "file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
    "working_dir": "${file_path}",
    "selector": "source.c, source.c++",

    "variants":
    [
        {
            "name": "Run",
            "shell_cmd": "g++ -std=c++11 \"${file}\" -o \"${file_path}/${file_base_name}\" && \"${file_path}/${file_base_name}\""
        }
    ]
}

from these site http://ift.tt/2oUA09K

It works but and I can see the result on the bottom console of the editor, the problem is that I can't use cin>> or scanf() inputs to insert the values on the bottom console, - I have to initialize the variables explicitly inside the code. What should I do or which package I have to install in order to read variables from the keyboard ? thank you.

I don't understand why I am recieving an error with string.replace

I do not understand what I am doing wrong here in this function. I am pretty sure I am using the parameters correctly. Is there a #include file I missed?

int countTemplate(const string& str)
{
int count = 0;
while (!str.empty())
{

    size_t beginningTemp;
    size_t endTemp;
    string foundTemp;

    beginningTemp = str.find('@');
    endTemp = str.find('@', beginningTemp+1);
    foundTemp = str.substr(beginningTemp, (endTemp + 1) - beginningTemp);
    count++;
    str.replace(str.find('@'), (endTemp + 1) - beginningTemp, "");
}

return count;
}

Is the final function specifier redundant when using the final class specifier?

Is there any reason to specify a function as final when the class is already final? Or is that redundant?

class B
{
public:
    virtual void f();
};

class D final : public B
{
public:
    virtual void f() final; // Redundant final?
};

Would it be a good rule of thumb to say: Start with making the whole class final, and only switch to making individual functions final when you need to derive from the class and/or override specific functions?

Is there any particular difference between "source code" and "translation unit"?

I know source code is what we write as a code and translation unit includes a source file and source files included via directive. Then what is the difference between the two?

samedi 29 avril 2017

How to call copy constructor of all base classes for copying most derived class object in diamond inheritance in C++?

Consider the below code:

#include<iostream>
using namespace std;
class A
{
public:
     A(){ cout <<"1";}
     A(const A &obj) { cout <<"2";}
};

class B: virtual A
{
public:
    B(){cout <<"3";}
    B(const B & obj) {cout<<"4";}
};

class C: virtual A
{
public:
   C(){cout<<"5";}
   C(const C & obj) {cout <<"6";}
};

class D:B,C
{
public:
    D()  {cout<<"7";}
    D(const D & obj) {cout <<"8";}
};

int main()
{
   D d1;
   cout<<"\n";
   D d(d1);
}

The output of the program is below: 1357 1358 So, for line D d(d1) copy constructor of D class is getting called. During inheritance we need to explicitly call copy constructor of base class otherwise only default constructor of base class is called. I understood till here. My Problem: Now I want to call copy constructor of all base classes during "D d(d1)" execution. For that if I try below D(const D & obj) : A(obj), B(obj), C(obj) {cout <<"8";} Then I get this error: error: 'class A A::A' is inaccessible within this context

How to resolve the issue. I want copy constructor of A, B and C when copy constructor of D gets called. It might be very small change but I am not getting. Please help. Thanks in advance!

Error 2 files include each other

i have this problems while trying to include 2 files each other:

./include/../include/../src/Socket/../LinuxClass/ThreadingPool.hpp:38:5: error: ‘Client’ does not name a type Client client;

I already find a solution about declaring the first class in the second files but the error is still there here is the 2 .h

#ifndef THREADINGPOOL_HPP_

#define THREADINGPOOL_HPP_

#include <functional>
#include <algorithm>
#include <queue>
#include "../Socket/Client.hpp"
#include "../Intefaces/IThread.hpp"
#include "Mutex.hpp"
#include "Thread.hpp"
#include "Condvar.hpp"
#include "Process.hpp"

class ThreadingPool {

  public:
    ThreadingPool(unsigned int num_thr);
    ~ThreadingPool();
    void Add_fct(std::function<void()> job);
  private:
    enum States {LIVE, DIE};
    std::vector<std::thread> thrdVec;
    std::vector<States> states;
    std::queue<std::function<void()>> jobs;
    Mutex mtex;
    Condvar cond;
    Process pros;
    Client client;
};

#endif  /* !THREADINGPOOL_HPP_ */

And the second one

#ifndef CLIENT_HPP_
# define CLIENT_HPP_

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <functional>

#include <unistd.h>

#include <fcntl.h>

#include <sys/socket.h>
#include <arpa/inet.h>

#define PORT 1043
#define METASIZE 1024

#include "check_cmd.hpp"

class ThreadingPool;

class Client {
public:
    Client();
    ~Client();

void ifMessage(ThreadingPool * thrdPool);

private:
    int csock;
    struct sockaddr_in csin;

};

#endif

overriding the template base method in derived class?

Suppose I have a base class as below:

template <typename T>
class Base {
// implementation
void do_something() { // ...} ;
};

then, I create a Derived class as below, and override the do_something() method:

template <typename T>
class Derived : public Base<T> {
    // implementation
    void do_something() { // ...} ;
};

I know virtualization does not work in class templates, but I do want to store a bunch of derived classes and base classes into a vector, (I do not want to use type erasure, or polymorphism),

my question is, given that static_cast of Derived class to base class gives me the do_something of based class, Is there any way that I can store them as base classes while each has their implementation of do_something() class ?!!!

Thanks

C++ newbie: Pretty printing BST using op overloading - initial value of reference to non-const must be an lvalue

I am just starting into C++ and created a binary search tree. Now I want to pretty print this tree using operator overloading for cout.

//declared in BST class
void printTree(Node* n, int indent) const;
friend ostream& operator<<(ostream& os, const BinarySearchTree& b);


void BinarySearchTree::printTree(Node * n, int indent) const
{

    if (n != nullptr)
    {
        printTree(n->left, indent + 4);
        if (indent > 0)
            cout << setw(indent) << " ";
        cout << n->data << endl;
        printTree(n->right, indent + 4);
    }

    return;

}

ostream & operator<<(ostream & os, const BinarySearchTree & b)
{
    b.printTree(b.root, 4);
}

In the b.printTree(b.root, 4) I get following errors

  • initial value of reference to non-const must be an lvalue
  • 'return': cannot convert from 'void' to 'std::ostream &'

Can anyone help me as to how to resolve these issue and what's the best way of going about pretty printing a BST by operator overloading in case my way is incorrect/not optimal

Member template for user defined types

I have a simple example below where AddField() is the member template.

What do I need to do to make AddField(T) work with either user defined types or a type such as vector. It works fine with primitive types.

class Data
{
public:
    template <typename T>
    void AddField(T val)
    {
        std::stringstream s;
        s << val;
        m_data += s.str();
    }

private:
    std::string m_data;
};

class A    
{
public:
    A(int val) : m_k(val) {}
private:
    int m_k;
};


int main() {
    Data x;
    // Add basic types
    x.AddField(1);
    x.AddField("_");
    x.AddField(0.5);

    **// Add a vector**
    std::vector<int> v;
    v.push_back(99);
    x.AddField(v);    <==== Not OK 

   **// Add a user defined type**
    A a(-45);
    x.AddField(a);    <==== Not OK

    return 0;
}

Thanks!

Surprising results comparing time taken to copy a large collection versus in-place manipulation

I am learning functional programming and now looking at how it can be applied to C++ programming.

One of my concerns was with the performance hit using a functional style of copying values from an input list to an output list. So I created a test program which measures the performance comparing a copy to results collection and return and an in-place manipulation. I assumed that the in-place manipulation would have been faster. But that was not the case as these results testify:

copying results to a new container took: 0.0312
in place over-write and truncate took: 0.0780002

Is my experiment flawed? If so, how so? And if not, why is copying faster?

Code here.

#include <algorithm>
#include <iostream>
#include <vector>
#include <iterator>     // std::back_inserter
#include <functional>
#include <chrono>

class Timer
{
public:
    Timer() : beg_(clock_::now()) {}
    void reset() { beg_ = clock_::now(); }
    double elapsed() const {
        return std::chrono::duration_cast<second_>
            (clock_::now() - beg_).count();
    }

private:
    typedef std::chrono::high_resolution_clock clock_;
    typedef std::chrono::duration<double, std::ratio<1> > second_;
    std::chrono::time_point<clock_> beg_;
};

std::vector<int> filter_functional(const std::vector<int>& collection, std::function<bool(int)> pred)
{
    std::vector<int> results;
    auto it = std::copy_if(collection.begin(), collection.end(), std::back_inserter(results), [=](int i){return pred(i); });
    return results;
}

// will this give much better performance?
std::vector<int>& filter_cpp(std::vector<int>& collection, std::function<bool(int)> pred)
{
    // in-place so do not have to copy collection to another collection
    auto it = std::copy_if(collection.begin(), collection.end(), collection.begin(), [=](int i){return pred(i); });
    collection.resize(std::distance(collection.begin(), it));  // shrink container to new size
    return collection;
}

int main() {

    std::vector<int> coll;
    coll.reserve(10000000);
    int starter = 0;
    std::generate_n(std::back_inserter(coll), 10000000, [&](){return starter++; });

    Timer tmr;
    std::vector<int> result = filter_cpp(coll, [](int v) { return v > 100; });

    double t = tmr.elapsed();
    std::cout << "copying results to a new container took: " << t << std::endl;

    tmr.reset();

    std::vector<int> result2 = filter_functional(coll, [](int v) { return v > 100; });

    t = tmr.elapsed();
    std::cout << "in place over-write and truncate took: " << t << std::endl;
}

Multiple threads access shared resources

I'm currently working on a particle system, which uses one thread in which the particles are first updated, then drawn. The particles are stored in a std::vector. I would like to move the update function to a separate thread to improve the systems performance. However this means that I encounter problems when the update thread and the draw thread are accessing the std::vector at the same time. My update function will change the values for the position, and colour of all particles, and also almost always resize the std::vector.

Single thread approach:

std::vector<Particle> particles;
void tick() //tick would be called from main update loop
{
    //slow as must wait for update to draw
    updateParticles();
    drawParticles();
}

Multithreaded:

std::vector<Particle> particles;
//quicker as no longer need to wait to draw and update
//crashes when both threads access the same data, or update resizes vector
void updateThread()
{
    updateParticles();
}
void drawThread()
{
    drawParticles();
}

To fix this problem I have investigated using std::mutex however in practice, with a large amount of particles, the constant locking of threads meant that performance didn't increase. I have also investigated std::atomic however, neither the particles nor std::vector are trivially copyable and so can't use this either.

Multithreaded using mutex:

NOTE: I am using SDL mutex, as far as I am aware, the principles are the same.

SDL_mutex mutex = SDL_CreateMutex();
SDL_cond canDraw = SDL_CreateCond();
SDL_cond canUpdate = SDL_CreateCond();
std::vector<Particle> particles;
//locking the threads leads to the same problems as before, 
//now each thread must wait for the other one
void updateThread()
{
    SDL_LockMutex(lock);
    while(!canUpdate)
    {
        SDL_CondWait(canUpdate, lock);
    }
    updateParticles();
    SDL_UnlockMutex(lock);
    SDL_CondSignal(canDraw);
}
void drawThread()
{
    SDL_LockMutex(lock);
    while(!canDraw)
    {
        SDL_CondWait(canDraw, lock);
    }
    drawParticles();
    SDL_UnlockMutex(lock);
    SDL_CondSignal(canUpdate);
}

I am wondering if there are any other ways to implement the multi threaded approach? Essentially preventing the same data from being accessed by both threads at the same time, without having to make each thread wait for the other. I have thought about making a local copy of the vector to draw from, but this seems like it would be inefficient, and may run into the same problems if the update thread changes the vector while it's being copied?

How to pass per-thread user data into asio handler?

I have a websocketpp-based (which as ASIO-based) server and a pool of threads. I need to allocate some resources (connection to DB and etc) and make sure they will be used exactly in the same thread always.

So, here is what I currently have:

class Server
    : public websocketpp::server<websocketpp::config::asio>
{
    Server();
    //...
    static void onMessage(Server * server,
                          websocketpp::connection_hdl hdl,
                          Server::message_ptr msg);
    //...
};

Server::Server()
{
    // ...some initialization routines.. //
    set_message_handler(
        std::bind(&onMessage,
                  this,
                  std::placeholders::_1,
                  std::placeholders::_2));
    listen(port);
    start_accept();
}

Somewhere at the main() function :

    Server server;

    // estimated thread pool
    std::vector<std::thread> threads;
    threads.reserve(threadsCount);
    for(int i = 0; i < threadsCount; ++i)
    {
        threads.emplace_back(
            [&server]()
            {
                mongo::Client mongo(config); // !HERE!
                server.run();
            });
    }

As you can see a mongo::Client instantiated at every thread. My goal is to pass ref/pointer to it (or any other resource that may be added in future) and receive it in Server::onMessage (as an additional parameter).

I'm completely out of ideas how to do this. Also, I don't want to create allocator interface like mongo::Client * Server::acquire() / Server::release(mongo::Client *), because it requires additional synchronization. My intention is to access (how?) to a some-kind of per-thread "userdata" within the Server::onMessage handler.

Is this nested template base class ambiguous?

This code used to compile in Clang 3.8, and still compiles in VS 2017, but started emitting an error in Clang 3.9.

template <typename D, typename ... I>
struct impl : I ...
{};

template <typename D, typename ... I>
void f(impl<D, I...> const&)
{}

struct A : impl<A> {};
struct B : impl<B, A> {};

int main()
{
    f(A());
    f(B()); // Error
}

Clang 3.9 says

<source>:15:5: error: no matching function for call to 'f'
    f(B());
    ^
<source>:6:6: note: candidate template ignored: failed template argument deduction
void f(impl<D, I...> const&)
     ^

All three compilers in action: http://ift.tt/2qpQwjl

I want f(A()) to deduce D = A, I... = <> and f(B()) to deduce D = B, I... = A, which is then deducible as an instance of impl. My end goal is to detect type in impl's parameter pack that are themselves instances of impl. Am I going about this the wrong way?

C++11 - enable_if - function implementation outside of class definition

How can I implement function with template that have enable_if?

class Test
{
public:
    Test(){}
    ~Test(){}

    template<typename T, typename std::enable_if<std::is_integral<T>::value>::type>
    void do_something(T v);

    template<typename T, typename std::enable_if<std::is_floating_point<T>::value>::type>
    void do_something(T v);

};

How to implement do_something for different types outsice od class definition (i.e. in inline file)?

Trying to Return a string(concatenated) through recursion in a binary tree

I have all but given up completely. This is part of a Huffman Code exercise using binary trees.

My Encode() function will not work because my helper CharToCode() does not work. It always returns a blank line, instead of a binary number (to signify it exact location on the tree).

CharToCode(): nonmember recursive helper function to find an encoding from the codetree.

Here is what I must accomplish:

Build a path (in string 'pathSoFar', by concatenating a 0 or 1 as appropriate) as the function traverses the tree. When a leaf node is reached, if the leaf data value is the character being encoded, return the path; otherwise, this was not the correct path and return the empty string.

Assume that the function is being called correctly in the driver (main) file and that the constructor and load functions are correct. Here is what I have:

void HuffmanTree::Encode(std::istream& messageFile, std::ostream & out)
{
   char ch;
   std::string pathSoFar;
   std::string huffman;


   while (messageFile.get(ch))
   {
      huffman = CharToCode(ch, root, pathSoFar);
      out << pathSoFar;
   }
   out << std::endl;
}

std::string CharToCode(char ch, TreeNode* localRoot, std::string pathSoFar)
{
   std::string code;
   if(localRoot->info == ch)
      return pathSoFar;
   else
   {  
      if(localRoot->left != NULL)    
         return CharToCode(ch, localRoot->left, pathSoFar+'0');
      else if(localRoot->right != NULL)
         return CharToCode(ch, localRoot->right, pathSoFar+'1'); 
   }
   return "";
}

Default construction of deleted constructor with braced initializer list

Let's say that I want to disable the construction of class, then I can do the following (as per Best style for deleting all constructors (or other function)? ):

// This results in Example being CopyConstructible:
struct Example {
  Example() = delete;
};

or

struct Example {
  template <typename... Ts>
  Example(Ts&&...) = delete;
};

or

struct Example {
  Example(const Example&) = delete;
};

where the first example can still be copied if constructed (which the intention is to disable), but the second two will disable almost all methods for creating Example. If I default construct any of the above using an empty braced initializer list, then the instance is successfully constructed. In Meyer's Effective Modern C++ he gives the example (bottom of page 51):

Widget w3{}; // calls Widget ctor with no args

which I would thus expect to fail for the above Example classes i.e:

Example e{};

should not construct since it should call the deleted default constructor. However, it does, is usable, and if defined as the first case above, is also copyable. See live demo. My question is: Is this correct, and if so, why?

How to compile a program using make with C11 standard

I am using Ubuntu 14.04 I was compling OMNET++ but got an error

pythonexporter.cc: In member function ‘virtual void omnetpp::scave::PythonExporter::saveResults(const string&, omnetpp::scave::ResultFileManager*, const omnetpp::scave::IDList&, omnetpp::common::IProgressMonitor*)’:
pythonexporter.cc:261:5: error: ‘unique_ptr’ is not a member of ‘std’
 std::unique_ptr<RunList> tmp(runList);
 ^
pythonexporter.cc:261:28: error: expected primary-expression before ‘>’ token
 std::unique_ptr<RunList> tmp(runList);
                        ^
pythonexporter.cc:261:41: error: ‘tmp’ was not declared in this scope
 std::unique_ptr<RunList> tmp(runList);
                                     ^
make[2]: *** [/home/user/final_project/omnetpp-5.1/out/gcc-release/src/scave/pythonexporter.o] Error 1
make[2]: Leaving directory `/home/user/final_project/omnetpp-5.1/src/scave'
make[1]: *** [scave] Error 2
make[1]: Leaving directory `/home/user/final_project/omnetpp-5.1'
make: *** [allmodes] Error 2

I did some some research and found that I need to use C11 compiler I tried to change different options in configure.user file but still i am getting the same error. Here is my configure.user file

# configure.user
#
# This file contains additional input for 'configure'. It is read (sourced)
# during the configuration process. You are free to edit the settings in here.
#
# The settings in this file are all optional in the sense that they all
# have reasonable default values in the configure script.
#

#
# Edit here if you want to use a different compiler from the one autodetected
# by configure. Turns off the compiler autodetection.
#
CC=gcc
CXX=g++
CFLAGS=-O3 -std=c++0x -pg -D_DEBUG -g -c -Wall
CXXFLAGS=-O3 -std=c++0x -pg -D_DEBUG -g -c -Wall

#
# Set to "yes" if you want to use clang/clang++ instead of gcc/g++ when both
# compiler is installed.
PREFER_CLANG=yes

#
# Compiler optimization switches. There are two sets of switches,
# and the MODE variable ("debug" or "release") decides which one gets used.
# (Note: For maximum debugging info use switch -ggdb or -gstabs+3 when using gcc and gdb)
# With gcc, do NOT use --omit-frame-pointer (it crashes when coroutines and
# C++ exceptions (throw/catch) are used together)!
#
CFLAGS_DEBUG='-g -std=c++11 -Wall'
CFLAGS_RELEASE='-O2 -std=c++11 -DNDEBUG=1'

#
# Linker switches used for linking.
#
#LDFLAGS="-std=c++11"

#
# Set to "yes" to enable the Tcl/Tk based graphical runtime environment (Tkenv)
#
WITH_TKENV=yes

#
# Set to "yes" to enable the Qt based graphical runtime environment (Qtenv)
#
WITH_QTENV=yes

#
# Set to "yes" to use Qtenv as the default graphical runtime environment (instead of Tkenv)
#
PREFER_QTENV=yes

#
# Set to "yes" to enable OpenSceneGraph and support in Qtenv
#
WITH_OSG=yes

#
# Set to "yes" to enable osgEarth support in Qtenv (requires OpenScreenGraph enabled)
#
WITH_OSGEARTH=yes

#
# Set to "yes" to enable simulation executables to load NED files dynamically.
#
WITH_NETBUILDER=yes

#
# Set to "yes" to enable the parallel distributed simulation feature.
#
WITH_PARSIM=yes

#
# Set to "yes" to use SQLite as default file format for output vector and
# output scalar files. As of version 5.1, SQLite support is an experimental 
# feature.
#
# To try SQLite result files without changing the default, add the following
# lines into the omnetpp.ini files of your simulations (or specify the same 
# settings on the simulation command line, with the "--" prefix):
#
# outputvectormanager-class="omnetpp::envir::SqliteOutputVectorManager"
# outputscalarmanager-class="omnetpp::envir::SqliteOutputScalarManager"
#
PREFER_SQLITE_RESULT_FILES=no

#
# Set to "yes" to enable SystemC support. (Available only in the commecial version (OMNEST))
# Please note that SystemC is not supported on MAC OS X and on the MinGW compiler on Windows.
#
WITH_SYSTEMC=no

#
# Set to no if you want to create static OMNeT++ libraries. Can be overriden
# with "make SHARED_LIBS=no" but then simulation models also need to be built
# with "make SHARED_LIBS=no"
#
SHARED_LIBS=yes

#
# Compiler and linker options for Tcl/Tk
#
# You can explicitly tell 'configure' which compile switches (TK_CFLAGS)
# and linker switches (TK_LIBS) are needed to build an application with Tcl/Tk.
# Normally these settings are autodetected by 'configure', so you only need to
# edit here if autodetection doesn't work.
#
# With gcc, settings typically look like this:
#
# exaple:TK_CFLAGS="-I/usr/local/include"
# example:TK_LIBS="-L/usr/local/lib -ltk8.6 -ltcl8.6 -lX11"
#
# /usr/local/include should be replaced with the directory where tcl.h and tk.h
# live. If they are in two different directories, use two -I switches.
#
# /usr/local/lib should be replaced with the directory that contains the Tcl/Tk
# library files (something like libtcl86.so, libtk8.6.a etc; search for libtcl*
# and libtk* to find them.) The -l options contain the library names: the
# library file names, with the leading 'lib' and trailing '.so*' or '.a*' cut
# off. Sometimes you need to explicitly link with the X11 libraries too, in that
# case add -lX11 to TK_LIBS.
#
# With MinGW I use the following:
# Note that we are using the "bin" directory as the LIB dir.
# i.e. directly linking to the DLLs instead of the importlibs in the "lib" directory.
#
#TK_CFLAGS="-I/c/Tools/Tcl-8.6.0/include"
#TK_LIBS="-L/c/Tools/Tcl-8.6.0/bin -ltk84 -ltcl84"
# or:
#TK_CFLAGS="-I$MSYS/include/tcl8.6"
#TK_LIBS="-L$MSYS/bin -ltk86 -ltcl86"

#
# It is possible to have the Tcl files embedded into the compiled     OMNeT++
# libraries and executables. This can be useful if you want to ship
# self-contained standalone executables which do not rely on external
# Tcl scripts. This option is available for Tkenv.
#
EMBED_TCL_CODE=yes

#
# Compiler and linker options for Qt
#
# If you wish to use a custom Qt bundle (for example downloaded from the
# official Qt web page, or built from source) instead of the one installed
# on your system as the default (most likely by the package manager), set
# this variable to the 'bin' directory of that bundle, where qmake is.
# Leave it empty or commented out to use the default Qt installation.
# Please note that on Windows and macOS it is highly recommended to just
# use the Qt bundle included in the OMNeT++ release, and not change this.
#
#QT_PATH="/home/user/Qt/5.7/gcc_64/bin"
#
# You can also explicitly tell 'configure' what compiler options (QT_CFLAGS)
# and linker switches (QT_LIBS) are needed to build an application with Qt
# support. Normally these are autodetected by 'configure' using the QT_PATH
# variable above, so you only need to edit here if autodetection doesn't work.
#
#QT_CFLAGS=
#QT_LIBS=

#
# OpenSceneGraph libraries we want to use. Leave empty for autodetection
# or specify some invalid value (like "no" to explicitly disable     OpenSceneGraph)
# At least the following libraries must be found: osg osgGA osgViewer     osgQt OpenThreads
#
#OSG_LIBS=

# osgEarth libraries to be used. Leave empty for autodetection.
# At least the following libraries are required: osgEarth osgEarthUtil
#
#OSGEARTH_LIBS=

#
# ZLib is a compression library needed by libxml2 and Tkenv's png support.
#
# On MinGW we use the following (dynamically linking against the DLL)
#
#ZLIB_CFLAGS="-I/c/Tools/zlib-1.2.3/include"
#ZLIB_LIBS="-L/c/Tools/zlib-1.2.3/bin -lzlib1"
# or:
#ZLIB_CFLAGS="-I$MSYS/include"
#ZLIB_LIBS="-L$MSYS/lib -lz"

#
# Compiler flags used to compile JNI code.
# -fno-strict-aliasing is needed for gcc when using -O2 otherwise Java
# native calls don't work
#
#JAVA_CFLAGS=-fno-strict-aliasing

#
# Compiler and linker options for MPI (optional component).
# On LAM/MPI, typing `mpic++ -showme' can give you a hint about MPI_LIBS.
#
# If commented out, the configure script will try to autodetect it
#
#MPI_CFLAGS="-I /usr/include"
#MPI_LIBS="-pthread -llammpio -llammpi++ -llamf77mpi -lmpi -llam -laio -laio -lutil"
#MPI_LIBS="-lmpi++ -lmpi"   #SGI

#
# Compiler and linker options for Expat (optional component)
#
# With MinGW I use the following:
#   EXPAT_CFLAGS="-I/d/home/tools/expat-1.95.2/Source/lib"
#   EXPAT_LIBS="-L/d/home/tools/expat-1.95.2/libs -lexpat"
# If commented out, the configure script will try to autodetect it
#
#EXPAT_CFLAGS=
#EXPAT_LIBS=

#
# Compiler and linker options for LIBXML (optional component)
#
# With MinGW I use the following:
#  LIBXML_CFLAGS="-I/c/Tools/libxml2-2.6.20.win32/include -I/c/Tools/iconv-1.9.1.win32/include"
#  LIBXML_LIBS="-L/c/Tools/libxml2-2.6.20.win32/bin -lxml2 -L/c/Tools/iconv-1.9.1.win32/lib -liconv"
# or:
#  LIBXML_CFLAGS="-I$MSYS/include"
#  LIBXML_LIBS="-L$MSYS/bin -lxml2 -L$MSYS/bin -liconv"
# If commented out, the configure script will try to autodetect it
#

#
# Compiler and linker options for Akaroa (optional component)
#
# With MinGW I use the following:
#  AKAROA_CFLAGS="-I/d/home/tools/akaroa-2.7.4/include"
#  AKAROA_LIBS="-L/d/home/tools/akaroa-2.7.4/lib -lakaroa"
# If commented out, the configure script will try to autodetect it
#
#AKAROA_CFLAGS=
#AKAROA_LIBS=

#
# The following OMNETPP_* variables don't need to be touched unless
# you want to relocate parts of the package (e.g. put libraries to
# /usr/lib, include files to /usr/include/omnetpp, and so on).
#
#OMNETPP_SRC_DIR="$OMNETPP_ROOT/src"
#OMNETPP_SAMPLES_DIR="$OMNETPP_ROOT/samples"
#OMNETPP_BIN_DIR="$OMNETPP_ROOT/bin"
#OMNETPP_INCL_DIR="$OMNETPP_ROOT/include"
#OMNETPP_LIB_DIR="$OMNETPP_ROOT/lib"

#
# Some more OMNeT++ variables. They select the programs opp_makemake-generated
# makefiles will use. (They get default values if commented out.)
#
#MSGC="$OMNETPP_BIN_DIR/opp_msgc"
#SMC="$OMNETPP_BIN_DIR/opp_smc"

#
#
# Override the following setting if you have additional icons somewhere else.
#
# OMNETPP_IMAGE_PATH="./images;./bitmaps;$OMNETPP_ROOT/images"

Reading in from file with modern c++ - data is not stored

maybe I get something wrong with shared_pointers or there is some basic shortcoming of mine but I couldn't get this right. So I want to read in some data from a file. There are position and momentum data on each line of the data file and the first line stores the number of data points.

I need to read this in to my data structure and for some reason my graph would not fill, although the data reads in correctly.

const int dim = 3; // dimension of problem

template <typename T, typename G>
// T is the type of the inputted locations and G is the type of the 
// distance between them
// for example: int point with float/double distance
struct Node{

    std::pair< std::array<T, dim>,std::pair< std::array<T, dim>, G > > pos; // position
    std::pair< std::array<T, dim>,std::pair< std::array<T, dim>, G > > mom; // momentum
    // a pair indexed by a position in space and has a pair of position
    // and the distance between these points

};

template <typename T, typename G>
struct Graph{

    int numOfNodes;
    std::vector< Node<T,G> > nodes;

};

This is the data structure and here's my read function (std::cout-s are only for testing):

template <typename T, typename G>
std::istream& operator>>(std::istream& is, std::shared_ptr< Graph<T,G> >& graph){

    is >> graph->numOfNodes; // there's the number of nodes on the first line of the data file
    std::cout << graph->numOfNodes << "\n";

    for(int k=0; k<graph->numOfNodes; k++){

        Node<T,G> temp;

        for(auto i : temp.pos.first){
            is >> i;
            std::cout << i << "\t";
        }

        std::cout << "\t";

        for(auto i : temp.mom.first){
            is >> i;
            std::cout << i << "\t";
        }

        std::cout << "\n";

        graph->nodes.push_back(temp);

    }

    return is;

 }

I have an output function as well. So if I output the graph which I intended to fill during read-in is zeroed out. Number of nodes os correct however positions and momente are all zeroed out. What did I do wrong? Thanks in advance.

vendredi 28 avril 2017

Why does this if conditional with string.length() evaluate inconsistently?

int main()
{
    std::string string = "hi";

    std::cout << "Enter index: ";
    int index;
    std::cin >> index;

    if(index < string.length())
        std::cout << index << " is less than " << string.length();
    else
        std::cout << index << " is greater than " << string.length();
}

The string length is 2. When I enter in a negative number, say -3, the if statement evaluates to false and executes else statement & prints -3 is greater than 2. If I enter in a positive number still less than the string length, say 1, if statement evaluates to true & prints 1 is less than 2.

Question:

So while -3 and 1 are both numbers less than string.length(), why is it that only 1 evaluate to true whereas -3 does not in this if statement?

data member access in template programming

I am creating a template class with specialized behavior for two different sizes, and general behavior in general class as below::

template<typename T, size_t DIM>
class Dataset
{
public:
    // all the constructors are defaulted
    // all the general behavior implementation

    std::vector<T> _data;
};

Given the flow of data for the class below, I am expecting to have access to _data vector, right ?!

template<typename T>
class Dataset<T, 1>
{
public:
    T & operator()(const size_t & index)
    {
        return _data[index];
    }
};

however, I get the compilation error of _data couldn't be resolved. What is the problem here ?!! Thanks

Getting an error - "undefined reference to 'logOn(int, int &)'"

I am working on this program (below) and keep getting the "undefined reference to 'logOn(int, int &)'". It also does this when I am calling the functions for logOn, logOff, and search when they are called. My code is not 100% correct, but I am trying to figure out my error before I can move on with the rest of the project.

    #include <iostream>#include <iostream>

    int menu(int &);
    void logOn(int, int &);
    int getUserID(int &);
    int getLabNum(int &);
    int getStation(int &, int &);
    void logOff(int, int &);
    void search(int, int &);

    int main()
    {
        int userChoice = 0;
        menu(userChoice);
        int userID = 0;

        int lab[4][6];
        if (userChoice == 1)
        {
            logOn(lab[4][6], userID);
        }
        else if (userChoice == 2)
        {
            logOff(lab[4][6], userID);
        }
        else if (userChoice == 3)
        {
            search(lab[4][6], userID);
        }

        return 0;
    }

And here are the three functions:

    void logOn(int lab[4][6], int &userID)
    {
        int labNum, station = 0;

        getUserID(userID);
        getLabNum(labNum);
        getStation(station, labNum);

        int *lab_ptr = &labNum;
        int *station_ptr = &station;
        int *user_ptr = &userID;

        for (int i = 1; i < 5; i++)
        {
            std::cout << "Lab " << i << ": ";
            if (i == 1)
            {
                for (int j = 1; j < 6; j++)
                {
                    lab[*lab_ptr][*station_ptr] = {*user_ptr};
                }
            } 
        }
    }

    void logOff(int lab[4][6], int &userID)
    {
        std::cout << "Please enter your student ID: ";
        std::cin >> userID;
        std::cout << std::endl;
        for(int i = 1; i < 5; i++)
        {
            for(int j = 1; j < 7; j++)
            {
                if(lab[i][j] == userID)
                {
                    lab[i][j] = 0;
                }
            }
        }
    }

    void search(int lab[4][6], int &userID)
    {
std::cout << "Please enter the User ID you would like to find: ";
std::cin >> userID;

for(int i = 1; i < 5; i++)
{
    if (i == 1)
    {
        for(int j = 1; j < 6; j++)
        {
            if(lab[i][j] == userID)
            {
                std::cout << "This user is in lab " << i << " and at station " << j << std::endl;
                return;
            }
        }
    }
    etc....

I think it has something to do with the lab[4][6] in the headers, but I saw another program with it and it ran with no problem. Any help would be appreciated!

Why is the destructor behaving so strange?

I am a first grade student and this is my first time asking in stackoverflow.Recently my professor sent me a piece of code asking me to find out what was wrong with it.

#include <iostream>
#include <cstring>

using namespace std;

class A
{
public:
 A(int c);
 ~A();
 int code;
 char *name;
};

A::A(int c)
{
 code = c;
 name = new char[50];
 if(name == 0)
  {
   cout << "Unavailable memory" << endl;
   exit(1);
  }
}

A::~A()
{
 cout << "Delete pointer to " << name << endl;
 delete [] name;
}

int main(void)
{
 A a1(100), a2(200);
 strcpy(a1.name, "Mike");
 a2 = a1;
 strcpy(a2.name, "Peter");
 cout << a1.name << endl;
 return 0;
} 

As far as i know,the program should crash after the destructor of object a2 is called because the destructor of object a1 will try to delete the same already deleted memory.After this line:

a2 = a1;

the char* of object a2 points at the same address that the pointer of object a1 points,thus creating a mess upon calling the destructor.What really doesn't make sense to me is the fact that the program runs perfectly fine right now without any crashes,however yesterday the program crashed with the following output on console:

Delete pointer to Peter
Delete pointer to [insert strange characters here]
Process exited with return value 344233377

So im asking if someone could enlighten me regarding the strange behaviour of this program.BTW is it better to use operator overloading like this

#include <iostream>
#include <cstring>

using namespace std;

class A
{
 public:
 A(int c);
 ~A();
 A operator=(A a1);
 int code;
 char *name;
};

A::A(int c)
{
 code = c;
 name = new char[50];
 if(name == 0)
  {
   cout << "Unavailable memory" << endl;
   exit(1);
  }
}

A::~A()
{
 cout << "Delete pointer to " << name << endl;
 delete [] name;
}

A A::operator=(A a1)
{
 *name=*a1.name;
 code=a1.code;
 return *this;
}

int main()
{
 A a1(100), a2(200);
 strcpy(a1.name, "Mike");
 a2 = a1;
 strcpy(a2.name, "Peter");
 cout << a1.name << endl;
 return 0;
} 

or should i use something like a copy constructor?

Seg fault while assigning memory to pointer array

I get seg fault when I try to assign memory to a object pointer (trying to dynamically create a 1D array). What am I doing wrong? I first I though it must be due to the kind of type T being used, but this happens even for native data types such as int. I come from a C background (new to C++), where I would have done memory allocation using malloc/calloc.

e.g.:

template <typename T>
struct test {
   T *element;
}

class Foo {

    Foo() {
    //empty
    }
    test *t;

    template <typename T>
    void setup(int n) {
      t->element = new T[n];
    }

    void run() {
      setup(10);
    }
}

Is there a way to simple 'commit' threads to raspberry pi

I'd like to use raspberry pi as a processing unit of the computer, for multiprocessing purposes, having a graphic interface at the computer and all heavy processes running at the device. Preferentially using C++.

I understand there I could use a Message Passing Interface for this, but there's any better or simpler way?

Select a constructor based on template parameters

I would like to alter a classes functions based on the value of a template parameter. Using this post, all of the member functions can be written differently based on the template parameter and that works great. The problem is that example is using the return type of the function so it doesn't work with constructors. Based on this post and this post, I have tried:

// I'm using gcc 4.8.4 so have to define enable_if_t myself although 
// I guess it's not really needed

template< bool B, class T = void >
using enable_if_t = typename std::enable_if<B,T>::type;

template<class T, std::size_t CAPACITY, bool USE_THREADS = true>
class C_FIFO
{
public:
//...other ctor defs

    template<bool trigger = USE_THREADS, enable_if_t<not trigger>* = nullptr >
    C_FIFO(const C_FIFO& that):
        m_buf_capacity(CAPACITY + 1), m_in_ctr(0), m_out_ctr(0), m_wait(true)
    {
        m_buffer_data = that.m_buffer_data;
        m_in_ctr = that.m_in_ctr;
        m_out_ctr = that.m_out_ctr;
        m_wait    = that.m_wait.load();
    }
// more stuff
}

and

template<class T, std::size_t CAPACITY, bool USE_THREADS = true>
class C_FIFO
{
public:
//...other ctor defs

    template<bool trigger = USE_THREADS>
    //enable_if_t<not trigger>
    C_FIFO(const C_FIFO& that, enable_if_t<not trigger, bool> t = false):
        m_buf_capacity(CAPACITY + 1), m_in_ctr(0), m_out_ctr(0), m_wait(true)
    {
        m_buffer_data = that.m_buffer_data;
        m_in_ctr = that.m_in_ctr;
        m_out_ctr = that.m_out_ctr;
        m_wait    = that.m_wait.load();
    }
// other stuff
}

but it both cases the compiler tries to use the default copy constructor which is deleted because the class contains non-copyable types (mutex and condition variable). Both cases seem like they should work, but apparently I'm not seeing something :). Any pointers (no pun intended) would be appreciated.

Fastest way to check if a value is all zeros (64-bit processor)

I want to write a function that can determine if any value is made completely of zeroes.

Here was my initial thought:

bool isZero(T* value) {
    char* ptr = reinterpret_cast<char*>(value);
    char sum = 0;
    for (size_t i = 0; i < sizeof(T); ++i) {
        sum |= ptr[i];
    }
    return sum == 0;
}

But then I thought that maybe on a 64-bit processor it will be faster to check 8 bytes at a time, instead of checking them one-by-one.

So I came up with this:

bool isZero(T* value) {
    uintptr_t* ptr = reinterpret_cast<uintptr_t*>(value);
    uintptr_t sum = 0;
    size_t i = 0;
    for (; (i + 1) * sizeof(uintptr_t) <= sizeof(T); ++i) {
        sum |= ptr[i];
    }
    uintptr_t leftover = ptr[i] >> (8 * ((i + 1) * sizeof(uintptr_t) - sizeof(T)));
    return (sum | leftover) == 0;
}

Can anybody shine some light on which of these might be faster? I'm not experienced enough to know how to properly benchmark this.

Class with static linkage

If I recall correctly, static linkage means that a variable or function is local to its compilation unit. Meaning that there could be variables or functions with the same name and parameters in other compilation units.

I want this for a class.

Let's say I have multiple compilation units that need to ensure proper deletion at exit. So I use atexit handlers. But every compilation unit should put its own atexit-handler into place.
I did this by making a class like this:

class Init {
private:
    static Init* self;

    Init() {
        std::atexit(Init::cleanup);
    }

    static void cleanup() {
        // Do cleanup
    }
};
Init* Init::self = new Init;

But if I have multiple classes called Init in various CUs the linker gets confused. And the compiler won't let me do static class Init {...}.

How do I archive my cleanup (if possible with classes that are called Init)?

How to free memory by pointer a (placement new)?

I can't understand how to properly free the memory by pointer a

MemoryManager mm;
char* a = new(mm) char[len];

C++11: Ensure that GUI calls are made from the main thread

I have a multithreaded GUI program where I need to queue events that are called from another thread. I would like to make sure that GUI calls are primarily made from the main thread. Does the call std::this_thread::get_id() preserve its value throughout the whole application?

I'm planning something like this:

GuiElement
{
    std::thread::id main_thread_id;
public:
    GuiElement()
    {
        main_thread_id = std::this_thread::get_id();
    }

    void thread_check() 
    {
        if(std::this_thread::get_id() != this->main_thread_id) 
        {
            throw std::runtime_error("You can't call this from a different thread");
        }
    }

    void remove_element(const std::string& element_name)
    {
        this->thread_check();
        //do stuff
    }
};

Is this the right thing to do? Or is there something better to achieve this functionality?

Although unlikely, but I'm worried that a thread id might change for some reason. Can this happen?

Cmake linking error between cu and cpp files

I feel like I have tried everything that I could come up with and what the web has to say and I'm still stuck with the same linking error so I hope someone here can help.

The problem is I have a method in a .cu file which is called from the main.cpp file, and the linker tells me that there is an undefined reference to the method. I'm using Cmake 3.3, Cuda 7.5, gcc 4.8.5.

I do need a templated method, and I do need separable compilation since (what isn't show here) NVCC is unable to compile some other code (ITK) that will be called in main(), and I do need c++11.

Any suggestions? It's probably just me overlooking something...

NOTE I have tried a couple of things, like using cuda_compile(...) to make cuda object files, and set(CUDA_SEPARABLE_COMPILATION ON), but these don't change the error at all... so I'm a little stuck.

The barebones code that produces the linking error is the following:

main.cpp

#include <iostream>

#include "ThrustCode.h"

using namespace std;

#define T float

int main() {
    cout << "Hello, World!" << endl;
    ThrustCode<T> t;
    t.test(10);
    return 0;
}

--

ThrustCode.h

#ifndef TESTCUDACPP_THRUSTCODE_HPP
#define TESTCUDACPP_THRUSTCODE_HPP

template <typename T>
class ThrustCode {
public:
    void test(T n);

};

#endif //TESTCUDACPP_THRUSTCODE_HPP

--

ThrustCode.cu

#include "ThrustCode.h"

template <typename T>
void ThrustCode<T>::test(T n) {
}

--

CMakeLists.txt

cmake_minimum_required(VERSION 3.3)

project(TestCudaCpp)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/Cmake)

find_package(CUDA QUIET REQUIRED)
set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS};-gencode arch=compute_52,code=sm_52)

# this line is supposed to have the path to cuda libraries
# (specifically it is needed for the line at `target_link_libraries` below which imports curand
#  to generate random numbers on the host, when the program is compiled to run strictly on CPU).
link_directories(
        /usr/local/cuda/lib64
)

set(SOURCE_FILES
        ThrustCode.cu
        main.cpp)

cuda_add_executable(TestCudaCpp ${SOURCE_FILES})
target_link_libraries(TestCudaCpp)

This results in

[ 33%] Building NVCC (Device) object CMakeFiles/http://ift.tt/2ppCVsO
Scanning dependencies of target TestCudaCpp
[ 66%] Building CXX object CMakeFiles/http://ift.tt/2pGlVlg
[100%] Linking CXX executable TestCudaCpp
CMakeFiles/http://ift.tt/2pGlVlg: In function `main':
..<some path>../TestCudaCpp/main.cpp:12: undefined reference to `ThrustCode<float>::run(float)'
collect2: error: ld returned 1 exit status
gmake[2]: *** [TestCudaCpp] Error 1
gmake[1]: *** [CMakeFiles/TestCudaCpp.dir/all] Error 2
gmake: *** [all] Error 2

terminate called after throwing an instance of 'std::system_error' threadpool

terminate called after throwing an instance of 'std::system_error'l

what(): Invalid argument

#ifndef CPP_PLAZZA_EXAMPLE_H
#define CPP_PLAZZA_EXAMPLE_H

#include <thread>
#include <vector>
#include <list>
#include <memory>
#include <functional>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <iterator>
#include <tuple>

class ThreadPool
{
 public:
  ThreadPool(size_t numThreads);
  virtual ~ThreadPool();
  void executeJob(std::function<void()> job, std::function<void()> notificationJob);
  void wait_for_done();
 private:
  void loop();
  std::pair<std::function<void()>, std::function<void()> > getNextJob();
  std::vector<std::thread> m_workers;
  std::list<std::pair<std::function<void()>, std::function<void()> > > m_jobs;
  std::mutex m_lockJobsList;
  std::condition_variable m_notifyJob;
  std::atomic<bool> m_bTerminate;
  class Terminated: public std::runtime_error
  {
   public:
    Terminated(const std::string& what): std::runtime_error(what) {}
  };

};

#endif //CPP_PLAZZA_EXAMPLE_H

and here it is my .cpp

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


ThreadPool::ThreadPool(size_t numThreads):
 m_workers(numThreads), m_bTerminate(false) {
  m_workers.reserve(numThreads);
  for (size_t i = 0; i < numThreads; i++) {
    this->m_workers.emplace_back(&ThreadPool::loop, this);
  }
  /*for (std::vector<std::thread>::iterator it = this->m_workers.begin(); it != this->m_workers.end(); it++)
    assert(std::next(it, 1) ==);*/
}

ThreadPool::~ThreadPool() {
    {
        std::unique_lock<std::mutex> lockList(m_lockJobsList);
        m_bTerminate = true;
        m_notifyJob.notify_all();
    }

/*  for(std::vector<std::thread>::iterator it = m_workers.begin(); it != m_workers.end(); it++) {
    it->join();
  }*/
  std::this_thread::sleep_for(std::chrono::seconds(5));
}

void ThreadPool::executeJob(std::function<void()> job, std::function<void()> notificationJob) {
    std::unique_lock<std::mutex> lockList(m_lockJobsList);
  m_jobs.emplace_back(std::pair<std::function<void()>, std::function<void()> >(std::move(job), std::move(notificationJob)));
  std::cout << m_jobs.size() << std::endl;
    m_notifyJob.notify_one();
}

std::pair<std::function<void()>, std::function<void()> > ThreadPool::getNextJob() {
    std::unique_lock<std::mutex> lockList(m_lockJobsList);

    while(!m_bTerminate)
    {
        if(!m_jobs.empty())
        {
      std::cout << "ici" << std::endl;
            std::pair<std::function<void()>, std::function<void()>> job = std::ref(m_jobs.front());
            m_jobs.pop_front();
            return job;
        }

        m_notifyJob.wait(lockList);
    }

    throw Terminated("Thread terminated");
}

void        func1() {
  std::cout << "BONJOUR je suis func1" << std::endl;

}

void ThreadPool::loop()
{
    try
    {
        for(;;)
        {
      std::pair<std::function<void()>, std::function<void()> > job = getNextJob();
      job.first();
      job.second();
        }
    }
    catch(Terminated& e)
    {
    }
}



void        func2() {
  std::cout << "AUREVOIR je suis func2" << std::endl;

}

void        ThreadPool::wait_for_done()
{
  std::cout << "nb workers = " << this->m_workers.size() << std::endl;
  int i = 0;
  for(std::vector<std::thread>::iterator it = m_workers.begin(); it != m_workers.end(); ++it) {
    std::cout << "je suis i :  " << i << std::endl;
    i++;

    (*it).join();
  }
}

int     main()
{
  ThreadPool        pool(6);

  pool.executeJob(func1, func2);
  pool.wait_for_done();
}

I think that my error is I join several time on one thread but how to fix it ?

Compilation line :

g++ -Wall -Werror -W -Wextra example.cpp -pthread -std=c++11

Chrono precision parameterizable function?

I am writing a utility function that returns the current time in ISO format. However, I would like to be able to specify the precision:

2017-04-28T15:07:37Z        //s
2017-04-28T15:07:37.035Z    //ms
2017-04-28T15:07:37.035332Z //us

I have working code to do this, however, I can't seem to find a way to make it generic:

string getISOCurrentTimestamp_us()
{
    char iso_buf[30];

    auto now = chrono::high_resolution_clock::now();
    auto s = chrono::duration_cast<chrono::seconds>(now.time_since_epoch());
    time_t seconds = (time_t) s.count();
    strftime(iso_buf, sizeof(iso_buf), "%FT%T", gmtime(&seconds));

    string iso_timestamp(iso_buf);

    auto us = chrono::duration_cast<chrono::microseconds>(now.time_since_epoch());
    auto us_diff = us - chrono::duration_cast<chrono::microseconds>(s);
    char buffer[8];
    std::snprintf(buffer, sizeof(buffer), ".%06d", (int) us_diff.count());

    iso_timestamp += string(buffer);
    iso_timestamp += "Z";

    return iso_timestamp;
}

As you can see, this one only returns the microsecond version. I have a separate function using chrono:milliseconds for the millisecond version. Seems like a DRY violation to have so much similar code when the only difference is the duration template parameter and the zero-padding.

Yet being able to specify the duration is tricky. I think I'm not quite understanding function templates, because I tried something like getISOCurrentTimestamp<chrono::microseconds>(), to no avail:

template <class T>
string getISOCurrentTimestamp() {
    ...
    auto t = chrono::duration_cast<T>(now.time_since_epoch());
    auto t_diff = t - chrono::duration_cast<T>(s);
}

Another problem is deducing the amount of zero padding based on T which doesn't seem trivial either (i.e. microseconds should be zero-padded up to 6, milliseconds up to 3, etc.

How can I make this ISO String function generic? Am I approaching this the wrong way?

nonatomic operations on std::atomic

I have a huge array of pointers and I need to use them atomically. C++11 provides std::atomic class and relative functions for these purposes, and it is quite fine for me in general. But at the initialization and cleanup stages I do not need it to be atomic, it is known that only one thread will operate the data. It would be easy if atomic pointers would be implemented as plain volatile variables like it actually was before C++11, but now here is my problem: std::atomic forces me to use only atomic operations. Is there a way of nonatomic use of std::atomic?

why I get an "use of delete function" from a class thats inherits from QAbstractListModel

I am trying to implement a ListView, so far I implement a class named PacientModel that inherits of QAbstractListModel.

#ifndef PACIENTMODEL_H
#define PACIENTMODEL_H

#include <QAbstractListModel>

class PacientModel : public QAbstractListModel {
    Q_OBJECT

public:
    enum PacientRole {
        CIRole,
        NameRole,
        LastNameRole
    };
    Q_ENUM(PacientRole)

    PacientModel(QObject * parent = nullptr);

    int rowCount(const QModelIndex & = QModelIndex()) const;
    QVariant data (const QModelIndex &index, int role = Qt::DisplayRole) const;
    QHash<int, QByteArray> roleNames() const;

    Q_INVOKABLE QVariantMap get(int row) const;
    Q_INVOKABLE void append (const QString &CI, const QString &name, const QString &lastName);
    Q_INVOKABLE void set (int row, const QString & CI, const QString &name, const QString &lastName);
    Q_INVOKABLE void remove (int row);

private:
    struct Pacient {
        QString CI;
        QString name;
        QString lastName;
    };

    QList<Pacient> m_pacients; };

#endif // PACIENTMODEL_H

I also have the implementation of the ListView but when I compile the code I got this error.

C:\Qt\Qt5.8.0\5.8\android_armv7\include\QtCore\qmetatype.h:765: error: use of deleted function 'PacientModel::PacientModel(const PacientModel&)' return new (where) T(*static_cast(t));

How can I resolve this, any help will be very usefull. Thanks in advance

Is it possible to switch to a different base class constructor at runtime?

Suppose I'm writing Derived and have to inherit from Base, which I don't control and has two separate constructors and a deleted copy and move constructors:

struct Base {
    Base(int i);
    Base(const char *sz);
    Base(const Base&) = delete;
    Base(const Base&&) = delete;
};

struct Derived {
    Derived(bool init_with_string);
};

Now, depending on the value of another_param I have to initialize my base class using either a constructor or the other; if C++ was a bit less strict it would be something like:

Derived::Derived(bool init_with_string) {
    if(init_with_string) {
        Base::Base("forty-two");
    } else {
        Base::Base(42);
    }
}

(this would also be useful for all the cases where it's cumbersome to calculate values to pass to base class constructors/fields initializers in straight expressions, but I'm digressing)

Unfortunately, even if I don't see particular codegen or object-model obstacles to this kind of thing, this isn't valid C++, and I cannot think of easy workaround.

Is there some way around this that I'm not aware of?

What is std::invoke in c++?

I've just reading about std::thread and std::bind which I've faced with callable concept and std::invoke.I read about std::invoke in cppreference but i don't understand what it said. here is my question: what is std::invoke, std::function, std::bind and callable concept? and what is relationship between them?

How to avoid calling copy constructor of the elements in a vector [duplicate]

This question already has an answer here:

In the C++ example below:

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

using namespace std;

struct foo{
  foo(int i) : s( to_string(i) ){ cout << "init foo : "+s+"\n"; }
  foo(foo&& f) : s( move(f.s) ){ cout << "move foo : "+s+"\n"; }
  foo(const foo& f) : s(f.s){ cout << "copy foo : "+s+"\n"; }
  string s;
};

int main(){
  vector<foo> f;
  for(int i=0; i<5; i++){
    cout << f.size() << endl;
    f.push_back( foo(i) );
  }
}

The output is :

0
init foo : 0
move foo : 0
1
init foo : 1
move foo : 1
copy foo : 0
2
init foo : 2
move foo : 2
copy foo : 0
copy foo : 1
3
init foo : 3
move foo : 3
4
init foo : 4
move foo : 4
copy foo : 0
copy foo : 1
copy foo : 2
copy foo : 3

It seems that std::vector will call the copy constructor for all foo elements in the container every time it changes its capacity.

Is there any way to force the use of move constructor instead of the copy constructor?

I do not know the final size of the vector so vector::reserve is not a possible choice.

How to correctly use std::normal_distribution in C++11?

I want to get random float numbers in the range [0.0,1.0], so most of these numbers should be around 0.5. Thus I came up with the following function:

static std::random_device __randomDevice;
static std::mt19937 __randomGen(__randomDevice());
static std::normal_distribution<float> __normalDistribution(0.5, 1);

// Get a normally distributed float value in the range [0,1].
inline float GetNormDistrFloat()
{
    float val = -1;
    do { val = __normalDistribution(__randomGen); } while(val < 0.0f || val > 1.0f);

    return val;
}

However, calling that function 1000 times leads to the following distribution:

0.0 - 0.25 : 240 times
0.25 - 0.5 : 262 times
0.5 - 0.75 : 248 times
0.75 - 1.0 : 250 times

I was expecting the first and last quarter of the range to show up much fewer than what is shown above. So it seems I am doing something wrong here.

Any ideas?

Can the C++ struct aggregate initialisation be used to create temporary instance?

To quickly initialise small structs I often use the aggregate initialisation to keep the code small and simple:

struct Foo {
    int a;
    int b;
    int c;
};
Foo temp = {1, 2, 3};

I would assume this should also work to create a temporary instance which can be passed as function argument:

void myFunc(Foo foo) {
    // ...
}

Is this possible? How is the exact syntax to use this feature?

myFunc({1, 2, 3}); // ???
myFunc(Foo {1, 2, 3}); // ???

Getting the destination port of incoming UDP packet

I've read through the ip man page along with the socket man page, all I could find was the destination IP address within the IP_PKTINFO control message in the header, there seems to be no way of pulling the destination port from the packet's header. Or is there?

If not, is there any way to get the port from the socket a packet has arrived to?

Is my wait - notify mechanism using std::mutex correct?

I started using std::mutexes to stop a thread and wait for another thread to resume it. It works like this:

Thread 1

// Ensures the mutex will be locked
while(myWaitMutex.try_lock());
// Locks it again to pause this thread
myWaitMutex.lock();

Thread 2

// Executed when thread 1 should resume processing:
myWaitMutex.unlock();

However I am not sure if this is correct and will work without problems on all platforms. If this is not correct, what is the correct way to implement this in C++11?

Could anyone help me with the pseudocode? I will do the coding myself. I actually dont know where to begin

Objectives: Design a comprehensive program that utilizes inheritance and polymorphism. Details (Changes are displayed in blue)  This project will use classes to create a doubly linked list  The seating arrangement for each auditorium will be stored in separate files. These files will be named A1.txt, A2.txt and A3.txt for auditorium 1, 2 and 3 respectively.  Each line in the file will represent a row in the auditorium. The number of rows in each auditorium is unknown to you.  The number of seats in each row of a single auditorium will be the same. For example, if the first line of the file has 15 seats, then every subsequent row in the theater will also have 15 seats. This does not mean that each auditorium has the same number of seats in each row. One auditorium may have 15 seats per row and another may have 20 seats.  Empty seats are represented by a pound sign (#).  Reserved seats are represented by a period (.).  Each file should be read into memory and stored in a linked list o For each auditorium, you will have 1 linked list (instead of the 2 linked lists of project 3) o The list should be sorted by row and seat number – all row 1 seats grouped together in order by seat, then row 2, etc.  Ticket prices are as follows: o Adult - $7.00 o Senior - $5.00 o Child - $3.00  If the user is reserving seats, ask the user for the row and seat number of each seat. If all seats selected are available, reserve the seats. o The seats selected by the user do not have to be consecutive o If all of the desired seats are not available, offer the user the best available consecutive seats for the number of tickets desired in the entire auditorium. The best available seats are the seats closest to the center of the auditorium.  Think of the distance between 2 points  For simplicity, use the distance between the first seat of the section and the center.  In the event of a tie for distance, the row closest to the middle should be selected.  You may develop this piece any way that you see fit. Please try to be as efficient as possible with the memory. o If the user declines the best available seats, return the user to the main menu. o If the user accepts the best available seats for that row, reserve them.  Tickets can only be reserved the day of the screening and all screenings are at 7 PM that night. There is no need to worry about multiple screenings or reserving seats on a specific day.  At the end of the program, overwrite the original files with the new information Classes The members to be included in each class are listed below. All classes should have an overloaded constructor, mutators and accessors. Other functions may be added to the class. Please

1.


remember that class functions should be generic enough to be used in any situation. Functions that solve a specific problem for this project should be defined in main rather than the class.  Linked List o Head (Node pointer) o Tail (Node pointer) o overloaded [] operator o overloaded += operator  Base Node (abstract) o Row (integer) o Seat (integer)  Reservation Node - Inherited from base node o Reservation status (Boolean) o Next (Node pointer) o Prev (Node pointer) o Overloaded << operator o Overloaded >> operator Overloaded Operators For all overloaded operators, include comments at the top of main.cpp including line numbers where each operator is used  += operator o Adds a node to the end of the linked list  [] operator o Treat the linked list like an array o First node will be [0] o Return a pointer to the node indicated inside the brackets  >> operator o Read the symbol from the file o Store correct value for reservation status based on symbol read in file  << operator o Print out correct symbol based on reservation status User Interface and Input: Present a user-friendly menu system for the user to reserve seats. 1. Reserve Seats 2. View Auditorium 3. Exit Although in reality the user would likely only make one purchase, for testing purposes, assume the user will repeat the ticket buying process until they decide to quit. After the user has selected a non-exit option, present the user with a menu to select the auditorium. 1. Auditorium 1 2. Auditorium 2 3. Auditorium 3 Once the auditorium has been selected, display the current seating availability for that auditorium. An example seating chart is provided below for an auditorium with 5 rows and 20 seats per row. 12345678901234567890 1 ...##..#####........ 2 ########....####..## 3 .........##......... 4 #.#.#.#.#.#.#.#.#.#. 5 ########.#####.##### The seats are numbered sequentially from left to right and only the ones digit is displayed above each column to make it easier to display the chart. It is understood that the second set of digits from 1-0 are for the numbers 11- 20 in the above example. After the user has selected the auditorium and the seating chart has been displayed, prompt the user for the following information in the order below: IN ORDER TO GRADE THE PROJECTS QUICKLY, PLEASE PROMPT FOR THE INFORMATION IN THE FOLLOWING ORDER. PROMPTING FOR INFORMATION IN A DIFFERENT ORDER (OR ADDING EXTRA PROMPTS) WILL CAUSE THE TEST CASES TO FAIL FOR YOUR PROGRAM. THERE WILL BE VERY LITTLE TIME FOR CORRECTIONS AND REGRADING DUE TO THE END OF THE SEMESTER.  Total Number of tickets  How many adult tickets  How many senior tickets  How many child tickets  Loop (iterations = total number of tickets) o Row o Column Do not prompt the user to enter the number of tickets for a category if the total number of tickets has already been met. For example, if the user wants to buy 4 tickets, and selects 4 adult tickets, there should be no prompt for senior or child tickets. If the desired seats are not available, offer the user the best available seats that meet their criteria in the entire auditorium. The best available seats are the seats closest to the middle of the auditorium. Prompt the user to enter a Y to reserve the best available or N to refuse the best available. Once the selection has been processed, return to the main menu. When prompting the user for input, expect anything. Do not assume any input will be valid. If you ask for a number, the user could put in a floating point number, symbols or maybe even the Gettysburg Address (or at least a sentence or two). Make sure that your program handles proper validation. You may validate with strings or Cstrings; the choice is yours.  Output: At the end of the program, write the current status of each auditorium to the proper file. Also display a formatted report to the console. The report should consist of 7 columns:  Column 1 – labels o Auditorium 1 o Auditorium 2 o Auditorium 3 o Total  Column 2 - Open seats: number of all open seats for each label  Column 3 – Total reserved seats: number of all reserved seats for each label  Column 4 - Adult seats: number of all adult seats reserved during this session for each label  Column 5 - Senior seats: number of all senior seats reserved during this session for each label  Column 6 – Child seats: number of all child seats reserved during this session for each label  Column 7 – Ticket sales: total amount of ticket sales during this session for each label