mardi 31 octobre 2017

Error C++ can fix it

void displayPhone(string* productID, vector& price, int qoh, int& numberofPhones);

void displayPhone(string* productID, vector& price, int qoh, int& numberofPhones,string ID) { int index = findID(productID, numberofPhones, ID); cout << "Product ID: " << *(productID + index) << " Price: "<< price[index] << " Quanity: "<< (qoh + index) << endl; }

keep getting this error : no matching function for call to 'displayPhone' displayPhone(productID,price,qoh,numberofPhones); ^~~~~~~~~~~~ note: candidate function not viable: no known conversion from 'int *' to 'int' for 3rd argument; dereference the argument with * void displayPhone(string* productID, vector& price, int qoh, int& numberofPhones); ^

C++ unordered_map indexing

Environment : LeetCode C++ or g++ (Ubuntu 5.4.0-6ubuntu1~16.04.5) 5.4.0 20160609

#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
using namespace std;

class TwoSum {
    unordered_map<int, int> record;        
public:

    /** Add the number to an internal data structure.. */
    void add(int number) {
        record[number]++;
    }

    /** Find if there exists any pair of numbers which sum is equal to the value. */
    bool find(int value) {
        for (auto it = record.begin(); it != record.end(); ++it) {
            int num = it->first;
            int count = it->second;
            if(num*2 == value && count >= 2){
                return true;
            }
            // if(num*2 != value && record.find(value - num) != record.end()){
            //     return true;
            // }
            if(num*2 != value && record[value - num,0] >= 1){
                return true;
            }
        }
        return false;
    }
};

int main(){
    TwoSum *A = new TwoSum();
    A->add(1);
    A->add(-2);
    A->add(3);
    A->add(6);
    cout<<A->find(-1)<<endl;
}

I used to check if some value exists in hashmap by record[value - num,0].

But under some testcase, the find function will break before iterating through all element and return 0. It confused me because it should only return true if there's a break.

So instead I use the find method and got accepted.

Could anyone tell me the reason why operator[] will affect the program like that?

Why is bool [][] more efficient than vector

I am trying to solve a DP problem where I create a 2D array, and fill the 2D array all the way. My function is called multiple times with different test cases. When I use a vector>, I get a time limit exceeded error (takes more than 2 sec for all the test cases). However, when I use bool [][], takes much less time (about 0.33 sec), and I get a pass.

Can someone please help me understand why would vector> be any less efficient than bool [][].

bool findSubsetSum(const vector<uint32_t> &input)
{
    uint32_t sum = 0;

    for (uint32_t i : input)
        sum += i;

    if ((sum % 2) == 1)
        return false;

    sum /= 2;

#if 1
    bool subsum[input.size()+1][sum+1];
    uint32_t m = input.size()+1;
    uint32_t n = sum+1;

    for (uint32_t i = 0; i < m; ++i)
        subsum[i][0] = true;

    for (uint32_t j = 1; j < n; ++j)
        subsum[0][j] = false;

    for (uint32_t i = 1; i < m; ++i) {
        for (uint32_t j = 1; j < n; ++j) {

            if (j < input[i-1])
                subsum[i][j] = subsum[i-1][j];
            else
                subsum[i][j] = subsum[i-1][j] || subsum[i-1][j - input[i-1]];
        }
    }

    return subsum[m-1][n-1];
#else
    vector<vector<bool>> subsum(input.size()+1, vector<bool>(sum+1));

    for (uint32_t i = 0; i < subsum.size(); ++i)
        subsum[i][0] = true;

    for (uint32_t j = 1; j < subsum[0].size(); ++j)
        subsum[0][j] = false;

    for (uint32_t i = 1; i < subsum.size(); ++i) {
        for (uint32_t j = 1; j < subsum[0].size(); ++j) {

            if (j < input[i-1])
                subsum[i][j] = subsum[i-1][j];
            else
                subsum[i][j] = subsum[i-1][j] || subsum[i-1][j - input[i-1]];
        }
    }

    return subsum.back().back();
#endif
}

Thank you, Ahmed.

Converting pointer to member function to std::function

I have a slightly convoluted use case of passing a member function pointer to an outside function which is then called again by a member function (Don't ask!). I'm learning about std::function and std::mem_fn but I can't seem to be able to convert my old school function pointer

void (T::*func)(int) to a std::function<void (T::*)(int) func>

in the code below, I'd like to be able to pass a std::function to memFuncTaker in the call from anotherMember

#include "class2.hpp" 
#include <iostream> 

class outer{ 
public: 
  void aMember(int a){ 
    std::cout << a <<std::endl; 
  } 
  void anotherMember(double){ 
    memFuncTaker(this, &outer::aMember); 
  } 

}; 


template<class T> 
void memFuncTaker(T* obj , void (T::*func)(int) ){ 
  (obj->*func)(7); 
} 

How to create (N + 1) x (N + 1) vertices in xy-plane with OpenGL

I'm trying to draw a grid made of triangles with the inmediate mode of OpenGL but I'm struggling with it. Particularly the number of vertices has to be (N + 1) x (N + 1) and "linked" between 2 x N x N Index-vectors. What I've got at this point is the following code:

void generate_grid(
    std::uint32_t N,
    std::vector<glm::vec3>* vertices, //vector which contains all the vertices
    std::vector<glm::uvec3>* indices) // vector which contains all the indices
{
    /*cg_assert(N >= 1);
    cg_assert(vertices);
    cg_assert(indices);

    vertices->clear();
    indices->clear();*/

    std::uint32_t size = 2*N*N;

    glEnableClientState(GL_VERTEX_ARRAY);

    glVertexPointer(2, GL_FLOAT, 0, vertices->data());
    glDrawElements(GL_TRIANGLES, size, GL_UNSIGNED_INT, indices->data());

    glDisableClientState(GL_VERTEX_ARRAY);

}

All your advices about it will be well-recibed (I'm in process of learn OpenGL, be kind ;)). Thanks in advance.

Factory function for initialization of static const struct with array and lambda

I have a structure that should be statically initialized.

struct Option
{ char Option[8];
  void (*Handler)(const char* value);
};

void ParseInto(const char* value, const char** target); // string option
void ParseInto(const char* value, int* target, int min, int max); // int option

static int count = 1;
static const char* name;

static const Option OptionMap[] =
{ { "count", [](const char* value) { ParseInto(value, &count, 1, 100); } }
, { "name",  [](const char* value) { ParseInto(value, &name); } }
  // ...
};

Up to this point it works.

To get rid of repeating the lambda function definition over and over (there are dozens) I want to use a factory like this:

struct Option
{ const char Option[8];
  const void (*Handler)(const char* value);
  template<typename ...A>
  Option(const char (&option)[8], A... args)
  : Option(option)
  , Handler([args...](const char* value) { ParseInto(value, args...); })
  {}
};

static const Option OptionMap[] =
{ { "count", &count, 1, 100 }
, { "name",  &name }
};

This does not work for two reasons:

  1. I did not find a type for the first constructor parameter option that perfectly forwards the initialization of the character array. The difficult part is that the length of the assigned array does not match the array length in general.
  2. The even harder part is that the lambda function has a closure and therefore cannot decay to a function pointer. But all parameters are compile time constants. So It should be possible to make the constructor constexpr. However, lambdas seem not to support constexpr at all.

Anyone an idea how to solve this challenge?

The current work around is a variadic macro. Not that pretty, but of course, it works.

Context is C++11. I would not like to upgrade for now, but nevertheless a solution with a newer standard would be appreciated. Problems like this tend to reappear from time to time.

There are some further restrictions by the underlying (old) code. struct Option must be a POD type and the first member must be the character array so a cast from Option* to const char* is valid.

Is C++11 available in Visual Studio 2017?

I am currently using Visual Studio Community 2017. From looking at the C++ Language Standards in the project properties, they only provide C++14 and C++17. Since my code was completed for a previous assignment using a compiler for C++11, I am unable to run my code using functions such as stoi. My question is if there is a way to add C++11 to the language standards for C++?

Operator >> with ifstream

I apologize if this is a duplicate, but I can't seem to find a concrete answer to my question. Assume I have a text file below:

Product id  Cost  Tax type
10012       34.56
10023       45.67 H
10234       12.32 P
10056       67.54
10029       54.12 H
10034       96.30 

I'm running through a while loop to read each line and then save them into a variable and then create an instance of a object depending whether it is a taxable product or not.

int _Id;
double _Price;
char _Tax;
iProduct* temp;

is >> _Id >> _Price; //First question: How does it know to read until the end 10012 into _Id and 34.56 into _Price?
if (is.get() != '\n') 
{
    is.get(_Tax); //Second question is at the bottom
    temp = new TaxableProduct(_Id, _Price, _Tax);
}
else
{
    temp = new Product(_Id, _Price);
}

My first question is how or when does the operator >> know what to read until? Second question is how does the is.get(_Tax) know that the last character is the _Tax?

Generic C++ copy between objects that support copy construction and those that don't

A long story short, I'm working on a container that can contain either copy constructable objects, or those that don't. Something like:

using AllocTraits = std::allocator_traits<Alloc>;
template <typename T>
void foo(T *to T *from, size_t n, Alloc alloc) {
  for (size_t i = 0; i < n; ++i) {
    AllocTraits::construct(alloc, to++, *from++);
  }
}

The problem I have is that my T can support either copy constructable classes or moveable classes. So, I moved to a slightly different approach:

using AllocTraits = std::allocator_traits<Alloc>;
template <typename T>
void foo(T *to T *from, size_t n, Alloc alloc) {
  auto mov_to = std::make_move_iterator(to);
  for (size_t i = 0; i < n; ++i) {
    AllocTraits::construct(alloc, mov_to++, *from++);
  }
}

But this will call T::(T&&), when I'd rather call T::T(const T&) if the type supports it.

How can I write foo so that it will call T::T(const T&) as a default, but move to T::T(T&&) otherwise?

Can threads access variables in a void?

I'm currently working on a game bot. It's a very simple bot, but I want to split it up into threads called. Move, search, click. If we have a int y in the thread search with a value of 900 can we get this integers value in click? Please include a code sample also if that's possible.

Boost Spirit failing on empty string input

I am trying to parse the following string and extract the parts inside the parenthesis.

This string fails:

_FIND('Something', '')_
Should return
part1 = 'Something'
part2 = ''

This string passes:

_FIND('Something', '*')_
Returns
part1 = 'Something'
part2 = '*'

I assume the problem lies with the "quoted_string"

    find_parser() : find_parser::base_type(start)
    {
        using qi::lit;
        using qi::lexeme;
        using standard_wide::char_;

        /// simple quoted string.
        quoted_string %= lexeme['\'' >> +(char_ - '\'') >> '\''];

        start %=
            -(lit("$(")) // optional
            >> lit("_FIND")
            >> '('
            >> quoted_string
            >> -(',' >> quoted_string) // 2nd parameter optional
            >> ")_"
            >> -(lit(")")) // optional
            ;
    }

I tried added an "empty" string lexeme like this, but it does not work.

        quoted_string %= lexeme['\'' >> +(char_ - '\'') >> '\''];
        empty_quoted_string %= lexeme['\'' >> +(qi::space - '\'') >> '\''];

        start %=
            lit("_FIND")
            >> '('
            >> (quoted_string|empty_quoted_string)
            >> -(',' >> (quoted_string|empty_quoted_string)) // 2nd parameter optional
            >> ")_"
            ;

I know it must be a simple thing, but I cannot put my finger on it.

Thanks for any inputs, hints or tips.

constructor errors in C++

Hello I am a beginner level C++ coder, still learning the basics of the programming language. I wrote the following code -

using namespace std;
namespace eLib
{
  class errorValue
  {
    public:
      errorValue(ErrorCode value, string text, int sec):
      {
        value_(value),
        text_(text),
        is_armed_(false),
        sec_(sec)
      ;}
    private:
      ErrorCode value_;
      string text_;
      bool is_armed_;
      int sec_;
  };
}

I get the following errors which I am not able to understand -

  1. following expressions cannot be used as a function

    value_(value),
    error_text_(error_text),
    is_armed_(false),
    retry_seconds_(retry_seconds)
    
    
  2. expected identifier before '{' token in Line 8

This might be a noob question but I am stuck and any help will be really appreciated. TIA

Partially filled template as parameter for template template

I have a template with two template arguments (MyCollection) and another template (TCTools) expecting a template with one template argument as template argument.

I defined a "bridge" (TypedCollection) to get a template with one parameter from MyCollection and an argument for it's first parameter with the aim of passing it to the template template.

This works fine, if I use the bridge with a fixed type as argument, but calling it from yet another template with the argument of that other template will not compile.

#include <iostream>
using std::size_t;

template <class Scalar, size_t size>
struct MyCollection
{
    MyCollection()
    {
        std::cout << "Made collection"
                  << std::endl
                  << "  " << __PRETTY_FUNCTION__
                  << std::endl;
    }
};

template <class Scalar>
struct TypedCollection
{
    template <size_t size>
    using value = MyCollection<Scalar, size>;
};

template <template <size_t> class TC>
struct TCTools
{
    static TC<10> *make_10_sized()
    {
        return new TC<10>();
    }
};

template <class S>
void test()
{
    // Will not compile
    TCTools<TypedCollection<S>::value>::make_10_sized();
}

int main()
{
    // works
    TCTools<TypedCollection<int>::value>::make_10_sized();

    test<int>();
    return 0;
}

GCC gives the following note:

expected a class template, got ‘TypedCollection<S>::value’

The whole thing has left me very confused. Why is the call in test() not compiling, while the one in main() works just as expected? Is it possible to get test to work?

unintended result of memcpy

I have the following code. I'm a newbie and would like to know what's wrong with the code below. The intent is to get the mac value from the function getMac correctly to the main.

#include <iostream>
#include <string>
#include <stdio.h>
#include <string.h>

void getMac(unsigned char *);

int main()
{
    unsigned char mac[6];
    getMac(mac);
    printf("back to main(), mac is %02x:%02x:%02x:%02x:%02x:%02x\n",
        mac[0],mac[1],mac[2], mac[3], mac[4], mac[5]);
}

void getMac(unsigned char *mac)
{
    unsigned char eth[] = "44:bg:23:1f:20:77";
    printf("eth: %s\n", eth);
    memcpy(mac, eth, 6);
    return;
}

std::vector emplace and underlying data get corrupted

I have some objects that I add them to a vector (vec1). Each object is dynamically created on the heap using new. And each object has a member (pointer) that points to the data in a different vector (vec2). The data must be created on the stack in vec2. I have problem setting the values of data through a pointer to obj, since it keeps crashing.

My strategy was to create data on the stack in vec2 using vec2.emplace_back() and set the pointer in obj through vec2.back() or vec2.data()+vec2.size(), as in the example below.

The code compiles was tested with clang and gcc. it crashes every time. What is going on?

class MyType
{
public:
    float* x;

public:
    MyType() { }
    MyType(const MyType& other) : x(other.x) { }
    MyType( MyType&& other) : x(other.x) {  }

    MyType& operator=(const MyType& other)
    {
        if(this!=&other)
            x = other.x;

        return *this;
    }

    MyType& operator=(MyType&& other)
    {
        if(this!=&other)
            x = std::move(other.x);

        return *this;
    }

    float data() const { return *x; }
    void setData(float dataX) { *x = dataX; }
};

void printObj(const MyType& obj)
{
    std::cout << "MyType x=" << obj.data() << std::endl;
}


int main (int argc, char const *argv[])
{
    std::size_t N = 10;

    std::vector<MyType*> vec1;
    std::vector<float> vec2;


    for(int i=0; i<N; i++)
    {
        MyType* ptr = new MyType;
        float* typePtr;

        vec2.emplace_back();
        typePtr = vec2.data()+vec2.size();

        ptr->x = typePtr;

        vec1.push_back(ptr);
    }

    for(int i=0; i<N; i++)
    {
        MyType* obj = vec1[i];
        obj->setData(1.0);

        printObj(*obj);
    }



    return 0;
}

The output of this:

MyType x=1
MyType x=1
MyType x=1
Segmentation fault: 11

Debugging it didnt prove successful, the problem:

* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x13f800000)
    frame #0: 0x0000000100001e89 vector_emplace2`MyType::setData(this=0x0000000100100360, dataX=1) at vector_emplace_02.cpp:31
   28           }
   29       
   30           float data() const { return *x; }
