dimanche 30 juin 2019

Inline definition of a const reference to function

int(&foo)(int, int) = [](int a, int b) { return a + b; };

doesn't compile since a mutable reference can't be initialized with a temporary. Where do I put the const?

Array of aligned structure that induces a regular array of individual members

If I have an structure (e.g. employee below), an array of such structure induces an strided array of members of the structure only if the size of the structure is a (least) common multiple (LCM) of the size all members.

Otherwise there will be pointers to specific members in the array that will not have integral pointer distances (measured in the size of the member class).

So, for example, given this structure:

struct employee{
    std::string name;
    short salary;
    std::size_t age;
};

A std::vector<employee> v (or an array employee[N] for that matter) induces a strided array of salary members (with stride sizeof(employee)/sizeof(short)) and also a strided arrays of age.

That is, an array of salaries is random accessed by &(v.data()->salary) + sizeof(employee)/sizeof(short)* n.

However it doesn't induce a stride array of names, because sizeof(employee) (=48) is not a multiple of sizeof(std::string) (32) (in my system).

Of course, I could define the struct in this other way to allow this:

struct alignas(32) employee{ // or alignas(sizeof(std::string)) std::string name; short salary; std::size_t age; employee(short salary, std::size_t age) : salary{salary}, age{age}{} };

I am wondering if finding this proper alignas argument is the only way to achieve this. Also, if there is an automatic way to obtain that number with out manually having to find the common multiple.

I seems that the most general way to do this, without reflection, is to do something like:

struct alignas(LCM(sizeof(std::string), sizeof(short), sizeof(std::size_t) ) employee{ std::string name; short salary; std::size_t age; employee(short salary, std::size_t age) : salary{salary}, age{age}{} };

That is, I have to enumerate all the members in advance. I could use constexpr std::lcm by chaining it several times).

Is this the proper way to do it?

Also, one can always find pathological cases in which this doesn't even work because there are extra restrictions that the alignment needs to be a power of 2 (in some systems). In which case the common multiple needs to be also a power of 2 and can that be a huge number:

using password_type = std::array<char, 103>; // suppose I cannot change the 103

struct alignas(std::lcm(std::lcm(std::lcm(sizeof(std::string), sizeof(short)), sizeof(std::size_t)), sizeof(password_type))) employee{ // bad alignment
    password_type password;
    std::string name;
    short salary;
    std::size_t age;
    employee(short salary, std::size_t age) : salary{salary}, age{age}{}
};

...error: requested alignment ‘3296’ is not a positive power of 2

For the alignment LCM to work I have to manually change the alignment of the specific member or add constexpr ceiling to the nearest power of 2.

struct alignas(std::lcm(std::lcm(std::lcm(sizeof(std::string), sizeof(short)), sizeof(std::size_t)), 128)) employee{ // bad alignment
    alignas(128) password_type password;
    std::string name;
    short salary;
    std::size_t age;
    employee(short salary, std::size_t age) : salary{salary}, age{age}{}
};

However that still doesn't solve the problem because alignas is not part of the password_type, it seems that the only solution then is to have a version of std::array that also takes an internal alignment argument! std::aligned_array<char, 103, 128>.

Ok, I still could do this, but at the cost of modifying other classes that where not coupled to employee initially.

struct alignas(128) password_type : std::array<char, 103>{};

and it might end up working. But it is a lot of manual work, and it could change when I change the system, or add new members, etc.

Is there a more automatic way to do this? or some conventions to follow to make this problem less painful

Why not define rvalue reference to be rvalue expression?

Let's consider the following code:

class X {
    std::vector<int> _v;
public:
    X(std::vector<int>&& v): _v(std::move(v)) {}
};

The compiler calls this constructor only for objects that can be moved. So why not just define an rvalue references to be rvalue expressions and don't write every time std::move for them?

The ctor member initializayion list would look like:

_v(v)

But this would still be a move, not a copy.

Performance difference for iteration over all elements std::unordered_map vs std::map?

I wanted to map data with pointer as the key. What container should I have chosen, map or unordered_map? There are multiple questions on stackoverflow for this topic but none of them covers the performance aspect when we need to iterate over all the key-value pairs.

std::map<classKey* , classData*> myMap;
std::unordered_map<classKey* , classData*> myUnorderedMap;

for (auto & iter : myMap) { //loop1
    display(iter.second);
}

for (auto & iter : myUnorderedMap) { //loop2
    display(iter.second);
}

loop1 vs loop2 which one gives better performance.

How to fix visual studio warning when using map.erase(key)

I'm programming for arduino in visual studio 2017 using the visual micro extension.

(I need to link a 1 byte value to a function pointer so that looking up the function corresponding to a given byte value is as efficient as possible. I thought std::map is appropriate for this.)

When using the map.erase(key) method, visual studio gives a warning:

img of error

However my project compiles without error and the method works (I have tested this in visual studio and the standard arduino IDE).

Note that this warning is not displayed in the arduino IDE

I guess this has something to do with the settings of visual studio but I can't find what the problem is.

Why don't I need to delete a temporay dynamic array sometimes?

We are always told to delete what is initialised with the new keyword, like dynamic arrays.

But I found that when people doing something like what is shown below, they do not delete the temporary dynamic array manually. But I think we should delete int* temp, otherwise it will become a dangling pointer. It came from the heap, so it never goes out of scope until the program ends.

void A::realloc(std::size_t size)
{
    // don't care about the contents of this->arr
    int* temp = new int[size];
    std::copy(this->arr, arr + this->size, temp);
    delete[] this->arr;
    this->arr = temp;
}

Why these results show there is no need to using reserve in vector?

I wrote the code below to measure the time taken to pushback integers 1000k times without using reserve and with reserving. The result was not what I wanted.

All the tests are performed on my Samsung ativtap7 having a core i5 @1.8 Ghz processor, 4 GB RAM and VS2018 C++ Compiler running under Windows 10.

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

int main()
{
    Stopwatch myWatch;
    //pushback 1000k times without reserve
    for (int i = 0; i < 10; i++)
    {
        cout << "try " << i + 1 << endl;
        myWatch.Start();
        vector<int> vec1;
        for (int i = 0; i < 1000000; i++)
        {
            vec1.push_back(i);
        }
        myWatch.End();
        myWatch.LookElapsedTime();

        //pushback 1000k times with reserve
        myWatch.Start();
        vector<int> vec2(1000000);
        for (int i = 0; i < 1000000; i++)
        {
            vec2.push_back(i);
        }

        myWatch.End();
        myWatch.LookElapsedTime();
        cout << endl;
    }
    return 0;
}

I expected results that show the meaningful difference between using reserve and not using reserve but actual results didn't match my expectations.

below is the results.

try 1
1.51118(sec)
1.46981(sec)

try 2 
1.43074(sec)
1.4381(sec)

try 3
1.4428(sec)
1.46196(sec)

try 4
1.41903(sec)
1.43688(sec)

try 5
1.47544(sec)
1.558(sec)

try 6
1.47474(sec)
1.45484(sec)

try 7
1.47731(sec)
1.5908(sec)

try 8
1.77192(sec)
1.72018(sec)

try 9
1.56832(sec)
1.447(sec)

try 10
1.43659(sec)
1.43572(sec)

I want to know why this happened.

What is the function of const specifier in enum types?

enum foo : const unsigned int
{
    F,
    S,
    T
};

void func()
{
    foo p;
    p = F;
}

The above compiles so the underlying type is not a const type?

simple linked list iterator

Hi i have a simple linked list.

I want to know how i would make a simple iterator for it.

Im not sure how th do this, would really love the help.

I want to be able to call it like this

    SList<class RandomClass> simpleList;
    for (auto i : simpleList)
    {

    }

but at the moment i call it like this

        SList<class RandomClass> simpleList;
        for (SLNode<RandomClass>* node = simpleList.Head(); node; node = node->Next())
        {

        }

Here is the list class

template<class T> class SList;
template<class T>
class SLNode
{
public:
    friend class SList<T>;
    SLNode<T>* NodeNext;
    T* NodeData;

    SLNode<T>* Next() const
    {
        return (SLNode<T>*)NodeNext;
    }

    T* Data() const
    {
        return (T*)NodeData;
    }
};


template<class T>
class SList
{
public:
    SLNode<T>* HeadNode;
    SLNode<T>* TailNode;

    SLNode<T>* Head() const
    {
        return HeadNode;
    }

