jeudi 31 mai 2018

Can variadic functors in C++ support named fields?

I'm implementing a variadic functor generic called "Signal" which manages an internal queue of functors of matching function signature types. On calling Signal::operator() every functor in the queue is executed with the same input args. The idea is that it is a pure C++11 object type which recreates some of the same design behaviors as Qt's Signal/Slot construct, but statically compiled with minimal dependencies. I have everything working, but I'd like to improve the readability of this generic.

Syntax I have:

Signal<int, double> mySignal;
signal.add(BLOCK, [](int EmployeeID, double FavoriteNumber) {
    std::cout << EmployeeNames[EmployeeID]
              << " has favorite number of "
              << FavoriteNumber << std::endl;
});
signal.add(BLOCK, [](int EmployeeID, double FavoriteNumber) {
    if (EmployeeID > FavoriteNumber) {
        std::cout << EmployeeNames[EmployeeID]
                  << " has ID bigger than favorite number.\n";
    }
});
mySignal(5, 3.1415); //execute both functors with args = (5, 3.1415)

What I would like to have:

Signal<int EmployeeID, double FavoriteNumber> mySignal;
signal.add(BLOCK, [](int EmployeeID, double FavoriteNumber) {
    std::cout << EmployeeNames[EmployeeID]
              << " has favorite number of "
              << FavoriteNumber << std::endl;
});
signal.add(BLOCK, [](int EmployeeID, double FavoriteNumber) {
    if (EmployeeID > FavoriteNumber) {
        std::cout << EmployeeNames[EmployeeID]
                  << " has ID bigger than favorite number.\n";
    }
});
mySignal(5, 3.1415); //execute both functors with args = (5, 3.1415)

The only difference is that I would like the declaration of the templated signal type to specify a name for the parameter for readability sake. Ideally I would like these names to be mandatory and fail compilation if unspecified.

Is there a way to achieve this?

Passing vector by reference makes iterative algorithm run differently

This one has me baffled. I was implementing the Dutch national flag problem in C++. I forgot to pass my array by reference initially, but was displaying the array at every step, which helped me conclude that my algorithm worked fine. To fix the minute error of the vector not getting partitioned finally, I changed the function definition to pass vector as reference, which somehow produced an error.

I have never encountered something like this before. The code isn't recursive, and so while the function is running it shouldn't matter whether it is running on a copy of the vector or is running on the actual vector.

Here is the code:

#include<iostream>
#include<vector>
#include<algorithm>
#include<iomanip>

using namespace std;

void optArr(vector<int> arr){
    for(auto i: arr){
        cout<<setw(3)<<i<<" ";
    }
    cout<<endl;
}

void _partition(vector<int> arr, int lo, int hi, int &i, int &k){  //Vector passed by value
    i=lo-1, k=hi+1;
    int ptr=lo, pivot=arr[hi];
    while(ptr<k){
        optArr(arr);
        cout<<"i: "<<i<<" ptr: "<<ptr<<" k: "<<k<<endl;
        if(arr[ptr]<pivot){
            swap(arr[++i],arr[ptr++]);
        }else if(arr[ptr] == arr[pivot]){
            ptr++;
        }else{
            swap(arr[--k],arr[ptr]);
        }
    }
}



int main(){
    vector<int> arr = {57,22,85,17,11,04,17,93,1,17,25,17};
    int i,k;
    _partition(arr, 0, arr.size()-1, i, k);
    optArr(arr);
    cout<<"i: "<<i<<" ptr: "<<0<<" k: "<<k<<endl;

    return 0;
}

And the output when vector is passed by value:

 57  22  85  17  11   4  17  93   1  17  25  17
i: -1 ptr: 0 k: 12
 17  22  85  17  11   4  17  93   1  17  25  57
i: -1 ptr: 0 k: 11
 17  22  85  17  11   4  17  93   1  17  25  57
i: -1 ptr: 1 k: 11
 17  25  85  17  11   4  17  93   1  17  22  57
i: -1 ptr: 1 k: 10
 17  17  85  17  11   4  17  93   1  25  22  57
i: -1 ptr: 1 k: 9
 17  17  85  17  11   4  17  93   1  25  22  57
i: -1 ptr: 2 k: 9
 17  17   1  17  11   4  17  93  85  25  22  57
i: -1 ptr: 2 k: 8
  1  17  17  17  11   4  17  93  85  25  22  57
i: 0 ptr: 3 k: 8
  1  17  17  17  11   4  17  93  85  25  22  57
i: 0 ptr: 4 k: 8
  1  11  17  17  17   4  17  93  85  25  22  57
i: 1 ptr: 5 k: 8
  1  11   4  17  17  17  17  93  85  25  22  57
i: 2 ptr: 6 k: 8
  1  11   4  17  17  17  17  93  85  25  22  57
i: 2 ptr: 7 k: 8
 57  22  85  17  11   4  17  93   1  17  25  17
i: 2 ptr: 0 k: 7

You can see that the output is correct, right up to the last one, which is called through the main function. When I saw this, I decided to pass the vector by reference by modifying the _partition signature to: void _partition(vector<int> &arr, int lo, int hi, int &i, int &k)

This produced the following output:

 57  22  85  17  11   4  17  93   1  17  25  17
i: -1 ptr: 0 k: 12
 17  22  85  17  11   4  17  93   1  17  25  57
i: -1 ptr: 0 k: 11
 25  22  85  17  11   4  17  93   1  17  17  57
i: -1 ptr: 0 k: 10
 17  22  85  17  11   4  17  93   1  25  17  57
i: -1 ptr: 0 k: 9
  1  22  85  17  11   4  17  93  17  25  17  57
i: -1 ptr: 0 k: 8
  1  22  85  17  11   4  17  93  17  25  17  57
i: 0 ptr: 1 k: 8
  1  93  85  17  11   4  17  22  17  25  17  57
i: 0 ptr: 1 k: 7
  1  17  85  17  11   4  93  22  17  25  17  57
i: 0 ptr: 1 k: 6
  1   4  85  17  11  17  93  22  17  25  17  57
i: 0 ptr: 1 k: 5
  1   4  85  17  11  17  93  22  17  25  17  57
i: 1 ptr: 2 k: 5
  1   4  11  17  85  17  93  22  17  25  17  57
i: 1 ptr: 2 k: 4
  1   4  11  17  85  17  93  22  17  25  17  57
i: 2 ptr: 3 k: 4
  1   4  11  17  85  17  93  22  17  25  17  57
i: 2 ptr: 0 k: 3

As you can see, this behaves abnormally right from the third line of output. I apologize for such a vague question, but I have no idea how else to go about looking for a solution to such an unusual problem.

candidate function not viable: no known conversion from std::vector

First, The title probably may not reflect the current question, so please feel free to change. Assuming I have the following classes;

#include  <iostream>
#include <vector>

template <typename K, class V>
class A {
public:
  K x;
  V y;
  A(K x, V y):x(x), y(y) {}
  void print(A<K, V>& z) {
    std::cout << x + z.x << "-" << y + z.y << std::endl;
  }
  void print(std::vector<A<K,V>> z) {
    for(auto& i:z) {
      print(i);
    }
  }
};

class B:public A<int, std::string> {
public:
  B():A(0, "zero") {}
  B(int x, std::string y):A(x, y) {}
};

void test() {
  B b1(1, "one");
  B b2(2, "two");
  B b3(3, "three");
  B b4(4, "four");
  B b5(5, "five");
  b5.print(b1);
  //
  std::vector<B> c;
  c.push_back(b1);
  c.push_back(b2);
  c.push_back(b3);
  c.push_back(b4);
  b5.print(c);
}

I get the following error at last last line (b5.print(c));

test_class.cpp:40:6: error: no matching member function for call to 'print'
  b5.print(c);
  ~~~^~~~~