-> 31           void setData(float dataX) { *x = dataX; }
   32       };
   33   
   34       void printObj(const MyType& obj)
Target 0: (vector_emplace2) stopped.   

Compile a file including boost libraries and appropriate linker

I have the following main.cpp file.

#include <iostream>
#include <boost/asio.hpp>

int main() {
  return 0;
}

To test if my libraries are correctly installed, I'd like to compile it in its current state.

After having done a bit of research, I have found out that I need to:

  • Tell the compiler (g++) to lookup for appropriate headers with the following flag (here, i'm using boost library, installed through homebrew, hence the directory)
    • -L/usr/local/Cellar/boost/1.65.1/lib
    • -I/usr/local/Cellar/boost/1.65.1/inc
  • "Link" the library
    • -lboost_system

I am not sure to have fully understand the meaning of these flags, but I have the following compiling instruction

g++ main.cpp -o main -L/usr/local/Cellar/boost/1.65.1/lib -I/usr/local/Cellar/boost/1.65.1/include -lboost_system

And ... I have the following error message among warnings

Undefined symbols for architecture x86_64:
  "_main", referenced from:
     implicit entry/start for main executable
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

What am I doing wrong?

Didn't have this error when I was using a IDE such as XCode. I'm using the default Mac Terminal, with Atom as a code editor.

Thanks for your help,

C++ struct template not found for architecture x86_64

test.h

struct Test {
    template <typename T>
    static const T test(T a, T b);
};

test.cpp

#include "test.h"

template <typename T>
const T Test::test(T a, T b){
   return a + b;
}

main.cpp

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

void main(){
   int a = 3, b = 5; 
   std::cout << Test::test(a, b) << std::endl;
}

clang++ -std=c++11 ./test.cpp ./main.cpp -o ./test

ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

In C++11 can the override and final keywords be used only in the declaration and not in the definition ?

It seems that override and final can be used in both declaration and definition. Is it possible to only use them at the declaration level ?

Why std::sort giving errors in a function?

I am using std::sort in main function, but when use in a function, it is giving errors.

int main()
{
   int arr[5] = {1,4,2,3,5};
   std::sort(std::begin(arr), std::end(arr));
   ...
}

above code works fine. but when I do

void my_sort(int a[], int length)
{
   std::sort(std::begin(a), std::end(a)); 
}
int main()
{
    int arr[5] = {1,4,2,3,5};
    my_sort(arr, 5);
}

It gives error that

error: no matching function for call to ‘begin(int*&)’
     std::sort(std::begin(a), std::end(a));
                           ^

Why is it so ? I am using g++

Fixing self-blocking includes in a module based library

I have written a simple templated, module-based header library. With module-based I mean that one can include only string.h or dynarray.h and the header will pull in all of its dependencies.

Now im facing an issue with missing types because of the way this system works. A module does:

  • #include all dependencies
  • Define an interface class Foo
  • #include an implementation file

Unfortunately in some situations two interfaces need to be available before including any implementations. I have broken down the problem here:

string.h

#pragma once

// A string depends on a DynArray.
#include "dynarray.h"

template<typename E>
class String {
public:
    DynArray<E> arr;
    /* ... */
};

// Include the implementation of all the different functions (irrelevant here)
#include "string_impl.h"

dynarray.h

#pragma once

// The dynarray header has no direct dependencies

template<typename E>
class DynArray {
public:
    /* ... */
    E& Get(int index);
};

// Include the implementation of all the different functions
#include "dynarray_impl.h"

dynarray_impl.h

#pragma once

// The dynarray implementation needs the OutOfRangeException class
#include "out_of_range_exception.h"

template<typename E>
E& DynArray<E>::Get(int index) {
    if (index >= size) {
        throw OutOfRangeException("Some error message");
    }
}

out_of_range_exception.h

class OutOfRangeException {
public:
    String message;
    OutOfRangeException(String message) {
        /* ... */
    }
};

Due to including the implementation of a module at its bottom, when including string.h somewhere, the content of dynarray_impl.h and with it out_of_range_exception.h comes before the string class interface. So String is not defined in OutOfRangeException.

Obviously the solution is to delay only the implementation part of dynarray (dynarr_impl.h) after definition of the string interface. The problem is that I have no idea how to do this without creating some kind of common header file, which is not compatible with a module based approach.

Access fields in a named union

I want to have a named union in the following struct so that I can memcpy it without knowing what field is "active".

struct Literal {
  enum class Type : size_t {
    INT = 1,
    LONG,
    FLOAT,
    DOUBLE
  } type;

  union {
    int li;
    long ll;
    float lf;
    double ld;
  } v;

  constexpr Literal(int li): type{Type::INT}, v.li{li} {}
  constexpr Literal(long ll): type{Type::LONG}, v.ll{ll} {}
  constexpr Literal(float lf): type{Type::FLOAT}, v.lf{lf} {}
  constexpr Literal(double ld): type{Type::DOUBLE}, v.ld{ld} {}
};

How can I initialize the fields in the constructors? Neither v.li{li} nor li{li} are working.

I also tried v{li} but it work only for the first constructor because it cast the 3 others to int.

How does the code given below works?

A thumb rule in C++ says "There shall be no references to references, no arrays of references, and no pointers to references"

#include <iostream>

int main()
{
  int n=9;
  int * a= &n;
  int &b =n ;
  int &c = b;
  int *d = &b ;  
  std:: cout << "\n" << n << " - "  << *a << " - " << b <<" - "  << c  << " - "<< *d << std::flush; 
}

Alias for a lambda

The ISO C++ FAQ (http://ift.tt/2z0JVDP, "Template aliases") quotes the following example:

using P = [](double)->void; // using plus suffix return type

I get an error trying to compile this with g++ -std=c++11:

error: expected type-specifier before ‘[’ token

What should the correct syntax be? If I do

auto p = [](double)->void {};

p gets deduced to be either <lambda(double)> or main()::<lambda(double)>, depending on the scope. However, I can't then do

using P = <lambda(double)>;

as that also gives an error:

expected type-specifier before ‘<’ token

How to remove this once member thread is finished

The goal is to implement the Worker which executes tasks in a separate thread. The problem is to design the Worker shutdown path correctly. So:

class Worker
{
    /* ... */
    /**
     * @brief Thread pool worker constructor
     *
     * Runs the worker's taskRunner() in the stand alone thread.
    */
    Worker( ThreadPool * threadPool )
    {
        /* Run the task runner in new thread */
        this->mThread = std::thread( std::bind( & Worker::taskRunner, this, threadPool ) );
    }
    /* ... */
};

The worker runs it's member method Worker::taskRunner in a standalone thread. The taskRunner looks like this (unnecessary stuff removed):

void taskRunner( ThreadPool * threadPool )
{
    /* Infinite loop */
    while( this->getState() != State::TERMINATED )
    {
        /* ... */
    }

    /* At this point, the thread is going to be finished */
}

Once the infinite loop of the taskRunner is exited I would like to delete the Worker itself which instance is held in ThreadPool class in std::list collection:

std::list<std::shared_ptr<Worker>> mWorkers;

I would like to use the void std::list::remove( const T& value ); method.

The problem is in which scope this remove() is called.

  1. If I call it at the end of the taskRunner() method, it is going to be executed in scope of the Worker's thread, right? But is it correct approach to delete the parent object from it's member thread?
  2. I also thought about using boost::signals2::signal to notify the worker object itself it's thread is finished and so the Worker can ask the thread pool to remove itself...? Isn't is an overkill? Would it be a meaningfull solution to signal between main and worker's thread?

In general I would like to avoid any blocking pattern in main thread (where the Worker is running)... Many thanks in advance to anyone for any idea how to solve this problem...

Store a function with arbitrary arguments and placeholders in a class and call it later

So I am creating a type of event handler and I am in the process of writing an "Event Listener Wrapper", if you will.

The basic idea is this: When you want to subscribe to an event, you create a function that should be called when the event fires. <-- already have that done (kinda, I'll explain)

You put this listener function into a wrapper to pass the function onto the dispatcher.

The dispatcher gets an event, finds the wrapper for you listener, and calls the underlying function with the parameter values set by the event.

I already have something working so long as the listeners all only accept one argument of my EventBase class. Then I have to type cast that into the proper event that the listener is passed.

What I want instead is for my listener functions to have "any" type of arguments, and store the function in a way that lets me call it with any arguments I want depending on the event fired. Each listener function would only ever receive one type of event, or the event it's self. This would allow me to not have to type cast each event in every listener, but instead the correct event would be passed.

I found a bit of code for this wrapper that is almost perfect, with a few minor issues that I can't seem to fix. I'll explain below.

Code by @hmjd:

#include <iostream>
#include <string>
#include <functional>
#include <memory>

void myFunc1(int arg1, float arg2)
{
    std::cout << arg1 << ", " << arg2 << '\n';
}
void myFunc2(const char *arg1)
{
    std::cout << arg1 << '\n';
}

class DelayedCaller
{
public:
    template <typename TFunction, typename... TArgs>
    static std::unique_ptr<DelayedCaller> setup(TFunction&& a_func,
                                                TArgs&&... a_args)
    {
        return std::unique_ptr<DelayedCaller>(new DelayedCaller(
            std::bind(std::forward<TFunction>(a_func),
                      std::forward<TArgs>(a_args)...)));
    }
    void call() const { func_(); }

private:
    using func_type = std::function<void()>;
    DelayedCaller(func_type&& a_ft) : func_(std::forward<func_type>(a_ft)) {}
    func_type func_;
};

int main()
{
    auto caller1(DelayedCaller::setup(&myFunc1, 123, 45.6));
    auto caller2(DelayedCaller::setup(&myFunc2, "A string"));

    caller1->call();
    caller2->call();

    return 0;
}

The first thing I did here was I had to replace unique_ptr with shared_ptr. Not sure why really. This almost works. In my use case, I need to store a method function (meaning bind needs to be passed the containing method object?), and at the time of storing the function I don't know what the argument value will be, thats up for the event to decide. So my adjustment is as follows:

class DelayedCaller
{
public:

    template <typename TFunction, typename TClass>
    static std::shared_ptr<DelayedCaller> setup(TFunction&& a_func,
                                                TClass && a_class)
    {

        auto func = std::bind(std::forward<TFunction>(a_func),
                              std::forward<TClass>(a_class),
                              std::placeholders::_1);

        return std::shared_ptr<DelayedCaller>(new DelayedCaller(func));
    }

    template <typename T>
    void call( T v ) const { func_(v); }

private:
    using func_type = std::function<void(  )>;
    DelayedCaller(func_type&& a_ft) : func_(std::forward<func_type>(a_ft)) {}
    func_type func_;
};

For the sake of testing, I removed the parameter pack and replaced it with a direct parameter to the class object holding the function. I also gave the bind a placeholder for 1 argument (ideally replaced by the void call() function later). It's created like this:

eventManager->subscribe(EventDemo::descriptor, DelayedCaller::setup(
                                &AppBaseLogic::getValueBasic,
                                this
                                ));

Problem is: on this line:

return std::shared_ptr<DelayedCaller>(new DelayedCaller(func));

I get "no matching function for call to 'DelayedCaller::DelayedCaller(std::_Bind(AppBaseLogic*, std::_Placeholder<1>)>&)' return std::shared_ptr(new DelayedCaller(func));"

This only happens when using the placeholder::_1. if I replace that with a known value of the correct type, it works, with the exception that the function gets called without any useful data of course.

So, I guess I need a way to store the function with placeholders that I don't know the type of?

Forgive me if I am getting names of things wrong. I am very new to c++, I have only started learning it the past few days.

CUDA 8.0: Compile Error with Template Friend in Namespace

I noticed that the following code compiles with g++/clang++-3.8 but not with nvcc:

#include <tuple>   // not used, just to make sure that we have c++11
#include <stdio.h>

namespace a {
template<class T>
class X {
  friend T;
};
}

I get the following compile error:

/usr/local/cuda-8.0/bin/nvcc -std=c++11 minimum_cuda_test.cu
nvcc warning : The 'compute_20', 'sm_20', and 'sm_21' architectures are deprecated, and may be removed in a future release (Use -Wno-deprecated-gpu-targets to suppress warning).
minimum_cuda_test.cu:7:10: error: ‘T’ in namespace ‘::’ does not name a type
   friend T;

Interestingly, this works with nvcc:

#include <tuple>   // not used, just to make sure that we have c++11
#include <stdio.h>

template<class T>
class X {
  friend T;
};

Is this a bug in the compiler? I thought nvcc would internally use g++ or clang as a compiler so I am confused why this would work with my local compiler but not with nvcc.

what the meaning of c++11 codes using member function like below

i do not understand "R (F::* /mf/)" ,R is a type ,after R it should be a reference parameters

template<typename F, typename R>
Fty make_adaptor(F fn, R (F::* /*mf*/)(const SemanticValues& sv) const) 
{
    return TypeAdaptor<R>(fn);
}

Undefined reference to std::__sso_string::__sso_string under Centos7 and devtoolset-7

I've got Centos 7 (CentOS Linux release 7.4.1708 (Core)) with installed devtoolset-7 (gcc/g++ 7.2.1) and I'm trying to build application in debug mode using conan and cmake :

cmake .. -DCMAKE_BUILD_TYPE=Debug && make

Compilation goes fine, but when it tries to link application, there's error:

[ 94%] Building CXX object test/CMakeFiles/tests.dir/main.cpp.o
cd /home/mmaka/Projekty/Test/build/test && /opt/rh/devtoolset-7/root/usr/bin/c++   -I/home/mmaka/.conan/data/Catch/1.9.4/uilianries/stable/package/5ab84d6acfe1f23c4fae0ab88f26e3a396351ac9/include -I/home/mmaka/.conan/data/LicenseVerifier/0.2/mmaka/stable/package/dddbe98cdf0fee1bc0e935b7d9cb55fb6ac91e9d/include -I/home/mmaka/.conan/data/Protobuf/3.3.0/memsharded/testing/package/af539cf88d500e43f07db880ead85caf03eb59f0/include -I/home/mmaka/.conan/data/armadillo/7.950.1/mmaka/stable/package/4738f25476b0f8f9c35b9ffa2ef93fc44ee1be3f/include -I/home/mmaka/.conan/data/civetweb/1.9.1/mmaka/stable/package/30521fa001812a885c3d40af3906c4b0ac52ba13/include -I/home/mmaka/.conan/data/jsoncpp/1.8.0/theirix/stable/package/4d157107cadad2bf785efc05e6135855814d60b0/include -I/home/mmaka/.conan/data/sndfile/1.0.28/mmaka/stable/package/3fc343d7c666aa132d336764f97b890ecc35ebaa/include -I/home/mmaka/.conan/data/soxr/0.1.2/mmaka/stable/package/f5439539398d3f0d2ead69e27fe93b1fc9c27772/include -I/home/mmaka/.conan/data/yaml-cpp/0.5.3/mmaka/stable/package/6a58f30b01a1a6b64beeccaddc7d285c7005ead0/include -I/home/mmaka/.conan/data/Boost/1.64.0/conan/stable/package/d6a3c401aaf63728d6c3923f0431fc81dc9c77d1/include -I/home/mmaka/.conan/data/FLAC/1.3.1/Outurnate/stable/package/b90c1b060ffc91d076415439aaf03a44b60edd18/include -I/home/mmaka/.conan/data/Logging/0.1/mmaka/stable/package/4d157107cadad2bf785efc05e6135855814d60b0/include -I/home/mmaka/.conan/data/OpenBLAS/0.2.19/mmaka/stable/package/6c3feb804f9f9215b3dcb50ece3a2a312634ba12/include -I/home/mmaka/.conan/data/cryptopp/5.6.5/hykersec/testing/package/2aefc0b964f0d251f8fb69f3a8450427b24224ea/include -I/home/mmaka/.conan/data/sigar/1.6.4/mmaka/stable/package/510b4fc3cf7267f3694200560a1a888c3f06acb2/include -I/home/mmaka/.conan/data/vorbis/1.3.5/Outurnate/stable/package/fb782e536e79ff49249495e9ac27db7dc508bde3/include -I/home/mmaka/.conan/data/bzip2/1.0.6/conan/stable/package/181529a9eea3709e521af1bd56b4985e73cf35fa/include -I/home/mmaka/.conan/data/ogg/1.3.2/coding3d/stable/package/181529a9eea3709e521af1bd56b4985e73cf35fa/include -I/home/mmaka/.conan/data/zlib/1.2.11/lasote/stable/package/af29216216700781418277965556f3bb047c2635/include -I/home/mmaka/Projekty/Test/common -I/home/mmaka/Projekty/Test/DSPServerTI -I/home/mmaka/Projekty/Test/DSPServerTI/include -I/home/mmaka/Projekty/Test/DSPServerTI/Utilities -I/home/mmaka/Projekty/Test/DSPServerTI/../SessionManager/FileManager -I/home/mmaka/Projekty/Test/build/DSPServerTI -I/home/mmaka/Projekty/Test/rest -I/home/mmaka/Projekty/Test/test  -g    -DBOOST_USE_STATIC_LIBS -DARMA_USE_CXX11 -DARMA_USE_BLAS -DARMA_DONT_USE_WRAPPER -std=gnu++14 -o CMakeFiles/tests.dir/main.cpp.o -c /home/mmaka/Projekty/Test/test/main.cpp
[ 95%] Linking CXX executable ../bin/tests
cd /home/mmaka/Projekty/Test/build/test && /usr/local/bin/cmake -E cmake_link_script CMakeFiles/tests.dir/link.txt --verbose=1
/opt/rh/devtoolset-7/root/usr/bin/c++     -g        CMakeFiles/tests.dir/main.cpp.o CMakeFiles/http://ift.tt/2A00Yn3 CMakeFiles/http://ift.tt/2xE9oPG CMakeFiles/http://ift.tt/2A1WYTj CMakeFiles/http://ift.tt/2xE7a2u CMakeFiles/http://ift.tt/2A1WZql CMakeFiles/http://ift.tt/2xBxF8J CMakeFiles/http://ift.tt/2A1WZXn  -o ../bin/tests  -L/home/mmaka/.conan/data/LicenseVerifier/0.2/mmaka/stable/package/dddbe98cdf0fee1bc0e935b7d9cb55fb6ac91e9d/lib  -L/home/mmaka/.conan/data/Protobuf/3.3.0/memsharded/testing/package/af539cf88d500e43f07db880ead85caf03eb59f0/lib  -L/home/mmaka/.conan/data/civetweb/1.9.1/mmaka/stable/package/30521fa001812a885c3d40af3906c4b0ac52ba13/lib  -L/home/mmaka/.conan/data/jsoncpp/1.8.0/theirix/stable/package/4d157107cadad2bf785efc05e6135855814d60b0/lib  -L/home/mmaka/.conan/data/sndfile/1.0.28/mmaka/stable/package/3fc343d7c666aa132d336764f97b890ecc35ebaa/lib  -L/home/mmaka/.conan/data/soxr/0.1.2/mmaka/stable/package/f5439539398d3f0d2ead69e27fe93b1fc9c27772/lib  -L/home/mmaka/.conan/data/yaml-cpp/0.5.3/mmaka/stable/package/6a58f30b01a1a6b64beeccaddc7d285c7005ead0/lib  -L/home/mmaka/.conan/data/Boost/1.64.0/conan/stable/package/d6a3c401aaf63728d6c3923f0431fc81dc9c77d1/lib  -L/home/mmaka/.conan/data/FLAC/1.3.1/Outurnate/stable/package/b90c1b060ffc91d076415439aaf03a44b60edd18/lib  -L/home/mmaka/.conan/data/Logging/0.1/mmaka/stable/package/4d157107cadad2bf785efc05e6135855814d60b0/lib  -L/home/mmaka/.conan/data/OpenBLAS/0.2.19/mmaka/stable/package/6c3feb804f9f9215b3dcb50ece3a2a312634ba12/lib  -L/home/mmaka/.conan/data/cryptopp/5.6.5/hykersec/testing/package/2aefc0b964f0d251f8fb69f3a8450427b24224ea/lib  -L/home/mmaka/.conan/data/sigar/1.6.4/mmaka/stable/package/510b4fc3cf7267f3694200560a1a888c3f06acb2/lib  -L/home/mmaka/.conan/data/vorbis/1.3.5/Outurnate/stable/package/fb782e536e79ff49249495e9ac27db7dc508bde3/lib  -L/home/mmaka/.conan/data/bzip2/1.0.6/conan/stable/package/181529a9eea3709e521af1bd56b4985e73cf35fa/lib  -L/home/mmaka/.conan/data/ogg/1.3.2/coding3d/stable/package/181529a9eea3709e521af1bd56b4985e73cf35fa/lib  -L/home/mmaka/.conan/data/zlib/1.2.11/lasote/stable/package/af29216216700781418277965556f3bb047c2635/lib -Wl,-rpath,/home/mmaka/.conan/data/LicenseVerifier/0.2/mmaka/stable/package/dddbe98cdf0fee1bc0e935b7d9cb55fb6ac91e9d/lib:/home/mmaka/.conan/data/Protobuf/3.3.0/memsharded/testing/package/af539cf88d500e43f07db880ead85caf03eb59f0/lib:/home/mmaka/.conan/data/civetweb/1.9.1/mmaka/stable/package/30521fa001812a885c3d40af3906c4b0ac52ba13/lib:/home/mmaka/.conan/data/jsoncpp/1.8.0/theirix/stable/package/4d157107cadad2bf785efc05e6135855814d60b0/lib:/home/mmaka/.conan/data/sndfile/1.0.28/mmaka/stable/package/3fc343d7c666aa132d336764f97b890ecc35ebaa/lib:/home/mmaka/.conan/data/soxr/0.1.2/mmaka/stable/package/f5439539398d3f0d2ead69e27fe93b1fc9c27772/lib:/home/mmaka/.conan/data/yaml-cpp/0.5.3/mmaka/stable/package/6a58f30b01a1a6b64beeccaddc7d285c7005ead0/lib:/home/mmaka/.conan/data/Boost/1.64.0/conan/stable/package/d6a3c401aaf63728d6c3923f0431fc81dc9c77d1/lib:/home/mmaka/.conan/data/FLAC/1.3.1/Outurnate/stable/package/b90c1b060ffc91d076415439aaf03a44b60edd18/lib:/home/mmaka/.conan/data/Logging/0.1/mmaka/stable/package/4d157107cadad2bf785efc05e6135855814d60b0/lib:/home/mmaka/.conan/data/OpenBLAS/0.2.19/mmaka/stable/package/6c3feb804f9f9215b3dcb50ece3a2a312634ba12/lib:/home/mmaka/.conan/data/cryptopp/5.6.5/hykersec/testing/package/2aefc0b964f0d251f8fb69f3a8450427b24224ea/lib:/home/mmaka/.conan/data/sigar/1.6.4/mmaka/stable/package/510b4fc3cf7267f3694200560a1a888c3f06acb2/lib:/home/mmaka/.conan/data/vorbis/1.3.5/Outurnate/stable/package/fb782e536e79ff49249495e9ac27db7dc508bde3/lib:/home/mmaka/.conan/data/bzip2/1.0.6/conan/stable/package/181529a9eea3709e521af1bd56b4985e73cf35fa/lib:/home/mmaka/.conan/data/ogg/1.3.2/coding3d/stable/package/181529a9eea3709e521af1bd56b4985e73cf35fa/lib:/home/mmaka/.conan/data/zlib/1.2.11/lasote/stable/package/af29216216700781418277965556f3bb047c2635/lib ../DSPServerTI/libDSPServerTI.a ../rest/libmmaka-Test-lib.a ../common/libcommon-dsp-lib.a -lLicensing -lpthread -lprotobuf -lcivetweb -lcivetweb-cxx -lrt -ljsoncpp -lsndfile -lsoxr -lyaml-cpp -lboost_atomic -lboost_system -lboost_chrono -lboost_container -lboost_context -lboost_exception -lboost_date_time -lboost_coroutine -lboost_thread -lboost_fiber -lboost_filesystem -lboost_regex -lboost_iostreams -lboost_graph -lboost_locale -lboost_log -lboost_timer -lboost_log_setup -lboost_math_tr1 -lboost_math_tr1f -lboost_math_tr1l -lboost_math_c99 -lboost_math_c99f -lboost_math_c99l -lboost_unit_test_framework -lboost_random -lboost_program_options -lboost_serialization -lboost_wserialization -lboost_signals -lboost_prg_exec_monitor -lboost_test_exec_monitor -lboost_type_erasure -lboost_wave -lFLAC -lFLAC++ -lLogging -lopenblas -lgfortran -Wl,-Bstatic -lcryptopp -Wl,-Bdynamic -lsigar-amd64-linux -ldl -lvorbis -lvorbisfile -lvorbisenc -lbz2 -logg -lz ../DSPServerTI/libDSPServerTI.a -lLicensing -lpthread -lprotobuf -lcivetweb -lcivetweb-cxx -lrt -ljsoncpp -lsndfile -lsoxr -lyaml-cpp -lboost_atomic -lboost_system -lboost_chrono -lboost_container -lboost_context -lboost_exception -lboost_date_time -lboost_coroutine -lboost_thread -lboost_fiber -lboost_filesystem -lboost_regex -lboost_iostreams -lboost_graph -lboost_locale -lboost_log -lboost_timer -lboost_log_setup -lboost_math_tr1 -lboost_math_tr1f -lboost_math_tr1l -lboost_math_c99 -lboost_math_c99f -lboost_math_c99l -lboost_unit_test_framework -lboost_random -lboost_program_options -lboost_serialization -lboost_wserialization -lboost_signals -lboost_prg_exec_monitor -lboost_test_exec_monitor -lboost_type_erasure -lboost_wave -lFLAC -lFLAC++ -lLogging -lopenblas -lgfortran -Wl,-Bstatic -lcryptopp -Wl,-Bdynamic -lsigar-amd64-linux -ldl -lvorbis -lvorbisfile -lvorbisenc -lbz2 -logg -lz
/opt/rh/devtoolset-7/root/usr/lib/gcc/x86_64-redhat-linux/7/libstdc++_nonshared.a(cow-stdexcept.o): In function `std::__sso_string::__sso_string(std::string const&)':
(.text._ZNSt12__sso_stringC2ERKSs+0x8): undefined reference to `std::__sso_string::__sso_string(char const*, unsigned long)'
/opt/rh/devtoolset-7/root/usr/lib/gcc/x86_64-redhat-linux/7/libstdc++_nonshared.a(cow-stdexcept.o): In function `std::_V2::error_category::_M_message(int) const':
(.text._ZNKSt3_V214error_category10_M_messageEi+0x30): undefined reference to `std::__sso_string::__sso_string(char const*, unsigned long)'
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: ../bin/tests: hidden symbol `_ZNSt12__sso_stringD1Ev' isn't defined
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: final link failed: Bad value
collect2: error: ld returned 1 exit status
make[3]: *** [test/CMakeFiles/http://ift.tt/2A1X0up: bin/tests] Error 1
make[3]: Leaving directory '/home/mmaka/Projekty/Test/build'
make[2]: *** [CMakeFiles/Makefile2:350: test/CMakeFiles/tests.dir/all] Error 2
make[2]: Leaving directory '/home/mmaka/Projekty/Test/build'
make[1]: *** [CMakeFiles/Makefile2:362: test/CMakeFiles/tests.dir/rule] Error 2
make[1]: Leaving directory '/home/mmaka/Projekty/Test/build'
make: *** [Makefile:197: tests] Error 2

Using c++filt, it says that symbol 'std::__sso_string::~__sso_string()' isn't defined.

Does anyone know how to solve this problem?

lundi 30 octobre 2017

How to do the Unpack to convert the 1D array to 2d array in c++?

I have the code that generate a no of files that are the values in the heat simulation for each time step. I would like to parallelize the main loop which performs the simulation. I want to parallelize my code by dividing up the heat simulation by splicing it into the specified number of rectangles. I may want to use the MPI_recv/send to do what is sometimes called a "halo" transfer and i need to mention that each rectangle needs the surrounding values to be able to calculate it's values for the next time step. I making each process to initialize it's own smaller sized array. To validate my results, I need to transfer data from each other process using MPI_Gatherv and then write the entire simulation to the output file. I have done the pack (2D->1D)and now i want to know how can i dot the unpack (1D->2D). Note: Still my MPI_Gatherv is has issue for displacement (displacement: where the data is going to be sent from in the array to each process). In my code i considered to not using the MPI_Rec/Send. Please let me know if i am wrong by not using. My goal in this programming is to use the MPI_Gather.

For compiling, i am doing with mpicxx mpi_code.cxx -o mip_code -Wall and For executing i am doing with mpirun -np #(which is: height*width) mip_code

example of executing: mpirun -np 4 mip_code simtest 20 20 2 2 10 simtest: is the output file.

Please fill free to let me know if you have any code or idea that help me to do the unpack (1D -> 2D) in a way that the order of the output 2d will be the same as input 2d,.Please include you c++ program that i can use it for improve my code.

Thanks a lot.

Below is my code. Please let me know if there is any other informations that i need to provide. Please do not down vote if you find any mistake from my side. Please comment the mistake and i will definetly fix it ASAP.

#include <iomanip>
using std::fixed;
using std::setprecision;
using std::setw;

#include <iostream>
using std::cout;
using std::endl;

#include <fstream>
using std::ofstream;

#include <sstream>
using std::ostringstream;

#include <string>
using std::string;

#include "mpi.h"

//write the state of the smulation to a file
void write_simulation_state(string name, int height, int width, int time_step, double **values) {
    ostringstream filename;
    filename << name << "_" << height << "x" << width << "_" << time_step;

    ofstream outfile(filename.str());
    //Integer type with a width of exactly 32 bits.
    for (uint32_t i = 0; i < height; i++) {
        for (uint32_t j = 0; j < width; j++) {
            outfile << setw(10) << fixed << setprecision(5) << values[i][j];
        }
        outfile << endl;
    }
}

//Void function for Packing
//void pack(double **my_values, double *my_pack, int my_rank, int halo_width, int halo_height){

int main(int argc, char **argv) {
    int comm_sz;
    int my_rank;
    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &comm_sz);
    cout << "process just got comm_sz: " << comm_sz <<endl;
    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
    cout << "process just got my_rank: " << my_rank <<endl;
    int height, width;
    int my_height;
    int my_width;
    int vertical_slices, horizontal_slices;
    int time_steps;
    int np;
    int base_width;
    int base_height;

    if (argc != 7) {
        cout << "ERROR, incorrect arguments." << endl;
        cout << "usage:" << endl;
        cout << "\t" << argv[0] << " <simulation name : string> <height : int> <width : int> <vertical slices : int> <horizontal slices : int> <time steps : int>" << endl;
        exit(1);
    }

    string simulation_name(argv[1]);
    //the height and width of the simulation
    height = atoi(argv[2]);
    width = atoi(argv[3]);

    //horizontal and vertical slices will be used to determine how to divide up your MPI processes
    vertical_slices = atoi(argv[4]);
    horizontal_slices = atoi(argv[5]);
    np = vertical_slices * horizontal_slices;
    cout << "The No of process at first is :  " << np << endl;
    //how long to run the simulation for
    time_steps = atoi(argv[6]);
    // widths and height initializing

    int *block_width = new int[vertical_slices];
    base_width = width / vertical_slices;
    int remaining_width = width % vertical_slices;
    for(int i=0; i< vertical_slices; i++){
        block_width[i] = base_width;
        if(i < remaining_width )
            block_width[i]++;
    }

    int *block_height = new int[horizontal_slices];
    base_height = height / horizontal_slices;
    int remaining_height = height % horizontal_slices;
    for(int i=0; i< horizontal_slices; i++){
        block_height[i] = base_height;
        if(i < remaining_height )
            block_height[i]++;
    }

    my_width = block_width[my_rank % vertical_slices];
    my_height = block_height[my_rank / vertical_slices];

    double **my_values = new double*[my_height];
    double **my_values_next = new double*[my_height];
    for (uint32_t i = 0; i < my_height; i++) {
        my_values[i] = new double[my_width];
        my_values_next[i] = new double[my_width];
        for (uint32_t j = 0; j < my_width; j++) {
            my_values[i][j] = 0.0;
            my_values_next[i][j] = 0.0;
        }
    }
    // width including halo
    int halo_width = my_width;

    if(vertical_slices != 1 && my_rank % vertical_slices == 0){ //this means we are on the left edge and we will have a halo on the right edge. this means we need to increase halo width by one
        halo_width++;
        cout << "left slice done " << endl;
    } else if (vertical_slices != 1 && my_rank % vertical_slices == (vertical_slices -1)) {
        halo_width++;
        cout << "right slice done" << endl;
    } else if (vertical_slices != 1){
        halo_width +=2;
        cout << "middle one done "<< endl;
    }

    int halo_height = my_height;

    if(horizontal_slices != 1 && my_rank / vertical_slices == 0){
        halo_height++;
        cout << "left slice done " << endl;
    } else if (horizontal_slices != 1 && my_rank / vertical_slices == (horizontal_slices -1)) {
        halo_height++;
        cout << "right slice done" << endl;
    } else if (horizontal_slices != 1){
        halo_height +=2;
        cout << "middle one done "<< endl;
    }
    //put a heat source on the left column of the simulation
    if(my_rank % vertical_slices == 0){
        for (uint32_t i = 0; i < my_height; i++) {
            my_values[i][0] = 1.0;
            my_values_next[i][0] = 1.0;
        }
    }
    //put a cold source on the left column of the simulation
    if(my_rank % vertical_slices == vertical_slices -1){
        for (uint32_t i = 0; i < my_height; i++) {
            my_values[i][my_width - 1] = -1.0;
            my_values_next[i][my_width - 1] = -1.0;
        }
    }
    int sx;
    if(my_rank % vertical_slices == 0){
        sx=0;
    } else {
        sx =1;
    }
    int sy;
    if(my_rank / vertical_slices == 0){
        sy=0;
    } else {
        sy =1;
    }
    int ex;
    if(my_rank % vertical_slices == (vertical_slices -1)){
        ex=0;
    } else {
        ex =1;
    }
    int ey;
    if(my_rank / vertical_slices == (horizontal_slices -1)){
        ey=0;
    } else {
        ey =1;
    }
    int p = 0;
    double *my_pack = new double[my_height * my_width];
    for(int i=sy; i < ey; i++){
        for(int j= sx; j < ex; j++){
            my_pack[p++] = my_values[i][j];
        }
    }
    //initialize all values to 0
    double **values;// = new double*[height];
    double *big_values; //So this is the 1D arrey that holding all values that comes from the values.
    big_values = new double[height * width];
    if (my_rank == 0){
        values = new double*[height];
        // big_values = new double[height * width];
        //double **values_next = new double*[height];
        for (uint32_t i = 0; i < height; i++) {
            values[i] = new double[width];
            //            for (uint32_t j = 0; j < width; j++) {
            //                values[i][j] = 0.0;
            //
            //            }
        }
    }

    int *displacements = new int[comm_sz];
    int *slice_sizes = new int[comm_sz];
    // loop to fill the inside of slice size
    int count = 0.0; // i think i may need to start with this
    int x=0;
    for (int i =0; i < vertical_slices; i++) { // my geuss is (int i = 0; i < comm_sz; i++)
        for(int j =0; j< horizontal_slices; j++){
            slice_sizes[x] =block_width[i] * block_height[j];
            x++;
            displacements[x] = ????? // I dont know how to go through count??

        }
    }
    MPI_Gatherv( my_pack /* the data we're gathering*/,
                slice_sizes[my_rank] /* the size of the data we're
                                      sending to the target process */,
                MPI_DOUBLE /* the data type we're sending */,
                big_values /* where we're receiving the data */,
                slice_sizes /* the amount of data we’re receiving
                             per process*/,
                displacements /* where the data from each process is
                               going to be stored in the array */,
                MPI_DOUBLE /* the data type we're receiving */,
                0 /* the process we're sending from*/,
                MPI_COMM_WORLD);

    //    //put a heat source on the left column of the simulation
    //    for (uint32_t i = 0; i < height; i++) {
    //        values[i][0] = 1.0;
    //        //values_next[i][0] = 1.0;
    //    }
    //
    //    //put a cold source on the left column of the simulation
    //    for (uint32_t i = 0; i < height; i++) {
    //        values[i][width - 1] = -1.0;
    //
    //    }
    if (my_rank == 0)
        write_simulation_state(simulation_name, height, width, 0, values);
    int np2;
    np2 = vertical_slices * horizontal_slices;
    cout << "The No of process at middle is :  " << np2 << endl;
    //update the heat values at each step of the simulation for all internal values
    for (uint32_t time_step = 1; time_step <= time_steps; time_step++) {
        //the border values are sources/sinks of heat
        for (uint32_t i = 1; i < height - 1; i++) {
            for (uint32_t j = 1; j < width - 1; j++) {
                /*double up = values[i - 1][j];
                 double down = values[i + 1][j];
                 double left = values[i][j - 1];
                 double right = values[i][j + 1];

                 //set the values of the next time step of the heat simulation
                 values_next[i][j] = (up + down + left + right) / 4.0;*/
            }
        }

        //swap the values arrays
        //double **temp = values_next;
        //values_next = values;
        //values = temp;

        //// Unpack

        //store the simulation state so you can compare this to your MPI version
        if (my_rank == 0){
            write_simulation_state(simulation_name, height, width, time_step, values);
        }
    }

    //free the memory
    //delete[] big_values;
    //    for (<#initialization#>; <#condition#>; <#increment#>) {
    //        delete[] values[i];
    //    }
    //    delete[] values;
    MPI_Finalize();
    return 0;
}

What's the c++11 data structure of this snippet of a memory dump

0x7fde40000d08: 0x91    0x7fde400000f8    
0x7fde40000d18: 0x7fde400000f8  0x7fde40000d28
0x7fde40000d28: 0xb8fcd0 <_ZTVNSt13__future_base11_State_baseE+16>      0x0
0x7fde40000d38: 0x0     0x0
0x7fde40000d48: 0x0     0x0
0x7fde40000d58: 0x0     0x200000001
0x7fde40000d68: 0xffffffffffffffff      0x1
0x7fde40000d78: 0x1     0x7fde40000d38
0x7fde40000d88: 0x100000000     0x200000090

I have a memory dump above (it is a malloc-chunk BTW.). Want to ask if anyone can guess what is the data structure of this. The user data part is from 0x7fde40000d10. But I guess this snippet is from a use-after-free memory, so the first two address is not right.

Getting the error: expect unqualifeid-id before & token const T LinkedList

template <class T>
const T LinkedList<T>::&getFirst() const
{
    if (!head)
    {
        throw "no element found";
    }
    return head->data;
}

code has a return type of type T where I have so return the first element of the list and throw the exception if the list is empty the definition in the header file looks as follow: virtual const T& getFirst() const; please help.

EXC_BAD_ACCESS, calling getter

I'm not very good with memory management and I'm hoping someone can help explain to me why I am getting the EXC_BAD_ACCESS (code=1...) error. Xcode says that the error occurs when calling the getWord() method.

I am implementing a trie data structure and the error occurs when I try to get a word from my node. I think the problem is with my add function but I cant figure out whats going on. Any suggestions are appreciated.

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include <sstream>


using namespace std;


class Node
{
private:
    string word;
    bool endOfSentence = false;
    int weight = -1;


public:

    vector<Node> children = {};

    Node() {
        this->setWord("");
    }

    Node(string s){
        this->setWord(s);
    }

    string getWord(){
        return this->word;
    }
    /*vector<Node> getChildren() {   //children private
        return this->children;
    }*/
    void setWord(string s) {
        this->word = s;
    }

    void setEOS(){
        this->endOfSentence = true;
    }

    void setWeight(int weight){
        this->weight = weight;
    }
};


class Trie
{
public:
    Node root = *new Node();

    string get(string p) {
        string s = "stub";
        return s;
    }

    void add(vector<string> phrase, int weight){
        Node current = this->root;
        vector<string> sentence = phrase;
        int w = weight;
        int found = -1;

        for (int i = 0; i < current.children.size(); i++) {
            if (phrase[0] == current.children[i].getWord()) {
                found = i;
            }
        }
        if (found >= 0) {
            current = current.children[found];
            sentence.erase(sentence.begin());
            add(sentence,w);
        }
        else {
            addPhrase(sentence,w);
        }
    }

    void addPhrase(vector<string> phrase, int weight) {
        Node current = this->root;
        for (int i = 0; i < phrase.size(); i++) {
            Node temp = *new Node(phrase[i]);
            current.children.push_back(temp);
            current = current.children[current.children.size() - 1];
            if (i == phrase.size() - 1) {
                current.setEOS();
                current.setWeight(weight);
            }
        }
    }
};

SFINAE, is callable trait

I am trying to implement a little is_callable trait to improve mysel. However I am running a little issue. The issue comes when I am trying to use functor with arguments (or lambda). I did not figure out how pass the argument types, or how to deduce them automatically... Here is my code and the results :

#include <iostream>
#include <type_traits>
#include <cstdlib>



template<typename T, typename = void>
struct is_callable_impl : std::false_type {};

template<typename R, typename ...Args>
struct is_callable_impl<R(Args...), std::void_t <R(Args...)>> : std::true_type {};

template<typename Fn>
struct is_callable_impl < Fn, std::void_t<decltype(std::declval<Fn>()())>> : std::true_type{};

struct fonctor {
    void operator()() {}
};

struct fonctor2 {
    void operator()(double) {}
};

int fonct();
int fonct2(double);


int main() {
    auto l = [](float) {return false; };
    auto l2 = [&l] {return true; };
    std::cout << "expr" << std::endl;
    std::cout << is_callable_impl<double()>::value << std::endl; //write 1
    std::cout << is_callable_impl<int(int)>::value << std::endl; // write 1
    std::cout << is_callable_impl<void(double)>::value << std::endl;// write 1
    std::cout << is_callable_impl<void(double, int)>::value << std::endl; // write 1

    std::cout << "lambda" << std::endl;
    std::cout << is_callable_impl<decltype(l)>::value << std::endl;// write 0
    std::cout << is_callable_impl<decltype(l2)>::value << std::endl;// write 1

    std::cout << "function" << std::endl;
    std::cout << is_callable_impl<decltype(fonct)>::value << std::endl;// write 1
    std::cout << is_callable_impl<decltype(fonct2)>::value << std::endl;// write 1

    std::cout << "functors" << std::endl;
    std::cout << is_callable_impl<fonctor>::value << std::endl; // write 1
    std::cout << is_callable_impl<fonctor2>::value << std::endl; // write 0

    std::cout << "uncalled type" << std::endl;
    std::cout << is_callable_impl<int>::value << std::endl;// write 0

    system("pause");
    return 0;
}

C++ : compile time assert the value of a floating point number

I am using C++ 11. I have a floating point number.

float some_float = 3.0;

Now I want to compile time check that this number is greater than some value. Say that I want to compile time assert that some_float is greater than 1.0. i am trying this:

static_assert(some_float > 1.0);

But, it errors out complaining,

error: static_assert expression is not an integral constant expression
static_assert(some_float > 1.0);
              ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Question:
what is wrong that I am doing?
How can I assert at compile time that some_float is set to something above 1.0?

Program crashes when pointer to value of a struct is accessed, Even after it has been given a value

I'm completely stumped by the issue I'm having. I have to write a program that creates, sorts, and modifies a linked list, there is also a sub list that consists of the even values of the list. The issue I'm having is when I add an even value to the list, then try to print the even list in descending order. It appears that when I place the value into the list, the variable that represents a pointer to the previous even in the list is not set. Even though i can see exactly when I set it to a value, if I try to access that value, the program crashes. I apologize if my code is sort of hard to follow. But I believe the problem to be somewhere inside of the addInt() method, inside the else if statement, I've marked the area. Any help would be appreciated, thanks.

    /*
     * Main.cpp
     * Author: Austin Johanningsmeier
     * Description: This program creates, stores, and modifys a linked list of integer values
     *  Created on: Oct 24, 2017
     */

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

    /*
     * sortInput()
     * Description: reads in the file of ints, then sorts them into a list
     * Pre-Condition: Reads a file as input
     * Post-Condition: creates a sorted linked list from the values that were input
     */
    bool sortInput();

    /*
     * logError(string)
     * Description:takes a string and writes it to a log file
     * Pre-Condition: takes a string as input
     * Post-Condition: input string is written to log.txt
     */
    void logError(string);

    /*
     * printList(char)
     * Description: prints out all the values of the list in either ascending or descending order
     * Pre-Condition: takes a char as input to decide ascending or descending order
     * Post-Condition: prints the values of the linked list
     */
    bool printList(char);

    /*
     * printEvenList(char)
     * Description: Prints all the even values in the linked list in either ascending or descending order
     * Pre-Condition: takes a char as input to decide ascending or descending order
     * Post-Condition: prints all even values in the linked list
     */
    bool printEvenList(char);

    /*
     * addInt(int)
     * Description: adds an int to the linked list in its sorted place
     * Pre-Condition: takes an int as input
     * Post-Condition: adds the int value to the list
     */
    bool addInt(int);

    /*
     * deleteInt(int)
     * Description: deletes the input int from the list
     * Pre-Condition: takes an int as input
     * Post-Condition: deletes the int from the list
     */
    bool deleteInt(int);

    struct sortedIntVals {
        int value;
        bool even;
        sortedIntVals* next;
        sortedIntVals* previous;
        sortedIntVals* nextEven;
        sortedIntVals* previousEven;
    }*list = new sortedIntVals, *listHead = list, *listTail, *tempPrev,
            *tempEvenPrev, *returnTo, *current, *returnToTemp;

    int listSize = 0, evenListSize = 0;

    int main() {
        char a = 'A';
        char d = 'D';
        sortInput();
        cout << "sorted" << endl;
        addInt(48);
        printList(a);
        printEvenList(a);
        printEvenList(d);
    }

    bool sortInput() {
        ifstream inFile;
        int sinceEven = 0, testInt, selectInt;

        //Tests for the existence of the file
        inFile.open("integer.txt");
        if (inFile.good() != true) {
            logError("Failed to open the file");
            return false;
        }

        //Tests for data in the file
        inFile >> testInt;
        if (testInt == inFile.eof()) {
            logError("No data in file");
            return false;
        }

        //finds the number ints in the file
        while (inFile >> testInt != '\0') {
            listSize++;
        }
        listSize++;

        int rawInt[listSize];

        //resets the file
        inFile.close();
        inFile.open("integer.txt");

        //places values from the file into an array
        for (int i = 0; i < listSize; i++) {
            inFile >> testInt;
            if (testInt < 0) {
                logError("Input value was less than 0, not added to the list");
                i--;
                listSize--;
            } else if (inFile.fail()) {
                logError("Element in file was not an int, Terminating input");
                return false;
            } else {
                rawInt[i] = testInt;

                //finds number of even ints
                if (testInt % 2 == 0) {
                    evenListSize++;
                }
            }
        }
        selectInt = rawInt[0];

        //Sorts the array using a bubble sort
        for (int j = 1; j < listSize + 1; j++) {
            if (rawInt[j - 1] > rawInt[j]) {
                selectInt = rawInt[j];
                rawInt[j] = rawInt[j - 1];
                rawInt[j - 1] = selectInt;
                j = 1;
            }
        }

        //Starts creating the list
        for (int i = 0; i < listSize; i++) {
            list->even = false;
            current = list;
            if (i == 0) {
                list->previous = NULL;
                list->previousEven = NULL;
            }

            list->next = new sortedIntVals;
            list->value = rawInt[i];
            (list->next)->previous = list;

            if (list->value % 2 == 0) {
                list->even = true;
                returnTo = list;
                if (i != 0 && sinceEven > 0) {
                    returnTo = list;
                    for (int i = 0; i < sinceEven; i++) {
                        list = list->previous;
                        list->nextEven = returnTo;
                    }
                    list->nextEven = returnTo;
                    returnTo->previousEven = list;
                    list = returnTo;
                }
                sinceEven = 0;
            }
            if (i == listSize - 1) {
                listTail = list;
                list->next = NULL;
                list->nextEven = NULL;
            }
            list = list->next;
            sinceEven++;
        }
        list = listHead;
        return true;
    }

    bool addInt(int value) {
        if (value < 0) {
            logError("Input value is less than 0");
            return false;
        }
        bool placed = false;
        while (placed == false) {
            if (list->value > value && list->previous == NULL) {
                list->previous = new sortedIntVals;
                returnTo = list;
                list = list->previous;
                list->previous = NULL;
                list->previousEven = NULL;
                if (value % 2 == 0) {
                    returnTo->previousEven = list;
                    list->even = true;
                    evenListSize++;
                }
                list->next = returnTo;
                if (returnTo->even == true) {
                    list->nextEven = returnTo;
                } else {
                    list->nextEven = returnTo->nextEven;
                }
                list->value = value;
                if (value % 2 == 0) {
                    returnTo = list;
                    while (list->even != true && list->next != NULL) {
                        list = list->next;
                        list->previousEven = returnTo;
                    }
                    list->previousEven = returnTo;
                    list = returnTo;
                }
                listHead = list;
                placed = true;
            } else if (list->value > value) {
                returnTo = list;
                tempPrev = list->previous;
                tempEvenPrev = list->previousEven;//I Belive the problem to be here
                list->previous = new sortedIntVals;
                list = list->previous;
                list->previous = tempPrev;
                list->previousEven = tempEvenPrev;
                cout << list->previousEven->value;
                list->previous->next = list;
                list->next = returnTo;
                list->value = value;
                if (value % 2 == 0) {
                    returnTo->previousEven = list;
                    list->even = true;
                    //sets nextEvens
                    returnToTemp = list;
                    list = list->previous;
                    while (list->even != true) {
                        list = list->previous;
                        list->nextEven = returnToTemp;
                    }
                    list = returnToTemp;

                    list->previous->nextEven = list;
                    returnTo->previousEven = list;

                    evenListSize++;
                }
                list->nextEven = returnTo;
                if (returnTo->even == false) {
                    list->nextEven = returnTo->nextEven;
                    if (list->even == true) {
                        returnTo->nextEven->previousEven = list;
                    }
                }
                if (list->next == NULL) {
                    listTail = list;
                }
                placed = true;
            }
            if (returnTo->value == value) {
                cout << "The value was already in the list" << endl;
            }
            list = list->next;
        }
        listSize++;
        list = listHead;
        return true;
    }

    bool deleteInt(int value) {
        if (value < 0) {
            logError("Input value was less than 0");
            return false;
        }
        bool deleted = false;
        while (deleted == false) {
            if (list->value == value) {
                if (list->even == true) {
                    list->previous->nextEven = list->nextEven;
                    list->next->previousEven = list->previousEven;
                }
                (list->previous)->next = list->next;
                (list->next)->previous = list->previous;
                deleted = true;
                delete list;
                listSize--;
            } else if (list->next == NULL) {
                logError("Value to delete was not found in list");
                list = listHead;
                return false;
            }
            list = list->next;
        }
        list = listHead;
        return true;
    }

    bool printList(char direct) {
        if (direct != 'A' && direct != 'D') {
            logError("Invalid Direction selected");
            return false;
        }
        if (direct == 'A') {
            cout << "Values in Ascending order: ";
            for (int i = 0; i < listSize; i++) {
                cout << list->value << " ";
                list = list->next;
            }
            cout << endl;
            list = listHead;
        } else if (direct == 'D') {
            list = listTail;
            cout << "values in descending order: ";
            for (int i = 0; i < listSize; i++) {
                cout << list->value << " ";
                list = list->previous;
            }
            list = listHead;
            cout << endl;
        }
        return true;
    }

    bool printEvenList(char direct) {
        if (direct != 'A' && direct != 'D') {
            logError("Invalid direction input");
            return false;
        }
        if (direct == 'A') {
            if (list->even != true) {
                list = list->nextEven;
            }
            cout << "Even Values in ascending order: ";
            for (int i = 0; i < evenListSize; i++) {
                //list -> nextEven = listHead;
                cout << list->value << " "; //here
                list = list->nextEven;
            }
            cout << endl;
            list = listHead;
        } else if (direct == 'D') {
            list = listTail;
            if (list->even == false) {
                list = list->previousEven;
            }
            cout << "Even Values in descending order: ";
            for (int i = 0; i < evenListSize; i++) {
                if (list->previousEven == NULL) {
                    cout << "Shit, it wasnt set at " << i << endl;
                    return false;
                }
                cout << list->value << " ";
                list = list->previousEven;
            }
            cout << endl;
            list = listHead;
        }
        return true;
    }

    void logError(string error) {
        cout << "ACTION FAILED: See info in log.txt" << endl;
        ofstream logOut;
        logOut.open("log.txt", fstream::app);
        logOut << error << endl;
        logOut.close();
    }

Choosing one of two pure virtual functions in c++

Is there a way for a derived class to choose to implement one of two pure virtual functions?

In my case, these pure virtual functions serve the same general purpose, but in certain settings of the class, one will require the function with an additional parameter. Of course there is always the option of making one pure virtual function with the full parameter set. However in this case there will always be the possibility of the end-user wondering about this extra parameter he isn't using.

Singleton Derived Class with multiple bases of non-default constructors

I have a class derived from multiple base classes and I want to make it a singleton. Problem is the derived and base classes do not use default constructors and take arguments, so I'm confused how I can manage. I want to be able to pass the arguments to what would have been the constructor, but I only want possible to do once (I don't want it to be a setter). My only solution was a static bool value in the getInstance() member of the derived class.

Basic case:

//Singleton Derived Class with multiple bases of non-default constructors
class base1 {
    public:
        base1(int* value) :
              val_{value} {;}
        ~base1();
    private:
        int val_;
}

class base2 {
    public:
        base2(int* value) :
              val_{value} {;}
        ~base2();
    private:
        int val_;      
}

class derived : public base1, public base2 {
    public:
        derived(int* value) :
                base1{value},   //Base 1 constructor call
                base2{value},   //Base 2 constructor call
                val_{value} {;}
        ~derived();
    private:
        int val_;
}

//Creation
derived newDerived(&value);

Attempt to make it singleton-like?

//Lets make it a singleton
class base1 {
    public:
        base1(); //Can I pass the construtor anything?
        ~base1();
    private:
        int val_;
}

class base2 {
    public:
        base2(); //Can I pass the construtor anything?
        ~base2();
    private:
        int val_;      
}

class derived : public base1, public base2 {
    public:
        static derived& getInstance(int* value) {
            static bool init;
            if (!init) {
                base1::val_ = value;
                base2::val_ = value;
                init=true;
            }
            static derived instance;
            return instance;
        }
        derived(int* value) {;}
        ~derived();
    private:
        derived(derived const&) = delete;           //Copy construct
        derived(derived&&) = delete;                //Move construct
        derived& operator=(derived const&) = delete;//Copy assign
        derived& operator=(derived &&) = delete;    //Move assign
        int val_;
}

//Creation
derived::getInstance(&value);

I'm looking for some direction on how I should go about this, or maybe reasons I shouldn't do it at all? Thanks

struct equivalent in Python [duplicate]

This question already has an answer here:

What is the data type in Python equivalent to struct in C++? I just want to create a simple struct with a few members like the following -

struct Error
{
  int word;
  int bit;
};

CAMERA_ERROR;

This is the code to add 2 time using object as arguement

This is my code to add time in c++ using obj as arguements. I am passing the objects through the function addTime(). Please try to find any bugs.


Using return value of constexpr function as parameter to another function

I have a constexpr function that computes CRC32 hash from string literal.

template <size_t len>
constexpr uint32_t ctcrc32(const char (&str)[len]) {
    return detail::crc32<len - 2>(str) ^ 0xFFFFFFFF;
}

(it refers to other constexpr functions)

What I want to do is to call some other function that accepts uint32_t value and uses it to access data in some unordered_map. Such call looks like this:

uniformByNameCRC32(ctcrc32("uPointLight.position"));

I expect that "uPointLight.position"'s hash computes once at build time and then a resulting constant is passed to uniformByNameCRC32(), but that is not the case and ctcrc32() is called at runtime which kills CPU basically, since I have a lot of uniformByNameCRC32() calls.

This, however, works fine:

std::array<uint64_t, ctcrc32("string_literal")> array;

Such code compiles and indicates that ctcrc32()'s return value is indeed a constexpr.

What am I missing here?

Replace leading and trailing whitespaces using std::regex?

I need to remove the leading and trailing whitespace of a string. It is from the GetText() from tinyxml2 which can have \t and \n characters in it which does not look good if I print out the text.

I have this line that as far as I understand is correct syntax for std::regex. I have verified the regex expression with the online regex.

std::string Printer::trim(const std::string & str)
{
   return std::regex_replace(str, std::regex("^\s+|\s+$"), "", std::regex_constants::format_default);
}

My understanding is that it will replace all of the leading and trailing white space with empty strings. Which effectively removes the trailing and preceding white space.

At result of passing in a test string \t\t\t\nhello world\t\t\n gives back the string \t\t\t\nhello world\t\t\n and the output should have been hello world.

The additional question I have is does c++ use the exact same regex syntax as ECMAScript? Also what kind of performance cost is associated with using regex over a more traditional approach such as using string.substr()

I am aware that there are other methods to achieving the same affect but I have plans to use std::regex in other places of my project so I am hoping I can figure out how to use this instead.

Solving Linear System Eigen library - implicit smoothing C++

Could somebody point me into right direction how to solve this equation in C++ using Eigen library?

I need to make implicit smoothing for the mesh using this equation: enter image description here

And I do not know how to create this matrix in Eigen: enter image description here

Could somebody point me to right resource, I believe this kind of implicit smoothing using Eigen library was already done many times...

C++ / OpenGL: Texture to pixmap example - narrowing conversion error

I am trying to run this texture to pixmap example from OpenGL and get the following error

tex_to_pix.cpp:40:1: error: narrowing conversion of ‘4294967295u’ from ‘unsigned int’ to ‘int’ inside { } [-Wnarrowing]

The error refers to the following code block of the example:

const int pixmap_config[] = {
    GLX_BIND_TO_TEXTURE_RGBA_EXT, True,
    GLX_DRAWABLE_TYPE, GLX_PIXMAP_BIT,
    GLX_BIND_TO_TEXTURE_TARGETS_EXT, GLX_TEXTURE_2D_BIT_EXT,
    GLX_DOUBLEBUFFER, False,
    GLX_Y_INVERTED_EXT, GLX_DONT_CARE,
    None
};

What is the reason for this error?

Is it a compiler or c++11 problem?

Is there a way i can either make my compiler ignore -Wnarrowing or make a safe conversion?

convert map

I am trying to cast a map pointer to void * with reinterpret_cast and then cast it back using static_cast

Right now i have a problem trying to get the values stored in the map after casting the void * back to map<string, int> *

I tried with both a range based loop and with an iterator but i can't seem to find a way to get the keys, every time i try to access the map values i get a segmentation fault.

This is a small example of the code i have:

auto *map_pointer = new map<string, int>;

for (const auto &entry : array){
    if (map_pointer->find(entry) == map_pointer->end()) {
        map_pointer->at(entry) = 1;
    } else {
        map_pointer->at(entry)++;
    }
}

void *test = reinterpret_cast<void *>(map_pointer);
auto foo = static_cast<std::map<std::string, int> *>(test);

I need to find a way, if possible, to retrieve the keys of the map to get the values back from it.
Right now i don't know if the problem leading to the segmentation fault is in the casting to void * and back or the error occurs when i was trying to get the keys back with the iterator or the loop.

are std::vector required to use move instead of copy?

Are std::vector required to use move instead of copy, by standard? Or this is purely implementation optimization?

If std::vector required to use move, at what conditions? Where these rules/conditions can be read?

I found this How to enforce move semantics when a vector grows? . But there are no answers about guarantees.

Difference between usage of type size_t and int when used as template type?

I am still at basic understanding of meta-programming.

I am struggling to understand the difference, if any, of using the int type or the size_t type when using this type as a template type.

I understand the difference between both in standard c++ programming as explained here What's the difference between size_t and int in C++?

Then when reading questions related to some template tricks, it seems that people tends to use them undifferently. For example on this one How can I get the index of a type in a variadic class template? Barry is using std::integral_constant instantiated with size_t type

In this question: C++11 Tagged Tuple ecatmur provides an answer where its index helpers use int type instance of std::integral.

Modify one with the other seems to have no impact for what I have tested. Those template specialization being recursive, I presume anyway that in practice compiler would collapse if the Index N was too big.

Is choosing int or size_t in this specific context only a question of coding style ?

Referring member before execution of not trivial constructor

I read c++ 11 draft standard (N3242 revision) and came across on following statement:

(12.7 Construction and destruction). For an object with a non-trivial constructor, referring to any non-static member or base class of the object before the constructor begins execution results in undefined behavior.

As I understand following default constructor of Foo has undefined behaviour (in piece of code i(&a.i)? Constructor of Foo is not trivial (because it is user defined) and I am referring to member a before execution of constructor.

struct A
{
    int i;
};

struct Foo
{
    A a;
    int* i;
    Foo() : a(), i(&a.i)
    {}
};

The type of a bracketed sequence

Let's consider the following code:

for(std::size_t j : {0,1,2,3,4,5,6,7})
{
   // do something with j
}

The question is: What will be the underlying type created by the compiler for the sequence {0,1,2,3,4,5,6,7} ?

Will it be a std::vector<T> and std::array<T, 8> or an std::initializer_list<T> ?

Where T is either int or std::size_t ...

Thanks for the help.

How c++ manage reference type variable? [duplicate]

This question already has an answer here:

Studying c++ these days. (I have C background). Recently I just found new feature of c++. It's called Reference. It's interesting syntactic sugar.

But I can't solve small curiosity. I can understand Reference is an alias for the variable. But I can't understand how it works internally.

For example.

    int data = 20;
    int &rData = data;
    cout << "Address in memory of data: " << &data << std::endl; // expected address of data
    cout << "Address in memory of rData: " << &rData << std::endl; // expected address of data

Address of data and address of rData is same. But how it works? data and rData has same value and same address. I searched stackoverflow a lot. But any of question treat this topic.(Maybe my poor searching skill makes me fail to search.)

So I assume that one hypothesis.

  • Maybe c++ internally have symbol table for the reference type, so reference type variable has no memory space in stack frame.

Is this hypothesis true? If not, how c++ treat this feature?

Dereferencing a function with default arguments - C++14 vs C++11

Following code can't be compiled with g++ version 5.4.0 with option -std=c++1y:

void f(int=0) ;

int main() {
    f(); // ok
    (*f)(2);// ok
    (*f)();// ok c++11; error with c++14: too few arguments to function
    return 0;
}

The function declared to have default argument, so what is wrong here? thanks for help.

And why does g++ -c -std=c++11 compile?

dimanche 29 octobre 2017

Unable to run workable VS2015 C++ program in ubuntu

I've been able to run C++ program that is developed in Visual Studio 2015 in Ubuntu for a longest time using this command

g++ -c -std=c++11 Example1.cpp Example2.cpp

g++ Example1.o Example2.o -o Execute.exe

./Execute.exe

However now i'm having errors such as this despite using the same way of running the program.

‘numeric_limits’ was not declared in this scope
cin.ignore(numeric_limits<streamsize>::max(), '\n');

I've ensured that i've added all the necessary header as well. Even my virtual function is returning an error stating that

call of overloaded ‘abs(double)’ is ambiguous

This is how i declare my virtual function in my .h file

virtual bool correctMath(int x, int y);

and this is how i utilize the virtual function

bool Square::isPointOnShape(int x, int y)
{     
    double x = x*2;
    double y = y*3;
    if (abs(x/y) < 0.00001) return true;
}

It's running perfectly on my VS2015 but not on my Ubuntu.

My visual studio target platform : 8.1, platform toolkit : v140 where as my ubuntu's version is 14.04.

Is frequently updating std::atomic

Problem

  • Assume static std::atomic<double> dataX =0.0; defined in a cpp(Module)
  • In that module two separate functions have been defined.
  • These functions will be invoked and run by two threads independently,under the hood(within functions) two continuous looping processes are defined there; until
    some break statement gets called(using predicate).
  • When the two functions are running one function responsible for writing data todataX and other function responsible for reading from dataX and then post it to a container.
  • These two execution of functions happen under two threads as described and each thread gets sleep for very tiny millisecond(1ms) of duration.
  • Therefore both Read/Write operations for dataX coupled and gets called within very less amount of CPU cycle time.

How does C/C++ run-time behave such condition for std::atomic<double> ?

Can we have a guarantee about both written and read values of std::atomic<double> dataX maintained such condition?

Why does structured binding fails with empty base class?

I saw following example here,

#include <iostream>

struct B 
{ 

};
struct D : B 
{ 
    int i;
};

int main() 
{
    auto [i] = D{};
    return 0;
}

I have compiled this program with GCC 7.2.0 (C++1Z), and I got following error:

error: cannot decompose class type 'D': both it and its base class 'D' have non-static data members
     auto [i] = D{};
          ^~~

So, Why does structured binding fails with empty base class?

Strange Behavior of std::set and < Operator Overloading?

I understand that if the < operator is overloaded in C++ (for example, to insert custom structs into std::set), the implementation must be a strict weak order over the underlying type.

Consider the following struct and implementation. This implementation is not a strict weak order, but appears to work just fine on my machine without throwing an error:

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

struct Pixel {
    int x;
    int y;
};

bool operator < (Pixel lhs, Pixel rhs){
    return lhs.x < rhs.x || lhs.y < rhs.y;
};

int main(){
    set<Pixel> mySet;

    Pixel *newPixelA = new Pixel;
    newPixelA->x = 1;
    newPixelA->y = 3;

    Pixel *newPixelB = new Pixel;
    newPixelB->x = 4;
    newPixelB->y = 2;

    mySet.insert(*newPixelA);
    mySet.insert(*newPixelB);

}

Is this the expected behavior?

C++ Structure and function

Define a structure for the polynomial coefficients as list elements and a function with a floating point number as single parameter to initialise a newly generated list element on the heap and return a pointer to it.

How to write it in cpp

reading from an already open if stream object

I have a text data that is three lines only

100,200,300,400, John
300,400,500,100, Abraham
600,500,500,200 , David

I want to go and read this line by line and save it in a map

This is my code and i can not get the correct output..

 void save_details ( map < vector<int> , string >m , ifstream dets ) {

     int a , b , c , d;
     string s;
     while ( dets >> a >> a >> c >> a >> s) {

         vector<int>mine.push_back(a);
         vector<int>mine.push_back(b);
         vector<int>mine.push_back(c);
         vector<int>mine.push_back(c);

         m.insert(pair<vector<int> , string>(mine , s));
     }
  }

How will i correctly and efficiently store those data in a map

sqrt being defined multiple places (xtgmath)

I include the c+ header <cmath>, rather than math.h and expect a function like sqrt to then be defined in std as std::sqrt, but to my surprise resharper kept insisting that std was redundant in writing std::sqrt

After some digging, it turns out that there is a sqrt in the global namespace and after digging even more, it comes from including <vector> which in turn includes xtgmath.h which defines sqrt in the global namespace.

Vector being a modern header (as in not named .h), this is a bit surprising to me.

I guess, apart from the annoying resharper notification, it doesn't really matter, since I can still explicitly write std::sqrt and be sure which I get, but then again, I could forget the std somewhere and effectively randomly be using a different implementation, which seems a bit off to me.

Am I seeing problems where none are? What is the proper way to deal with this?

template compiler error - does not refer to a value

The following code results in the compiler error 'Exception' does not refer to a value

    template <typename T>
    class A {
    public:
        virtual ~A() = 0;
        class Exception {
        };
    };

    template<typename T>
    inline A<T>::~A() {}

    template <typename T>
    class B : public A<T> {
    public:
        B() {}

        ~B() {}

        void foo() {
            throw B<T>::Exception();
        }
    };
    int main()
    {
        try {
            B<int> instB = B<int>();
            instB.foo();
        }
        catch(B<int>::Exception &e) {
            std::cout << "uh oh" << std::endl;
        }
    }

but, if the type is explicitly specified into the throw, it works. It seems there is an issue in specifying the template type.

throw B<int>::Exception   // this works

From Template compilation error: 'X' does not refer to a value this is an indicate that clang is expecting 'Exception' to be a value, not a type.

What is the proper way to thrown the template class Exception?

libc++ implementation of std::condition_variable_any

Condition variables should have have a single order with respect to notify() and unlock_sleep() operations. To achieve this with arbitrary lockables std::condition_variable_any implementations typically use another mutex internally (to ensure atomicity and to sleep on)

If the unlock_sleep() and notify() operations are not atomic with respect to each other you risk a thread unlocking the mutex, another thread signaling and then the original thread going to sleep and never waking up.

I was reading the libstdc++ and libc++ implementations of std::condition_variable_any and noticed this code in the libc++ implementation

{lock_guard<mutex> __lx(*__mut_);}
__cv_.notify_all();

the internal mutex is locked and then immediately unlocked before the signal operation. Doesn't this risk the problem I described above?

libstdc++ seems to have gotten this right