    SLNode<T>* Tail() const
    {
        return TailNode;
    }
};

Typename redefinition inside class scope

This is the code

typedef double Money;

class Account {
public:
    Money balance() {
        return bal;
    }
private:
    typedef long Money;
    Money bal;
};

According to C++ Primer 5e, it is an error to redefine the same type (Money) in inner class scope.
However, it's also mentioned that some compilers may not enforce this.

Does that mean it is an undefined behavior, or unspecified behavior? If standard explicitly says that this is not allowed, how can major compilers decide not to flag this as an error?

How to insert multiple elements in the vector at different positions using iterator?

I want to write a function that changes the vector [2, 1, 4, 0, 5] to

[2, 2, 1, 4, 4, 4, 4, 5, 5, 5, 5, 5]

I could do it by popping the vector into an array and then pushing the elements back to the vector.

How can I use insert to do it? Can I modify the following program? What is the most efficient way?

void timesDuplicates(vector<int>& a) 
{
    int s = a.size(), count = 0;
    for(int i = 0; count < s ; i+=a[i], count++) {
        if(a[i] == 0) continue;
        a.insert(a.begin()+i, a[i], a[i]); 
    }
}

samedi 29 juin 2019

Write the type of a pointer to member data from other template types

I have a function that extracts pointer to member type from other types, and this works:

template<class T2, class Array,
    class Element = typename std::decay_t<Array>::element,
    class PointerToMemberType = T2 Element::*
>
v f(Array&& a, PointerToMemberType pm);

However I cannot find the way to write PM, without first definining Element which can be omitted.

How can I write PointerToMemberType directly without using the auxiliary Element?

I tried plain substitution but it doesn't work:

template<
    class T2, class Array, 
    class PointerToMemberType = T2 typename std::decay_t<Array>::element::*
>
void f(Array&&, PointerToMemberType pm);
// error: expected identifier before ‘*’ token
  677 |  class PointerToMemberType = T2 typename std::decay_t<Array>::element::* 
                                                                               ^

I also tried adding typename and parenthesis in several places.

Note that PointerToMemberType is not used for deduction at the moment, although I would try to use it in the future.

In some places it recommends using std::invoke so one doesn't need to deal with pointers-to-data-members, How would that fit or simplify something here?

SFINAE fails for custom template. Need to understand why

My code needs to test various pixel types for "validity". For example, floating point pixels are invalid if they report true for std::isnan().

So I have a "validator" template struct that I specialize for my various pixel types (here, just for float). My code uses a global template function to invoke the right overload through SFINAE

// Dummy implementation breaks compilation if no overload found.
template<class PEL, typename Enable=void> struct pixel_validator  { };


template<class PEL> 
struct pixel_validator<PEL, typename std::enable_if<std::is_floating_point<PEL>::value>::type>
{
    static bool validate(const PEL& p) { return !std::isnan(p);  }
};


template<class PEL>
inline bool is_valid_pixel(const PEL& p) 
{
    // Dispatch to validator above
    return pixel_validator<PEL>::validate(p); 
};


void main
{
     float x = 1.0f;
     std::cout << "is it valid ?" << std::boolalpha << is_valid_pixel(x);
}

And this example works just fine. The pixel_validator specialization for float is chosen. All is well.

But then I tried to reduce the verbosity of my template expressions for clarity via a custom version of "enable_if" specifically for float.

template<class T, class VAL=T>
struct enable_if_floating
    : std::enable_if<std::is_floating_point<T>::value, VAL>
{};

So now instead of writing this:

std::enable_if<std::is_floating_point<PEL>::value>::type

I can write

enable_if_floating<PEL>::value

... so my validator becomes:

template<class PEL> 
struct pixel_validator<PEL, typename enable_if_floating<PEL>::type>
{
    static bool validate(const PEL& p) { return !std::isnan(p); }
};

Unfortunately, the moment that I change my "pixel_validator" to use it, the code fails to build. My enable_if_floating does not work and so Visual Studio cannot find the appropriate specialization. My output is not surprising then.

1>------ Build started: Project: TestApp7, Configuration: Debug Win32 ------
1>TestApp7.cpp
1>C:\Test\TestApp7\TestApp7.cpp(62,34): error C2039:  'validate': is not a member of 'pixel_validator<PEL,void>'
1>C:\Test\TestApp7\TestApp7.cpp(62,34): error C2039:         with
1>C:\Test\TestApp7\TestApp7.cpp(62,34): error C2039:         [
1>C:\Test\TestApp7\TestApp7.cpp(62,34): error C2039:             PEL=float
1>C:\Test\TestApp7\TestApp7.cpp(62,34): error C2039:         ]
1>C:\Test\TestApp7\TestApp7.cpp(62): message :  see declaration of 'pixel_validator<PEL,void>'
1>C:\Test\TestApp7\TestApp7.cpp(62): message :         with
1>C:\Test\TestApp7\TestApp7.cpp(62): message :         [
1>C:\Test\TestApp7\TestApp7.cpp(62): message :             PEL=float
1>C:\Test\TestApp7\TestApp7.cpp(62): message :         ]
1>C:\Test\TestApp7\TestApp7.cpp(82): message :  see reference to function template instantiation 'bool is_valid_pixel<float>(const PEL &)' being compiled
1>C:\Test\TestApp7\TestApp7.cpp(82): message :         with
1>C:\Test\TestApp7\TestApp7.cpp(82): message :         [
1>C:\Test\TestApp7\TestApp7.cpp(82): message :             PEL=float
1>C:\Test\TestApp7\TestApp7.cpp(82): message :         ]
1>C:\Test\TestApp7\TestApp7.cpp(62,1): error C3861:  'validate': identifier not found
1>Done building project "TestApp7.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

My question is, why? What is wrong with my enable_if_floating?

Note: I even put this code in my main, just for sanity checking. If my template were bad, I would expect the static_assert to fail, but it does not.

// Sanity check #2.  Does my enable_if_floating test  reports that float
// enables because it's numeric?  If not then the static_assert below should fail

using float_type = enable_if_floating<float>::type;
static_assert(std::is_same_v<float_type, float>, "Not same as float...");

Note also: My real world code uses a predicate that saves a whole lot more space than in this simple example

Transferring a vector

I have a class which contains a vector<shared_ptr<T>>:

using SharedItems = std::vector<std::shared_ptr<Item>>;

class LargeLift
{
public:
    SharedItems& getItems()
    {
        return _items;
    }

    void setSharedItems(SharedItems& items)
    {
        _items = items;
    }

private:
    SharedItems _items;
};

I then do the following:

LargeLift a;
// Gets populated

SharedItems& items = a.getItems();

LargeLift b;
b.setSharedItems(items);

// Assume a now goes out of scope but b is being used

Is it safe to retrieve the vector of shared pointers by reference, to then re-assign by reference, or am I violating the sharing mechanism and I should be making a copy?

Function template parameter pack followed by template parameter and specialisation

Can a template parameter pack used in the definition of a function template, be followed by another template parameter, when that parameter is only given its required default value, in the definition; and not the declaration? Consider the following example:

template <typename ...Ts, typename T>
auto sz(Ts...);

template <typename ...Ts, typename T = int>
auto sz(Ts...) { return sizeof...(Ts); }

I find that GCC and Clang disagree on this (GCC gives a compilation error).

How to insert values into single linked list

I'm trying to learn some basics about single linked lists, so I went with idea of creating some code. Sadly, I have given constructor to follow.

Untill now I've created all methods I've wanted. Unfortunately, seems like my insert doesn't work, so I can't even check if other methods works. Ofc role of insert method is to add number into sorted list L. This number should be put before first number, if it's bigger or put at the end of the list, if there is no such number.

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

struct lnode
{
    int key;
    lnode* next;
    lnode(int k, lnode* n=nullptr):key(k),next(n){}
};

void insert( lnode* &L, int x)
{
    while(L)
    {
        if(x >= L->key)
        {
            L = L->next;
        }
        else
        {
            lnode* temp = L;
            L = new lnode(x, nullptr);
            L->next = temp;
            break;
        }
    }


}

int main()
{
    lnode* t = nullptr;

    insert(t,3);
    insert(t,4);
    insert(t,1);
    insert(t,7);
    insert(t,-4);
    insert(t,9);
    insert(t,2);

        while(L) {
        std::cout << L->key << " ";
    }
}

What do I expect? My expectations is to see elements of my list. At this moment there is nothing. No error, no result.

Std::string::iterator doesn't return char

I wanted to clear string from unwanted chars, and I tried to iterate it through a loop like this.

for(auto it=numer.begin(); it!=numer.end(); ++it)
    {
        if(it*=='-') numer.erase(it);
    }

The error is: "expected primary-expression before '=' token"; I could, of course, I could do this with [] operator. But I am wondering why it doesn't work. I appreciate your help.

Design a simple C++ iterator for Matrix

I was thinking to design a simple C++ iterator with ++ operation behave differently for backward and forward iterations like STL. So that a matrix A can be access through row and column as below,

  A.row(3).begin()
  A.row(3).end()
  A.col(3).begin()
  A.col(3).end()
  A.col(3).rbegin()
  A.col(3).rend()