test_class.cpp:10:8: note: candidate function not viable: no known conversion from 'std::vector<B>' to 'A<int, std::__1::basic_string<char> > &' for 1st argument
  void print(A<K, V>& z) {
       ^
test_class.cpp:13:8: note: candidate function not viable: no known conversion from 'vector<B>' to 'vector<A<int, std::__1::basic_string<char> >>' for 1st argument
  void print(std::vector<A<K,V>> z) {
       ^
1 error generated.

I basically expect an implicit conversion from vector<B> to std::vector<A<int,std::string>> but it is not. Hence, I came up with two solutions to the issue.

  1. Define typedef std::vector<A<int,std::string>> MyWeirdVector; in class A and use se B::MyWeirdVector c; instead of std::vector<B> c;.
  2. Define each print function as template <typename U> in A class and accept typename U as argument.

Both solutions has its own drawback. In first, I have to instantiate c as B::MyWeirdVector and in second, I don't (feel like) have a type safety. Second solutions works even if I don't define type in <>.

So, is there an elegant solution to this issue like to let implicit type conversion from std::vector<B> to std::vector<A<int,std::string>>?

Is writing std::deque at different memory locations concurrently thread-safe?

I have a std::deque<std::pair<CustomObj, int>> that doesn't change in size when starting the concurrent block.

The concurrent block reads each CustomObj of the deque and sets the int.

I can guarantee that the deque won't change size therefore it won't reallocate, and that each thread will only access a memory chunk of the deque but not the other thread's.

Does it lead to undefined behaviour reading and writing concurrently? Should put the writing and reading in a mutual exclusion zone?

how to do optional nullable template wrapper

How to represent a type which is optional and also nullable, i.e. can be explicitly set to null?

Is there something in the standard library or boost?

Otherwise I thought to do something like:

template<typename T>
class optnull : public optional<optional<T>>
{
public:
    bool isSet() { ...; }
    bool isNull() { ...; }
    T& get() { ...; }
};

is that good?

std::pair of strings as custom key of unordered_map defined in std fails with template errors

I have a map defined and used like this

// def.h
struct X{};
struct Y{};
struct myStruct
{
   X x;
   Y y;
};

typedef std::unordered_map<std::pair<std::string, std::string>, myStruct> myMap;
namespace std
{
   template<> struct pair<std::string, std::string>
   {
      std::string s1,s2;
      pair(const std::string& a, const std::string& b):s1(a),s2(b){}
      bool operator < (const pair<std::string,std::string>& r)
      {
         return (0 < r.s1.compare(s1) && (0 < r.s2.compare(s2)));
      }
   };
} 

//use.cpp
class CUse
{
  myMap m;
public:
   CUse():m(0){}
};

Some errors emitted by the compiler are extracted as below

  1. At the constructor CUse initialization,

note: see reference to function template instantiation 'std::unordered_map,myStruct,std::hash<_Kty>,std::equal_to<_Kty>,std::allocator>>::unordered_map(unsigned __int64)' being compiled

  1. At the declaration of m in CUse

note: see reference to class template instantiation 'std::unordered_map,myStruct,std::hash<_Kty>,std::equal_to<_Kty>,std::allocator>>' being compiled

Random bytes generation in c++11

I've written a funtion to prouduce random bytes in a uint8_t type array, unless I seed this with a random_device object it works fine but when I seed there are some compiler errors.

code:

#include <algorithm>
#include <random>
#include <functional>
#include <stdint>

void generateInitVector(uint8_t IV_buff[16])
{
using bytes_randomizer = std::independent_bits_engine<std::default_random_engine, CHAR_BIT, uint8_t>;
std::random_device rd;
bytes_randomizer bytes(rd);

std::generate(std::begin(IV_buff), std::end(IV_buff), std::ref(bytes));
}

compiler errors:

  1. error: no matching function for call to 'begin(uint8_t*&)'|

  2. error: request for member 'begin' in '__cont', which is of non-class type 'unsigned char*'|

  3. error: request for member 'begin' in '__cont', which is of non-class type 'unsigned char* const'|

  4. error: no matching function for call to 'end(uint8_t*&)'|

  5. error: request for member 'begin' in '__cont', which is of non-class type 'unsigned char*'|

  6. error: request for member 'end' in '__cont', which is of non-class type 'unsigned char* const'|

  7. error: 'class std::random_device' has no member named 'generate'|

There's catch that if I define a uint8_t type array within th function

uint8_t data[16];
std::generate(std::begin(data), std::end(data), std::ref(bytes));  //and pass this array in `generate()`.

then only error 7 remains.

I'm using codeblocks 16.01

Any solutions to this.

Thanks.

inherit signal in libsourcey lib

I'm using libsourcey lib for learning. I try to write a new class that inherit a class named Signal.

in libsourcey

template <typename RT> class Signal;
template <typename RT, typename... Args> class Signal<RT(Args...)> {...}

and my way

template <typename RT> class NewSignal;
template <typename RT, typename... Args> class NewSignal<RT(Args...)> : public Signal<RT(Args...)> {...}

but i can't access any property of class Signal, also attribute (although I modify attribute to public). Complier (eclipse) report: was not declared in this scope

Anyone explain why complier report like this. How i can inherit Signal class. If not, have any solution? Thank for supporting.

Same mutex in multiple function calling each other

I have two functions

void myclass::func()
{
     std::shared_lock<std::mutex>(m_mutex);
     func1();
}

void myclass::func2()
{
     std::shared_lock<std::mutex>(m_mutex);
}

is it right way to using mutex ? or it will cause any problem ? I have lots of function which are doing reading/writing but they are also calling in each other frequently. how should I implement this scenario ?

I am using c++11 for mutex.

Formating C++ integers

This is a follow up question to this question:

How do I print bytes as hexadecimal?

The question above however, doesn't answer exactly what I need.

What is the c++ 11 equivalent of C# ToString("X8") for numbers?

an example of what I'm talking about in C#:

using System;
using System.Globalization;

public class Example

{
   public static void Main()

   {
    int value;
    value = 0x2045e;
    Console.WriteLine(value.ToString("x"));
    Console.WriteLine(value.ToString("X"));
    Console.WriteLine(value.ToString("X8"));

    value = 123456789;
    Console.WriteLine(value.ToString("X"));
    Console.WriteLine(value.ToString("X2"));
  }
}

/* 
2045e
2045E
0002045E
75BCD15
75BCD15 
*/

Formating integers

What is the c++ 11 equivalent of C# ToString("X8")?

an example of what I'm talking about in C#:

using System;
using System.Globalization;

public class Example

{
   public static void Main()

   {
    int value;
    value = 0x2045e;
    Console.WriteLine(value.ToString("x"));
    Console.WriteLine(value.ToString("X"));
    Console.WriteLine(value.ToString("X8"));

    value = 123456789;
    Console.WriteLine(value.ToString("X"));
    Console.WriteLine(value.ToString("X2"));
  }
}

/* 
2045e
2045E
0002045E
75BCD15
75BCD15 
*/

mercredi 30 mai 2018

regex performance java vs c++11

I am learning regex in c++ and java. So i did a performance test on c++11 regex and java regex with same expression and same no of inputs. Strangely java regex is faster than c++11 regex. There is something wrong in my code. Pls correct me

Java code:

import java.util.regex.*;

public class Main {
    private final static int MAX = 1_000_000;
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        Pattern p = Pattern.compile("^[\\w._]+@\\w+\\.[a-zA-Z]+$");
        for (int i = 0; i < MAX; i++) {
            System.out.println(p.matcher("abcd_ed123.t12y@haha.com").matches());
        }
        long end = System.currentTimeMillis();
        System.out.print(end-start);
    }
}

C++ code:

#include <iostream>
#include <Windows.h>
#include <regex>

using namespace std;

int main()
{
    long long start = GetTickCount64();
    regex pat("^[\\w._]+@\\w+\\.[a-zA-Z]+$");
    for (long i = 0; i < 1000000; i++) {
        cout << regex_match("abcd_ed123.t12y@haha.com", pat) << endl;
    }
    long long end = GetTickCount64();
    cout << end - start;
    return 0;
}

Performance:

Java -> 1003ms
C++  -> 124360ms

can I use std::move with class that doesn't provide a move constructor?

I have a class like this:

class myClass
{
    int x[1000];
 public:
     int &getx(int i)
    {
        return x[i];
    }
}

Please note that I did not provide a move construct here.

if I use the following code:

myClass A;
auto B=std::move(a);

does A moves to B or since I did not provided a move constructor, A is copied to B?

Is there any default move constructor for an object? If yes, how it does work with pointers and dynamically allocated arrays?

what happens when you dynamic_cast from derived_1 class to derived_2 class

I am trying to figure out what happens when you dynamic_cast from one derived class to another derived class. Why does the below code raise a segmentation fault? Note that I am not trying to use this code for anything. I merely want to understand what is happening. It's also worth noting that the same code works using static_cast. I can't seem to find any documentation that goes into the finer details of what is happening here. Can somebody explain?

struct base 
{ 
    virtual void printing(){cout<<"base printing"<<endl;};
};
struct derived_1 :public base 
{ 
    virtual void printing(){cout<<"derived_1 printing"<<endl;};
};
struct derived_2 :public base 
{ 
    virtual void printing(){cout<<"derived_2 printing"<<endl;};
};

int main()
{
    base * b = new derived_2();
    derived_1 *d_1 = dynamic_cast<derived_1*>(b);

    // calling printing raises segmentation fault
    d_1->printing(); 
}

How to erase a vector containing structs with std:unique_ptr?

The next source code does not even compile unless the clear() vector line is commented. Is anyone able to explain me why and how to fix it?

#include <vector>

class Class
{
public:
    typedef std::unique_ptr<int> Variable;

public:
    Class() {}
    Class(Class&& other) { variables = std::move(other.variables); }

private:
    std::vector<Variable> variables;
};

void main()
{
    std::vector<Class> container;
    container.push_back(Class());
    container.clear();
}

How to compile against C++11

I am using VS2013 Update 5 for compiling my C++ source. Which compiler version VS2013 Update 5 using? Can I compile my source against C++ 11 version?

C++ : Vectors in Structure

enter image description here **Problem Is that when I run Program it donot ask for first persons first name.. After that it asks every thing. **

int main()
{
    int a;
    cout<<"How Many Persons data you want to Enter ?";
    cin>>a;
    vector<data> persons;
    cout<<"\n\n\t\t\t\t First Name , Last Name and CNIC Number \n\n";
    for(int i=0;i<a;i++)
    {
        persons.push_back(data());
        cout<<"Please Enter First Name of Person "<<i+1<<" :  ";
        getline(cin,persons[i].fn);
        cout<<"Please Enter Last Name of Person "<<i+1<<" : ";
        getline(cin,persons[i].ln); 
        persons[i].full_name=persons[i].fn+persons[i].ln;
    }

C++11 synchronisation in Linux signal handler

I have a multithreaded Linux app that is required to terminate smoothly in response to SIGTERM.

The way it's currently implemented uses a std::promise<void> and associated future: the main thread first installs a simple SIGTERM handler that sets the promise and returns, then it launches all the subsidiary threads, and then it waits on the future. When SIGTERM is received, the handler sets the promise. This unblocks the main thread, which controls orderly shutdown of the subsidiary threads and then exits.

This all works fine - but as far as I can tell there's actually no guarantee that it's safe to use std::promise::set_value() (or, for that matter, any other C++11 synchronisation mechanism) within the signal handler.

Is this actually risky in practice? Should I replace this with e.g. sem_post or some other mechanism explicitly described as safe?

Can I use static const float in header with value initialization

I have this question bugging me.

Why cant I have code like this in my .hpp file.

class H {
  private:
    static const int i =5;
    static const float f = 1.0;
    static const string s = "string";
}

Only int, bool, enum and constexpr etc can be declared and initialized like that.

My questions:

  1. Why do strings and other complex datatypes needs proper initialization in cpp? They are constant.

  2. Why do we have different behavior for floats and ints? my guess:gcc does not support that, but can be supported easily if we use constexpr.

c++1y copy and modify a shared_ptr

I would like to know how to "copy" a shared_ptr and modify the contents.

In the following example a "template person" is created and I would like to use it as a "Person" that every body would copy from it. However when std::shared_ptr p2 is assigned the template_person every modification in p2 impacts template_person as well. Is there a way to avoid this, or should I use a normal pointer?

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

class Person{
public:
    ~Person() {}
    Person(int a, std::string b) : age_(a), name_(b) {}

    void set_age(int x) { age_ = x; }
    int age() { return age_; }

private:
    int age_;
    std::string name_;
};

int main () {

    std::shared_ptr<Person> template_person = std::make_shared<Person>(10, "test");

    std::shared_ptr<Person> p2 = template_person;

    p2->set_age(20);

    std::cout << p2->age() << " " << template_person->age() << std::endl;
    //prints 20 20

    return 0;
}

How would I use initializer list to directy create my linked list?

I wrote a linked list in the template format.

Now what I would like to do is this:

mylib::list<int> x = {2,3,4,5}

Where mylib is the namespace, and what I would like to do is create a constructor or overload assignment operator to do this. I read here Initializer list for dynamic array and overloading assignment operators

I cannot possibly think a way of how to this.

mardi 29 mai 2018

Could it be possible to have types with move operations that throw in containers?

While explaining move operations on objects with a colleague, I basically said that move operations should not throw exceptions in a container because if the move operation fails, then there is no way to bring back the original object reliably. Thinking about this more, I'm wondering if that is not correct and that if a move operation that does throw, it could revert the original object back to it's original state.

The reason for this, is that if an object can throw, then it would throw not due to copying or moving the contained objects from the old to the new address, but throw if a resource failed to be acquired. So all of the original information should still be there. If this is the case, then should the compiler not be able to reverse the operations that it did to reconstitute the original object?

It could be possible for an operation to be one way, like moving an integer, but in that case it could just terminate the application, and perhaps if the developer wanted to avoid the one way operation could use a swap method instead.

This would only be possible on default move operators, as if there are any additional logic, it may be difficult for the compiler to do a reverse partial transform.

Am I oversimplifying things? Is there something that I missed which keeps containers from moving objects without a non-throwing move constructor/operator?

Pass argument to member function as with std::cout

I want to create a class with a member function which can be used as std::cout. To demonstrate the problem I created this code example

#include <iostream>
#include <string>

class myClass
{
public:
    void myFunc(? data)
    {
        std::cout << data << std::endl;
    }
};

int main()
{
    myClass myObject;
    int var = 1;
    myObject.myFunc() << "Text" << var;
}

As you can see I would like to pass arguments to the function as if I would have used std::cout directly. Is that possible? I searched the net and read a lot but didn't get it to work, can anybody help or link a page with more information? Thank you very much.

Apply smart pointer on all objects

I'm trying to design a c++ application myself and apply these coding convention rules:
1. All objects have to be wrapped in a smart pointer. No raw pointer.
2. Containers such as std::vector, std::list,... will be declared as normal variable.
3. Always using HAS A, no inheritance.
Ex:

class Base {
public:
    void foo() {}
};

class Derived : public Base {
public: 
    void bar() {
        b->foo();
    }
private:
    shared_ptr<Base> b;
};

Could everyone tell me the pros and cons of these rules? And, Can you provide bad cases?

Pushing back a pointer to a vector and then modifying its value affects the pushed value. What should i do instead?

I am using pointers in c++ to achieve polymorphism and I store pointers to the derived classes into a vector. Changing the value of a stored pointer affects the value of all the copies of the same pointer, as it should, however i would like to modify the value of each object individually. Is it possible?

Main class

#include "Cat.h"
#include "Dog.h"
#include <vector>

int main()
{
  std::vector<Animal*> animalVector;

  Animal* animal;
  animal = new Dog();

  animal->setDescription("Good Dog");
  animalVector.push_back(animal);

  animal->setDescription("Bad Dog");
  animalVector.push_back(animal);

  animal = new Cat();

  animal->setDescription("Good Cat");
  animalVector.push_back(animal);

  for (auto& it : animalVector) {
    it->info();
  }
}

Base class

#pragma once

#include <string>

using std::string;

class Animal
{
  protected:
    string mType; //! Holds the type of the Animal
    string mDescription; //! Holds the description of the Animal

  public:

    Animal();
    virtual ~Animal();
    virtual void info();

    virtual void setDescription(string description) {mDescription = description;}
};

Derived class

#pragma once

#include "Animal.h"

class Dog : public Animal
{
  public:
    Dog();
};

Output

Bad Dog
Bad Dog
Good Cat

Desired output

Good Dog
Bad Dog
Good Cat

Shared pointer to a static const object?

For context, I am implementing a user access system where people can log in to my application. The current logged in user is accessed by a pointer to a CUser:

std::shared_ptr<CUser> m_pCurrentUser;

When a user logs out, I want this pointer to point to a "default" user that I have declared as a static const:

static const CUser xDefaultUser(L"Default", L"password", CUser::EAccessLevels::eAnon);

My first question is whether or not applying static const to the default user object is correct. My reasoning is that it should never change (const) and that I want it available for the lifetime of the application (static).

The second question is how I should assign the default user as the m_pCurrentUser. Should I instead declare a const shared_ptr<CUser> instead of a straight up object?

How to calc inner product of two vectors by stl container and algorithm libraries?

sure there are many ways:

assert(v1.size() == v2.size());
for (auto&& i = 0; i < v1.size(); ++i) {
    acc += v1[i]*v2[i];
}

but there is a zip operator in python, so python code would be easy as following codes:

acc = accumulate([ele1 * ele2 for ele1, ele2 in zip(v1, v2)])

my question is: are there any similar approaches to write some codes as styled as python code? especially by std::algorithm library.

Performance comparison: f(std::string&&) vs f(T&&)

I'm trying to understand the performance implications of using WidgetURef::setName (URef being a Universal Reference, the term coined by Scott Meyers) vs WidgedRRef::setName (RRef being an R-value Reference):

#include <string>

class WidgetURef {
    public:
    template<typename T>
    void setName(T&& newName)
    {
        name = std::move(newName);
    }
    private:
        std::string name;
};

class WidgetRRef {
    public:
    void setName(std::string&& newName)
    {
        name = std::move(newName);
    }
    private:
        std::string name;
};

int main() {
    WidgetURef w_uref;
    w_uref.setName("Adela Novak");

    WidgetRRef w_rref;
    w_rref.setName("Adela Novak");
}

I do appreciate that with universal references one should be using std::forward instead, but this is just an (imperfect) example to highlight the interesting bit.

Question In this particular example, what is the performance implications of using one implementation vs the other? Although WidgetURef requires type deduction, it's otherwise identical to WidgetRRef, isn't it? At least in this particular scenario, in both cases the argument is an r-value reference, so no temporaries are created. Is this reasoning correct?

Context The example was taken from Item25 of Scott Meyers' "Effective Modern C++" (p. 170). According to the book (provided that my understanding is correct!), the version taking a universal reference T&& doesn't require temporary objects and the other one, taking std::string&&, does. I don't really see why.

Visual Studio 2017 C++ 11 Error

Does Visual Studio 2017 not support C++ 11. When trying to compile code for C++11, it throws an error. This here is the code:

This code works fine and isn't written in C++11.

    #ifndef SALESITEM_H
    #define SALESITEM_H

    // Definition of Sales_item class and related functions goes here


    #include <iostream>
    #include <string>

    class Sales_item {
    friend bool operator==(const Sales_item&, const Sales_item&);
    // other members as before
    public:
        // added constructors to initialize from a string or an istream
        Sales_item(const std::string &book):
                  isbn(book), units_sold(0), revenue(0.0) { }
        Sales_item(std::istream &is) { is >> *this; }
        friend std::istream& operator>>(std::istream&, Sales_item&);
        friend std::ostream& operator<<(std::ostream&, const Sales_item&);
    public:
        // operations on Sales_item objects
        // member binary operator: left-hand operand bound to implicit this pointer
        Sales_item& operator+=(const Sales_item&);
        // other members as before

    public:
        // operations on Sales_item objects
        double avg_price() const;
        bool same_isbn(const Sales_item &rhs) const
            { return isbn == rhs.isbn; }
        // default constructor needed to initialize members of built-in type
        Sales_item(): units_sold(0), revenue(0.0) { }
    // private members as before
    private:
        std::string isbn;
        unsigned units_sold;
        double revenue;

    };


    // nonmember binary operator: must declare a parameter for each operand
    Sales_item operator+(const Sales_item&, const Sales_item&);

    inline bool 
    operator==(const Sales_item &lhs, const Sales_item &rhs)
    {
        // must be made a friend of Sales_item
        return lhs.units_sold == rhs.units_sold &&
               lhs.revenue == rhs.revenue &&
           lhs.same_isbn(rhs);
    }

    inline bool 
    operator!=(const Sales_item &lhs, const Sales_item &rhs)
    {
        return !(lhs == rhs); // != defined in terms of operator==
    }

    using std::istream; using std::ostream;

    // assumes that both objects refer to the same isbn
    inline
    Sales_item& Sales_item::operator+=(const Sales_item& rhs) 
    {
        units_sold += rhs.units_sold; 
        revenue += rhs.revenue; 
        return *this;
    }

    // assumes that both objects refer to the same isbn
    inline
    Sales_item 
    operator+(const Sales_item& lhs, const Sales_item& rhs) 
    {
        Sales_item ret(lhs);  // copy lhs into a local object that we'll return
        ret += rhs;           // add in the contents of rhs 
        return ret;           // return ret by value
    }

    inline
    istream& 
    operator>>(istream& in, Sales_item& s)
    {
        double price;
        in >> s.isbn >> s.units_sold >> price;
        // check that the inputs succeeded
        if (in)
            s.revenue = s.units_sold * price;
        else 
            s = Sales_item();  // input failed: reset object to default state
        return in;
    }

    inline
    ostream& 
    operator<<(ostream& out, const Sales_item& s)
    {
        out << s.isbn << "\t" << s.units_sold << "\t" 
            << s.revenue << "\t" <<  s.avg_price();
        return out;
    }

    inline
    double Sales_item::avg_price() const
    {
        if (units_sold) 
            return revenue/units_sold; 
        else 
            return 0;
    }


    #endif

When I go for this Code that is C++11, I get an error

    #ifndef SALESITEM_H
    // we're here only if SALESITEM_H has not yet been defined 
    #define SALESITEM_H

    #include "Version_test.h" 

    // Definition of Sales_item class and related functions goes here
    #include <iostream>
    #include <string>

    class Sales_item {
    // these declarations are explained section 7.2.1, p. 270 
    // and in chapter 14, pages 557, 558, 561
    friend std::istream& operator>>(std::istream&, Sales_item&);
    friend std::ostream& operator<<(std::ostream&, const Sales_item&);
    friend bool operator<(const Sales_item&, const Sales_item&);
    friend bool 
    operator==(const Sales_item&, const Sales_item&);
    public:
        // constructors are explained in section 7.1.4, pages 262 - 265
        // default constructor needed to initialize members of built-in type
    #if defined(IN_CLASS_INITS) && defined(DEFAULT_FCNS)
        Sales_item() = default;
    #else
        Sales_item(): units_sold(0), revenue(0.0) { }
    #endif
        Sales_item(const std::string &book):
                  bookNo(book), units_sold(0), revenue(0.0) { }
        Sales_item(std::istream &is) { is >> *this; }
    public:
        // operations on Sales_item objects
        // member binary operator: left-hand operand bound to implicit this pointer
        Sales_item& operator+=(const Sales_item&);

        // operations on Sales_item objects
        std::string isbn() const { return bookNo; }
        double avg_price() const;
    // private members as before
    private:
        std::string bookNo;      // implicitly initialized to the empty string
    #ifdef IN_CLASS_INITS
        unsigned units_sold = 0; // explicitly initialized
        double revenue = 0.0;
    #else
        unsigned units_sold;  
        double revenue;       
    #endif
    };

    // used in chapter 10
    inline
    bool compareIsbn(const Sales_item &lhs, const Sales_item &rhs) 
    { return lhs.isbn() == rhs.isbn(); }

    // nonmember binary operator: must declare a parameter for each operand
    Sales_item operator+(const Sales_item&, const Sales_item&);

    inline bool 
    operator==(const Sales_item &lhs, const Sales_item &rhs)
    {
        // must be made a friend of Sales_item
        return lhs.units_sold == rhs.units_sold &&
               lhs.revenue == rhs.revenue &&
               lhs.isbn() == rhs.isbn();
    }

    inline bool 
    operator!=(const Sales_item &lhs, const Sales_item &rhs)
    {
        return !(lhs == rhs); // != defined in terms of operator==
    }

    // assumes that both objects refer to the same ISBN
    Sales_item& Sales_item::operator+=(const Sales_item& rhs) 
    {
        units_sold += rhs.units_sold; 
        revenue += rhs.revenue; 
        return *this;
    }

    // assumes that both objects refer to the same ISBN
    Sales_item 
    operator+(const Sales_item& lhs, const Sales_item& rhs) 
    {
        Sales_item ret(lhs);  // copy (|lhs|) into a local object that we'll return
        ret += rhs;           // add in the contents of (|rhs|) 
        return ret;           // return (|ret|) by value
    }

    std::istream& 
    operator>>(std::istream& in, Sales_item& s)
    {
        double price;
        in >> s.bookNo >> s.units_sold >> price;
        // check that the inputs succeeded
        if (in)
            s.revenue = s.units_sold * price;
        else 
            s = Sales_item();  // input failed: reset object to default state
        return in;
    }

    std::ostream& 
    operator<<(std::ostream& out, const Sales_item& s)
    {
        out << s.isbn() << " " << s.units_sold << " "
            << s.revenue << " " << s.avg_price();
        return out;
    }

    double Sales_item::avg_price() const
    {
        if (units_sold) 
            return revenue/units_sold; 
        else 
            return 0;
    }
    #endif

This code is from C++ Primer 5th edition. The previous one is from the forth edition. The forth edition one(First one) works fine, but the second one throws error.

So, if in case C++11 doen't work with Visual Studio 2017, then how can I enable it.

lundi 28 mai 2018

QStyledItemDelegate stuck in hover state when leaving a QListView

I'm stuck at trying to remove a hover state from a QStyledItemDelegate when I leave a QListview .

I check the hover state in the QStyledItemDelegate as follows:

void MyDelegate::paint( QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const
{
    if( option.state & QStyle::State_MouseOver)
     {
        // Paint in MouseOver state
     }
     else
     {
        // Paint normally
     }
 }

Now when I leave the view the paint method is either not called or option.state is still in mouse over state.

Then I tried to implement the leaveEvent in my QListView to call update.

void MyListView::leaveEvent(QEvent *event)
{
   update();
   QListView::leaveEvent(event);
}

This does call the paint method of the delegate on leave but doesn't change the hover state of the item last hovered over in the QListView.

Is there a way to force the delegate to repaint and not be in mouse over state when the cursor leaves the listview ?

Usage of this* in make_unique

I have a small example of Factory design pattern, and I am interested in this part std::make_unique< A >(*this) especially *this. Does it mean that the clone() method return unique pointer which point to member of factory class? And createInstance() returns always the same member of Factory class? I am just confused what std::make_unique< A >(*this) is supposed to do, because A has in constructor std::string, not a pointer to itself.

Example:

class Base{
    public:
        virtual ~Base() {}
        virtual std::unique_ptr<Base> clone() = 0;
        virtual void print() = 0;
};

class A: public Base{
        std::string name_;
    public:
        A(std::string name ){name_ = name;};
        std::unique_ptr<Base> clone() override{
            return std::make_unique<A>(*this);
        };
        void print( ) override{
            std::cout << "Class A: " << name_;    
        };
        virtual ~A(){};
};

class Factory{
        std::unique_ptr<A> type = std::make_unique<A>("MyName");  
    public:
        std::unique_ptr<Base> createInstance(){
            return type->clone();
    }
};

int main(){
    Factory factory;
    auto instance = factory.createInstance();
    instance->print();
}

Replacing std::function from within itself (by move-assignment to *this?)

Is it possible to replace one std::function from within itself with another std::function?

The following code does not compile:

#include <iostream>
#include <functional>

int main()
{
    std::function<void()> func = []()
    {
        std::cout << "a\n";
        *this = std::move([]() { std::cout << "b\n"; });
    };
    func();
    func();
    func();
}

Can it be modified to compile?
The error message right now is: 'this' was not captured for this lambda function - which I completely understand. I don't know, however, how I could capture func's this-pointer. I guess, it is not even a std::function inside the lambda, yet?! How can this be done?

Background: What I want to achieve is the following: In the first invocation of a given std::function, i would like do some initialization work and then replace the original function with an optimized one. I want to achieve this transparently for the user of my function.

The expected output of the example above is:

a
b
b

Variable return template variables in c++

The following code is intended to allow user to access data inside an image which is stored in a vector. The purpose of Pixel structure is to encapsulate variying number of channels in an image by the means of array stored on stack.

(Following code is simplified to provide an overview of the problem)

class Image
{
public:

    const int m_psize;

    Image(int psize) :
        m_psize(psize)
    { }

    template <int psize>
    struct Pixel
    {
        // This array stores pointers to unsigned char
        // which would be stored in Image class

        unsigned char * m_channels[psize];
    };

    // This is my intention \/

    template <int n = this->m_psize>
    Image::Pixel<n> Image::At(int x, int y)
    {
        return Pixel<n>();
    }
}

My question is how would one use templates to allow the following behaviour:

    Image img1(3), img2(3);

    img1.At(2,4) = img2.At(4,3);

But not this:

    Image img1(4), img2(3);

    img1.At(2,4) = img2.At(4,3);

Note: My questions is quite general. I'm not saying this compiles. However, this does:

...
template <int n>
Image::Pixel<n> Image::At(int x, int y)
{
    return Pixel<n>();
}
...

Image img1(3), img2(3);

img1.At<img1.m_psize>(2,4) = img2<img2.m_psize>.At(4,3);

map iterator no field is resolved

I'm trying to use a global map which is defined in a .h file like these:

const std::map<std::string, std::map<std::string, DWORD>> myMap { .. }

And then in the .cpp file I'm trying to define a global function and find values in the map like this:

bool GetValueFromMap(std::string key1, std::string key2, DWORD& val)
{ 
     auto it = myMap.find(key1);
     if(it != myMap.end())
     {
         auto result = it->second;
         ...
     }
     return true;
}

The problem is that the variable it has no fields at all, meaning it doesn't have anything to dereference and the compiler doesn't know what "second" is or anything related to the iterator. Why is that?

C++ way of creating a structure with variable number of items

I need to create a memory region with variable number of items at the end. Something that I can write like this:

#pragma pack(push,0)
struct MyData
{
    int noOfItems;
    int buffer[0];
};
#pragma pack(pop)

MyData * getData(int size)
{
     bufferSize = size* sizeof(int) + sizeof(MyData ::noOfItems);
     MyData * myData= (MyData *)new char[m_bufferSize];
     return myData;
}

This code works on VS 2015 with a warning that array of size of zero is not standard

A bit of search showed me that this is a C hack and is not supported on C++.

Array with size 0

Array of zero length

What happens if I define a 0-size array in C/C++?.

How can I do this in C++

How to correctly deallocate a list of pointer to pair?

In my c++ program I have this variable:

std::list<std::pair<MyClass,MyClass> * > * myList=new std::list<std::pair<MyClass,MyClass> * >() 

How can I correctly delete all information of this structure to avoid memory leaks? I think to do in this mode:

 list< pair< MyClass,MyClass> *>::iterator it;
for(it=myList->begin();it!=myList->end();it++){
    delete *it;
}
delete myList;

Is it a correct approach?

unique_ptr without move, why is this working?

During a code review I found that a C++ function expecting a unique_ptr gets passed the uniqe_ptr by std::move but neither does the function move the unique_ptr as return value nor assigns the caller the return unique_ptr back to it's unique_ptr, so I'd expect this would crash.

Example:

   std::unique_ptr<X> fun(std::unique_ptr<X> p) {
     // Do something with the unique_ptr p
     return p;
   }

At some other place, I found the following calls:

void someFunction() {
  auto p = std::make_unique<X>();
  //...
  fun(std::move(p));
  // Do something else
  fun(std::move(p));
  //...
}

So I'm wondering whether this code is OK or if it is just luck that it executes.

[EDIT]: Completed the example

How to force the compiler to show implicit constructors

There's "-E" option for gcc or clang to run preprocessor and show how all macros are expanded, and I need something like this for implicitly generated methods.

Is there a way to force gcc or clang to print implicitly created and deleted constructors/destructors/assignment operators for each class?

VTK5.10, QT4: Refresh Renderer on updated points

I've tried so much, but I don't get this work.

I want to build up an QT4 Application with an QVTK Widget. Sadly I need to use QT4 and therefore VTK 5.10.

There is an vtkActor that is dealing with some vtkPoints that should be rendered (nothing fancy, more or less from the Examples from VTK). Here is the pipeline initialization:

m_pdata = vtkSmartPointer<vtkPolyData>::New();

m_pdata->SetPoints(m_points);

m_vfilter = vtkSmartPointer<vtkVertexGlyphFilter>::New();
m_vfilter->SetInputConnection(m_pdata->GetProducerPort());
m_vfilter->Update();

m_vdata = vtkSmartPointer<vtkPolyData>::New();

m_vdata->ShallowCopy(m_vfilter->GetOutput());

m_mapper = vtkSmartPointer<vtkPolyDataMapper>::New();

m_mapper->SetInputConnection(m_vdata->GetProducerPort());

m_pactor = vtkSmartPointer<vtkActor>::New();
m_pactor->SetMapper(m_mapper);
m_pactor->GetProperty()->SetPointSize(2);

m_renderer->AddActor(m_pactor);

After this the App calls m_rwindow->Render() to render the scene ...

Then I have an QT QLineEdit to add a Point to the vtkPoints, like this:

m_points->InsertNextPoint(point[0], point[1], point[2]);

And I want to refresh the view, so that the new point will be rendered too. But this will not happen ...

I tried to Update the pipeline like this (more or less in every constellation):

m_pdata->Modified();
m_pdata->Update();
m_vfilter->Modified();
m_vfilter->Update();
m_vdata->Modified();
m_vdata->Update();
m_mapper->Modified();
m_mapper->Update();
m_pactor->Modified();

But everything I get updated will be the old points (for example the color, or size of points ...).

Is it possible to rerender the points so the new Points are displayed too?

How to convert a std::map to a std::function?

A std::map<K,V> implements a partial function of type std::function<V(K)>.

I am trying to implement a generic function map2fun that turns a map into a function object.

The following does not compile:

template<typename M>
function<M::mapped_type(M::key_type)> map2fun(M& m)
{
  return [&m](M::key_type k)
    {
      return m[k];
    };
}

My questions are:

  • Is there a similar functionality available in the STL for C++11?
  • If not, how can I implement it with C++11?

Hierarchically organization of most important subjects in C++ for candidates evaluation

Currently, I am responsible to evaluate new C++ candidates for my Company. After few interviews, I started wondering which would be the most "possible" fair way to evaluate candidates.

For instance, if I write down a set of questions, and setup whichever punctuation level, and I evaluate candidates according to their responses, I feel this is not enough (and, consequently, not fair) because I feel, I should consider also the weight that one specific question has in C++ "big picture". For example: a simple question about inheritance, might not have the same weight as a question related to smart pointers. Even if in both questions, the candidate shows himself as "strong", it is not the same being strong in a subject (let's say) "A", which is 40% in the overall C++ picture, than being strong in a subject "B", which is 20% in the same context.

I also know you might say: "This is industry specific question. You might require strong candidates in X point, while I might require strong ones in Y". But this is not the case.

I am thinking about building up a table of most important subjects in C++11 (not just new features but all C++ including C++11/14). I think it has no sense (for the project nature) going beyond including C++17 questions.

Thus, before building up this table I considered a better option to post this subject here a receive, please, your opinion about:

Which subjects would you consider the most important to evaluate a C++ candidate? (note: The answer to this question, should be the same to this other one: Which subjects would you consider the most important in C++?),

and

Which is the weight (%) you should assign for each one of those subjects in the overall picture of C++11/14?

Example: OOP: 40 %

STL containers: 30 %

(and so forth).

Best practice for using "overriden" values for global constants

I got a c++ code in which I got a mapping from string to int using std::map.

Most of the strings got the same values always, for example {"a", 123}. However, there are some cases in which "a" can be some other values, depending on some configuration.

I was starting to save the constants in a map mapping from a string to another map which maps between string and int:

const std::map<std::string, std::map<std::string,int>> myMap 
{
    {"configuration1", {"a", 123}},
    {"configuration1", {"b", 1}},
    {"configuration2", {"a", 124}},
    {"configuration2", {"b", 2}},
    ...
}

This works, but it's very repetitive.

Is there a better way of doing it with the constraints of it needing the map to be global and easily accessible, and also, the configuration itself can change in runtime, meaning it can't be determined before the run starts and just use the same one.

Read & write log on specific time interval c++

I want to write to log file with timestamp. The timestamp should represent the time interval from beginning of the application like below:

1: This log message arrived after 1s of starting the application

5: This log message arrived after 5s of starting the application

Then i want to read the log message in that exact time interval. Like after 1s i will read the first message then when 5s is passed i will read the second message.

Is there any library by which i can do that? I have found some library like easyloggingcpp which can save log file using timestamp. But the timestamp is the corresponding time. Also i have not found any way how to read the message on specific time interval.

Is there any way i can do it?

dimanche 27 mai 2018

Doesn't compile C++ Code

I am new to C++ and I am trying to create an object but somehow the compiler does not compile and throws me an exception "Exception thrown at 0x76EBE3DC (ntdll.dll) in projectLinkedList.exe: 0xC0000005: Access violation reading location 0x00829CE8." while popping up the "CreateProcessA.cpp". I have no idea on how to solve this issue. I think there are some errors in my code.

This is my code in .h

#ifndef WORDDATA_h
#define WORDDATA_h
#include "NumList.h"

class WordData
{
    private:
        char* wordData;
        int wordLength;
        int frequency;
        //declare a numlist object
        NumList numList;

        //print function
        friend std::ostream& operator<< (std::ostream&, const WordData&);

    public:
        //default constructor
        WordData();

        //parameterized constructor 
        WordData(std::string word, int linenumber);

        //destructor
        ~WordData();

        //copy constructor
        WordData(const WordData&);

        //copy assignment operator
        WordData& operator= (const WordData&);

        //setter
        void addFrequency();


        //getter
        int getNumListFElement() const;

        bool searchLineNum(int) const;
        void appendLineNum(int);
        int frequencyCount() const;

        //read-only pointer to the stored word
        const char * getPointerWordData() const;

        //read-only reference to the numlist object
        const NumList getReferenceNumList();

        //compare 2 words
        int compare(const WordData&) const;


};

#endif 

This is my code in .cpp

#include <iostream>
#include <string>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "WordData.h"

using namespace std;
//Default Constructor
WordData::WordData()
{
    wordData = nullptr;
    wordLength = 0;
    frequency = 0;
    NumList numList;
}

WordData::WordData(std::string word, int lineNumber)
{
    //Covert the string to lowercase
    for (size_t i = 0; i < word.length(); ++i) {
        if ('A' <= word[i] && word[i] <= 'Z') {
            word[i] = char(((int)word[i]) + 32);
        }
    }

    wordData = new char[word.length()+1];

    //Set a dumpy max char of 50
    strcpy_s(wordData, 50, word.c_str());
    wordLength = sizeof(wordData) / sizeof(*wordData);
    frequency = 1;
    NumList numList;
    this->numList.insertEnd(lineNumber);
}

//Destructor
WordData::~WordData()
{

}

//Copy Constructor
WordData::WordData(const WordData& anotherWord)
{
    wordLength = strlen(anotherWord.wordData);
    frequency = anotherWord.frequency;
    numList = anotherWord.numList;
    wordData = new char[wordLength+1]; //+1 for \0 at the end
    //for (int i = 0; i < wordLength; ++i)
    //{
    //  wordData[i] = anotherWord.wordData[i];
    //}
    strcpy_s(wordData, 50, anotherWord.wordData);

}

//Copy Assignment Operator
WordData& WordData::operator= (const WordData& anotherWord)
{
    //Calling copy constructor
    WordData temp(anotherWord);

    //Exchanging the content of WordData
    std::swap(wordData, temp.wordData);
    std::swap(wordLength, temp.wordLength);
    std::swap(frequency, temp.frequency);
    std::swap(numList, temp.numList);

    return *this;
}

//Setter
void WordData::addFrequency()
{
    frequency += 1;
}

//Getter
int WordData::getNumListFElement() const
{
    return numList.getElement(0);
}


bool WordData::searchLineNum(int lineNum) const
{
    if(this->numList.search(lineNum))
        return true;
    else
        return false;
}

void WordData::appendLineNum(int lineNum)
{
    if (!(this->numList.search(lineNum)))
        this->numList.insertEnd(lineNum);
    else
        cout << "The line number already exists in the list." << "\n";
}

int WordData::frequencyCount() const 
{
    return frequency;
}

//Read-only pointer to the wordData
const char* WordData::getPointerWordData() const
{
    return wordData;
}

//Read-only reference to the numList
 const NumList WordData::getReferenceNumList()
{
     NumList numList;
     return numList;
}

//Compare 2 words
int WordData::compare(const WordData& anotherWord) const
{
    return (strcmp(anotherWord.wordData, wordData));
}


std::ostream& operator<< (std::ostream& out, WordData& word)
{

    out << "The word of " << word.getPointerWordData() << " has a frequency of " << word.frequencyCount() << "\n" << "It appears on lines "; 
    word.getReferenceNumList().print();
    return out;
}

This is my code in main

#include <iostream>
#include <string>
#include "WordData.h"

int main()
{
    cout << "Hello" << endl;
    WordData data1("hello" , 10);
    data1.getPointerWordData();




    system("pause");
    return 0;

}

Enabeling C++ 11 support in my makefile using CXXFLAGS

I'm trying to compile my program on my School's server but need to enabel C++ 11 in order to get my program to compile. I'm not sure if I how to implement the g++ -std=c++11 *.cpp *.h -o programName that I used when compiling from my the terminal.

This is my makefile:

all, Project4, Project4.exe: Character.o Barbarian.o BlueMen.o Vampire.o 
Medusa.o HarryPotter.o LinkedList.o Queue.o Stack.o main.o
g++ main.o Character.o Barbarian.o BlueMen.o Vampire.o Medusa.o 
HarryPotter.o LinkedList.o Queue.o Stack.o -o Projec4

Character.o: Character.cpp Character.h
    g++ -c Character.cpp

Barbarian.o: Barbarian.cpp Barbarian.h
    g++ -c Barbarian.cpp

BlueMen.o: BlueMen.cpp BlueMen.h
    g++ -c BlueMen.cpp

Vampire.o: Vampire.cpp Vampire.h
    g++ -c Vampire.cpp

Medusa.o: Medusa.cpp Medusa.h
    g++ -c Medusa.cpp

HarryPotter.o: HarryPotter.cpp HarryPotter.h
    g++ -c HarryPotter.cpp

LinkedList.o: LinkedList.cpp LinkedList.h
    g++ -c LinkedList.cpp

Queue.o: Queue.cpp Queue.h
    g++ -c Queue.cpp

Stack.o: Stack.cpp Stack.h
    g++ -c Stack.cpp

main.o: main.cpp Character.h Barbarian.h BlueMen.h Vampire.h Medusa.h 
HarryPotter.h LinkedList.h Queue.h Stack.h
    g++ -c main.cpp

clean:
    -rm *.o

Ranged loop behaviour when passing arrays by reference

What is the difference, if any, between

template <typename T, int N>
void input (T (&Array) [N])
{
    for (T& val: Array) cin >> val;
}

and

template <typename T>
void input (T (&store))
{
    for (auto& val: Array) cin >> val;
}

N.B. The former won't compile with T (&Array) [] since that is a "reference to array of unknown bound". The latter won't compile if we wrote T& val: Array instead.

Can't use the lambda function inside function template

I have a problem with my function template.

I have 3 different collections and I've got iterators for the collections. Now I have to create an function template 'apply' which will do the following: 1. Pass through all elements of collections and check if predicate is true:

1.1 If predicate return true - then element of collection need to be changed with lambda 'passed'

1.2 if predicate return false = then element of collection need to be changed with lambda 'rejected'

Please give me an example how should I write it.

Thank you soo much for help. Updated code here:

#include <iostream>
#include <vector>
#include <list>
#include <functional>

using namespace std;

template<typename T>
void apply(T collBegin, T collEnd, function<bool(int)> f1, function<int(int)> f2, function<int(int)> f3)
{
    for (T actualPosition = collBegin; actualPosition != collEnd; ++actualPosition) {
        if (f1(*actualPosition)) {
            //the argument matches the predicate function f1
            *actualPosition = f2(*actualPosition);
        }
        else {
            //the argument doesn't match the predicate function f1
            *actualPosition = f3(*actualPosition);
        }
    }
}

int main()
{
    int arr[]{ 1,2,3,4,5,6,7,8,9 };

    auto predicate = [](int arg) -> bool { return arg % 2 == 0; };

    auto passed = [](int arg) -> int { return arg / 2; };

    auto rejected = [](int arg) -> int { return (3 * arg) + 1; };

    apply(arr, arr + std::size(arr), predicate, passed, rejected);

    std::vector<int> vec(arr, arr + std::size(arr));
    apply(vec.begin(), vec.end(), predicate, passed, rejected);

    std::list<int> lis(vec.begin(), vec.end());
    apply(lis.begin(), lis.end(), predicate, passed, rejected);


    for (auto e : lis) std::cout << e << " ";
    std::cout << '\n';
}

This code works. But I want to make change it from int to T. How can I do this ?

How exactly std::async is executed

I wonder how does the following code work?

#include <thread>
#include <future>
#include <set>
#include <iostream>
struct Task;
std::set<const Task*> dead_tasks;
struct Task
{
   ~Task() { dead_tasks.insert(this); std::cout << "dtor\n";}
   Task() { std::cout << "ctor\n";}
   Task(Task&&) { std::cout << "move-ctor\n";}
   void operator()() const { std::cout << "func()\n"; }
};
int main(){
   std::cout << dead_tasks.size() << '\n';
   std::async(std::launch::async, Task());
   std::cout << dead_tasks.size() << '\n';
}

This code prints

0 ctor move-ctor move-ctor dtor func() dtor dtor 3

If we use std::launch::deferred instead of std::launch::async we will get

0 ctor move-ctor move-ctor dtor dtor dtor 3

So in the latter we miss the member function call. Why? I can understand the presence of the call to the default constructor and the call to the move constructor. Task() calls the default constructor, then std::async does a call to the move constructor... However I missed the idea behind the second call to the move constructor and the call to the member function. I can think that the second move constructor is called by std::future, can't I?

What replaced asio::tcp::resolver?

I'm currently trying to build a project without any deprecated methods and hit a problem with the resolver. My old code used to look like this:

const asio::ip::tcp::resolver::query query(params.host, std::to_string(params.port));
      m_resolver.async_resolve(query, [&](const std::error_code &ec_, asio::ip::tcp::resolver::iterator iter) {
        if (ec_) {
          ec = ec_;
          return;
        }
        while (iter != asio::ip::tcp::resolver::iterator()) {
          m_socket.reset(new asio::generic::stream_protocol::socket(m_service));
          m_socket->async_connect((*iter++).endpoint(), [&](const std::error_code &err_code) {
            if (err_code) {
              ec = err_code;
              return;
            }
            connected = true;
          });
        };
      });

But now Asio says asio::tcp::resolver::query is deprecated. How is hostname resolution done now?

Why my simple C++ fibonacci for negative numbers doesn't work?

I am learning C++ and I am trying to implement fibonacci generator for negative numbers. I totally don't understand what is wrong in my code. When I add condition for negative number, program each time ends with exit value (-1).

According to wiki: F(-n) = (-1)^(n+1) * F(+n)

http://cpp.sh/74fl2

#include <iostream>
#include <cmath>

int fibonacci_r(int num);

int main(){
    int n;
    std::cout << "Please provide number: ";
    std::cin >> n;

    std::cout << fibonacci_r(n);
    //std::cout << "F(" << n << ") = " << fibonacci_r(n);

    return 0;
}


int fibonacci_r(int n){
    if(n < 1){
        return std::pow(-1, n+1) * fibonacci_r(std::abs(n));
    }
    if(n == 1 || n == 0){
        return n;
    }
    else
        return (fibonacci_r(n-1) + fibonacci_r(n-2));
}

C++ sort coordinates stored as object in vector

In the next code I can input a number n then I can input n number of (x,y) coordinates.

Code:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int n = 0;
char cr;
class punto{
private:
    int x;
    int y;
public:
    punto();
    ~punto(){}
    void setx(int xn){ x = xn;}
    void sety(int yn) { y = yn; }
    void printcoord();
};
punto::punto()
{
    x=0;
    y=0;
}
void punto:: printcoord()
{
    cout << x << " " << y << endl;
}
int main()
{
    vector<punto> list;
    int x;
        int y;
        punto *p1;
    cin >> n >> cr;
    for(int contador=0; contador<n; contador++){
        if(contador<n){
                cin >> x;
                cin >> y;
                p1=new punto;
                p1->setx(x);
                p1->sety(y);
                list.push_back(*p1);
                cin.get();
            }
        }
    vector<punto>::iterator it;
    if(cr=='x'){
     for ( it = list.begin(); it != list.end(); ++it ) {
            it->printcoord();
     }
    }
    if(cr=='y'){
     for ( it = list.begin(); it != list.end(); ++it ) {
            it->printcoord();
     }
    }
    return 0;
}

That means that if we input this:

5 x
1 2
3 4
6 1
2 2
1 1

We get this output.

1 2
3 4
6 1
2 2
1 1

Problem is I don't know how to sort coordinates with respect to x or y.

Coordinates are stored as objects within a vector.

If I try to use sort it says that x and y are non-class type int.

Output should be:

1 1                    1 1
1 2                    6 1 
2 2     for x          1 2          for y    
3 4                    2 2 
6 1                    3 4

I would appreciate any help.

C++ Program On Elementary Database Operations i.e. Record Management

When i execute the program and select option number 2 it reads the data from the file successfully but when i select the option number 2 for the second time , third time and so on... nothing comes up and it returns back to the menu. I have tried so many times, same error comes every time. PLEASE HELP. Thanks to all in advance. love all.

#include <fstream>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <iomanip>
#include <iostream>

using namespace std;

//class for database functions
class group
{
private:
    struct person {
            char flag;
            char empcode[5];
            char name[10];
            int age;
            float sal;
    }p;
public:
    fstream file,t_file;
    ifstream fin;
    ofstream fout;
    group();
    void addrec();
    void listrec();
    void modirec();
    void delrec();
    void recovrec();
};

//main function
int main()
{
    char choice;
    group g;
    do
    {
        system("cls");
        cout<<"1.Add Records"<<endl;
        cout<<"2.List Records"<<endl;
        cout<<"3.Modify Records"<<endl;
        cout<<"4.Delete A Record"<<endl;
        cout<<"5.Recover Deleted Records"<<endl;
        cout<<"6.Exit"<<endl;
        cout<<"Your choice ?: ";
        cin>>choice;
        system("cls");
        switch(choice)
        {
            case '1':
                g.addrec();
                break;
            case '2':
                g.listrec();
                break;
            case '3':
                g.modirec();
                break;
            case '4':
                g.delrec();
                break;
            case '5':
                g.recovrec();
                break;
            case '6':
                exit(0);
        }
    } while(choice!=6);

    return 0;
}

//default constructor
group::group()
{
    file.open("EMP.DAT",ios::in|ios::out|ios::binary);
    p.flag=' ';
    if(!file)
        cerr<<"Unable to open file";
}

//Add records at the end
void group::addrec()
{
    char ch;
    cout<<"Do You Want To Erase Previous Records ?: ";
    cin>>ch;
    if(ch=='y'||ch=='Y')
        remove("EMP.DAT");
    fout.open("EMP.DAT",ios::binary);
    fout.seekp(0L,ios::end);
    system("cls");
    do
    {
        cout<<"Enter Emp_Code, Name, age, Salary"<<endl;
        cin>>p.empcode>>p.name>>p.age>>p.sal;
        fout.write((char*)&p,sizeof(p));
        cout<<"Add another record ?: ";
        cin>>ch;
    } while(ch=='y'||ch=='Y');

    fout.close();
}

//list all the records
void group::listrec()
{
    int j=0;
    //position get pointer at beginning
    //fin.open("EMP.DAT",ios::binary);
    file.seekg(0L,ios::beg);
    while(file.read((char*)&p,sizeof(p)))
    {
        if(p.flag!='*')
        {
            cout<<"\nRecord N. "<<++j;
            cout<<"\nEmp Code: "<<p.empcode;
            cout<<"\nName: "<<p.name;
            cout<<"\nAge: "<<p.age;
            cout<<"\nSalary: "<<p.sal<<endl;
        }
    }
    cin.ignore();
    getchar();
}

//modifies a given record from file
void group::modirec()
{
    char code[5];
    int count=0;
    long int pos;
    cout<<"Enter Emp Code";
    cin>>code;
    file.open("EMP.DAT",ios::in|ios::out|ios::binary);
    file.seekg(0,ios::beg);
    //search an employee
    while(file.read((char*)&p,sizeof(p)))
    {
        //if record is found
        if(strcmp(p.empcode,code)==0&&p.flag==' ')
        {
            //recieve new data
            cout<<"Enter new Data: "<<endl;
            cout<<"Enter Emp_Code, Name, age, Salary"<<endl;
            cin>>p.empcode>>p.name>>p.age>>p.sal;
            //position put pointer to overwrite record
            pos=count*sizeof(p);
            file.seekp(pos,ios::beg);
            file.write((char*)&p,sizeof(p));
            file.close();
            cout<<endl<<"Press Any Key...";
            getchar();
            return;
        }
        count++;
    }
    file.close();
    cout<<endl<<"No Employee In File With Code: "<<code;
    cout<<endl<<"Press Any Key...";
    getchar();
}

//marks a record for deletion
void group::delrec()
{
    char code[5];
    long int pos;
    int count =0;
    cout<<"Enter Emp Code";
    cin>>code;
    file.open("EMP.DAT",ios::in|ios::out|ios::binary);
    //position pointer at beginning
    file.seekg(0L,ios::beg);
    //search an employee
    while(file.read((char*)&p,sizeof(p)))
    {
        //if record is found
        if(strcmp(p.empcode,code)==0&&p.flag==' ')
        {
            p.flag='*';
            //position put pointer
            pos=count*sizeof(p);
            file.seekp(pos,ios::beg);
            file.write((char*)&p,sizeof(p));
            file.close();
            return ;
        }
        count++;
    }
    cout<<endl<<"No Employee In File With Code: "<<code;
    file.close();
    cout<<endl<<"Press Any Key...";
    getchar();
}

//unmarkmarks a record
void group::recovrec()
{
    char code[5];
    long int pos;
    int count =0;
    cout<<"Enter Emp Code";
    cin>>code;
    file.open("EMP.DAT",ios::in|ios::out|ios::binary);
    //position pointer at beginning
    file.seekg(0L,ios::beg);
    //search an employee
    while(file.read((char*)&p,sizeof(p)))
    {
        //if record is found
        if(strcmp(p.empcode,code)==0&&p.flag=='*')
        {
            p.flag=' ';
            //position put pointer
            pos=count*sizeof(p);
            file.seekp(pos,ios::beg);
            file.write((char*)&p,sizeof(p));
            file.close();
            return ;
        }
        count++;
    }
    file.close();
    cout<<endl<<"No Employee In File With Code: "<<code;
    cout<<endl<<"Press Any Key...";
    getchar();
}

overload resolution of templated special member (operator=)

Context: In an attempt to implement the copy and swap idiom on a templated homemade shared_ptr. I'm having trouble to get this function called:

    template<typename U>
    shared_ptr<T>& operator=(shared_ptr<U> rhs)
    {
        static_assert(std::is_base_of<T, U>::value);
        swap(*this, rhs);
        return *this;
    }

Code stripped from the unecessary:

The following code does not compile. The "x=y" line is an attempt to use:

    foo<T>& operator=(const foo<U>& ptr) = delete;

If I remove/comment the deleted functions line. Meaning if I do not define them, the compiler will do it for me and the code will compile. However,the special member generated by the compiler will be preferred to my operator which will not be called.

template<typename T> 
class foo
{
public:

    // copy&swap
    template<typename U>
    foo<T>& operator=(foo<U> rhs)
    {
        // whatever is needed swap and all
        return *this;
    }

    template<typename U>
    foo<T>& operator=(const foo<U>& ptr) = delete;
    template<typename U>
    foo<T>& operator=(foo<U>&& ptr) = delete;

    foo<T>& operator=(foo<T>&& ptr) = delete;
};

int main()
{
    foo<int> x,y;
    x = y;
    return 0;
}

Questions:

  • The overload resolution is not clear to me here. Why is one signature preferred to the other?
  • If the function is deleted, I understand it is not a "substitution failure", but still it is a failure at signature level, not inside the body, why does the compiler stop looking for a match?
  • Any solution to get the function to be called ?

How to return dynamically allocated array from function and correctly delete it

I'm new in C++ and I've a problem with memory management.

I've one method a() that call 3 method (b(),c(),d()) that, each one return dinamically allocated array of MyClass objects.

void a(){
    MyClass * one=b();
    MyClass * two=c();
    MyClass * three=d();
    //operate with 3 array (one, two and three)
    delete one;
    delete two;
    delete three;
}

MyClass * b(){
    MyClass * array=new MyClass[2000];
    //many operations on array
    return array;
}

MyClass * c(){
    MyClass * array=new MyClass[2000];
    //many operations on array
    return array;
}

MyClass * d(){
    MyClass * array=new MyClass[2000];
    //many operations on array
    return array;
}

After many operation in a() I must delete the 3 arrays that I created with the 3 methods. If I do the 3 delete like code in the top of question is it ok?

I asked myself this question because I think that this code correctly delete all but analyzing the memory allocation of my c++ program I can't notify this delete.

samedi 26 mai 2018

Library archive has main defined

I am using a library file that has a main function defined.When I compile and link, I get the linker error "Multiple definitions of main" first defined here. It points to the library.a file. Can you please advise as to how I can direct the linker to ignore the library's main and use the one in the CPP file.

Thank you.

How to run multiple threads in C++ code

I'm a beginner for c++. I wrote a program to extract data from one DB and store those data to another DB. I just want to add multiple threads to speed up the process. I hope to do this in two ways.

  1. Extract data from the first DB and store those data in memory. (In this case, I need to those data in two std::vector types)
  2. while extracting data from the database, if vector size is more than 10000, two threads need to invoke and need to start, get data from two vectors(separately) and store those data in the second database.

Consider the below example. It's a simple code to demonstrate the above scenario. There is a for-loop with huge iterations. I need to start two threads for this code to extract data from dataOne and dataTwo vectors (separate threads for both) and store those data in dataThree and dataFour vectors when the i = 10000.

using namespace std;

int main(){

   std::vector<std::vector<int>> dataOne;
   std::vector<std::vector<int>> dataTwo;

   std::vector<std::vector<int>> dataThree;
   std::vector<std::vector<int>> dataFour;

   for(int i=0; i < 10000000; i++){
       std::vector<int> temp = {1,2,3};
       dataOne.push_back(temp);          //store data in vector-one 

       std::vector<int> temp2 = {3,4,5};
       dataTwo.push_back(temp2);        //store data in vector-two      
   }
}

when i=10000, there should be three threads running,

  • Thread one - Getting data from dataOne vector and store in dataThree

  • Thread two - Getting data from dataTwo vector and store in dataFour

  • Thread main - process the for-loop in main function

anyone can help me to solve this?

Which will be more efficient to em-place in following?

I wrote a code as follows:

#include <iostream>
#include <vector>
using type = std::vector<std::string>;

int main()
{
    int query = 5;

    std::vector< type > answer;  
    answer.reserve(query);

    auto vecReturn = [](const std::string& x, const std::string& y) -> decltype(auto)
    {
        std::vector<std::string> tempVec = {x, y};
        return std::move(tempVec);
    };

    while(query--)
    {
        std::string xName, yName;
        std::cin >> xName >> yName;
        answer.emplace_back( vecReturn(xName, yName) );
    }

    return 0;
}

I can rewrite the above without the lambda function, something like follows:

using type = std::vector<std::string>;
int query = 5;
std::vector< type > answer;  // group set
answer.reserve(query);

while(query--)
{
    std::string xName, yName;
    std::cin >> xName >> yName;

    type tempVec = { xName, yName };
    answer.emplace_back( tempVec );
}

Which looks pretty less code than the first one. Now the question is,

  1. Is there any efficiency differences between in these two ways, considering that, query could be up to the maximum integer numeric limit.
  2. If so, which one of above mentioned ways, would you suggest me to do?

Thanks for your time.

Auto failed for vector size

I am trying use auto to infer the type.

for (auto i = remaining_group.size() - 1; i >= 0; --i) {
    std::cout << i;
}

I get very large number like 18446744073709534800 which is not expected. When I change auto to int it is the number I expected between 0 and 39.

Is there any reason auto will fail here?

remaining_group's type is a std::vector<lidar_point> and lidar_point is struct like:

struct LidarPoint {
  float x;
  float y;
  float z;
  uint8_t field1;
  double field2;
  uint8_t field3;
  uint16_t field4;
}

Is a const reference bound to a temporary which is cast to const reference a dangling reference?

Below is the code snippet:

#include <iostream>
using namespace std;
struct B{
     int b;
     ~B(){cout <<"destruct B" << endl;}
};
B func(){
    B b;
    b.b = 1;
    return b;
}
int main(){
    const B& instance = (const B&)func(); //is `instance` a dangling reference?
    cout <<instance.b<<endl;
    return 0;
}

in this online compiler the output is

destruct B
destruct B
1

So the return value seems to destruct earlier than the cout operation. So the instance seems to be a dangling reference.

If we change const B& instance = (const B&)func(); to const B& instance =func();, then the result is

destruct B
1
destruct B

Count columns in TXT with C++?

I have these types of data in txt files.

1   3   4   5
2   4   5   2
3   5   7   8
2   5   7   8

or even

1 3 4 5
2 4 5 2
3 5 7 8
2 5 7 8

Separated with TABs, with one space or exported from excel. I need a function to count columns, that returns an int, how can I do this?

Thanks!

Implementation of CBC mode of operation of AES

I have an implementation of AES cipher for 128, 192 and 256 bit keys. I'm trying to implement block cipher mode of operations, currently implementing Cipher Block Chaining mode.

I have two questions regarding the implementation of CBC mode:

1. Whether to read file and pass data to cipher function within the cbc() //it implements CBC mode or I can read data and pass blocks of data to cbc(), which one of them should I use and will be secure?

2. CBC mode requires a randomly generated initialization vector aka IV(I'm using a random bytes generator in c++11 for this), since user only enters key at the time of encryption/decryption how can I know what was the intialization vector used when the file was encrypted. Also if I need to give the IV to user, how?

I'm implementing these in C++11.

thanks.

C++ set objects within an array to NULL

I have a class Modal

class Modal {
private:
   A* obj1;
   B* obj2;
}

where A is B's parent class

class A {
};

class B : public A {
};

in the destructor of Modal I want to set obj1 and obj2 to NULL

I created a convenience method:

void remove(A*& obj) {
    if (obj == NULL) { return; }
    obj = NULL;
}

and in the destructor I do something like this:

A* objects[] = { obj1, obj2 };
for(auto obj: objects) { remove(obj); }

But it does not set the obj1 and obj2 values to NULL If I call directly:

remove(obj1);

it works as it should. So what am I doing wrong with the array?

Also: The reason why I put obj1 and obj2 into an array is because I will have more objects and I want to keep the code for the removal short.

Only defined inside a class

#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <string>
using namespace std;
class Meny
{
public:
    void Meny2()
    {
        cout << "Welcome " << Name << LastName;
    }
};

class Kund
{
public:
    string  Name, LastName, personnummer;

    void LoggaIn()
    {
        cout << "Please enter your full name: " << endl;
        cin >> Name >> LastName;
        cout << "Please enter your social security number: " << endl;
        cin >> personnummer;
    }
};

So currently cout << "Welcome " << Name << LastName; wont work because Name and LastName are undefined in the Meny class, is there a way to make them be defined even though they are defined in another class?

Variadic Template Function Call

Let's suppose we have the following variadic template function:

template <int... Ints> 
void foo() {
  Foo<Ints...> f;
  // do something with f.
}

Note that foo need a sequence of integers at compile time, in order to build Foo class.

We can simply invoke it:

foo<1, 2, ,3 , 4>();

Is there any method to "mitigate" this function call? For example, to have something like:

foo(1, 2, 3, 4);

Notes:

  • No C-style (Macro, or vargs).
  • foo needs compile time sequence of integers.
  • Any C++ standard is fine.

How to declare the return of `emplace()` of an instantiated `std::set`?

  1. I have a class template:

    template<class idxT>
    class SimpleGraph {
    private:
      // ...
      std::set<std::pair<idxT,idxT>> edgeSet;
      // ...
      void addEdge(idxT a, idxT b);
      // ...
    }
    
    
  2. I need to use the return of edgeSet.emplace(a,b) inside addEdge(), which is denoted as r in the following.
  3. The declaration and the assignment of r need to be separated since the value of a and b is determined by a if-else statement. Thus, I cannot use

    auto r = edgeSet.emplace(a,b);
    
    
  4. I tried the following strategies but neither is successful. The first one is

    std::pair<decltype(edgeSet)::iterator,bool> r;
    // some code
    r = edgeSet.emplace(a,b);
    
    

    The second one is

    // inside class template
    typedef std::set<std::pair<idxT,idxT>> EdgeSetType;
    EdgeSetType edgeSet;
    
    // inside definition of `addEdge()`
    std::pair<EdgeSetType::iterator,bool> r;
    // some code
    r = edgeSet.emplace(a,b);
    
    

How can I declare the return of edgeSet.emplace(a,b)?

How do I increase a value per second?

I've done some research but couldn't find a way to do it. All solutions I've seen offers only to calculate how much time passed during the execution of the code.

const auto start = std::chrono::high_resolution_clock::now();
// your code
const auto end = std::chrono::high_resolution_clock::now();
const auto elapsed_seconds = std::chrono::duration_cast<std::chrono::seconds>(end - start).count();

I've thought maybe I can create a value and keep adding elapsed_seconds as milliseconds to it, with modulo I can check if it's above 1000 and if elapsed_seconds % 1000 == 0, I can increase the value.

I failed to do it however. Here is my code:

long long total_time_passed = 0;

int main(int argc, char* argv[])
{
    while (true)
    {
        // some code
        const auto start = std::chrono::high_resolution_clock::now();
        // some code
        const auto end = std::chrono::high_resolution_clock::now();
        const auto elapsed_seconds = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
        total_time_passed += elapsed_seconds;
        cout << "TTPass: " << total_time_passed << "\n";
    }
}

Always prints:

TTPass: 0

How do I make it so TTPass increases by 1 in real time as 1 second passes.

Expected output (per second):

TTPass: 1
TTPass: 2
TTPass: 3
...

I don't want to use sleep(1000). I'm aware of it but it blocks code execution.

If it helps, I'm using Windows 10 with Visual Studio 2017.

Thank you.

Will changing a private derived class affect the ABI if I use only pointers to the base class?

I've been recently reading about the PIMPL idiom in C++ and its advantages over abstract base classes. One of the main points for the PIMPL is that it preserves ABI if the implementation changes. I've seen many articles in the internet and even similar questions here in StackOverflow. However, I haven't been able to find the answer to the following question:

Let's say I have a base class A and an implementation(derived class) B. Now, external code receives B objects but only via pointers to the base class A(and they can only use whatever methods or data members are available in A). Now if I change the implementation of B, for example adding new private members, will this result in an ABI breakage? My logic tells me this shouldn't be the case, because the external code doesn't know anything about B and so changes in it shouldn't affect the external code at all.

Can someone tell me if I'm wrong and also explain why? Thank you in advance.

C++ - 60603 (Fedora Cygwin 5.4.0-2) when using std::cout

I was practicing using the auto and decltype keywords.

When I tried to add 2 values and print the resul, I got 60603 (Fedora Cygwin 5.4.0-2) in the console.

I'm think that's probably the name of my compiler, right? Why did I get that? Because that's pretty confusing, as I'm only a rookie to the C++ world.

Here's the complete code:

#include <iostream>

template<class T, class K>
auto test(T val1, K val2) -> decltype(val1 + val2) {
    return val1 + val2;
};

int main() {

    std::cout << test("Hello There!", 99);

    return 0;
}

Thanks for your time!

What the heck is going on with mod (%) operator in C++?

So, I'm implementing a ring buffer. I got a bug. The culprit is the mod operator. According to C++, -1 % 15 is 0. What??

From ISO14882:2011(e) 5.6-4:

The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined. For integral operands the / operator yields the algebraic quotient with any fractional part discarded; if the quotient a/b is representable in the type of the result, (a/b)*b + a%b is equal to a.

The remainder of the division. Okay. So, according to python and google, -1 % 15 = 14 – that's the 'normal' behavior of mod. However, C++ is funky. -1 % 15 should yield -1, right? After all, -1/15 = 0 in integer division, and therefore the remainder is -1. Yet, I'm clearly getting 0! What the hell is going on?

As an added bonus, -2 % 15 is giving me 14. WHAT!

I'm using g++ -std=c++11

vendredi 25 mai 2018

Inherit from const type passed as template parameter

The following code is not valid:

struct base {
};

struct inherit : const base {
};

You cannot inherit from a const type.

Does the situation change when templates are involved? In other words, is this code valid:

struct base {
};

template<typename T>
struct inherit : T {
    using T::T;
};

int main() {
    inherit<base const>{};
}

gcc is says it is fine, but clang reports

<source>:6:2: error: 'const base' is not a direct base of 'inherit<const base>', cannot inherit constructors

        using T::T;

        ^        ~

<source>:10:2: note: in instantiation of template class 'inherit<const base>' requested here

        inherit<base const>{};

        ^

1 error generated.

Compiler returned: 1

To make clang happy, I need to do something like this:

template<typename T>
struct inherit : T {
    using U = std::remove_const_t<T>;
    using U::U;
};

Which version is correct? Or are neither of them correct and I need to inherit from std::remove_const_t<T>?

What is the best way to share data containers between threads in c++

I have an application which has a couple of processing levels like:

InputStream->Pre-Processing->Computation->OutputStream

Each of these entities run in separate thread. So in my code I have the general thread, which owns the

std::vector<ImageRead> m_readImages;

and then it passes this member variable to each thread:

InputStream input{&m_readImages};
std::thread threadStream{&InputStream::start, &InputStream};
PreProcess pre{&m_readImages};
std::thread preStream{&PreProcess::start, &PreProcess};
...

And each of these classes owns a pointer member to this data:

std::vector<ImageRead>* m_ptrReadImages;

I also have a global mutex defined, which I lock and unlock on each read/write operation to that shared container. What bothers me is that this mechanism is pretty obscure and sometimes I get confused whether the data is used by another thread or not.

So what is the more straightforward way to share this container between those threads?

How to avoid use of goto and break nested loops efficiently

I'd say that it's a fact that using goto is considered a bad practice when it comes to programming in C/C++.

However, given the following code

for (i = 0; i < N; ++i) 
{
    for (j = 0; j < N; j++) 
    {
        for (k = 0; k < N; ++k) 
        {
            ...
            if (condition)
                goto out;
            ...
        }
    }
}
out:
    ...

I wonder how to achieve the same behavior efficiently not using goto. What i mean is that we could do something like checking condition at the end of every loop, for example, but AFAIK goto will generate just one assembly instruction which will be a jmp. So this is the most efficient way of doing this I can think of.

Is there any other that is considered a good practice? Am I wrong when I say it is considered a bad practice to use goto? If I am, would this be one of those cases where it's good to use it?

Thank you

Repeating values for in a random bytes generator in c++

I have made a random bytes generator for intialization vector of CBC mode AES implementation,

#include <iostream>
#include <random>
#include <climits>
#include <algorithm>
#include <functional>
#include <stdio.h>

using bytes_randomizer =    std::independent_bits_engine<std::default_random_engine, CHAR_BIT, uint8_t>;

int main()
{
bytes_randomizer br;
char x[3];
uint8_t data[100];
std::generate(std::begin(data), std::end(data), std::ref(br));

for(int i = 0; i < 100; i++)
{
    sprintf(x, "%x", data[i]);
    std::cout << x << "\n";
}
}

But the problem is it gives the same sequence over and over, I found a solution to on Stack which is to use srand() but this seems to work only for rand().

Any solutions to this, also is there a better way to generate nonce for generating an unpredictable Initialization Vector.

Unable to starve writer thread in reader-writer scenario

Reader-Writer problem:

I have implemented a very basic version of reader-writer problem with the following conditions:

  1. Multiple readers are allowed to read data at a time.
  2. Only 1 writer is allowed to update data at a time.
  3. When readers are reading,then, writer cannot acquire access to the data.

I am doing the following in my code:

  • I am launching reader thread in every 10 milliseconds. Whereas,
  • I am launching writer thread in every 2 seconds.

So, that means, my writer should have starved but this is not happening.

Can somebody explains:

  1. Why writers are not getting starved?
  2. How to starve writer(where is the mistake in my code)?

Code:

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


int dataa = 0; // shared resource
mutex _mData; // mutex to protect shared resource

mutex _mReaders;
int totalReaderThreads = 0;

void sharedPrint(string threadName, std::thread::id threadID, int dataa)
{
    cout << threadName.c_str() << "[" << threadID << "]. data[" << dataa << "]" << endl;
}

void producer()
{
    _mData.lock(); //Allow only 1 writer at a time to access shared resource:
    //<<critical-section-begin>>
        dataa++; //update data
        sharedPrint("Writer Thread", this_thread::get_id(), dataa);
    //<<critical-section-end>

    _mData.unlock();
}


void consumer()
{
    unique_lock<mutex> ul(_mReaders); //Allow only one reader

    //<<critical-section-begin>>
        totalReaderThreads++;
        if (totalReaderThreads == 1)
        {
            _mData.lock();//lock the data from writers
        }
    //<<critical-section-end>
    ul.unlock();


    //Allow all reader threads:
    int i = dataa; //Readers reading data
    sharedPrint("Reader Thread", this_thread::get_id(), i);


    ul.lock();  //Allow only one reader
    //<<critical-section-begin>>
        totalReaderThreads--;
        if (totalReaderThreads == 0)
        {
            _mData.unlock();//unlock the data for writers
        }
    //<<critical-section-end>
    ul.unlock();
}

void runConsumers()
{
    vector<thread> con;
    int counterr = 1;
    int seconds_ = 10;
    while (counterr)
    {

        Sleep(seconds_);// A new reader will attempt to read data in every 10 milliseconds.
        con.push_back(thread(consumer));
    }
    //joining consumers:
    for (int i = 0; i < 10; i++)
        con[i].join();
}

void runProducers()
{
    vector<thread> pro;
    for (int i = 0; i < 10; i++)
    {

        Sleep(2000); //A new producer will attempt to write data in every 2 seconds.
        pro.push_back(thread(producer));
    }
    //joining producers:
    for (int i = 0; i < 10; i++)
    {
        pro[i].join();
    }
}

int main()
{
    thread t1(runProducers);
    thread t2(runConsumers);

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

    getchar();
    return 0;
}