  ++ A.row(3).begin()
  ++ A.col(3).rbegin()

My matrix class would look like below,

class Matrix {
 public:
  Iter row(size_t rowID);
  Iter col(size_t colID);
 private:
  vector<int> data_{1, 2, 3, 4, 5, 6};
  size_t nRow{3};
  size_t nCol{2};
};

Is there any suggestions on how I can design my Iter class?

How can I search for a employee record (by name) in a text file and only display it's details?

I am making a program where I input the details of many employees and store it in a text file. How can I make a function to search the entire text file and display the only details of that employee and not anyone else's? The details is always being inputted in append mode. I can't use eof() as it will display the entire document.

This is a school project and we have only studied cin and cout and not std::, hence I am using using namespace std;

void hr::menu()
{
    int option, searchopt;

    //................
    cout<<"2. Search Employee"<<endl;      /* By empno, name, dept */
    //.................

    mainopt:
    cout<<"\nChoose your option-";
    cin>>option;

    switch (option)
    {
    //................

    case 2:
        cout<<"1. Search by empno";

        cout<<"\n2. Search by name";
        cout<<"\n3. Search by dept";            
        search:
        cout<<"\n\nChoose your search option-";
        cin>>searchopt;

      switch (searchopt)
        {
            case 1: 
                cout<<"\nEMPNO SEACRH\n";
                empnosearch();
                break;
            case 2:
                cout<<"\nNAME SEARCH\n";
                namesearch();
                break;
            case 3: 
                cout<<"\nDEPARTMENT SEARCH\n";
                deptsearch();
                break;

            default:
            cout<<"Invalid Option. ";
            goto search;
                break;
            }


        break;
             //................

    }
void hr::newemp()       
{
    //declaring all datamembers
        char firstname [30], lastname [30], dept[30]; //etc.

        long localcon;
    int day, month, year;

    ofstream outfile;
    outfile.open ("example.txt",ios::app);

        //inputting all details
        //....................etc.


        //writing details into text file...

        outfile<<"First name:";
    outfile<<firstname;
    outfile<<"\nLast name: ";
    outfile<<lastname;
    outfile<<"\nEmployee no: ";
    outfile<<empnum;

        //...................etc.

        outfile<<"\nLocal Contact: ";
    outfile<<localcon;
    outfile<<"\n\n*************************************************";//indicating end of employee's details
}




vendredi 28 juin 2019

Need help in writing dynamic programming code

I have a problem of dynamic programming where i know dp would be applied but i am not able to come up with optimal code.

The problem goes like this say i have 7 unique numbers in an array. say 1,2,3,4,5,6,7 are my numbers. I want to combine these numbers into two sets of (3,4) elements or (2,5) elements or (1,6) elements such that the count is maximum . The count i am calculating in a bottom up manner from similar such sets. To clarify further

(1,2) has own count (2,3) will have a own count , similarly (1,3,4) will have a count and so will (1,5,6,7) while building bottom up . Now my goal is to combine the 7 numbers from 2 sets so that the sum of counts is maximum i.e. if (1,4,6,7) has a count 2000 and (2,3,5) 1000 and (1,2,3,4) has a count 1500 and (5,6,7) has a count 500.

My final solution should have (1,4,6,7) and (2,3,5) since the sum if maximum.

Quick help is highly appreciated , please ask me if any further clarification is required. Thanks in advance

Populate a large array using OpenMP

I want to create a 1D array of size (10^7) and want to populate it randomly. Is it possible to create many 10 arrays each of size 10^6, populate them randomly and later merge them into one array using OpenMP?

std::random_device rd{};
std::mt19937 rng{rd()};
std::bernoulli_distribution distribution(p);
int array_size = 10000000, N = 50;
array = new uint64_t[array_size];
#pragma omp parallel 
{
    #pragma omp parallel for
    for(int i = 0; i < (array_size); i++){
        uint64_t rn = 0;
        for(int j = 0; j < N; j++){
            rn = ((rn<<1)+(distribution(rng)?1:0));
        }
        array[i] = rn;
    }
}

Getting 'member is ambigous' error when compiling derived classes from templated base class

Below is a simplified version of my code. Basically, I am trying to create some Data Provider classes, and also some Data Inquirer classes that call the method from the registered Data Providers.


#include <iostream>


template <typename T>
class Provider
{
    public:
        virtual ~Provider( ) = default;
        virtual T Provide( ) = 0;
};


template <typename T>
class Inquirer
{
    public:
        Provider<T>* provider;

    public:
        void Register( Provider<T>& provider ) {
            this->provider = &provider;
        }

    public:
        void Inquire( T& data ) const {
            data = provider->Provide( );
        }
};


class Data1 : public Provider<int>
{
    public:
        int Provide( ) {
            return 42;
        }
};


class Data2 : public Provider<double>
{
    public:
        double Provide( ) {
            return 3.14;
        }
};


class Query : public Inquirer<int>, public Inquirer<double>
{
    public:
        void PrintInt( ) {
            int data;
            Inquire( data );
            std::cout << "Value: " << data;
        }


    public:    
        void PrintDouble( ) {
            double data;
            Inquire( data );
            std::cout << "Value: " << data;
        }
};


int main( void )
{
    Data1 data1;
    Data2 data2;
    Query query;

    query.Register( data1 );
    query.Register( data2 );

    query.PrintInt( );
    query.PrintDouble( );
    return 0;
}


When compiling, I get 'member is ambigous' errors in both the query.Register() calls and the Inquire() calls inside the Query Class. Since I am passing very specific parameters to each method, I don't understand why this error is happening...

How can I fix this, so that the correct methods are called?

P.S. I am compiling with gcc -std=c++11 (gcc version 5.4)

Simple Cypher Program Not Resetting Correctly

I'm learning programming and c++ as my first language for fun. I'm trying to create a simple program that encrypts and decrypts input so I can practice with strings.

Everything works okay, but somehow I am ending up with old inputs popping up when i run the program again for a second time.

For example if I input "greg" , then decrypt it, then enter greg again, I get two "greg"(encrypted)- so it's not resetting correctly, it will keep adding new words on without resetting.

#include <iostream>
#include <string>

using namespace std;

int main() {
  string alphabet{"a b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 "
                  "5 6 7 8 9 0"};
  string key{"m h i p g f b t x u r l w a j e q k z d y v o c n s 9 5 0 7 8 2 "
             "3 4 1 6"};
  string word{};
  string secretword{};
  string decryptedword{};
  int selection{};
  // int newpos {};
  int position{};
  int keypos{};

  do {
    cout << "-------------------------------------" << endl;
    cout << "Select an Option: " << endl;
    cout << "1: Encrypt" << endl;
    cout << "2: Decrypt" << endl;
    cout << "3: Quit" << endl;

    cin >> selection;

    if (selection == 1) {
      cout << "Enter a Word to Encrypt:";
      cin.sync();
      getline(cin, word);

      for (auto i : word) {
        if (isupper(i)) {
          cout << "Please use lower case only" << endl;
          break;
        }

        position = alphabet.find(i);
        secretword += key.at(position);
      }
      cout << "Encrypted Word: " << secretword << endl;
      secretword = "";
    }

    if (selection == 2) {
      cout << "Enter a Word to Decrypt: ";
      cin.sync();
      getline(cin, secretword);

      for (auto i : secretword) {
        if (isupper(i)) {
          cout << "Please use lower case only" << endl;
          break;
        }
        position = key.find(i);
        decryptedword += alphabet.at(position);
      }

      cout << "Decrypted Word: " << decryptedword << endl;
      decryptedword = "";
    }
  } while (selection != 3);

  return 0;
}

How to convert unsigned short into unsigned char and store the value in string

I'm trying to convert unsigned short value to unsigned char type and store the result in the string. Then again converting the string back to unsigned char to get back the original unsigned short values.I got struct around this conversion.

I have converted unsigned short values to string. How do I get back unsigned short value using unsigned char array.Please help me out to solve this

unsigned short a=1234;
 unsigned short b=5678;
 std::string str="";
 str+=std::to_string((unsigned char)a & 0xFF);
 str+=std::to_string((unsigned char)(a>>8)& 0xFF);
 str+=std::to_string((unsigned char)b & 0xFF);
 str+=std::to_string((unsigned char)(b>>8)& 0xFF);
 cout<<"String Value: "<<str<<endl;

expected output to be "12345678" where a=1234 b=5678;

Deducing Lambda Capture Types

I've recently found that capturing a const object by value in a lambda, implies that the variable inside the labmda's body (i.e. the lambda's data member) is also const.
For example:

const int x = 0;
auto foo = [x]{
  // x is const int
};

This behavior is mentioned in § 8.1.5.2 in the draft for C++17:

For each entity captured by copy, an unnamed non-static data member is declared in the closure type. The declaration order of these members is unspecified. The type of such a data member is the referenced type if the entity is a reference to an object, an lvalue reference to the referenced function type if the entity is a reference to a function, or the type of the corresponding captured entity otherwise. A member of an anonymous union shall not be captured by copy.

I would expect that deducing type of captured variables will be the same as deducing auto.
Is there a good reason for having different type-deduction rules for captured types?

Zeromq router-dealer high latency

Using libzmq 4 2.5 on centos 7. Getting very high latency when messages are sent from dealer to router and even from router to dealer. So i wrote simple client-server program using tcp and sent messages between them just for comparison. Tcp appears to be fast.

Sending single byte from dealer to router, zmq takes 900 microseconds.

Sending single byte from client to server, tcp takes 150 microseconds.

What am I doing wrong. I thought zmq will be atleast as fast as tcp. Is there any tuning I can do to make zmq faster?

C++ g_signal_connect realize gtkmm, return warnings

The problem I'm having is with the g_signal_connect, I'm trying to hide the mouse cursor, but I need the window instance to be able to do that (I think). But the prolem here is when I use the function g_signal_connect to do a call back when window realize. I have a main class which implements Window. In case someone knows how to hide the cursor without using this method I would appreciate.

The warning messages:

(main:20441): GLib-GObject-WARNING **: instance of invalid non-instantiatable type '(null)'

(main:20441): GLib-GObject-CRITICAL **: g_signal_connect_data: assertion 'G_TYPE_CHECK_INSTANCE (instance)' failed


The function with g_signal_connect:

g_signal_connect(G_OBJECT(this), "realize", G_CALLBACK(MainWindow::WindowRealize), NULL);

My MainWindow.cc class:

#include "MainWindow.h"


MainWindow::MainWindow() {
  set_title("Canvas exemple");
  fullscreen();

  Gdk::RGBA *gray_bg = new Gdk::RGBA("#333232");
  Gdk::RGBA *light_pink_bg = new Gdk::RGBA("#CEB7B3");
  Gdk::RGBA *black_bg = new Gdk::RGBA("#000000");


  // Here is the problem -------------
  g_signal_connect(G_OBJECT(this), "realize", G_CALLBACK(MainWindow::WindowRealize), NULL);
  // Cria o painel
  this->painel = new Gtk::Box(Gtk::ORIENTATION_VERTICAL);

  // Cria a area de desenho do canvas
  this->canvas = new Canvas();
  this->canvas->set_size_request(500, 500);

  // Meu primeiro conainer onde ficara os botoes
  this->m_Container = new Gtk::Grid();
  this->m_Container->set_orientation(Gtk::ORIENTATION_HORIZONTAL);
  this->m_Container->override_background_color(*gray_bg);

  // Meu segundo container onde ficara o canvas
  this->second_Container = new Gtk::Grid();
  this->second_Container->set_orientation(Gtk::ORIENTATION_HORIZONTAL);
  this->second_Container->override_background_color(*light_pink_bg);

  // Cria o botao e o adiciona no primeiro container
  this->m_New_Line = new Gtk::Button();
  this->m_New_Line->set_label("On/Off");
  this->m_New_Line->signal_pressed().connect( sigc::mem_fun(
    *this, &MainWindow::newPoint));
  this->m_New_Line->signal_released().connect( sigc::mem_fun(
    *this, &MainWindow::cancelButtonFlag));

  this->m_Container->add(*this->m_New_Line);

  // Adiciona o canvas no segundo container
  this->second_Container->add(*this->canvas);

  // Configura tudo no painel
  this->painel->pack_start(*this->m_Container, Gtk::PACK_SHRINK);
  this->painel->pack_start(*this->second_Container, Gtk::PACK_SHRINK);

  // Exibe o painel
  add(*this->painel);

  show_all_children();
}

void MainWindow::newPoint() {
  std::cout << "Botao pressionado" << std::endl;
  this->buttonFlag = 1;

  doMyDraw = new std::thread([this] {
    this->keepDraw();
  });
}

void MainWindow::keepDraw() {
  while (this->buttonFlag == 1) {
    this->canvas->newPoint();
     std::this_thread::sleep_for(std::chrono::milliseconds(250));
  }
}


void MainWindow::cancelButtonFlag() {
  std::cout << "Botao liberado" << std::endl;
  this->buttonFlag = 0;
  if (doMyDraw) {
    if (doMyDraw->joinable()) {
      doMyDraw->join();
    }
  }
}

MainWindow::~MainWindow() { }

MainWindow.h:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <gtkmm/window.h>
#include <gtkmm/grid.h>
#include <gtkmm/button.h>
#include <gtkmm/box.h>
#include <gdkmm/rgba.h>

#include <iostream>
#include <mutex>
#include <thread>
#include <unistd.h>

#include "Canvas.h"

class MainWindow : public Gtk::Window {
public:
  MainWindow();
  virtual ~MainWindow();

protected: /**Buttons handlers */
  int buttonFlag = 0;
  virtual void newPoint();
  void keepDraw();
  inline void changecursor() {
    // assert(G_WINDOW != NULL);
    // gdk_window_set_cursor(G_WINDOW, G_CURSOR);
    std::cout << "Aqui 2" << std::endl;
  }

  inline static void WindowRealize(GtkWidget *window, gpointer data) {
    // G_CURSOR_HAND = gdk_cursor_new_for_display(gdk_display_get_default(), GDK_HAND2);
    // G_WINDOW = gtk_widget_get_window(window);
    std::cout << "Aqui" << std::endl;
  }
  virtual void cancelButtonFlag();

private:
  Gtk::Grid *m_Container, *second_Container;
  Gtk::Button *m_New_Line, *m_Save;
  Gtk::Box *painel;
  Canvas *canvas;
  std::thread* doMyDraw;
};

#endif

Insertion sort crashing at certain array sizes but not others?

*By size, I mean number of elements

My insertion sort program is crashing at some array sizes but not others.* If I feed an unordered array of size 80+ or an ordered array of 100+ or a reversed ordered array of 100+, it will crash. It won't crash for any array below that size, I've tested.

The error is malloc: Incorrect checksum fo freed object 0x7fed6cc02bb0: probably modified after being freed.

I've checked for allocating and deleting memory... no issues as far as I can tell. I'm having a hard time understanding why it's crashing at specific numbers for different array types.

void sort(int* const array, int size) const{
    int key = 1;

    for (int i = 0; i < size; i++){
        if(array[key] < array[i]){
            traverse(array, key);
        }
        key++;
    }
    std::cout << "here" << std::endl;
}

void traverse(int* const array, int key) const{
    int i = key - 1;
    while(array[key] < array[i]){
        std::cout << "key = ";
        std::cout << key << std::endl;

        std::cout << "i = ";
        std::cout << i << std::endl;

        if(key == 0){
            return;
        }
        else if(array[key] < array[i]){
            swap(array[i], array[key]);
        }
        key--;
        i--;
    }
}

void swap(int &a, int &b) const{
    int hold = a;
    a = b;
    b = hold;
}
void unordered(int size){
  time_t t;
  srand((unsigned) time(&t));

  int* array = new int[size];
  for(int i = 0; i < size; i++)
    array[i] = (rand() % size) + 1;

  sort(array, size);

  bool b = isSorted(array, size);
  assert(b == true);
  delete [] array;
}

void ordered(int size){
  int* array = new int[size];
  for(int i = 0; i < size; i++)
    array[i] = i;

  sort(array, size);

  bool b = isSorted(array, size);
  assert(b == true);
  delete [] array;
}

int main(){
  unordered(5);
  unordered(30);
  unordered(40);
  unordered(50);
  unordered(60);
  unordered(80);
}

In the above code, I believe it's crashing at unordered(80) in sort() right after leaving the for loop since the last thing the program prints out is:

key = 2
i = 1
here

Why compiler implicitly deletes constructor while trying to initialize an array of objects with C++11 style

I'm trying to write a very simple constructor init list but falling short on an array of objects. The compiler says:

...parent-class.cpp:5: error: use of deleted function ‘SubClass::SubClass(SubClass&&)’
     , subObjects{ {this} }
                    ^

I'm sure this is a basic concept about Modern C++ and seen many answered questions around. But none of them clarified what I'm missing.

Here's the basic code which creates this compiler error (which is g++ 8.3.0)

ParentClass declaration:

#ifndef PARENTCLASS_H
#define PARENTCLASS_H

#include <QObject>
#include "sub-class.h"

class ParentClass : public QObject
{
    Q_OBJECT
public:
    explicit ParentClass(QObject *parent = nullptr);

private:
    SubClass subObjects[3];
};

#endif // PARENTCLASS_H

Parent Class Implementation:

#include "parent-class.h"

ParentClass::ParentClass(QObject *parent)
    : QObject(parent)
    , subObjects{ {this} }
{
}

Sub Class Decleration:

#ifndef SUBCLASS_H
#define SUBCLASS_H

#include <QObject>

class SubClass : public QObject
{
    Q_OBJECT
public:
    SubClass(QObject *parent = nullptr);
};

#endif // SUBCLASS_H

SubClass Implementation:


#include "sub-class.h"
SubClass::SubClass(QObject *parent)
    : QObject(parent)
{
}

Creating a dynamic array could be a workaround but I'm trying to adapt to Modern C++. Since I'm mostly an embedded guy, dynamic arrays are also out of question many times.

Thanks in advance.

Casting template class based on template argument type

Currently I store pointers of different types in a vector. To archive this, I implemented a class template "Store" which derives from a non class template "IStore". My vector finally stores pointers to "IStore". In code:

class IStore
{
public:
    IStore() = default;
    virtual ~IStore() = default;

    virtual void call() = 0;
    // ... other virtual methods
};

template<typename T>
class Store : public IStore
{
public:
    Store() = default;
    virtual ~Store() = default;

    virtual void call() override;
    // ... other virtual methods

private:
    T* m_object = nullptr;
}

And in my main class which holds the vector:

class Main
{
public:
    template<typename T>
    void registerObject(T* ptr);

    template<typename T>
    void callObjects();
    // ... other methods

private:
    std::vector<IStore*> m_storedObjects;
};

So far the current class structure. To describe the problem I need to introduce the following three example structs:

struct A {}
struct B : public A {}
struct C : {}

Other classes should call the Main::registerObject method with pointers to objects of A, B or C types. This method will then create a new Store<A>, Store<B> resp. Store<C> template class object and inserts this objects pointer to m_storedObjects.

Now the tricky part starts: The method Main::callObjects should be called by other classes with a template argument, such as Main::callObjects<B>(). This should iterate though m_storedObjects and call the IStore::call method for each object, which is of type B or which type B is derived from.

For example:

Main::registerObject<A>(obj1);
Main::registerObject<B>(obj2);
Main::registerObject<C>(obj3);
Main::callObjects<B>();

Should call obj1 and obj2 but not obj3, because C isn't B and B isn't derived from C.

My approaches in Main::callObjects were: 1. Perform dynamic_cast and check against nullptr like:

for(auto store : m_storedObjects)
{
    Store<T>* base = dynamic_cast<Store<T>*>(store);
    if(base)
    {
        // ...
    }
}

which will only work for the same classes, not derived classes, because Store<B> isn't derived from Store<A>. 2. To overwrite the cast operator in IStore and Store, such that I can specify Store should be castable when the template argument is castable. For example in Store:

template<typename C>
operator Store<C>*()
{
    if(std::is_convertible<T, C>::value)
    {
        return this;
    }
    else
    {
        return nullptr;
    }
}

But this method is never called.

Does anyone has a solution for this problem? Sorry for the long post, but I thought more code would be better to understand the problem. Thanks for your help anyway :)

How can I get and edit a FString inside a Struct inside a TArray using UProperties

I have these structs:

USTRUCT(BlueprintType)
struct FBaseCreateEditVariable {

    GENERATED_USTRUCT_BODY()
public:
    FBaseCreateEditVariable() {}
    UPROPERTY(EditAnywhere, BlueprintReadWrite, meta = (DisplayName = "variableName"))
        FString variableName = "";
    UPROPERTY(EditAnywhere, BlueprintReadWrite, meta = (DisplayName = "variableValue"))
        FString variableValue = "";

};

USTRUCT(BlueprintType)
struct FCreateEditVariable : public FInteractStruct {

    GENERATED_USTRUCT_BODY()
public:
    FCreateEditVariable() {}

    UPROPERTY(EditAnywhere, BlueprintReadWrite, meta = (DisplayName = "variables"))
        TArray<FBaseCreateEditVariable> variables;

};

So if I have these two variables:

UArrayProperty* arrayProp; //The property "variables" inside "FCreateEditVariable" struct
void * dir2; //The address of "variables"'s parent ("FCreateEditVariable")

How can I get and how can I edit dynamically using Uproperty and "for/while" all of the FString properties inside FBaseCreateEditVariable (can be more than these two FString variables)?

Sort vector consisting of nested pairs based on different values of pairs with respect to each other?

So I have a vector say:

vector<pair<pair<int,int>,pair<int,int>>>

having elements as:

[(11,13),(2,1)], [(5,6),(1,2)] ,[(9,10),(1,3)] ,[(5,8),(3,4)] , 
[(12,14),(2,7)].

After sorting (i.e. primarily with respect to the first value of the second pair and secondarily with respect to second value of the first pair... So after sorting the output should look like this:

[(5,6),(1,2)] ,[(9,10),(1,3)] ,[(11,13),(2,1)] ,[(12,14),(2,7)] ,
[(5,6),(3,4)]

I had read that we can sort using first or the second value if a vector contains a pair , but how to proceed if a vector contains nested pairs....

Label generation in Antlr4 with C++ does not allow accessing the label value

I have an old grammar that I had working with some Java code, I'm changing the generation now in Cpp.

My rule contains a label but when I'm implementing the Listener upon enter rule, there is no way to get the value of the item by label

the rule is :

msg : 
    destination=address
    time
    sender=address
;

My old code in Java was like this:

MyMessage.setDestinationAddess(ctx.destination.getText());

but some how now in CPP I can see that in the generated base listener the destination label is used to generate a nullptr that is never used.

MessageGrammar::AddressContext *destination = nullptr;

I'm I doing something wrong? are the labels not used in the CPP generation ?

Update xml file using qtXml

i'm just trying to modify my xml file using QtXml lib , so i need some help b'cause i don't understand how it's work. so this is my xml file config.xml :

<?xml version="1.0" encoding="UTF-8"?>
<BBBBOX>

    <ListeConfigurationLS>
        <ConfigurationLS Id="1" Nom="URL"   NumeroPort="8" Vitesse="57600" BitsDonnees="8" BitsParite ="0" BitsStop="1"/>
        <ConfigurationLS Id="2" Nom="BOR"   NumeroPort="4" Vitesse="57600" BitsDonnees="8" BitsParite ="0" BitsStop="1"/>
        <ConfigurationLS Id="3" Nom="XBEE"  NumeroPort="7" Vitesse="57600" BitsDonnees="8" BitsParite ="0" BitsStop="1"/>
        <ConfigurationLS Id="4" Nom="BBI"   NumeroPort="5" Vitesse="57600" BitsDonnees="8" BitsParite ="0" BitsStop="1"/>
    </ListeConfigurationLS>

</BBBBOX>

what i want to do :

Change NumeroPort = "5" to NumeroPort = "9".

If I want to transfer a resource, which kind of parameter type should I choose? weak_ptr? or shared_ptr

There is a resource: "aaa", who's type is "AAA". "aaa" is managed by shared_ptr, and we can get it's weak_ptr by function: get_aaa_weakPtr()

Now, the client_code want to visit "aaa", and transfer "aaa" to it's child_functions. Just like this:

void mainFunc(){

std::shared_ptr<A> sPtr = get_aaa_weakPtr().lock();
assert( sPtr );
// use sPtr
// ...

childFuncA( /* also_need_aaa */ );
childFuncB( /* also_need_aaa */ );
childFuncC( /* also_need_aaa */ );
}

which kind of parameter type should I choose in child_functions? weak_ptr? or shared_ptr?

jeudi 27 juin 2019

Readable concept in Range v3

What are the minimum syntaxis requirements for an iterator to be Readable according to Range v3? Can that be written a set of statemens-that-must-compile.

I have an iterator It with which I can do the basic stuff (what I would call "readable"), yet it doesn't pass the concept check:

    It i; // ok
    typename It::value_type val = *i; // ok
    typename It::reference ref = *i;   // ok
    static_assert( ranges::Readable<multi::array<double, 2>::iterator>{} ); // assert error

What other constructs involving i I can write that it will make obvious that It is not Readable?

C++ Custom Thread Wrapper with Templatized Constructor causes compile time error for insertion into std::map

I'm writing my own basic game engine and I'm multithreading it. I've created a RawThread object which wraps an std::thread with message queues, etc. I want to map these RawThreads to an id(unsigned int). So I try to insert one into an std::map<unsigned int, RawThread>, but I get a bunch of very ambiguous template errors. If I comment out the map.insert line, then the code compiles just fine, everything works, but I want to be able to insert a RawThread into the map, as tried in main().

I've stared at this code for an hour, checking to see if I got my RawThread constructor template wrong, or if I'm using my references/pointer incorrectly, but I can't see the problem.

#include <map>
#include <utility>
#include <thread>

class RawThread
{
public:

    RawThread(const RawThread& you)
    {
        *this = you;
    }



    ~RawThread()
    {
        delete mThread;
    }

    template<class Function, class... Args>
    RawThread(Function&&f, Args&&... args)
    {       
        mThread = new std::thread(std::forward<Function>(f),         
                                          std::forward<Args>(args)...);
    }

    const RawThread& operator=(const RawThread& in)
    {
        this->mThread = in.mThread;
        return *this;
    }

    void join()
    {
        mThread->join();
    }
    std::thread* mThread;
};



void hello(int x){while(true)++x;}

int main()
{
    int arg = 0;
    RawThread myThread(&hello, arg);
    unsigned int threadId = 0;
    std::map<unsigned int, RawThread> threadMap;
    threadMap.insert(std::make_pair(threadId, myThread));
    return 0;
}

I got a nasty looking error, so I put it on pastebin: https://pastebin.com/9A4wN7kL

How to use container classes with vector and list(Inheritance)?

I am trying to implement a class with inheritance specified with operator overloading.I am new to c++ so I am facing a problem with with list and vector constructors and operators[] overriding.Any help is highly appreciated

#include <iostream>
#include <list>
#include <vector>
#include <iterator> 
using namespace std;

class container
{
public:
    virtual ~container() = default;
    virtual double& operator[](size_t idx) = 0;
    virtual const double& operator[](size_t idx) const = 0;
    virtual size_t size() const = 0;
};

class vec: container
{
    vector<double> vectr;
    vec(size_t size) :
            vectr(size, 0)
    {
    }
    ;
    double& operator[](size_t idx) override
    {
        return vectr[idx];
    }
};
class lst: container
{
    const list<double> mylist;
    lst(size_t size) :
            mylist(size, 0)
    {
    };
    const double& operator[](size_t idx) const
    {
        list<double>::iterator it = mylist.begin();
        advance(it, 5);
        return *it;
    };

};

int main()
{
    vec Avec;
    lst Blst;
    Avec(10);
    Blst(10);
    return 0;
}

Following error are occuring In member function 'virtual const double& lst::operator const': 43:55: error: conversion from 'std::list::const_iterator {aka std::_List_const_iterator}' to non-scalar type 'std::list::iterator {aka std::_List_iterator}' requested In function 'int main()':aa 52:6: error: no matching function for call to 'vec::vec()'

Why can't I use the result of a static constexpr in the declaration of another function in a class?

This is my barebones code:

#include <iostream>
#include <array>

class cColor {
  public:
  enum eValue { k_Red, k_Green, k_Blue };
  static constexpr std::size_t NumValues() { return 3; }
  static constexpr std::array<eValue, NumValues()> Values()  { return {k_Red, k_Green, k_Blue}; }
};

int main() {
  std::cout << "NumColors=" << cColor::NumValues() << '\n';
}

I'm trying to declare Values() as a static constexpr and I thought I should be able to use NumValues() as it's a static constexpr as well. However, this program fails to compile and throws this error:

main.cpp:8:39: error: non-type template argument is not a constant expression
  static constexpr std::array<eValue, NumValues()> Values()  { return {k_Red, k_Green, k_Blue}; }
                                      ^~~~~~~~~~~
main.cpp:8:39: note: undefined function 'NumValues' cannot be used in a constant expression
main.cpp:7:32: note: declared here
  static constexpr std::size_t NumValues() { return 3; }

What am I missing about constexpr here?

When to make a destructor defaulted using =default?

Although using =default for constructors is clear for me (i.e. forcing the compiler to create the default constructor while other ctors exist), I still cannot understand the difference between these two type of destructors:

  1. Those that use =default
  2. Those that are not defined explicitly and generated by compiler automatically.

The only thing that comes to my mind is that the group-1 destructors can be defined as virtual, but group-2 is always non-virtual. So, is that the only difference between them? Is there any scenarios that the compiler is not generating the destructor, but using =default forces the compiler to generate it?

p.s. I have checked lots of Qs in stackoverflow, but none of them answers my Q. Here are some relevant questions.

  1. Difference between =default and {} ctos/destructors
  2. Defaulting virtual destructors
  3. Difference between =default and empty dtrs

Why is shared_ptr counter incremented when passed as const reference to base class?

Why is shared_ptr<drived> counter incremented when I pass it to a function that expects a const shared_ptr<base>&?

In this question one of the answers mentions:

shared_ptr<Base> and shared_ptr<Derived> are not covariant

I suspect that this is relevant to my question. What does it mean that they are not covariant?

Here is a code snippet to show case the scenario:

#include <iostream>
#include <memory>

class Base {};

class Derived : public Base {};

void f(const std::shared_ptr<Base>& x)
{
    std::cout << "in function expecting const shared_ptr<Base>& - Use count: " << x.use_count() << std::endl;
}

int main(int argc, char const *argv[])
{
    std::cout << "Base class" << std::endl;
    auto a = std::make_shared<Base>();
    std::cout << "Created shared_ptr:  Initial use count: " << a.use_count() << std::endl;
    f(a);

    std::cout << "------------------\nChild class" << std::endl;
    auto b = std::make_shared<Derived>();
    std::cout << "Created shared_ptr. Initial use count: " << b.use_count() << std::endl;
    f(b);

    return 0;
}

Results in:

>> g++ -std=c++17 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
Base class
Created shared_ptr:  Initial use count: 1
in function expecting const shared_ptr<Base>& - Use count: 1
------------------
Child class
Created shared_ptr. Initial use count: 1
in function expecting const shared_ptr<Base>& - Use count: 2

GNUMakefile and gcc: resolving the order of conflicting "-std=c++" requirements

Many packages these days come with a configuration utility to help set compiler requirements. I can give more specific examples if required, but a Makefile that links against two libraries might have something like:

CPPFLAGS += $(shell PackageA-config --cflags)
CPPFLAGS += $(shell PackageB-config --cflags)

%.o : %.cc 
    $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $< -o $@

Now let's say that PackageA requires at least c++11, and PackageB requires c++17, i.e. PackageA-config --cflags would yield -std=c++11 and PackageB-config --cflags would yield -std=c++17. gcc will use whichever flag came last, and since all the standards are backwards compatible, this is fine and dandy.

But what if I write my Makefile in the "wrong" order, so that PackageB comes first? Now PackageA's -std=c++11 flag is the one that actually gets used, and compilation fails.

Is there a way to tell gcc to take the highest flag given, rather than just use the last one? If not, is there a standard way to tackle this headache? Failing everything else, can some guru come up with a fix by manipulating the Makefile variable?

Compiling a c++ including root libraries with g++

I am trying to compile a c++ program, which uses the TF1 library of the ROOT-framework, with the g++ compiler.

I tried

I already tried

g++ a.cpp -o 'root-config --cflags --glibs' 

But that just gives me the error

g++: error: no such file or directory: 'root-config --cflags --glibs'

I am very new to both ROOT and C++ so help is very mucha appreciated!

insert const pair vs non-const pair vs non-const key to unordered_map

I watch this CppCon video: https://youtu.be/ncHmEUmJZf4?t=2284 (time 38:04)

I don't understand what is the different between calling:

std::pair<iterator,bool> insert( const value_type& value );

and

std::pair<iterator,bool> insert( value_type&& value );

I wrote my own code, and looks like in both cases this same constructor was called.

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

struct A
{
  A() noexcept                      {cout << "A()" << endl; }
  A(const A&) noexcept              {cout << "A(const A&)" << endl;}
};


int main()
{
    unordered_map<int, A> m;
    const pair<const int, A> p = {}; //first case OK
    //pair<const int, A> p = {};    //second case NOK
    //const pair<int, A> p = {};    //third case NOK
    cout << "---------" << endl;
    {
        m.insert(p);
        m.insert(p);
        m.insert(p);
        m.insert(p);
    }
    cout << "---------" << endl;
}

Output for first case:

A()
---------
A(const A&)
---------

Output for second and third case:

A()
---------
A(const A&)
A(const A&)
A(const A&)
A(const A&)
---------

1) Why pair must be const to don't make a copy? (second case)

2) Why key must be const to don't make a copy (unordered_map's key in definition is non-const)? (third case)

How can I set some predefined values for some values in a template function like with a #define?

I want to overload an operator (e.g. operator<<) with different types, but also change only 1 or 2 values in the function itself.

I want to get some fancy output of a vector with the primitive integer types. I have tried to create a template function like template<int width, typename T> operator<<... but this would need to set the width and typename explicitly with each call of the operator<< e.g.

I have a following minimal code example (which is not the shortest tbh):

main.cpp

#include <iostream>
#include <vector>

#include "utils.h"

using namespace std;

int main(int argc, char* argv[]) {
  vector<int8_t> vec_s_1 = {1, 2, 3, -1, -2, -123};
  vector<uint8_t> vec_u_1 = {1, 2, 3, 127, 128, 129};
  vector<int16_t> vec_s_2 = {1, 2, 3, -1, -2, -123};
  vector<uint16_t> vec_u_2 = {1, 2, 3, 127, 128, 129};
  vector<int32_t> vec_s_3 = {1, 2, 3, -1, -2, -123};
  vector<uint32_t> vec_u_3 = {1, 2, 3, 127, 128, 129};
  vector<int64_t> vec_s_4 = {1, 2, 3, -1, -2, -123};
  vector<uint64_t> vec_u_4 = {1, 2, 3, 127, 128, 129};

  cout << "vec_s_1: " << vec_s_1 << endl;
  cout << "vec_u_1: " << vec_u_1 << endl;
  cout << endl;
  cout << "vec_s_2: " << vec_s_2 << endl;
  cout << "vec_u_2: " << vec_u_2 << endl;
  cout << endl;
  cout << "vec_u_3: " << vec_u_3 << endl;
  cout << "vec_s_3: " << vec_s_3 << endl;
  cout << endl;
  cout << "vec_s_4: " << vec_s_4 << endl;
  cout << "vec_u_4: " << vec_u_4 << endl;

  return 0;
}

utils.h

#ifndef MODULO_SEQUENCE_UTILS_H
#define MODULO_SEQUENCE_UTILS_H

#include <vector>
#include <iomanip>
#include <ostream>
#include <sstream>

using namespace std;

template<typename T>
ostream& operator<<(ostream& os, const vector<T>& obj);

#endif // MODULO_SEQUENCE_UTILS_H

utils.cpp

#include "utils.h"

#define GET_FUNCTION(WIDTH, TYPENAME, MASK) \
template<> ostream& operator<<(ostream& os, const vector<TYPENAME>& obj) { \
  size_t size = obj.size(); \
  os << "["; \
  for (size_t i = 0; i < size; ++i) { \
    if (i > 0) { \
      os << ", "; \
    } \
    stringstream ss; \
    ss << "0x" << hex << uppercase << setw(WIDTH) << setfill('0') << (obj[i] & MASK); \
    os << ss.str(); \
  } \
  os << "]"; \
  return os; \
}

GET_FUNCTION(2, int8_t, 0xFF)
GET_FUNCTION(2, uint8_t, 0xFF)
GET_FUNCTION(4, int16_t, 0xFFFF)
GET_FUNCTION(4, uint16_t, 0xFFFF)
GET_FUNCTION(8, int32_t, 0xFFFFFFFF)
GET_FUNCTION(8, uint32_t, 0xFFFFFFFF)
GET_FUNCTION(16, int64_t, 0xFFFFFFFFFFFFFFFF)
GET_FUNCTION(16, uint64_t, 0xFFFFFFFFFFFFFFFF)

So far it is working like expected and the output is like I wanted to have it. It is solved by calling #define for each function separately (which is a really looking ugly code).

The output looks like this:

vec_s_1: [0x01, 0x02, 0x03, 0xFF, 0xFE, 0x85]
vec_u_1: [0x01, 0x02, 0x03, 0x7F, 0x80, 0x81]

vec_s_2: [0x0001, 0x0002, 0x0003, 0xFFFF, 0xFFFE, 0xFF85]
vec_u_2: [0x0001, 0x0002, 0x0003, 0x007F, 0x0080, 0x0081]

vec_u_3: [0x00000001, 0x00000002, 0x00000003, 0x0000007F, 0x00000080, 0x00000081]
vec_s_3: [0x00000001, 0x00000002, 0x00000003, 0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFF85]

vec_s_4: [0x0000000000000001, 0x0000000000000002, 0x0000000000000003, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFE, 0xFFFFFFFFFFFFFF85]
vec_u_4: [0x0000000000000001, 0x0000000000000002, 0x0000000000000003, 0x000000000000007F, 0x0000000000000080, 0x0000000000000081]

I need the different widths of the leading zeros in the output plus the mask for getting the exact hex number for each type.

My question is: How can/could I achieve the same result with only using templates?

is there a C ++ library for viewing videos in mp4 format and others? [on hold]

lately I'm looking for a C ++ library to view mp4 videos, for a code could you recommend a library that meets my requirements?

I tried searching on the internet but couldn't find anything

Is standard guarantee safe usage of std::future after moving std::packaged_task?

Let's say we have following code:

#include <iostream>
#include <future>

int main() {
    auto packagedTask = std::packaged_task<int()>([] {
        std::cout << "hello!\n";
        return 10;
        });

    auto packagedTaskFuture = packagedTask.get_future();
    auto packagedTaskPtr = std::make_shared<decltype(packagedTask)>(std::move(packagedTask));

    auto v1 = packagedTaskFuture.valid(); // is valid
    auto v2 = packagedTaskFuture.wait_for(std::chrono::seconds(0)); // timeout state
    (*packagedTaskPtr)(); // execute task
    auto v3 = packagedTaskFuture.wait_for(std::chrono::seconds(1)); // ready state
    auto v4 = packagedTaskFuture.get(); // 10

    return 0;
}

It works perfect on my Visual Studio environment, as you see I retrieve std::future right before I moving std::packaged_task to newly created std::shared_ptr. I've took a look into C++ standard about std::packaged_task, so §30.6.9.1 packaged_task(packaged_task&& rhs) noexcept p.6:

Effects: constructs a new packaged_task object and transfers ownership of rhs’s shared state to *this, leaving rhs with no shared state. Moves the stored task from rhs to *this.

and §30.6.9 p.2 says:

When the packaged_task object is invoked, its stored task is invoked and the result (whether normal or exceptional) stored in the shared state. Any futures that share the shared state will then be able to access the stored result.

Based on this info I have two questions:

1) Am I right saying that std::packaged_task would be linked to the same std::future after std::move?

2) It's safe to use my std::shared_ptr in other thread and execute task there, checking std::future from current one?

Boost Ptree Custom Sort

Hey i want to use this Function and make a custome sorting function. But i dont know how the Compare Function works or with a lambda.

Could someone be so kind to give me a working example for using it.

/** Sorts the direct children of this node according to the predicate. * The predicate is passed the whole pair of key and child. */ template void sort(Compare comp);

The predicate is passed the whole pair of key and child.

Is this a pair of key/ptree ? Dont know how the datatype must be

How to get the actual type of a template typed class member with Clang?

For example, I have the following class:

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

private:
    T bar_;
};

It is instantiated as:

Foo<Bar> foo;

I extract the clang::CXXRecordDecl node of class Foo, and iterate through its fields:

for (const clang::FieldDecl *fieldDecl: fooRecordDecl->fields()) {
    // fieldDecl->getType() gives T
    // fieldDecl->getNameAsString() gives bar_
}

I want something that does fieldDecl->getInstantiatedType() that gives Bar

I understand that the AST for the CXXRecordDecl of Foo shouldn't contain any information on the instantiated type. I was wondering if this linking information was stored somewhere else in the AST, and how I could retrieve it.


My current solution involves getting uninitialized template parameters in order, say {A, B, C} for template<typename A, typename B, typename C> class Baz {}; and storing them in an std::vector. Then finding the instantiation call Baz<Foo, Bar, Baz>, and store the instantiated types in order in another std::vector, and link them together by index to get:

{ A: Foo, B: Bar, C: Baz}

This seems very convoluted and "un-Clang" like.

How can i return only few values from an array

I have a array of floats i need to return only the position values from the array as std::vector, which are the first three values.

Currently i am not able to figure out how can i do that.

 float vertices[] = {
// positions          // normals           // texture coords
-0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  0.0f,  0.0f,
 0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  1.0f,  0.0f,
 0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  1.0f,  1.0f,
 0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  1.0f,  1.0f,
-0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  0.0f,  1.0f,
-0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  0.0f,  0.0f,

-0.5f, -0.5f,  0.5f,  0.0f,  0.0f,  1.0f,  0.0f,  0.0f,
 0.5f, -0.5f,  0.5f,  0.0f,  0.0f,  1.0f,  1.0f,  0.0f,
 0.5f,  0.5f,  0.5f,  0.0f,  0.0f,  1.0f,  1.0f,  1.0f,
 0.5f,  0.5f,  0.5f,  0.0f,  0.0f,  1.0f,  1.0f,  1.0f,
-0.5f,  0.5f,  0.5f,  0.0f,  0.0f,  1.0f,  0.0f,  1.0f,
-0.5f, -0.5f,  0.5f,  0.0f,  0.0f,  1.0f,  0.0f,  0.0f,

-0.5f,  0.5f,  0.5f, -1.0f,  0.0f,  0.0f,  1.0f,  0.0f,
-0.5f,  0.5f, -0.5f, -1.0f,  0.0f,  0.0f,  1.0f,  1.0f,
-0.5f, -0.5f, -0.5f, -1.0f,  0.0f,  0.0f,  0.0f,  1.0f,
-0.5f, -0.5f, -0.5f, -1.0f,  0.0f,  0.0f,  0.0f,  1.0f,
-0.5f, -0.5f,  0.5f, -1.0f,  0.0f,  0.0f,  0.0f,  0.0f,
-0.5f,  0.5f,  0.5f, -1.0f,  0.0f,  0.0f,  1.0f,  0.0f,

 0.5f,  0.5f,  0.5f,  1.0f,  0.0f,  0.0f,  1.0f,  0.0f,
 0.5f,  0.5f, -0.5f,  1.0f,  0.0f,  0.0f,  1.0f,  1.0f,
 0.5f, -0.5f, -0.5f,  1.0f,  0.0f,  0.0f,  0.0f,  1.0f,
 0.5f, -0.5f, -0.5f,  1.0f,  0.0f,  0.0f,  0.0f,  1.0f,
 0.5f, -0.5f,  0.5f,  1.0f,  0.0f,  0.0f,  0.0f,  0.0f,
 0.5f,  0.5f,  0.5f,  1.0f,  0.0f,  0.0f,  1.0f,  0.0f,

-0.5f, -0.5f, -0.5f,  0.0f, -1.0f,  0.0f,  0.0f,  1.0f,
 0.5f, -0.5f, -0.5f,  0.0f, -1.0f,  0.0f,  1.0f,  1.0f,
 0.5f, -0.5f,  0.5f,  0.0f, -1.0f,  0.0f,  1.0f,  0.0f,
 0.5f, -0.5f,  0.5f,  0.0f, -1.0f,  0.0f,  1.0f,  0.0f,
-0.5f, -0.5f,  0.5f,  0.0f, -1.0f,  0.0f,  0.0f,  0.0f,
-0.5f, -0.5f, -0.5f,  0.0f, -1.0f,  0.0f,  0.0f,  1.0f,

-0.5f,  0.5f, -0.5f,  0.0f,  1.0f,  0.0f,  0.0f,  1.0f,
 0.5f,  0.5f, -0.5f,  0.0f,  1.0f,  0.0f,  1.0f,  1.0f,
 0.5f,  0.5f,  0.5f,  0.0f,  1.0f,  0.0f,  1.0f,  0.0f,
 0.5f,  0.5f,  0.5f,  0.0f,  1.0f,  0.0f,  1.0f,  0.0f,
-0.5f,  0.5f,  0.5f,  0.0f,  1.0f,  0.0f,  0.0f,  0.0f,
-0.5f,  0.5f, -0.5f,  0.0f,  1.0f,  0.0f,  0.0f,  1.0f
};

Is gcc missing an opportunity to optimize ctor initializer lists?

Consider these two structs (legal C++11 and beyond):

struct A {
    unsigned int a = 5;
} a;

struct B {
    unsigned int b;
    B() : b(5) {}
} b;

As far as I understood, a and b should produce exactly the same code.

clang (8.0.0) does what I expect and produces the following assembly:

a:
        .long   5                       # 0x5
b:
        .long   5                       # 0x5

g++ (9.1) seems to miss this optimization opportunity:

_GLOBAL__sub_I_a:
        mov     DWORD PTR b[rip], 5
        ret
b:
        .zero   4
a:
        .long   5

See the code on godbolt. What g++ compiles to is equivalent to this:

struct C {
    unsigned int c;
    C() { c = 5; } // initialize + assign
} c;

which I would not expect, especially because I compile with -O3. Is this an "optimization bug"?

Multithreaded embedded python and Tensorflow

I have a TensorFlow model written in python and I have a c++ application which acquires the training data and passes it to Tensorflow with embedded python Api.

The application has a GUI so it naturally should be multithreaded.

The problem is that although application runs without errors it seems that the model is not training (at least, not in the way I expect), i.e. the trained variable is always some random number close to the initial value. I tried to dump the data and feed it to the python class directly from python and it worked perfectly.

I assume I am doing something wrong with threading. Right?

The definition of the python class looks like this (for simplicity I will assume that we have only one variable):

class TrainingClass:
    def __init__(self, params):
        # assign params
        # build graph, loss etc...
        self.variable = tf.Variable(42, dtype=tf.float64)


        self.session = tf.Session()
        self.session.run([tf.global_variables_initializer()])

    def train(self, train_params):
        return self.session.run([list_of_optimizers, self.loss], feed_dict = {self.param_placeholders: params})[-1]

    def get_trained_variable(self):
        return self.session.run(self.variable)

On c++ side things look like this.

class MyCppClass {

    std::thread *m_training_thread;
    bool thread_is_canceled();

    void on_start_button_pressed() {
        PyObject * python_class_instance = PyObject_CallFunctionObjArgs(python_class_type, params..., NULL);

        m_training_thread = new std::thread(&MyCppClass::cpp_train_function, this, python_class_instance );
    }

    void cpp_train_function(PyObject * python_class_instance) {
        while(!thread_is_canceled()) {
             // Acquire lock
             PyGILState_STATE state = PyGILState_Ensure();

             PyObject * py_list = PyList_New(42);

             /* Long and boring code for assigning 
              * the items of the list 
             */

             // Pass the py_list to tensorflow
             PyObject * py_loss = PyObject_CallMethodObjArgs(python_class_instance, train_function_name, py_list, NULL );

             if( py_loss ) {
                // Display current loss value to the user
             }

             // Release lock
             PyGILState_Release(state);
        }
    }

    void show_trained_parameters(PyObject * python_class_instance)
    {
        // Acquire lock
        PyGILState_STATE state = PyGILState_Ensure();

        PyObject * trained_vars = PyObject_CallMethodObjArgs(python_class_instance, get_trained_variable_py_str , NULL);

        // Show the trained variable

        // Release lock
        PyGILState_Release(state);
    }
};

I verified that the py_list is correctly assigned by printing it from python.

OS: Ubuntu 18.04 C++ 11 Python 3.6

mercredi 26 juin 2019

How to perform component labelling in a .bmp(binary image) containing digits 9 4 3 6?

I have the binary .bmp image of size 284*1280. The image contains the digits 9 4 3 6. I want to perform component labelling on the image and mark the labels whenever the digits occur. Initially, it is a binary image with only 0 and 1 in the 2d array(0 marked as background and 1 marked as the digits)

I tried to write a component labelling function(checking 8 neighbours) and incrementing a counter whenever I find a component labelled 1

#include<stdio.h>
#include<string.h>
#include<malloc.h>
#include<stdlib.h>
int func(int w, int h, int a[][1280], int i, int j, int c)
{
 if(i==h||j==w)
  {
   return 0;
  }
 if(a[i][j+1]==1)
  {
a[i][j+1]=c; return func(w,h,a,i,j+1,c);
  }
 if(a[i+1][j]==1)
  {
a[i+1][j]=c; return func(w,h,a,i+1,j,c);
  }
 if(a[i+1][j+1]==1)
  {
a[i+1][j+1]=c; return func(w,h,a,i+1,j+1,c);
  }
 else
  {
    return 0;
  }
  }

 unsigned char* read_bmp(char *fname, int* _w, int* _h)
   {
    unsigned char head[54];
    FILE *f=fopen(fname,"rb");
    //BMP header is 54 bytes
    fread(head,1,54,f);
    int w=head[18]+(((int)head[19]) << 8)+(((int)head[20]) << 16)+ 
    (((int)head[21]) << 24);
    int h=head[22]+(((int)head[23]) << 8)+(((int)head[24]) << 16)+ 
    (((int)head[25]) << 24);
    //lines are aligned on 4-byte boundary
    int lineSize = (w / 8 + (w / 8) % 4);
    int fileSize=lineSize * h;
    unsigned char *img, *data;
    img =(unsigned char*)malloc(w * h), data =(unsigned 
    char*)malloc(fileSize);
    //skip the header
    fseek(f,54,SEEK_SET);
    //skip palette - two rgb quads, 8 bytes
    fseek(f,8,SEEK_CUR);
    //read data
    fread(data,1,fileSize,f);
    //decode bits
    int i, j, k, rev_j;
    for(j=0, rev_j=h-1;j<h;j++,rev_j--)
    {
      for(i=0;i<w/8;i++)
      {
        int fpos= j * lineSize + i, pos = rev_j * w + i * 8;
         for(k=0;k<8;k++)
          {
           img[pos+(7-k)]=(data[fpos] >> k) & 1;
          }
       }
    }
     free(data);
     *_w = w; *_h = h;
     return img;
   }


   int main()
   {
    int w, h, i, j, c1=0, c2=0, c3=0, c4=0, c5=0, c6=0;
    unsigned char* img=read_bmp("binary.bmp",&w,&h);
    int array[h][1280];
    char ch;
    for(j=0;j<h;j++)
     {
       for(i=0;i<1280;i++)
       {
        array[j][i]=(int(img[j * w + i])==0);
       }
     }
      register int c=2;
      for(i=0;i<h;i++)
      {
        for(j=0;j<1280;j++)
        {
          if(array[i][j]==1)
          {
            array[i][j]=c;
            func(w,h,array,i,j,c);
          }
       }
     }
      for(i=0;i<h;i++)
      {
       for(j=0;j<w;j++)
       {
         printf("%d",array[i][j]);
       }
      printf("\n");
     }
     return 0;
 }   

I am getting an array of just 0 and 2, whereas it should contain 0,2,3,4,5 labels for other digits. How to fix it?

How to take unbuffered input in c++ (i.e without hitting enter key)?

I'm trying to take comma delimited input from the user so that without pressing enter key,the input is accepted.

Avoid TOCTOU (time-of-check, time-of-use) race condition between stat and rename

How to avoid TOCTOU(time-of-check, time-of-use) race condition for race condition between stat and rename for LOGFILE ?

Required to move the log file after its size value exceeds the max size.

result = stat(LOGFILE, & data);
if (result != 0) {
  // stat failed
  // file probably does not exist
} else if (data.st_size > MAX_LOGSIZE) {
  unlink(PREV_LOGFILE);
  (void) rename(LOGFILE, PREV_LOGFILE);
}

Why brace initialization assignment fills variable with garbage

I have fallen into belief that variables are assigned to it's default values when using a brace initialization. But I was wrong.

In the following example:

#include <string>
#include <iostream>

#include <stdint.h>


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

    int var1;
    int32_t var2;
    int64_t var3;
    std::string var4;
    double var5;
    float var6;

    std::string info() const {
        return "var1=" + std::to_string(var1) + " " +
               "var2=" + std::to_string(var2) + " " +
               "var3=" + std::to_string(var3) + " " +
               "var4=" + var4 + " " +
               "var5=" + std::to_string(var5) + " " +
               "var6=" + std::to_string(var6) + " " +
               "\n"
               ;
    }
};

int main()
{
    A a;
    std::cout << "Before assigning variables: " << a.info();

    a.var1 = 1;
    a.var2 = 2;
    a.var3 = 3;
    a.var4 = "4";
    a.var5 = 5;
    a.var6 = 6;
    std::cout << "After assigning variables: " << a.info();

    a = {};
    std::cout << "After brace init assignemnt: " << a.info();
}

Here is the result:

Before assigning variables: var1=0 var2=0 var3=4198240 var4= var5=0.000000 var6=0.000000 
After assigning variables: var1=1 var2=2 var3=3 var4=4 var5=5.000000 var6=6.000000 
After brace init assignemnt: var1=2114725200 var2=32766 var3=4199416 var4= var5=0.000000 var6=0.000000

To fix this I need ethier to get rid of default constructor, or assign each variable with brace constructor: int var1{};

Can someone please explain why this happens?

Problem with linkage in a Doubly Linked List

I am trying to implement a doubly linked list with the following API :

  • bool empty(); // is the list empty?
  • void append(char c); // inserts the character c at the back of the list
  • int size(); // the number of elements in the list
  • string toString(); // return the list as a string.
  • CharList(string s); // constructor. Initializes the list to the contents of the string.
  • ~CharList(); // destructor. Returns all memory in the list.

I have a really persistent bug where my pointers from the header node. to the next link are not working The problem manifests itself when I use the toString function.The problem manifests itself when I use the toString function.

My constructor ( with a default argument of s = "" ) calls on the append function and is shown below. I have also shown the toString function too.

I have tried using the trailer for the toString function and can confirm that indeed I do get the string back ( although it will be reversed which would be an easy fix.

CharList::CharList(string s)
{
  count = 0;
  header = new CharListNode;
  trailer = new CharListNode;
  int length = s.length();
  header->next = trailer;
  trailer->prev = header;
  if(length == 0)
  {
    return;
  }
   const char* c_string = s.c_str();
   for(int i = 0; i<length; i++)
   {
     char letter = c_string[i];
     CharList::append(letter);
   }
}

void CharList::append(char c)
{
  CharListNode *z = new CharListNode;
  z->element = c;
  z->next = this->trailer;
  z->prev = this -> trailer->prev;
  this->trailer->prev->next = z;
  trailer->prev = z;
  count++;
  return;
}

string CharList::toString() const
{
  cout<< " entered toString()"<<endl;
  string s= "";
  int length = CharList::size();
  CharListNode * traversal = header;
  cout << trailer->prev->element<<endl;
  cout << header->next->element<<endl;
  //cout<<header->next->next->element<<endl;
  for(int i=0; i < length; i++)
  {
    traversal = header -> next;
    char x = header->element;
    cout << x << endl;
    s = s+x;
  }
  cout<< s << endl;
  return s;
}

So for example the following piece of code :

CharList CharList_2 = CharList("abcd");
string word = CharList_2.toString();

is giving an exit status 1 error.

Is this acquire fence observed?

This question is about standalone fences in C++

In an attempt to encapsulate the use of acquire and release fences, I have written the following code:

#include <thread>
#include <atomic>
#include <cassert>

class sync {
    std::atomic<bool> flag{false};

public:
    void release()
    {
        std::atomic_thread_fence(std::memory_order_release);
        flag.store(true, std::memory_order_relaxed);
    }

    bool acquire()
    {
        return flag.load(std::memory_order_relaxed);
        std::atomic_thread_fence(std::memory_order_acquire); // Is this acquire fence observed by the application ?
    }
};

int main()
{
    sync s;
    int data = 0;

    std::thread t1{[&] { data = 12; s.release(); }};
    std::thread t2{[&] { if (s.acquire()) assert(data==12); }};

    t1.join(); t2.join();
}

I believe that the fences are positioned correctly ('release' before the store and 'acquire' after the load).

I am not sure if the load/acquire actually works.
Since the acquire fence is after the load/return statement, I am wondering if it is taken into account at all.

Is this use of acquire fence correct ?

How to use a range-based for loop with a vector of future

I have a program that calculates some values in different threads with std::packaged_task<int()>. I store the std::future I get from the packaged tasks via get_future() in a vector (defined as std::vector<std::future<int>>).

When I calculate the sum of all the tasks I use a for loop and it's working:

// set up of the tasks
std::vector<std::future<int>> results;
// store the futures in results
// each task execute in its own thread

int sum{ 0 };
for (auto i = 0; i < results.size; ++i) {
    sum += results[i].get();
}

But I would rather use a range-based for loop:

// set up of the tasks
std::vector<std::future<int>> results;
// store the futures in results
// each task execute in its own thread

int sum{ 0 };
for (const auto& result : results) {
    sum += result.get();
}

Currently I get a compile error with clang:

program.cxx:83:16: error: 'this' argument to member function 'get' has type 'const std::function<int>', but function is not marked const

       sum += result.get();
              ^~~~~~
/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/9.1.0/../../../../include/c++/9.1.0/future:793:7: note: 'get' declared here

       get()
       ^

Is it possible to use Range-based for loop with a vector of future<int>?

Undefined behaviour in initializer list order using move semantics

Is (1) undefined behavior, or is the first element of the pair always evaluated first?

#include <array>
#include <utility>

int bar(std::array<int, 3>&& ) {
    return 1;
}

std::pair<std::array<int, 3>, int> foo() {
    std::array<int, 3> a;
    return { a, bar(std::move(a)) };  // (1)
}

As a side note, would using return make_pair(a, bar(std::move(a))); instead be different?

C++ : Vectors forming the columns of a CSV file?

Is there a way to take a series of vectors in C++ and output a CSV file where the columns of the CSV file are the elements of the vectors respectively? So column 1 would be the elements of say the first vector of doubles for examples, etc.

Pass C++ vector of unique_ptr

I have a class Outer which contains an Inner member and owns a vector of unique_ptr elements:

using Elements = std::vector<std::unique_ptr<Element>>;

class Outer
{
    void call()
    {
        _inner.aMethod(_vec);
    }

    Inner _inner;
    Elements _vec;   // This should remain the owner of each Element
};

Inner receives the vector of unique_ptr elements and it transfers ownership to it's own vector class member:

class Inner
{
    public:
    Inner() = default;
    ~Inner() = default;

    void aMethod(Elements& vec)
    {
        _vec = std::move(vec);
    }

    private:

    Elements _vec;  // This is a vector of unique_ptr but I don't want this class to own the memory
};

I stupidly used std::move() because otherwise the compiler complained I was trying to call a deleted function (probably the copy constructor) on each vector element.

I have an illegal memory access and I believe it is because both classes think they own the vector elements and one has tried to delete an already-deleted Element.

How do I have Outer owning the memory and just pass the elements to Inner to use (not take ownership)?

Why does make_pair

The following piece of code works fine when compiling as C++ 98, but it fails as C++ 11. Why?

#include <iostream>
#include <utility>

using namespace std;

int main()
{
    int u = 1;
    pair<int, int> p = make_pair<int, int>(0, u);
    cout << p.first << " " << p.second << "\n";
}

The error message from g++ (Debian 8.3.0-6) 8.3.0 is:

foo.cpp: In function ‘int main()’:
foo.cpp:9:45: error: no matching function for call to ‘make_pair<int, int>(int, int&)’
  pair<int, int> p = make_pair<int, int>(0, u);
                                             ^

I'm aware that I can compile this simply by removing the template specifier from make_pair and letting the compiler decide the types on its own. But I'm interested in understanding what changes from C++ 98 to C++ 11 that makes this code no longer compliant.

How to choose dynamicly in C/C++ the type to cast to?

Is there a way to do

if(...)
  return (int)value;

return (unsigned int)value;

by moving the check into the cast to get something like

return (???)value;

Is a move constructor/assignment needed for RVO to kick in in C++11?

For example:

In accepted answer https://stackoverflow.com/a/14623480/1423254,

Does copy elision and RVO would still work for classes without move constructors?

Yes, RVO still kicks in. Actually, the compiler is expected to pick: RVO (if possible)

In accepted answer https://stackoverflow.com/a/38043447/1423254,

Under non-guaranteed copy elision rules, this will create a temporary, then move from that temporary into the function's return value. That move operation may be elided, but T must still have an accessible move constructor even if it is never used.

The point is that I thought that RVO and "lvalue moves" (or how to call them) are 2 totally separate operations, but my colleague told me that for RVO to kick in, the class returned needs a move constructor. So I checked the internet and SO and obviously, the information can't be found quickly...

Why does the function return two different values even when nothing is changed in the function call?

In the first case the code returns -1

#include <iostream>

template <typename T>
int compare( const T &val1, const T &val2){

    if(val1 < val2) return -1;
    if(val2 > val1) return 1;
    return 0;
}

int main(){

    std::string v1= "hello", v2 = "world";
    std::cout << compare("hello", "world") << std::endl;
}

In the second case the code returns zero even when there is no change in the method call.

#include <iostream>

template <typename T>
int compare( const T &val1, const T &val2){

    if(val1 < val2) return -1;
    if(val2 > val1) return 1;
    return 0;
}

int main(){

    std::cout << compare("hello", "world") << std::endl;
}

I am using g++ 7.4.0.

How can I build a stand-alone binary with a c++ pistache rest-api for an embedded board(with i686 architecture)?

I'm trying to build a stand-alone binary containing a Rest API made with pistache framework. For that purpose I created a docker image using "FROM i386/ubuntu:16.04" and installing all dependencies in it. But the binary throws "Segmentation fault" error when I try to execute it and it's compilation shows some warnings.

I compile it with this command (output warnings included):

g++ server.cpp -std=c++11 -lpistache -lssl -lcrypto -pthread -ldl -static -o server

root@91cb986a4e48:/workspace# g++ server.cpp -std=c++11 -lpistache -lssl -lcrypto -pthread -ldl -static -o server
/usr/lib/gcc/i686-linux-gnu/5/../../../i386-linux-gnu/libcrypto.a(dso_dlfcn.o): In function `dlfcn_globallookup':
(.text+0xa): warning: Using 'dlopen' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking
//usr/local/lib/libpistache.a(listener.cc.o): In function `Pistache::Tcp::Listener::bind(Pistache::Address const&)':
listener.cc:(.text+0x1b94): warning: Using 'getaddrinfo' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking
//usr/local/lib/libpistache.a(net.cc.o): In function `Pistache::Address::init(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)':
net.cc:(.text+0x14ce): warning: Using 'gethostbyname' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking


server.cpp contains the hello world code from pistache:

#include <pistache/endpoint.h>

using namespace Pistache;

struct HelloHandler : public Http::Handler {
  HTTP_PROTOTYPE(HelloHandler)
  void onRequest(const Http::Request&, Http::ResponseWriter writer) override{
    writer.send(Http::Code::Ok, "Hello, World!");
  }
};

int main() {
  Http::listenAndServe<HelloHandler>("*:9080");
}

When I compile and run it in my pc there is no problem (compiling with "g++ server.cpp -std=c++11 -lpistache -o server"), but how can I make it work in my i686 board?

caching component for general object

I'm building an application that serves requests for returning XML documents. I want to cache document read to improve application performance by reducing the number of I/O operations. Also, I need it to invalidate the documents after a specific period.

For example:

  1. My app reads 'document1'
  2. My app asks cache component to save the read document for 2 minutes.
  3. For the second request, the app asks cache component if 'document1' is cached or not?
  4. If yes, don't read it from the disk and get it from the cache
  5. If no (due to the period is expired) go to step 1

Is there any open source solution for those requirements and available for code to code integration?

List destructor causing crash in thread-local singleton class

I've tried to create thread-local singleton class with member of std::list type. During testing my solution with multiple threads, I've encountered strange crash caused by std::list destructor (more precisely, _M_clear() method invoked by destructor). It happens even without performing any operations on mentioned list. What is even more strange - this crash ocurrs randomly.

Any ideas, what can be problem here?

Below is minimal example to repreduce this error:

#include <list>
#include <thread>

class tls_list_test
{
private:
    std::list<int> test_list;

    tls_list_test() = default;

    ~tls_list_test() = default;

public:
    static tls_list_test& get_instance()
    {
        thread_local tls_list_test instance;
        return instance;
    }
};

int main()
{
    std::list<std::thread> threads;

    for (int i = 0; i < 3; ++i)
    {
        std::thread thread([]()
           {
               auto& instance = tls_list_test::get_instance();
           });
        threads.push_back(std::move(thread));
    }

    for (auto& thread : threads)
    {
        thread.join();
    }

    return 0;
}

Code in std::list causing segfault:

  template<typename _Tp, typename _Alloc>
    void
    _List_base<_Tp, _Alloc>::
    _M_clear() _GLIBCXX_NOEXCEPT
    {
      typedef _List_node<_Tp>  _Node;
      __detail::_List_node_base* __cur = _M_impl._M_node._M_next;
      while (__cur != &_M_impl._M_node)
    {
      _Node* __tmp = static_cast<_Node*>(__cur);
      __cur = __tmp->_M_next; // <- SEGFAULT on this line
      _Tp* __val = __tmp->_M_valptr();
#if __cplusplus >= 201103L
      _Node_alloc_traits::destroy(_M_get_Node_allocator(), __val);
#else
      _Tp_alloc_type(_M_get_Node_allocator()).destroy(__val);
#endif
      _M_put_node(__tmp);
    }
    }

GDB Variables:

Signal = SIGSEGV (Segmentation fault)
__tmp = {std::__cxx11::_List_base<int, std::allocator>::_Node * | 0xfeeefeeefeeefeee} 0xfeeefeeefeeefeee
__val = {int * | 0x2ee4448} 0x2ee4448
this = {std::__cxx11::_List_base<int, std::allocator> * const | 0x2ee5be8} 0x2ee5be8
__cur = {std::__detail::_List_node_base * | 0xfeeefeeefeeefeee} 0xfeeefeeefeeefeee

G++ version:

g++ (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 8.1.0

using initializer list to initialize unordered_map

I have this class

class A {
    unordered_map<string, unordered_set<string>> n_;
  public:
    A(unordered_map<string, unordered_set<string>>& n) : n_{n} {}
};

And I want to be able to use the constructor with that syntax

int main() {
    A aC};
    return 0;
}

But in the way it's written now, I'm getting error

error: no matching function for call to ‘A::A(<brace-enclosed initializer list>)’ A aC};

How can it be fixed?

Thanks

How to efficiently prepend a vector to a vector

I have 2 vectors like so:

std::vector<unsigned char> v1;
std::vector<unsigned char> v2;

Each of them has some data of course.

I know that following is the way if I want to append v2 to v1. v1.insert(v1.end(), v2.begin(), v2.end());

Question:
How can I prepend v1 to v2 instead?
v2.insert(v2.begin(), v1.begin(), v1.end()) doesn't seem to work here?

I know that I might get suggestions of using std::deque instead but the problem is that v2 is coming as a std::vector out a legacy piece of code I cannot change. And it contains a huge amount of data which I do not want copy over to v2 by appending. So, I simply want to prepend v1 to v2 because v1 is extremely small compared to v2

Generate unique values for global constexpr variables

I am using global constexpr as keys to access a map, and I was wondering if there was a way to automatically initialize them with the next available integer.

constexpr size_t ON_EVENT_X = 0;
constexpr size_t ON_EVENT_Y = 1;
constexpr size_t ON_EVENT_Z = 2;

Is it possible, given ON_EVENT_X, ON_EVENT_Y and ON_EVENT_Z to automatically initialize them with the correct values ? I think it could be done with a preprocessor macro but I haven't used it enough to know exactly how.

Any suggestions ?

Thanks!

mardi 25 juin 2019

How can we efficiently store objects using stl containers? (viz. for searching based on values of their fields)

I have objects of something like this:

struct stStudents 
{
    int roll_number;
    std::string name;
    // There could be more fields here
}

I need to store these objects using stl containers in such a way that I should be able to search them as fast as possible based on field(s) e.g roll_number or name (or both) in above example.

What I already tried/thought of:

  1. As plain as it can get, if I simply store them in std::vector (and probably by using std::find_if) searching will be O(n).

  2. With std::set and std::map it would take O(log N), but for that however overloaded comparison operator of the object needs to be based on particular field (or may be set of fields by using std::tie)

  3. Having various std::unordered_set of pointers to those objects. And define comparison operator in struct based on search criteria (just like we define multiple indices in database). This will be O(1) search but limited to predefined search criteria.

Question:

How are these approaches and what are other better alternatives can we think of?

About compiling C++98 codes using C++11 standard

What are additional configurations required in compilations and linking to successfully compile the c++98 codes using C++11/gnu+11 standard?

Stateless Lambda and Private members

In certain cases when programming with libraries written in C involving callbacks, I like to use Lambda expressions; however, if I need to alter the state of a class member variable I can't juts pass this into a stateless(function pointer) lambda. But I can assign this to a data in a context structure. What I find strange is being able to access that member variable even if it's private in the class. Here's an example code I wrote to demonstrate.

#include <iostream>
using std::cout;
typedef struct extradatatype{
    void* data;
}extradata;
extradata e = {0};
typedef void(*callback)(extradata* e);
void cb(callback c){
    c(&e);
}

class Test{
private:
    int x;
public:
    Test(int x){
        this->x = x;
    }
    void setcb(){
        cb([](extradata* e){
            Test* self = reinterpret_cast<Test*>(e->data);
            self->x = 20;
        });
    }

    int getx(){
        return x;
    }
};

int main(){
    Test t(10);
    e.data = &t;
    t.setcb();
    cout << t.getx();

    return 0;
}

In the Lambda expression Test* self is assigned to e->data but I can access self->x as if it were a public member instead of private. So what I'm confused about is, is the lambda expression expression being executed within the stack/context of the setcb function or is it being executed elsewhere as its own function but C++ is doing some weird trick to allow private members to be accessed. Because I assume a stateless lambda is really no different than a non member static function which has no access to private members of a class.