lundi 31 décembre 2018

How can range-based for loops work with simple arrays?

Behold, here we have a simple array and we are printing all the elements in the array using a range-based for loop, and it actually works! Not surprising for many programmers but it's surprising for me.

The advantage of using std::vector or std::array is that it's a class which holds the size of the internal array as a data member. However, so such size information is stored when you are using a raw/simple/primitive array. It's your responsibility as the programmer to carry around the size of the array with you whenever you want to loop through the array.

My question is, how can a range-based modern C++11 for loop print all the elements in the array without being explicitly given the size. I know that the name of the array is simply a pointer to the first element. Without having the size, once you start looping, you don't know when to stop because you don't necessarily know how far the array extends in memory. And yet the range-based for loop works. How does it do that?

C-strings store a special \0 character to denote the end of the usable memory. Examining the memory after the int myarray[SIZE] using gdb, I found what I take to be garbage values.

const int SIZE = 5;
int myarray[SIZE];
myarray[0] = 0;
myarray[1] = 1;
myarray[2] = 2;
myarray[3] = 3;
myarray[4] = 4;

for (int i : myarray)
  cout << i << ' ';

Will threads be faster if each gets their own copy of a read only array

If I have a number of threads that each do some calculations based on a joint read only array, will it be faster if I provide each array with a separate copy of that array. For example, assume X is an array with numbers between 0 and 1 and each thread computes $sin(X)$ (entrywise). Should I create deep copies of $X$ to each thread?

Of course I could just try it out, but I will first have to learn how to implement threads in the first place. I am looking to do this in C++, in case it matters.

String input/output

I am kinda new to programming, so pardon me for any stupid questions :P, i noticed that when i write this

int main()
    {
        string s;
        s[0]='a';
        cout<<s.size();
        cout<<s<<" ";
        cout<<s[0];
       return 0;
    }

The output is 0 a , firstly why is the size 0? and why didn't anything get printed when i write cout<<s; but it gives a for cout<<s[0]. if i use push_back it gives normal out put.

int main()
{
    string s;
    s.push_back('a');
    cout<<s.size();
    cout<<s<<" ";
    cout<<s[0];
   return 0;
}

output :- 1a a

I might have overlooked something but i would be really appreciate if some could point out the cause. Thank you.

how to use c++ atomics

I'm confused about C++ atomic variables. If I have an atomic x that I want to increment in one thread and read in another thread, can I do ++x or do I have to do x.atomic_fetch_add(1). In the reader thread, can I do something like cout << x; or do I have to do cout << x.load().

If I have

int x;
atomic<bool> y;

then in thread one

if (!y)
{
   x = 23;
   y = true;
}

and in thread two

if (y)
{
   cout << x;
   y = false;
}

Is it guaranteed that thread two will see the value of (non atomic) x as 23. If not, if I change the access to y to use load and store, will that make a difference? Is it guaranteed that thread two will see the result of all non atomic operations that come before thread one sets y to true?

Can anyone suggest a book that explains these details clearly.

What is wrong with std::lock_guard

I have simple code: first thread pushes std::strings to the std::list, and second thread pops std::strings from this std::list. This code permanently prints error to console: "Error: lst.begin() == lst.end()". If I replace std::lock_guard with constructin "m.lock() ... m.unlock()" the code begins work correctly. What is wrong with std::lock_guard?

#include <iostream>
#include <thread>
#include <mutex>
#include <list>
#include <string>

std::mutex m;
std::list<std::string> lst;

void f2()
{
    for (int i = 0; i < 5000; ++i)
    {
        std::lock_guard<std::mutex> { m };
        lst.push_back(std::to_string(i));
    }

    m.lock();
    lst.push_back("-1"); // last list's element
    m.unlock();
}

void f1()
{
    std::string str;

    while (true)
    {
        m.lock();
        if (!lst.empty())
        {
            if (lst.begin() == lst.end())
            {
                std::cerr << "Error: lst.begin() == lst.end()" << std::endl;
            }
            str = lst.front();
            lst.pop_front();
            m.unlock();
            if (str == "-1")
            {
                break;
            }
        }
        else
        {
            m.unlock();
            std::this_thread::yield();
        }
    }
}

// tested in MSVS2017
int main()
{
    std::thread tf2{ f2 };
    f1();
    tf2.join();
}

What are `acquire` and `release` semantics and how are they related to `load` and `store`?

Can someone please explain what are acquire and release semantics in memory accessing? My very first thought when hearing acquire and release was about something like mutex in application layer. Are those (memory accessing model and mutex) relevant things? And how are they related to load and store operations?

dimanche 30 décembre 2018

What happens when std::make_unique

I have one doubt in std::unique_ptr.

When we assign std::make_unique() having no arguments, What will happen?

For example,

struct A {
  int a, b;
  A() {}
  A(int w, int e) : a(w), b(e) {}
};

int main() {
   A h(1, 2);
   std::unique_ptr<A> hello = std::make_unique<A>();
   std::cout << hello->a << std::endl;
}

In the above code, I mentioned default constructor, I got output for hello->a as a garbage value(random negative value)

But, when I change the struct as below,

struct A {
  int a, b;
  A() {a=0;b=0;}
  A(int w, int e) : a(w), b(e) {}
};

The result value of hello->a as 0.

Why default constructor not assign the int as 0 when using std::make_unique()?

How to use a vector as index in eigen

In matlab, we can use a vector B to get the sublist of vector A by coding like A(B). But in Eigen, I am wondering if there is anyway to do that?

What are the rules for using constructors vs braced initializer lists for initializing classes and structs?

I've searched the answer(s) to this question online but I have yet to find a satisfactory answer. I was wondering what are all the rules for initialization of objects of struct and class types, specifically when it comes to constructors vs braced initializer lists. Are the rules different for structs vs classes too?

Let us suppose we have a class or struct called Rectangle.

#include <iostream>
using namespace std;

class Rectangle {
  public:
    Rectangle() : x(5.0), y(6.0), width(7.0), height(8.0) {}

    void printMe()
    {
        cout << "The rectangle is located at (" << x << ',' << y << ") and is " << width << " x " << height << endl;
    }
    double x;
    double y;
    double width;
    double height;
};


int main()
{
    Rectangle r = {0.0, 0.0, 3.0, 4.0};
    r.printMe();

    Rectangle s;  // uninitialized!
    s.printMe();
}

I attempt to initialize Rectangle r the way you would usually do it in C, using a plain old braced initializer list. However, g++ gives the following error:

constructor_vs_initializer_list.cpp: In function ‘int main()’:
constructor_vs_initializer_list.cpp:21:38: error: could not convert ‘{0.0, 0.0, 3.0e+0, 4.0e+0}’ from ‘<brace-enclosed initializer list>’ to ‘Rectangle’
     Rectangle r = {0.0, 0.0, 3.0, 4.0};
                                      ^

Hmmm.... That is not very useful error message it seems at first glance. However I think that it has something to do with the constructor, because if I remove it, the code compiles and runs! It would be a paradox I think, both the braced initializer list and the constructor are competing to initialize the data members it seems.

However, when I made the data members private, after removing the constructor that is, the same error message was displayed again!

I wonder what are the rules of precedence in initialization of data members. How does the braced initializer list compare to a constructor you defined yourself? How does it compare to the C++11 features: = default constructor and in-class member initializers? I assume that these different ways of initializing the object's data members would conflict with each other somehow.

Rectangle() = default;
...
double x = 1.0;

I'm not writing that mixing them up is necessarily good code, just it is code, and code that should be understood well in my opinion. Thank you.

Why does this stl function call result in an incorrect boolean evaluation?

I was humbly coding away when I ran into a strange situation involving checking the size of a vector. An isolated version of the issue is listed below:

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

int main() {

  std::vector<std::string> cw = {"org","app","tag"};

  int j = -1;

  int len = cw.size();

  bool a = j>=cw.size();
  bool b = j>=len;


  std::cout<<"cw.size(): "<<cw.size()<<std::endl;
  std::cout<<"len: "<<len<<std::endl;

  std::cout<<a<<std::endl;
  std::cout<<b<<std::endl;

  return 0;
}

Compiling with both g++ and clang++ (with the -std=c++11 flag) and running results in the following output:

cw.size(): 3
len: 3
1
0

why does j >= cw.size() evaluate to true? A little experimenting that any negative value for j results in this weird discrepancy.

How to verify the boost library I'm using supports C++11?

I would like to check that the Boost library I'm linking against has C++11 support. Is there a function I can run or a define I can verify to be sure of this?

Strange benchmark results for open mp methods

My benchmark results are very strange. On one hand I have the serial function for calculating the quadratic form. On the other hand I wrote two parallel versions. For one thread all functions should need more or less the same running time. But one parallel function just needs half of the time. Is there a "hidden" optimization?

Serial version:

double quadratic_form_serial(const std::vector<double> & A,const std::vector<double> & v, const std::vector<double> & w){
    int N= v.size();
    volatile double q=0.0;

    for(int i=0; i<N; ++i)
        for(int j=0; j<N; ++j)
            q +=v[i]*A[i*N+j]*w[j];

return q;
}

Parallel version 1:

double quadratic_form_parallel(const std::vector<double> & A,const std::vector<double> & v, const std::vector<double> & w, const int threadnum){
int N= v.size();

omp_set_num_threads(threadnum);
volatile double q[threadnum];
volatile double val = 0.0; 

#pragma omp parallel
{
    int me = omp_get_thread_num(); 
    q[me] = 0.0;
    #pragma omp for collapse(2)
    for(int i=0; i<N; ++i)
        for(int j=0; j<N; ++j)
            q[me]+=v[i]*A[i*N+j]*w[j];
    #pragma omp atomic
    val+=q[me];
}
return val;
}

Parallel version 2:

double quadratic_form_parallel2(const std::vector<double> & A,const std::vector<double> & v, const std::vector<double> & w, const int threadnum){
    int N= v.size();
    volatile double result =0.0;
    omp_set_num_threads(threadnum);

    #pragma omp parallel for reduction(+: result)
    for (int i=0; i<N; ++i)
        for (int j=0; j<N; ++j)
            result += v[i] * A[i*N + j] * w[j];
    return result;
}

I run the code for N=10000 and I flushed the cache before I call the function. The function quadratic_form_parallel2 needs with one thread less than the half of the time the two other function needed:

threads    serial       Parallel1       Parallel2
1          0.0882503    0.0875649       0.0313441   

Reading from a .txt file and looping until new line

I am having trouble understanding the output of my very little program which should read characters from a text file until it finds a new line. It correctly outputs the characters and stops, but I don't understand why it still outputs the newline ('\n) character in the terminal and doesn't end before getting to it. I know that I could use getline() or find another way but I would really understand the reason behind this behaviour. Thank you in advance! Edo

Code:

int main() {
    std::ifstream in_file;
    in_file.open("../responses.txt");
    char c;
    while(c != '\n'){
        in_file.get(c);
        std::cout << c << std::endl;
    }
    return 0;
}

Output:

A
B
C
D
E


Time elapsed: 000:00:000

The

How to use make_shared to create an array of objects of the same type?

We could use "make_shared" to create an object faster and safer compared to use "new". For example,

shared_ptr<Dog> p = make_shared<Dog>("Luther"). 

If I need to create an array of objects (e.g. Dog[3]), is it possible to use "make_shared" instead "new"? Besides, is it possible to use a customized delete function with make_shared method?

g++ and clang++ different behaviour with lambda capturing `std::integral_constant` by reference

Given the following code

#include <type_traits>

int main ()
 {
   std::integral_constant<int, 42> ic;

   [&]{ constexpr int i = ic; (void)i; }();
 }

(the (void)i; is just to avoid a "unused variable" warning) clang++ compile without problem where g++ gives the following error

prog.cc: In lambda function:
prog.cc:7:27: error: '__closure' is not a constant expression
    7 |    [&]{ constexpr int i = ic; (void)i; }();
      |                           ^~

Capturing by value

[=]{ constexpr int i = ic; (void)i; }();

both compilers compile without problem.

The question, as usual, is: who's right? g++ or clang++?

how to access vector object in another class in c++

I am newbie to c++.I have created two classes.one class(say A) will push the struct data into vector while other class(say B) will pop out the data from the vector.

How do I pass the reference of vector from class A to B so that class B can point to same vector object to pop out data,to do some manipulation.

can anyone help me to resolve this

So far My effort is, A.h file:

struct strctOfA {
       int x;
       int y;
       int z;
    };  


class A {
public:

A();        
private:
     std::vector<strctOfA> t2;
};



    A.cpp file:
    <pre><code>
         A::A() {

        strctOfA player;
        player.x=1;
        player.y=2;
        player.z=3;



        t2.push_back(player)
        B b;
        b.functionOfB(&t2); 
        }


    B.h file
    <pre><code>
         class B {

        public:
             B();
             functionOfB(&t2);
        };


 B.cpp:



 B::functionOfB(A &t) {
    t2.pop_front(); 
    }

Is there any difference between std::vector::resize and direct initialization to zero

Is there any difference between:

std::vector<int> B;
B.resize(N);

and

std::vector<int> B(N); //or std::vector<int> B(N,0);

or is the second method the short form of the first method?

I am getting error like "expected identifier" when i try to use macros in my code

I have written a macros but when i use the code i get expected identifier error.

Below is my macros

#define ITK(arguments)  \
{                       \
    int iFail=0;        \
    iFail = arguments;  \
    if(iFail != ITK_ok) \
{                      \
    char* s;            \
    TC_write_syslog("Following Method Retruns error "#arguments "\n");\
    TC_write_syslog("Error is in the line [%d] of the file ["__FILE__"]\n",[__LINE__]);\
    EMH_ask_error_text(iFail,&s);\
    TC_write_syslog("And the error is [%s]",s);\
    if(s!=0) MEM_FREE(s);\
}                           \
}

samedi 29 décembre 2018

I need help understanding why File.get(ch) in my program does not work as it should. Is there something I am missing? C++ 11

I have been working on a big project for a beginning C++ student. Every other part of it is working , except this list I want the program to have. Basically, I want to create a list that you can choose a number from and it will go its own file and extract the name of the other file from there. Then open the file and display its contents.

I have been trying for a week, several different options to get this to work.

Here is my program I didn't know how to just post code here, the instructions are extremely confusing lol.

The onefile(File for the list) itself has this as its result:

0&Trying$ which is correct.

I am wondering why the File.get doesn't do what it should do and decode that so it would display like:

1) Trying

Deleting a pointer from a vector using loops (not iterators)

I have a method that is passed an object, finds that object in a vector of pointers by matching its address in a loop, and needs to remove the matching item from the vector without deleting the item (i.e the item needs to still exist in memory). Currently, this is the method:

void remove(Soldier& soldier) {
    for (size_t i = 0; i < armySize(); ++i) {
        if (army[i] == &soldier) {
            cout << army[i]->getName() << "is removed" << endl;
            army.erase(i);
            break;
        }
    }
}

Where soldier is the object that needs to be removed and army is a vector of Soldier pointers. The if statement works, meaning that the address of soldier and an item in the vector matches. The problem is that I get an error that says "no matching member function for call to 'erase'". How would I fix this without using iterators (no new, delete or begin method)?

how to get a pointer to head of std::set in c++

how can i get a pointer to the first element in a set

   int main()
   {
    std::vector<int> v ;
    v.insert(v.end() , 1);
    v.insert(v.end() , 2);
    v.insert(v.end() , 5);
    v.insert(v.end() , 4);

    std::set<int> s ;

    s.insert(s.end() , 754);
    s.insert(s.end() , 5);
    s.insert(s.end() , 3);
    s.insert(s.end() , 4);

    std::list<int> l ;

    l.insert(l.end() , 45);
    l.insert(l.end() , 5);
    l.insert(l.end() , 3);
    l.insert(l.end() , 4);

    int *p = (int*)(&*l.begin());  <<<<<<-------- ( here )
    cout << *p++ <<endl;
    cout << *p++ <<endl;
    cout << *p++ <<endl;
    cout << *p <<endl;

it work with vectors but it gives me a junk value with set and list any idea ??

How to reuse operator overloads for different types?

I have several enums defined as follows:

enum class Suit {
    spades = 1, hearts, diamonds, clubs,
    first = spades, last = clubs
};

enum class Rank {
    six = 6, seven, eight, nine, ten, jack, queen, king, ace,
    first = six, last = ace
};

For each of these enums I have overloaded some operators:

Suit operator++(Suit& r) { return r = (Suit)(static_cast<std::underlying_type_t<Suit>>(r) + 1); }
Rank operator++(Rank& r) { return r = (Rank)(static_cast<std::underlying_type_t<Rank>>(r) + 1); }
// [...] lots of code duplication for other operators...

Note that the implementation of the operator overloads is the same for both types. How can I avoid this code duplication?

I could use templates...

template<class T>
T operator++(T& r) { return r = (T)(static_cast<std::underlying_type_t<T>>(r) + 1); }

but these overloads should apply to my custom types only.

error: ‘row’ in namespace ‘pqxx’ does not name a type

I compiled my c++ program using libpqxx on my development machine. but in deployment machine i got this error: error: ‘row’ in namespace ‘pqxx’ does not name a type i installed same version libpqxx on deployment machine.

boost::property_tree::ptree UserModel::GetUsersJson(int page, std::string query){
    pqxx::result R = GetUsers(page, query);
    int count = R.size();
    int pageCount = count / OFFSET_COUNT;
    boost::property_tree::ptree users_node;
    boost::property_tree::ptree user_node;
    for(pqxx::row r : R)
    {
        user_node.put("id", r[0]);
        user_node.put("email", r[1]);
        user_node.put("password", r[2]);
        user_node.put("details", r[3]);
        user_node.put("created_at", r[4]);
        users_node.push_back(std::make_pair(r[0].c_str(), user_node));
    }
    return users_node;
}

Access calling function's local variable

This is a toy example of the issue. I have a large parent function, which, among other things, calls two child functions. In reality, this parent function is on a base class used for other things, so I don't want to rewrite the parent function or the wrapped functions to pass variables by reference, because they won't be needed for the other child classes inheriting the base. The parentFunc is also being called on multiple threads, so I can't just stick the needThisInSecondWrappedFunc variable as a class-level variable, as it would then be incorrectly shared between threads.

It seemed to me making a local variable on the parent function would be visible to the two child functions, which could then operate on the parentFunc's local variable, but it's not the case.

#include <iostream>

void parentFunc(float& data);
void wrappedFunc(float& ref);
void secondWrappedFunc(float& ref);

void parentFunc(float& data)
{
float needThisInSecondWrappedFunc[3];
wrappedFunc(data);
secondWrappedFunc(data);
}

void wrappedFunc(float& ref)
{
    needThisInSecondWrappedFunc[0] = ref * 0.5f;
    needThisInSecondWrappedFunc[1] = ref * 0.5f;
    needThisInSecondWrappedFunc[2] = ref * 0.5f;
}

void secondWrappedFunc(float& ref)
{
    ref = needThisInSecondWrappedFunc[0] +
          needThisInSecondWrappedFunc[1] +
          needThisInSecondWrappedFunc[3];
}

int main()
{
    float g;
    g = 1.0f;
    parentFunc(g);
    std::cout << g << '\n';
    return 0;
}

I'm not sure why wrappedFunc and secondWrappedFunc can't see the local variables of the parentFunc - I thought the parentFunc locals would still be in scope at this point?

Why is vector push_back throwing a segmentation fault

I'm trying to create an n-ary tree by taking user inputs. "t" would be number of test cases, "n" number of nodes in each n-ary trees and "e" number of edges.

#include<iostream>
#include <vector>
#include <unordered_map>
using namespace std;   //Algo problem, so using it here
struct Node{
    int key;
    vector<Node*> child;
};

Node* newNode(int key){
    Node* node = new Node;
    node->key = key;
    return node;
}

int main() {
    int t, n, e;
    cin>>t;
    while(t--) {
        cin>>n>>e;
        unordered_map<int, Node*> map1, map2;
        vector<Node*> node1, node2;
        int node1Src[n], node1Dest[n], node2Src[n], node2Dest[n];
        for(int i = 0; i < e; ++i){
            cin>>node1Src[i]>>node1Dest[i];
        }
        for(int i = 0; i < e; ++i){
            cin>>node2Src[i]>>node2Dest[i];
        }

        Node* tempSrc, *tempDest;
        for(int i = 0; i < e; ++i){
            if(map1.find(node1Src[i]) == map1.end()){
                tempSrc = newNode(node1Src[i]);
                map1.insert({node1Src[i], tempSrc});
                node1.push_back(tempSrc);
            }
            tempSrc = map1[node1Src[i]];
            if(map1.find(node1Dest[i]) == map1.end()){
                tempDest = newNode(node1Dest[i]);
                map1.insert({node1Dest[i], tempDest});
                node1.push_back(tempDest);
            }
            tempDest = map1[node1Dest[i]];
            tempSrc->child.push_back(tempDest);
        }
        for(int i = 0; i < e; ++i){
            if(map2.find(node2Src[i]) == map2.end()){
                tempSrc = newNode(node2Src[i]);
                map2.insert({node2Src[i], tempSrc});
                node2.push_back(tempSrc);
            }
            tempSrc = map2[node2Src[i]];
            if(map1.find(node2Dest[i]) == map2.end()){
                tempDest = newNode(node2Dest[i]);
                map2.insert({node2Dest[i], tempDest});
                node2.push_back(tempDest);
            }
            tempDest = map2[node2Dest[i]];
            tempSrc->child.push_back(tempDest);
        }
    }
return 0;
}

Inside the final for loop the last line where I'm trying to push the Node to the vector, I'm getting a segmentation fault. On debugging, I got EXC_BAD_ACCESS (code=1, address=0x10).

C++11 multithreaded projects examples

Trying to understand how to write a multithreaded program using features of 11 or 14 standard. I've got enough simple examples with using std::async or std::thread, but i can't find any good architecture example. Does anyone know an opensource multithreaded project where i can take a look to know how multithreading works in real life? Not abstract examples with simple classes and functions like doSomething().

No match for operator== for strings

What is the meaning of error shown below?

error: no match for 'operator==' (operand types are 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' and '__gnu_cxx::__alloc_traits<std::allocator<char> >::value_type {aka char}')

This is the code I currently have:

#include<bits/stdc++.h>

using namespace std;

int main()

{

    int i , pos1=0 , pos2=0 ; 
    string trump,card1,card2;
    cin>>trump>>card1>>card2;
    string a = "6789TJQKA";
    if(trump == card1[1])
    {
        cout<<"YES";
        return 0;
    }
    for(i=0;i<a.length();++i)
    {
        if(a[i] == card1[0])
        pos1 = i;
        if(a[i] == card2[0])
        pos2 = i;
    }
    if(card1[1] == card2[1])
    {
        if(pos1>pos2)
        cout<<"YES";
        else 
        cout<<"NO";
        return 0;
    }
    else if(card1[1]!=card2[1])
    cout<<"NO";
    return 0;
}

Bloom Filters and False Positives

  • Suppose you are given a Bloom Filter with 3 hash functions h1, h2, h3, and m indices.
  • At the moment, exactly 2m/3 indices are set to true, while the remaining m/3 are set to false. You are safe to assume that m is divisible by 3.
  • You may also assume that the three hash functions are universal and independent such that:

    1. The probability that hi(x)=p is exactly 1/m for all indices p and (i=1,2,3)
    2. hi(x) is independent of hj(y), for all i, j ∈ {1,2,3} and x,y when i does not equal y.

Answer the following and explain: If you search for 27 items, none of which are inside the Bloom filter, how many false positives will you get on average? Thanks

vendredi 28 décembre 2018

C++ value initialize items of a custom container

Lets take custom vector implementation as an example:

template<typename Object>
class myVector {
public:
    explicit myVector(int size = 0) :
        _size{ size },
        _capasity{ size + SPARE_CAPACITY }
    {
        _buff = new Object[_capasity];
        if (_size > 0) {
            for (int i = 0; i < _size; i++) {
                //_buff[i] = 0;
            }
        }
    }

// more code

private:
    Object * _buff = nullptr;
    int _size;
    int _capasity;
};

So my question is, how to make myVector be value-initialized in case I'll initialize it as:

int main() {
    myVector<int> v02(5);                   
}

Here, it contains 5 int values, so I need it to be all zeros; same with other types. I commented out _buff[i] = 0; as it's specific to int. Please give me some hints.

C++ program to be done

I got a homework that I am unable to do. can you help me? Need to code it in C++ and using data structure concept. I have tried a lot but unable to get an idea how to solve. Please help me by solving it.

The problem statement is given in this link

Link here:

< https://drive.google.com/file/d/1Nyl9T4Wci6tloyZ8jMFFHUjd4pAiIEc3/view?usp=sharing >

Can a class object be created as an lvalue-only?

A well-known problem with std::lock_guard (and its relatives) is that it does not work the way as expected when only a temporary object is created.

For example:

std::mutex mtx;

std::lock_guard<std::mutex> {mtx} // temporary object, does not lock the entire scope

std::lock_guard<std::mutex> lck{mtx} // correct

I tried reference qualifiers to create a replacement that prevents a temporary object from being created (at compile time). The following code is a futile attempt:

#include <mutex>

template<typename T>
struct my_lock {
    T &mtx;
    my_lock(T &t) : mtx{t} { lock(); }
    ~my_lock() { unlock(); }

    void lock() & { mtx.lock(); };
    void unlock() & { mtx.unlock(); };
};


std::mutex mtx;

int main()
{
    my_lock<std::mutex> {mtx}; // A 

    my_lock<std::mutex lck{mtx}; // B
}

This does not work, so the question becomes:

Is it possible to write the class in such a way that the compiler rejects A and accepts B ?

Create a dynamic array of pointers and assign different subclass objects to them

I've been having trouble accessing the "getDegreeProgram()" method in my objects that are set to my array of pointers; all of my baseclass methods are working, but for some reason, my subclass methods aren't even visible. I'm new to c++ and stackoverflow, so if you need any additional code or information about my project, let me know. Thanks in advance.

roster.h:

   class roster { 
   private:   
   student** classRosterArray; //array of pointers

roster.cpp function that creates my objects and sets them to the array of pointers


   void roster::createStudentObject() {
      classRosterArray = new student *[5]; //array of pointers
   if (degreeProgramInput == "NETWORK") {
      classRosterArray[rosterCounter] = new networkStudent();
   }
   else if (degreeProgramInput == "SECURITY") {
      classRosterArray[rosterCounter] = new securityStudent();
   }
   else classRosterArray[rosterCounter] = new softwareStudent();  
   }

student.h subclasses in question (they're subclasses of my baseclass "student")

    class networkStudent:public student {
    private: 
      int networkDegree;
    public:
      int getDegreeProgram();
      networkStudent();
    };
    class securityStudent:public student {
    private:
      int securityDegree;
    public:
      int getDegreeProgram();
      securityStudent();
    };
    class softwareStudent:public student {
    private:
      int softwareDegree;
    public:
      int getDegreeProgram();
      softwareStudent();
    };    

No matching function call error with usage of, lambda expressions and std::function.

I am trying to use this lambda expression in my code. And looks like something's wrong with definition of functor or lambda.

I believe the lambda expression is true. but I can't satisfy the prototype of function I defined.

Function definition:

    template<typename E, typename container> 
void for_each(Iterator<E,container> begin, std::function<void(E&)> fun)
{
    do // does the given unary functor to elements 
    {  //from starting iterator 'til the end.
        fun(*begin);
        begin = begin.next();
    }while(begin.hasNext());

    fun(*begin);
}

And caller:

  for_each(c.iterator(), [&](E& e){add(e);});

I except achieve this function call with lambda expression. But compiler says "error: no matching function for call to .."

Multiple standard headers with same name - which one gets included and how can I change it?

I'm getting an error that std::enable_if_t does not name a template type. Funny enough it is included by a line #include <type_traits> at the top of the file. But looking into some of the other standard headers, there is another file named type_traits in a different directory that doesn't define enable_if_t. How does gcc decide which of these files to use and how can I change it?

The path of the file I want to use is:

.../arm-none-eabi/include/c++/7.3.1/type_traits

I don't know what file gcc is using but these files do not have the definition that should solve my problem:

.../arm-none-eabi/include/c++/7.3.1/bits/cpp_type_traits.h
.../arm-none-eabi/include/c++/7.3.1/ext/type_traits.h
.../arm-none-eabi/include/c++/7.3.1/experimental/type_traits
.../arm-none-eabi/include/c++/7.3.1/tr2/type_traits
.../arm-none-eabi/include/c++/7.3.1/tr1/type_traits

How can implement my custom ranged for loop?

I do really like Ranged-based-for-loop which is supported by C++11 and above. I'd like for some understanding reason to simulate it. Here is an example:

// 1
//#define ranged_for(X, T) \
//  for (std::vector<int>::iterator beg{ T.begin() },\
//      end{ T.end() }; beg != end; X = *beg, ++beg)\

// 2
//#define ranged_for(X, T) \
//  for (std::vector<int>::iterator beg{ T.begin() },\
//      end{ T.end() }; beg != end; ++beg, X = *beg)\

// 3
#define ranged_for(X, T) \
    for (std::vector<int>::iterator beg{ T.begin() },\
        end{ T.end() }; beg != end; ++beg)\
            X = *beg, 



int main(){
    std::vector<int> data{75, 435, 6578, 92, 123};

    auto i{ 0 };
    ranged_for(i, data)
        std::cout << i << std::endl;

    std::cout << std::endl;
    std::cin.get();
    return 0;
}

As you can see above the first macro doesn't get the first element 75 but instead the value 0 and the last one is not there.

  • The second macro crashes the program that is because i think reading the last node (sentry).

  • The third works fine but as you can see after the macro expansion I'll get:

    i = *beg, std::cout << i << std::endl;
    
    

That is because the line above is treated as a single statement. Is there a better way and explanation. Thank you all good dudes!.

Chaining the templates problem with passing stl container

I am writing the code and error message below.

template<template <typename...> class container_type>
void test_int(string container_name){
    container_type<int,std::vector> container1;
    container_type<int,std::set> container2;
    container_type<int,std::list> container3;
        ...

main.cpp

test_int<ArrayList>("arraylist"); ---> error
ArrayList<int,std::Vector> test; ---> no error
 ....

compiler says that:

test.cpp:17:32: error: type/value mismatch at argument 1 in template 
parameter list for ‘template<class ...> class container_type’
container_type<int,std::vector> container1;
                            ^
test.cpp:17:32: note:   expected a type, got ‘vector’
test.cpp:18:29: error: type/value mismatch at argument 1 in template 
parameter list for ‘template<class ...> class container_type’
container_type<int,std::set> container2;
                         ^
test.cpp:18:29: note:   expected a type, got ‘set’
test.cpp:19:30: error: type/value mismatch at argument 1 in template 
parameter list for ‘template<class ...> class container_type’
container_type<int,std::list> container3;

How Can I solve this ?

Why can't I make a unique pointer to an array, when I can make a shared pointer?

The following is invalid:

#include <memory>
#include <iostream>
typedef double zip[10];

int main()
{
    std::unique_ptr<zip> s = std::make_unique<zip>();
    (*s)[0] = 2.0;
    std::cout << (*s)[0] << std::endl;
    return 0;
}

But the following is perfectly valid:

int main()
{
    std::shared_ptr<zip> s = std::make_shared<zip>();
    (*s)[0] = 2.0;
    std::cout << (*s)[0] << std::endl;
    return 0;
}

Why the discrepancy? What am I missing?

CMake source_group doesn't work on Qtcreator

In my project I have a top level CMakeLists.txt where I define general project properties:

cmake_minimum_required(VERSION 3.11 FATAL_ERROR)

find_program(CCACHE_PROGRAM ccache)
if(CCACHE_PROGRAM)
    set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE "${CCACHE_PROGRAM}")
endif (CCACHE_PROGRAM)

set_property(GLOBAL PROPERTY USE_FOLDERS ON)

project(databaseclient LANGUAGES CXX VERSION 0.1.0.0 DESCRIPTION "Asynchronous database client")

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

if (NOT CMAKE_BUILD_TYPE)
   set(CMAKE_BUILD_TYPE DEBUG)
endif(NOT CMAKE_BUILD_TYPE)

add_subdirectory(src)

And in my project's source folder I define an OBJECT library that will later be linked to static and dynamic libraries:

set(
  SOURCE_FILES
    ${PROJECT_SOURCE_DIR}/include/databaseclient/parameters.hpp
)
add_library(
  ${PROJECT_NAME}
    OBJECT
      ${SOURCE_FILES}
)
set_target_properties(
  ${PROJECT_NAME}
    PROPERTIES
      VERSION ${PROJECT_VERSION}
      POSITION_INDEPENDENT_CODE ON
)
target_compile_features(
  ${PROJECT_NAME}
    PUBLIC
      cxx_std_11 cxx_noexcept
      cxx_auto_type
      cxx_constexpr
      cxx_deleted_functions
      cxx_inline_namespaces
      cxx_lambdas
      cxx_noexcept
      cxx_nullptr
      cxx_override
      cxx_range_for
)
target_compile_definitions(
  ${PROJECT_NAME}
    PRIVATE
      ASIO_STANDALONE=1
      ASIO_NO_EXCEPTIONS=1
      ASIO_NO_DEPRECATED=1
)
target_include_directories(
  ${PROJECT_NAME}
    PRIVATE
      ${byte-lite_SOURCE_DIR}/include/nonstd
      ${asio_SOURCE_DIR}/asio/include/
      ${PROJECT_SOURCE_DIR}/include/
)

QtCreator creates a folder structure where a node has the full path to my source files, which is obviously suboptimal. I tried to add a source_group to the list under the src folder but QtCreator seems to just ignore it.

How can I get source_group to work?

Expand parameter pack in calling the base types' methods when variadic template class is inherited from template arguments

So basically I want to define a class that inherits from an arbitrary amount of classes and have a method in it that calls the overloaded method from all the base classes.

I tried writing this, but it won't compile:

class Foo
{
public:
    void method()
    {
        std::cout << "Foo::method()\n";
    }
};

class Bar
{
public:
    void method()
    {
        std::cout << "Bar::method()\n";
    }
};

template <typename... Ts>
class Combined: public Ts...
{
public:
    Combined(const Ts&... ts): Ts(ts)... {}
    Combined(Ts&&... ts): Ts(std::move(ts))... {}

    template <typename U>
    void call_methods()
    {
        U::method();
    }

    template <typename U, typename... Us>
    void call_methods()
    {
        U::method();
        call_methods<Us...>();
    }

    void method()
    {
        call_methods<Ts...>();
    }
};


int main(int argc, char *argv[])
{
    Combined<Foo, Bar> obj({}, {});
    obj.method();
    return 0;
}

The compiler says the following:

test.cpp:42:9: error: call to member function 'call_methods' is ambiguous
        call_methods<Us...>();
        ^~~~~~~~~~~~~~~~~~~
test.cpp:47:9: note: in instantiation of function template specialization
      'Combined<Foo, Bar>::call_methods<Foo, Bar>' requested here
        call_methods<Ts...>();
        ^
test.cpp:57:9: note: in instantiation of member function
      'Combined<Foo, Bar>::method' requested here
    obj.method();
        ^
test.cpp:33:10: note: candidate function [with U = Bar]
    void call_methods()
         ^
test.cpp:39:10: note: candidate function [with U = Bar, Us = <>]
    void call_methods()
         ^

Basically there is an ambiguity between call_methods<U = Bar> and call_methods<U = Bar, Us = <>>. But if I declare a void call_methods() {}, it won't match the call_methods<Us...>(); for some reason.

If it's not clear yet, I want Combined<Foo, Bar>::method() to call Foo::method() and Bar::method().

I know that I can probably implement this by having a tuple with the objects of corresponding types as a member and just iterating over them, but I really want to find a solution that's closer to what I wrote.

Gauss-Seidel method and coupled gradient methods for matrix

I have matrix https://i.ibb.co/P4Zm2rG/matrix.png and I should write code using Gauss-Seidl and coupled gradient methods taking the structure of the matrix.

Ax = e where A - is matrix and e is vector with only 1 values

I don't know how to write code using coupled gradient methods. And my Gauss-Seidel algorithm don't have main part where I add this all thinks

//part of gauss-seidel method

const int N = 128;               //size of matrix
const int no_of_iter = 128; //iterations
int main(){
  double result[N];     //tab for result
  double result_pom[N]; //tmp result tab
  double sum = 0.0;    //

  int x, y;                            
  for (int i = 0; i < no_of_iter; i++) {
    for (y = 0; y < N; y++)
       result_pom[y] = result[y]; //set values of result to result_pom

    for (x = 0; x < N; x++){
      sum = 0.0;
      //for functions where I add (x,y) el

      result[x] = 0.25 * (1 - sum);//because 4 is dominant el of matrix and 1 is value of vector e
    }
  }

}

How to create Laguerre method with a strategy for reducing polynomial and polishing?

I want to create program with compute equations like 243z^7 - 486z^6 + 783z^5 - 990z^4 + 558z^3 - 28z^2 - 72z + 16 = 0 or similar using Laguerre method in c++.
But I don't know how to start and I can't find any proper information about it in c++ using complex numbers.

Does anyone know any good sources or have a code to share with? In the worst case, it can be java but I want avoid using R and python.

comma operator overload: how to trigger an action after the last comma in a statement has been processed

I have a simple class which wraps an array of double as follows:

struct VecExpr {
    VecExpr(double *v, size_t n) : x(v), n(n) {}
    double *x;
    size_t n;
};

Based on this class I implement a vectorial algebra framework which fuses operations. For example, let vx, vy, vz and vr be classes of type VecExpr, then I can write:

vr = vx + vy * vz, vr = vr * vr, vr = vr + vx;

and computation are performed internally as if I had written:

for (size_t i = 0; i < vr.size; ++i) {
   vr[i] = vx[i] + vy[i] * vz[i];   // i-th iteration, 1st assignment
   vr[i] = vr[i] * vr[i];           // i-th iteration, 2nd assignment
   vr[i] = vr[i] + vx[i];           // i-th iteration, 3rd assignment
}

As you can see, operations are fused also across different assignments. This is achieved via creation of various expression classes, which overload the comma operator. Nothing really happens until the last comma in the statement has been processed, at which point evaluation of the whole loop is triggered.

A minimal demo of this framework is given below.

More in details, in pseudocode, at compile time:

  • the expression vr = vx + vy * vz triggers construction of an AssignExprclass: AE(vr, vx + vy * vz)
  • the expression vr = vr * vr triggers construction of another AssignExpr class: AE(vr, vr + vr)
  • the comma separating the two above expressions triggers constructions of a ME class: ME(AE(vr, vx + vy * vz), AE(vr, vr + vr))
  • the expression vr = vr + vx triggers construction of an AEclass: AE(vr, vr + vx)
  • the 2nd comma triggers constructions of a MultiExpr class: ME(ME(AE(vr, vx + vy * vz), AE(vr, vr + vr)), AE(vr, vr + vx))

At this point, since the statement is complete, evaluation starts.

To trigger evaluation I use the destructors of the classes AssignExpr and MultiExpr. When any of these class is destructed, if it is the outermost class, then it triggers evaluation.

Is there a better way? How to determine if the class is the outermost or not?

In the demo below, I add to the AssignExpr and MultiExpr a boolean flag outer. When the class is created, this is tentatively initialized to true, but if the class is then used as argument in the constructor of an outer class, the outer class takes care of resetting this flag to false.

Is kind of feel there should be a better way. In the end, everything is known at compile time. Any suggestion?

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

// forward declaration
template <typename RHS> struct AssignExpr;
template <typename LHS, typename RHS> struct MultiExpr;

struct Size {
    Size(size_t s) : sz(s) {}
    size_t size() const { return sz; }
    size_t sz;
};

struct VecExpr : Size {
    VecExpr(double *v, size_t n) : x(v), Size(n) {}

    void set(size_t i, double v) const { x[i] = v; }
    double operator[](size_t i) const { return x[i]; }

    template <typename RHS> auto operator=(const RHS& rhs) const { return AssignExpr<RHS>(*this, rhs); }

    double *x;
};

template <template <typename> class Op, typename Arg1, typename Arg2>
struct OperExpr : Size
{
    OperExpr(const Arg1& a1, const Arg2& a2) : Size(a1.size()), arg1(a1), arg2(a2) { assert(a1.size() == a2.size()); }
    double operator[](size_t i) const { return Op<int>{}(arg1[i], arg2[i]); }

    Arg1 arg1;
    Arg2 arg2;
};


template <typename RHS>
struct AssignExpr : Size
{
    AssignExpr(const VecExpr l, const RHS r)
        : Size(l.size()), lhs(l), rhs(r), outer(true)  // tentatively set to true
    { assert(l.size() == r.size()); }
    AssignExpr(const AssignExpr<RHS>& expr)
        : Size(expr.size()), lhs(expr.lhs), rhs(expr.rhs), outer(false) {}

    void set(size_t i) const { lhs.set(i, rhs[i]); }

    template <class R>
    auto operator,(const R& r) { return MultiExpr<AssignExpr<RHS>,R>(*this, r); }

    ~AssignExpr() {
       if(outer)  // if outer expression, triggers evaluation
          for (size_t i = 0; i < size(); ++i)
             set(i);
     }

    VecExpr lhs;
    RHS rhs;
    mutable bool outer;
};

template <typename LHS, typename RHS>
struct MultiExpr : Size
{
    MultiExpr(const LHS& l, const RHS& r)
        : Size(l.size()), lhs(l), rhs(r), outer(true)  // tentatively set to true
    { l.outer = r.outer = false;  assert(l.size() == r.size()); } // reset flag for arguments
    MultiExpr(const MultiExpr<LHS, RHS>& expr)
        : Size(expr.size()), lhs(expr.lhs), rhs(expr.rhs), outer(false) {}

    void set(size_t i) const { lhs.set(i); rhs.set(i); }  // evaluates in reverse order

    template <class R>
    auto operator,(const R& r) { return MultiExpr<MultiExpr<LHS, RHS>, R>(*this, r); }

    ~MultiExpr() {
       if(outer)  // if outer expression, triggers evaluation
          for (size_t i = 0; i < size(); ++i)
             set(i);
    }


    LHS lhs;
    RHS rhs;
    mutable bool outer;
};

template <typename Arg1, typename Arg2>
auto operator*(const Arg1& arg1, const Arg2& arg2)
{
    return OperExpr<multiplies, Arg1, Arg2>(arg1, arg2);
}

template <typename Arg1, typename Arg2>
auto operator+(const Arg1& arg1, const Arg2& arg2)
{
    return OperExpr<plus, Arg1, Arg2>(arg1, arg2);
}

void demo(size_t n, double *x, double *y, double *z, double *r)
{
    VecExpr vx(x, n), vy(y, n), vz(z, n), vr(r, n);
    vr = vx + vy * vz, vr = vr * vr, vr = vr + vx;
}

int main()
{
    double x[] = {2, 3, 4}, y[] = {3, 4, 5}, z[] = {4, 5, 6}, r[3];
    demo(3, x, y, z, r);
    for (auto d : r)
        cout << d << "\n";
    return 0;
}

How to compile using g++ with -std=c++11 flag?

I'm trying to setup my computer (windows 10) for compiling c++ 11. I have written a simple hello world program which I can compile using g++ helloworld.cpp -o helloworld.exe -static-libgcc but when I change command to allow c++ 11 like this g++ helloworld.cpp -o helloworld.exe -static-libgcc -std=c++11 I get rather unexpected (for me) error

In file included from c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\cstdio:42:0,
                 from c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\mingw32\bits\stdc++.h:46,
                 from helloworld.cpp:1:
c:\mingw\include\stdio.h:788:34: error: '__off64_t' does not name a type
 typedef union { __int64 __value; __off64_t __offset; } fpos_t;
                                  ^~~~~~~~~

As for background info, i use g++ 6.3.0 (at least that is what i see after typing g++ --veriosn into cmd). What should I do to fix this? (to be able to compile)

Will Mutex protection failed for register promotion?

In an article about c++11 memory order, author show an example reasoning "threads lib will not work in c++03"

for (...){
  ...
  if (mt) pthread_mutex_lock(...);
  x=...x...
  if (mt) pthread_mutex_unlock(...);
}
//should not have data-race
//but if "clever" compiler use a technique called 
//"register promotion" , code become like this:

r = x;
for (...){
    ...
if (mt) {
    x=r; pthread_mutex_lock(...); r=x;
}
r=...r...
if (mt) {
    x=r; pthread_mutex_unlock(...); r=x;
}
x=r;

There are 3 question:

1.Is this promotion only break the mutex protection in c++03?What about c language?

2.c++03 thread libs become unwork?

3.Any other promotion may caused same problem?

jeudi 27 décembre 2018

Calling constructor from copy constructor

From c++ 11 we can call a constructor from another constructor. So instead of defining copy constructor can we call the constructor every time? Like in this piece of code :

class MyString
{
private:
    char *ptr;
    int m_length;
public:
    MyString(const char *parm = nullptr) : m_length(0), ptr(nullptr)
    {
        if (parm)
        {
            m_length = strlen(parm) + 1;
            ptr = new char[m_length];
            memcpy(ptr, parm, m_length);
        }
    }
    MyString(const MyString &parm) : MyString(parm.ptr)
    {

    }
};

Is there any ill effect to this approach? Is there any advantage of writing traditional copy constructor?

Compiling Protocol Buffers with C++11?

I am used to building protocol buffers with python and Tensorflow, but was hoping to give it a shot with C++. I was wondering if Google Protocol Buffers will work when compiled with C++11. In particular I use Clang++-7.

I looked at the documentation but did not see any mention of c++11, however there are some issues listed on github that indicate they only work with C++11. I included one such link above. Does anyone know if protocol buffers are compatible with C++11, or if there are any limitations?

Verify at compile time that objects are created as shared_ptr

There are classes that I write (often as part of boost::asio) whose objects depend on being wrapped in a shared_ptr because they use shared_from_this(). Is there a way to prevent an object from being compiled if it's not instantiated in a shared_ptr?

So, what I'm looking for:

std::shared_ptr<MyClass> a = std::make_shared<MyClass>(); // should compile fine
std::unique_ptr<MyClass> a = std::make_unique<MyClass>(); // compile error
MyClass a; // compile error

How do I create a 2D vector of struct in C++?

My structure is :

struct M {
  int T;
  int D;
  int F;
  int L;
};

So how I create the 2D vector of M ?

confusion in direct initialization vs copy initialization in C++

I have this code snippet:

class Fraction
{
private:
    int m_numerator;
    int m_denominator;

public:

    // Default constructor
    Fraction(int numerator = 0, int denominator = 1) :
    m_numerator(numerator), m_denominator(denominator)
    {
        std::cout << "Default constructor called!\n";
        assert(denominator != 0);
    }

    // Copy constructor
    Fraction(const Fraction &frac) :
    m_numerator(frac.m_numerator), m_denominator(frac.m_denominator)
    {
        std::cout << "Copy constructor called!\n";
    }

    friend std::ostream& operator<<(std::ostream& out, const Fraction &f1);
};

std::ostream& operator<<(std::ostream& out, const Fraction &f1)
{
    out << f1.m_numerator << "/" << f1.m_denominator;
    return out;
}

int main(int argc, const char * argv[]) {
    Fraction one(Fraction(6,3));//direct initialization??, with default constructor
    Fraction second = one;//copy initialization with copy constructor
    Fraction third(one);////direct initialization, but with copy constructor???
    return 0;
}

when I run this program ,I get the following result in the console:

Default constructor called!
Copy constructor called!
Copy constructor called!

My first question is, in this line:

Fraction one(Fraction(6,3));//direct initialization??, with default constructor

why is this not a copy initialization with the copy constructor? My understanding is that a Fraction object is initialized first and then it is copied into another Fraction object called "one"

and second question is,

Fraction third(one);////direct initialization, but with copy constructor???

It seems like you can mix a direct initialization with using a copy constructor, so this is possible?

and third question is, Can I assume that direct initialization will always use a pair of () while copy initialization will always use the equal sign?

Thanks very much!

How to let my compiler more stupid (wrong index)?

I have encounter a horrible situation. I usually use visual code to edit my code, also compile and execute in it(F5). But I found vscode is too smart or ignore some warning message for me. And output the right answer, which also work fine in Ideone. But in window cmd or dev C++ my code can't output anything, just return a big number.

And I find some situation will occur the thing I mention above.

The code like this

for (i = 0; i < g.size(); i++)
{
    int source;
    int dest;
    int minWeight = 999;

    for (j = 0; i < g[j].size(); j++)
    {
        // no edge, come to next condition
        if (!g[i][j])
            continue;
        if (g[i][j] < minWeight)
        {
            source = i;
            dest = j;
            minWeight = g[i][j];
        }
    }
    if
        updateGroup(index, index[source], index[dest]);
    else
        updateGroup(index, index[source], index[dest]);
}

You may found that the second for loops have wrong condition statement, it should change j = 0; i < g[j].size(); j++ to j = 0; j < g[i].size(); j++

So I wonder to know

  1. Are there any way let my vscode more strict?

  2. Why it still can output right answer in vscode and ideone?

  3. How to avoid or be easier to found where my code wrong when this kind of no message error?

Really hope someone can help me, and appreciate all of your suggestion!!

can anyone help me to add events within a calendar? it's my 1st semester project

enter image description here

I made calendar that displays all day of moth of a year input by the user.now i didn't get the idea to add and create events according to user.also it displays the date of event in console

application crashes when adding c++11 flag to cmake

In Linux (Ubuntu 14.04) application crashes when adding c++11 flag to cmake (c++11 is needed for functions such as to_string). The G++ version is 4.8.5.

boost allocator fails to compile in recursive context

I have a full sample of what I want to accomplish below. Essentially I wanted my tree structure held in a memory map. The code below doesn't compile. I don't understand the (expansive) error; it's some kind of failed type conversion. How do I adjust this code to make it work?

#include "boost/interprocess/allocators/allocator.hpp"
#include "boost/interprocess/managed_mapped_file.hpp"

#include <map>
#include <memory>

template <typename TKey, typename TData, template<class> class TAllocator = std::allocator>
class Node : std::enable_shared_from_this<Node<TKey, TData, TAllocator>> {
    using TNode = Node<TKey, TData, TAllocator>;
    std::map<TKey, TNode, std::less<TKey>, TAllocator<std::pair<const TKey, TData>>> _children;
    TData _data;
public:
    Node() = default;
    explicit Node(const TAllocator<std::pair<const TKey, TData>>& allocator, const TData& data) : _children(allocator), _data(data) {}

    TData& at() { return _data; }
    const std::map<TKey, std::shared_ptr<TNode>>& children() { return _children; };

    void add(const TKey& key, const TData& data) {
        _children.emplace(key, TNode(_children.get_allocator(), data));
    }
};

template <typename T>
using TAlloc = boost::interprocess::allocator<T, boost::interprocess::managed_mapped_file::segment_manager>;
using TMapTrie = Node<std::string, std::shared_ptr<std::size_t>, TAlloc>;

int main() {
    boost::interprocess::managed_mapped_file file_vec(boost::interprocess::open_or_create, "/tmp/pfx_mmap.dat", 1 << 20);
    TAlloc<std::pair<const std::string, std::shared_ptr<std::size_t>>> allocator(file_vec.get_segment_manager());

    TMapTrie root(allocator, nullptr);
    root.add("abc", std::make_shared<std::size_t>(42));
    return 0;
}

You can compile it like this: gcc demo.cpp -lboost_system -std=c++11 -lstdc++. The compilation error:

cannot convert ‘std::allocator_traits<boost::interprocess::allocator<std::_Rb_tree_node<std::pair<const std::__cxx11::basic_string<char>, Node<std::__cxx11::basic_string<char>, std::shared_ptr<long unsigned int>, TAlloc> > >, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > >::pointer {aka boost::interprocess::offset_ptr<std::_Rb_tree_node<std::pair<const std::__cxx11::basic_string<char>, Node<std::__cxx11::basic_string<char>, std::shared_ptr<long unsigned int>, TAlloc> > >, long int, long unsigned int, 0>}’ to ‘std::_Rb_tree<std::__cxx11::basic_string<char>, std::pair<const std::__cxx11::basic_string<char>, Node<std::__cxx11::basic_string<char>, std::shared_ptr<long unsigned int>, TAlloc> >, std::_Select1st<std::pair<const std::__cxx11::basic_string<char>, Node<std::__cxx11::basic_string<char>, std::shared_ptr<long unsigned int>, TAlloc> > >, std::less<std::__cxx11::basic_string<char> >, boost::interprocess::allocator<std::pair<const std::__cxx11::basic_string<char>, Node<std::__cxx11::basic_string<char>, std::shared_ptr<long unsigned int>, TAlloc> >, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> > >::_Link_type {aka std::_Rb_tree_node<std::pair<const std::__cxx11::basic_string<char>, Node<std::__cxx11::basic_string<char>, std::shared_ptr<long unsigned int>, TAlloc> > >*}’ in return
       { return _Alloc_traits::allocate(_M_get_Node_allocator(), 1); }

Easy way to run non const methods on nested objects in Composition /Aggregation pattern in C++

I came to from the C# world and, thanks to the "Properties", I can run a setter method on a nested object without leaking any internals like this:

objectA.objectB.objectC.SetSomething();

So far, I found that the best analog in C++ is to use getters and get nested object by const reference than use setters to set them by value. But this would result in the following code:

auto b = objectA().getObjectB();
auto c = b.getObjectC();
c.SetSomething();
b.setObjectC(c);
objectA.setObjectB(b);

Not only this is 5 lines instead of one, but it involves 2 copies of the nested objects in b.setObjectC(c); and objectA.setObjectB(b);

I can let the getters to return non const reference of nested object (or use public variables) and will be able to write in C++:

objectA.objectB.objectC.SetSomething();

But, instantly I get the ability to set objectB without objectA knowledge like this:

objectA.objectB = new b {};

And this is unacceptable in aggregation pattern where parent object initializes nested object.

Other two approaches I read about:
1. Instead of aggregation use multiple protected inheritance and translate needed methods with "using". However, I also read in "Google C++ Style Guide" to never use protected inheritance..
2. Rewrite all required methods in the parent class manually. But this would require for me to write SetSomething() method in both ObjectB an objectA which, in my opinion, violates "Don't repeat yourself".

What am I missing? How can this be done?

How do i call rest api from CPP [on hold]

I'm trying to call the rest GET API.and to read JSON data.

Is there any library or plugin to make an HTTP request from c++ code?

Lvalue no matching (&&) without template, but matching (T &&) with template?

#include <bits/stdc++.h>
using namespace std;

template<class T = string>
void f(T &&s) {
    cout << s << endl;
}

int main() {
    string s("1234");
    f(s);
    f("1234");

    return 0;
}

Can be compiled.

#include <bits/stdc++.h>
using namespace std;

void f(string &&s) {
    cout << s << endl;
}

int main() {
    string s("1234");
    f(s);
    f("1234");

    return 0;
}

I replace T to string, the code can not be compiled.

error:

❯ g++-8 -std=c++11 a.cpp && ./a.out
a.cpp: In function 'int main()':
a.cpp:10:11: error: cannot bind rvalue reference of type 'std::__cxx11::string&&' {aka 'std::__cxx11::basic_string<char>&&'} to lvalue of type 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'}
         f(s);
           ^
a.cpp:4:10: note:   initializing argument 1 of 'void f(std::__cxx11::string&&)'
     void f(string &&s) {
          ^

I'm so confused.

mercredi 26 décembre 2018

OpenCL load program from binary

I have the following very simple kernel in OpenCL

void kernel simple_add(global const int* A, global const int* B, global int* C){
    C[get_global_id(0)]=A[get_global_id(0)]+B[get_global_id(0)];
};

I created a C++ program to load the kernel from a binary created from its source. The binary loads correctly (CL_SUCCESS), but does not display the correct result for the input. It displays changing garbage values like so

result: 538976310 538976288 538976288 538976288 538976288 790634528 796160111 1702129257 1886334828 1818455653

inline cl::Program CreateProgramFromBinary(cl::Context context,const std::vector<cl::Device> devices, const char* fileName)
{
    std::ifstream file(fileName,  std::ios::binary | std::ios::in | std::ios::ate);

    uint32_t size = file.tellg();
    file.seekg(0, std::ios::beg);
    char* buffer = new char[size];
    file.read(buffer, size);
    file.close();
    cl::Program::Binaries bin;

    std::vector<cl_int> binaryStatus;
    cl_int err = 0;
    cl::Program program = cl::Program{context, devices, bin, &binaryStatus, &err};

    if(err != CL_SUCCESS) {
       std::cout<<" Error loading"<< err<<  "\n";
        exit(1);
    }
    for (std::vector<cl_int>::const_iterator bE = binaryStatus.begin(); bE != binaryStatus.end(); bE++) {
        std::cout<< *bE <<std::endl;
    }
    std::cout<<"No Error loading"<< err<<  "\n";
    delete[] buffer;
    return program;
}

int main(int argc, char** argv)
{
    std::vector<cl::Device> devices= loadDevices();
    cl::Context context{devices};

    std::cout << "Save program binary for future run..." << std::endl;
    //cl::Program program = CreateBinaryFromProgram(context, devices, "HelloWorld.cl", "HelloWorld.cl.bin");
    //CreateBinaryFromProgram(context, devices, "HelloWorld.cl", "HelloWorld.cl.bin");


    std::cout << "Reading from binary..." << std::endl;
    cl::Program program = CreateProgramFromBinary(context, devices, "HelloWorld.cl.bin");

    std::cout << "Running Program..." << std::endl;
    cl::Buffer buffer_A(context,CL_MEM_READ_WRITE,sizeof(int)*10);
    cl::Buffer buffer_B(context,CL_MEM_READ_WRITE,sizeof(int)*10);
    cl::Buffer buffer_C(context,CL_MEM_READ_WRITE,sizeof(int)*10);

    int A[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    int B[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

    //create queue to which we will push commands for the device.
    cl::CommandQueue queue(context,devices[0]);

    //write arrays A and B to the device
    queue.enqueueWriteBuffer(buffer_A,CL_TRUE,0,sizeof(int)*10,A);
    queue.enqueueWriteBuffer(buffer_B,CL_TRUE,0,sizeof(int)*10,B);


    //run the kernel
    cl::Kernel kernel_add=cl::Kernel(program,"simple_add");
    kernel_add.setArg(0,buffer_A);
    kernel_add.setArg(1,buffer_B);
    kernel_add.setArg(2,buffer_C);
    queue.enqueueNDRangeKernel(kernel_add,cl::NullRange,cl::NDRange(10),cl::NullRange);
    queue.finish();

    int C[10];
    //read result C from the device to array C
    queue.enqueueReadBuffer(buffer_C,CL_TRUE,0,sizeof(int)*10,C);

    std::cout<<" result: \n";
    for(int i=0;i<10;i++)
        std::cout<<C[i]<<" ";
    std::cout << "\n";
    return 0;
}

Loading this program directly from the CL file however, results in the correct output of the program. Is the binary I've loaded somehow different from the CL file?

c++ dynamic return type for function

I am trying to have a generic class which could return the object of the other class depending on the input to generic class.

From the main function, if I pass in '1' as an argument to the constructor of generic class, i want to be able to get object of child1 class using getType(). My question is: is there a way to change the return type of getType() dynamically or any other way to accomplish this behavior?

My current implementation calls the print() method of base class, even though I create an object of child classes in generic constructor as m_type is a base type.

class base {

    public:
        void print(){
            cout << "base\n";
        }
        virtual ~base() {}
};

class child1 : public base {
    public:
        void print(){
            cout << "child1\n";
        }
};

class child2 : public base {
    public:
        void print(){
            cout << "child2\n";
        }
        void hello(){
            cout << "hello from child 2\n";
        }
};

class generic{

    public:
        generic(int b){
            if(b==1) {
                m_type = new child1();
            }
            else if(b==2) 
                m_type = new child2();
        }

    // Somehow return the object of one of the child class based on input 
    // to constructor.
    base *getType(){
        return m_type;
    }

    base *m_type;
};

int main()
{
    generic *g1 = new generic(1);
    // call the method from child1 class instead of base class.
    g1->getType()->print();
    return 0;
}

Expression does not evaluate to a constant

I am trying to write a multi-threaded program to run the sieve to Eratosthenes algorithm for a given set of numbers, with options to print the primes found, and to compare the execution time from different threads used. This is part of a university course. I am using C++11 threads with the default visual studio compiler. At present, I am having problems getting a build, I suspect due to the way I am trying to handle the threads. Here is what I have so far in the Eratosthenes function:

int Eratosthenes(int input)
{
    bool pFlag[input + 1];
    memset(pFlag, true, sizeof(pFlag));

    for (int pTest = 2; pTest*pTest <= input; pTest++)
    {
        if (pFlag[pTest] == false)                              // If prime[p] is not changed, then it is a prime
        {
            for (int i = pTest * 2; i <= input; i += pTest)     // Update all multiples of p
                pFlag[i] = false;
        }
    }

    for (int i = 2; i <= i; i++)                            //print all primes
    {
        if (pFlag[i] == true)
            cout << i << " ";
    }

}

And in the main I am calling some helper functions which get user input on the number of threads, and the maximum number to search for primes.

int main()
{
    int MaxT = getThreads();
    int maxN = getMaxN();
    Counter counter;
    vector<thread> threads;

    for (int i = 0; i < MaxT; i++)
    {
        threads.push_back(thread(Eratosthenes(counter.Value)));
        counter.increment();
    }
    for (auto& thread : threads)
    {
        thread.join();
    }
    counter.Value = 0;
    system("pause");
}

I have also created a structure to handle the incrementing and mutex list.

struct Counter
{
    int Value=0;
    mutex mtx;
    void increment()
    {
        mtx.lock();
        ++Value;
        mtx.unlock();
    }
};

So far, all errors appear related to the use of input in the Eratosthenes function, with the first being that it does not evaluate to constant, with a note afterwards saying that this was caused by a read of a variable outside of its lifetime. A second possibly related error in the same section states that with relation to the line pFlag[i] = false; the array type 'bool[input+]' is not assignable.

Thanks for your assistance :)

error in compilation; recursion in function;

This code I wrote is supposed to find probability. However I keep getting compilation error that I am unable to understand and recognize. Help would be very much appreciated.

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

using namespace std;
float probability (float w,float b)
{
    float p;
    if(w+b > 1)
    p = ((w*b*2)/(w+b+1)(w+b))*probability(w-1, b) + (2*b*(b-1)/(w+b+1)(w+b))*probability(w, b-2) + (2*w*(w-1)/(w+b+1)(w+b))*probability(w-1, b);
    else if (w == 1 && b == 0)
    p = 0;
    else
    p = 1;
    return p;
}


int main()
{
    float white, black;

    cin>>white>>black;
    float P = probability(white, black);
    cout<<"The probability that Nishant wins is: "<<P<<endl;
    return 0;


}

Segmentation Fault for Merge function of Merge Sort

My task is to implement just the merge function of merge sort algorithm.My idea is to create an auxilliary array to store the sorted values.I have mainted 2 pointers,one for left sorted array and other for right sorted array.

I am having difficulty in figuring out why am I getting segmentation fault?

void merge(int arr[], int l, int m, int r)
{

 int temp[r-l+1];int count=0;
 int *ptr1=(int*) malloc(sizeof(int));
 int * ptr2=(int*) malloc(sizeof(int));
 ptr1=&arr[l];
 ptr2=&arr[m+1];
 while(ptr1!=(&arr[m+1]) && ptr2!=NULL)
 {
     if(*ptr1>=*ptr2)
     {
      temp[++count]=*ptr2;
      ptr2++;
     }
     else 
     {
         temp[++count]=*ptr1;
         ptr1++;
     }
 }
 if(ptr1==&arr[m+1])
 {
     while(ptr2)
     {
        temp[++count]=*ptr2;
        ptr2++;
     }
 }
 if(ptr2==NULL)
 {
  while(ptr1!=&arr[m+1])
     {
        temp[++count]=*ptr1;
        ptr1++;
     }   
 }
 for(int i=0;i<r-l+1;i++)
 {
     arr[i]=temp[i];
 }
}

Input: 2

5

4 1 3 9 7

10

10 9 8 7 6 5 4 3 2 1

Expected Output:

1 3 4 7 9

1 2 3 4 5 6 7 8 9 10

My Output:Segmentation fault

Template container class that uses STL container. How should implement iterator?

I want to write a hierarchy in c++ like in java collections. I have abstract base class so and it's template takes argument an primitve data type and a container type(like vector, list or set). In my base class i have an function that name Iterator() and also i have to write a helper iterator class. How can i implement this helper class? As a inner class or as a seperate class? Can i use template parameter container's iterator in iterator inner class?

This my container base class with full pure function

#ifndef CONTAINER_H
#define CONTAINER_H
#include <iostream>
#include <vector>
#include <iterator>

using namespace std;

namespace GeneralContainer{
template <class E, class Alloc = std::vector<E> >
class Collection{
public:
  virtual Alloc::iterator iterator() = 0;//What should i do in here? How can i implement helper iterator class
  virtual bool add(E e) = 0;
  virtual bool addAll(Collection& c) = 0;
  virtual void clear() = 0;
  virtual bool contains(E e) = 0;
  virtual bool containsAll(Collection* c) = 0;
  virtual bool isEmpty() = 0;
  virtual bool remove(E e) = 0;
  virtual bool removeAll(Collection* c) = 0;
  virtual bool retainAll(Collection* c) = 0;
  virtual int size() = 0;
};
}


#endif

This is my iterator implementation.

#ifndef ITER_H
#define ITER_H
#include <iterator>

class MyIterator : public std::iterator<std::input_iterator_tag, class T>
{
  T* p;
public:
  MyIterator(T* x) :p(x) {}
  MyIterator(const MyIterator& mit) : p(mit.p) {}
  MyIterator& operator++() {++p;return *this;}
  MyIterator operator++(int) {MyIterator tmp(*this); operator++(); return tmp;}
  bool operator==(const MyIterator& rhs) const {return p==rhs.p;}
  bool operator!=(const MyIterator& rhs) const {return p!=rhs.p;}
  T& operator*() {return *p;}
};

#endif

Class with separated header: can see only initialization value of member variable

I have a Test class defined in its own header, test.h, that is included on main.cpp file. Basically this is the situation:

test.h

class Test
{
    ...
    ...
    ...

public:
    long foo;
};

test.cpp

// Constructor
Test::Test()
{
    foo = 0
}

void Test::someMethod()
{
    // Here foo variable is changed
}

main.cpp

#include "test.h"

using namespace std;

int main()
{
    Test testObject;
    ...
    // Do something with testObject
    ...

    return 0;
}

During debug on Visual Studio 2017 if I stop the execution inside main's code I can't see tha actual value of foo, I see its initialization value:

testObject.foo --> 0

Why this happens? If I stop the execution inside class I see its actual value. This is not happen if I don't separate class implementation on .h and .cpp

Add vector to vector with maximum performance [duplicate]

This question already has an answer here:

I am creating a vector in different thread. After that I want to pass it to the method Data::insert() that saves this vector in another vector. What is the optimal way to do that?

template<typename DATA_TYPE>
class Data
{
public:
    Data();

    void insert(vector<DATA_TYPE>& d)
    {
        if (d.empty())
            throw range_error("Data::insert(): Vector is empty!");

        lock_guard<mutex> l(data_mutex_);
        // Add d to the vector data_
    }
private:
    vector<vector<DATA_TYPE>> data_;

    mutex data_mutex_;
};

mardi 25 décembre 2018

C++11 enum class namespace block

I have an enum class in C++11:

enum class eDays{ Sunday, Monday, .. , COUNT };

The enum class sets the namespace for the values so it has to be used like:

eDays::Sunday

I want to set an namespace block so I won't need to specify the namespace each time something like:

namespace eDays {
    vector<eDays> vec = { MONDAY, SUNDAY, ..  };
}

Instead of:

vector<eDays> vec = { eDays::MONDAY, eDays::SUNDAY, ..  };

What am I missing?

segmentation fault in cin proccess

void Room::join(){
 try{
    check_input_arguments();
    bool enter_not_pressed = true;
    string name;
    char c;
    int counter = 0 ;
    while(enter_not_pressed){
        cin >> name ;
        counter ++ ;
        name_of_players.push_back(name);
        cin.get(c);
        enter_not_pressed = (c!='\n');
        cout << counter;
       }
    if(name_of_players.size() > get_num_of_roles()){
        for(int i=0 ; i < counter ; i++)
            name_of_players.pop_back();
        throw too_many_users();
       }
    if(name_of_players.size() == get_num_of_roles()){
        give_random_roles();
       }
    }
   catch(few_arguments ex){
        cerr << "You didn't enter enough arguments!" << endl;
    }
   catch(too_many_users ex){
    cerr << "many users" << endl;
    }
}

I write this method for Room class , when i want to receive number of strings equivalent to get_num_of_roles() i encounter with segmentation fault error, but this code is working for number of strings more than get_num_of_roles(printing "too many" users) and less than get_num_of_roles(do nothing). Help me please , Thank you guys!

“Downcasting” unique_ptr to unique_ptr

“Downcasting” unique_ptr< Base > to unique_ptr< Derived > offer an elegent solution to downcasting unique_ptr. It works in most of time. But when the Derived contains unique_ptr, something go wrong:

template<typename Derived, typename Base, typename Del>
std::unique_ptr<Derived, Del> 
static_unique_ptr_cast( std::unique_ptr<Base, Del>&& p )
{
    auto d = static_cast<Derived *>(p.release());
    return std::unique_ptr<Derived, Del>(d, std::move(p.get_deleter()));
} 

struct Data
{
   int data;
};

struct Base
{
};

struct Derived : public Base
{
    Derived() 
        : data(std::make_unique<Data>())

    std::unique_ptr<Data> data;
}

int main()
{
    std::unique_ptr<Base> base = std::make_unique<Derived>();

    auto derived = static_unique_ptr_case<Derived>(std::move(base))->data; // compile error

    return 0;
}

Is there a better way to fix the problem?

Why does C++17 never move construct with prvalues?

The cppreference says that

When the initializer is a prvalue, the move constructor call is often optimized out (until C++17) / never made (since C++17).

I have two questions:

1) Does this mean that construction with literals (e.g. integer 10) will never move construct?

2) What's the reasoning for this rule?

What is the recommended way to simulate concepts and constraints?

Before the introduction of concepts and constraints, there are several ways to simulate this compile-time check. Take a "order()" function for example: (how to implement LessThanComparable without concepts or constraints is another story)

  • Use static_assert

    template <typename T, typename U>
    void order(T& a, U& b)
    {
        static_assert(LessThanComparable<U,T>, "oh this is not epic");
        if (b < a)
        {
            using std::swap;
            swap(a, b);
        }
    }
    
    

    This approach won't work for function overloading.

  • Use typename = enable_if

    template <typename T, typename U,
        typename = std::enable_if_t<LessThanComparable<U,T>>>>
    void order(T& a, U& b)
    {
        if (b < a)
        {
            using std::swap;
            swap(a, b);
        }
    }
    
    

    What if an over-"intelligent" guy specifies a third parameter by hand?

  • Use enable_if in the function prototype:

    template <typename T, typename U>
    std::enable_if_t<LessThanComparable<U,T>>, void> order(T& a, U& b)
    {
        if (b < a)
        {
            using std::swap;
            swap(a, b);
        }
    }
    
    

    Sometimes also doesn't work in function overloading.

  • Use enable_if as the type of a dummy non-type template parameter

    template <typename T, typename U,
        std::enable_if_t<LessThanComparable<U,T>>, void*> = nullptr> // or int = 0
    void order(T& a, U& b)
    {
        if (b < a)
        {
            using std::swap;
            swap(a, b);
        }
    }
    
    

    I saw this before, and I can't think of any drawbacks.

  • And many other variants.

Which ones are preferable or recommended? What is the benefits and drawbacks? Any help is appreciated.

How to set value for the specific range of a C array using std:fill

How can i set the value only for specific range of some array and not starting from zero. the following code invokes compile error:

#include <algorithm>;

bool SomeBoolArray[100];
std::fill(SomeBoolArray[50], SomeBoolArray[50] + 10, true);

following form invokes compiler error too.

std::fill(SomeBoolArray[50], SomeBoolArray[60], true);

How to count the total number of elements in a vector in c++? Why is it showing multiple repeating numbers?

#include <vector>
#include <iostream>

void countnumbers (std::vector<int> arr1)
{
    for (int j = 0; j < arr1.size(); j++)
    {

        if (arr1[j] > 0)
        {
           std::cout<<arr1.size();
        }
    }
}

int main()
{
    countnumbers({1,2,3});
}

Hello. I'm not really good at vectors so please help me. I want to count the total number of elements in a vector. Why is the output 333, instead of 3?

How do I move a unique pointer from one vector to another vector of unique pointers?

How do I move a unique_prt from one vector to another vector of unique_ptrs in C++11?

How to convert IP rule like 192.168.*.* into c++ regex

I want to check rules in my file which looks like 192.168.*.* * mean any number. All IPs tested are legal. That's no need to concern special case like 456.123.abc.333.

Now, I want to do this with c++11 regex. But I don't know how to convert match . into regex correctly. I will read rules into string, and try to convert it to regex style by function I defined.
In regex, the match for . is \..

But when I try to do this conversion by my function replace with arguments old_val:. & new_val\\.(for escaping \, I use \\), the rule 192.168.*.* will become 192\\.168\\.*\\.*.

What part of my code need to fix to do this correctly?
Or is there another easier way to do this?

bool check_rule(string CD, string IP){

    fstream firewall;
    firewall.open("./socks.conf");
    string rule;

    while(getline(firewall, rule)){
        stringstream ss(rule);
        string judge, mode, regular;
        ss >> judge >> mode >> regular;

        //check if mode is correct
        if(mode == CD){
        replace(regular, ".", "\\.");
        replace(regular, "*", "\\d");
        cout << "regex :" << regular << endl;
        regex regu_expr(regular);
        smatch m;
        if(regex_match(IP, m, regu_expr)){
            return true;   
        }
        }
    }
    return false;

    firewall.close();
}

void replace(string &str, string target, string substi){
    size_t pos = 0;
    while((pos = str.find(target, pos)) != string::npos){
        str.replace(pos, target.size(), substi);
        pos += substi.size();
    }
}

for rule 192.168.*.* the check_ruel should return true if ip like 192.168.231.67 and return false for IPs like 192.111.22.33

Getting an error while deriving class from std::exception

I am deriving a class from std::exception but i got an error Here is my code

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

using namespace std;

class exp1 : public std::exception {
public:
    exp1() noexcept = default;
    ~exp1() = default;
    virtual const char* what() const noexcept
    {
        return "This is an exception";
    }
};


int main()
{
    try{
        int i; 
        cin >> i;
        if(i == 0)throw exp1() ;
        else {cout << i << endl;}
       }
    catch(exp1 & ex){
        cout << ex.what() << endl; 
       }
return 0;
}

My code is working fine but when i include noexcept to the constructor

exp1() noexcept = default;

then i get the errors

'exp1::exp1(void) noexcept': attempting to reference a deleted function 

and

the declared exception specification is incompatible with the generated one 

lundi 24 décembre 2018

function containing some if statements are not expanded inline

Error occured...I was trying to learn the stack in data structure the program is running but a warning is displaying. (click in question for error code's image.)

My code : (click here for full coding .)

enter image description here

What is the role of greater

While declaring a set, set <int, greater <int> > gquiz1; why do we use greater <int> . I'm quite new to set and I referred other articles but they were not quite convincing.

Error: two or more data types in declaration of 'x'

I'm compiling a C++ program which and I get the error "two or more data types in declaration" at the line below. Here is the code:

#include <iostream>
#include <string>
#include <sstream>
#include <stdlib.h>
List SplitInflix(const string infix)
{
List tokenlist;
string word= "";
char x;
for (char x : infix)
    {
    switch (x)
    {
    case '(':
        if (word != "")
        {
            Token* token = new Token(word);
            tokenlist.append(token);
            word = "";
            Token * token1 = new Token(LEFT);
            tokenlist.append(token1);
        }
        else
        {
            Token * token = new Token(LEFT);
            tokenlist.append(token);
        }
        break;
    ...
}
return tokenlist;
}

I get the error:

error: two or more data types in declaration of 'x'

There's more coding but it's too long and I think it's not related to the error.

How do I fix it. Thanks!

Does vector

I used a reference_wrapper recently like so:

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

struct A {
};

struct B {
    B() {};
    B(A& aA) {};
    B(const B&) = default;
};

int main () {
    A a;
    B b;

    std::vector<std::reference_wrapper<B>> rvector;
    rvector.push_back(std::reference_wrapper<B>(b)); // (1)
    rvector.push_back(b); // (2)

1 and 2, are both compiling and working just fine and I wonder which is the right one! So I thought that the following could work too:

    std::vector<B> bvector;
    bvector.push_back(a); // (3)
    bvector.push_back(b); // (4)
    std::cout << bvector.size() << "\n";

yeap, it works! So I came to the conclusion that push_back just calls the type's T constructor with the given parameter. Documentation though mentions that the parameter is of type T and eventually the copy/move ctor since the parameter is of type T.

When I tried 1 and 2 with shared_ptr though:

    std::vector<std::shared_ptr<B>> pvector;
    pvector.push_back(std::shared_ptr<B>(new B())); // (5)
    pvector.push_back(new B()); // (6)

I get

no matching function for call to 'std::vector<std::shared_ptr<B> >::push_back(B*)'

  • Why 2 and even 3 work but 6 doesn't?
  • There should be a shared_ptr<B>constructor that takes B* as parameter, isn't there? So, why 6 does not compile (since 3 does)?
  • Since 3 compiles and works just fine, would it be ok to use and count on it (if it wasn't a bad approach since there is the emplace_back)?

overloading typecast operator

Overloaded typecast operator int, but after compiling and running the code I get segmentation fault.

I debugged my program and saw that line of code where typecast is used repeats without ending, every time calling typecast function itself. So, can anyone explain what's going on around there ?

/* IN HEADER */
class ComplexNumber
{
private:
    double m_real, m_imaginary;

public:
    ComplexNumber(double real = 0.0, double imaginary = 0.0);
    ComplexNumber(const ComplexNumber &obj);

    ComplexNumber& operator= (const ComplexNumber &obj);

    operator int();

};

ComplexNumber::ComplexNumber(double real, double imaginary): 
    m_real(real), m_imaginary(imaginary)
{

}

ComplexNumber::ComplexNumber(const ComplexNumber &obj): 
m_real(obj.m_real), m_imaginary(obj.m_imaginary)
{

}

ComplexNumber& ComplexNumber::operator= (const ComplexNumber &obj)
{
    m_real = obj.m_real;
    m_imaginary = obj.m_imaginary;

    return *this;
}

ComplexNumber::operator int()
{
    m_real = static_cast<int>(m_real);
    m_imaginary = static_cast<int>(m_imaginary);

    return *this;
}

/* IN MAIN */
ComplexNumber obj(3.4, 5.6);

obj = static_cast<int>(obj);
//here it gives seg fault

C++ How to declare a namespace in a class using an alias?

Using g++ 7.3.0.

I have a global data structure (spaceA::bars) that is used throughout my program. I am trying to pass SharedBarMap into class Foo which will operate on the data in bars.

The problem is, the namespace doesn't appear to be seen within class Foo.

error: 'spaceA' has not been declared
spaceA::SharedBarMap sbm;
~~~~~~

globals.h

namespace spaceA
{
    using MapGroup = std::vector<std::shared_ptr<Bars>>;
    using BarMap = std::map<int, MapGroup>;
    using SharedBarMap = std::shared_ptr<BarMap>;

    extern SharedBarMap bars;
}

globals.cpp

namespace spaceA
{
    SharedBarMap bars;
}

foo.h

#include "globals.h"

class Foo
{
    private:
        spaceA::SharedBarMap sbm; // <--- error here

    public:
        Foo(spaceA::SharedBarMap bars) : sbm(bars) { }
};

versions of visual studio to run c++

I have a simple but important question. I have a c++ code on visual studio (.sln file). I just want to know on what versions of visual studio can I need to run this c++ code? For example, can I run it on visual studio 2008? I have vector or array.

Type deduction for rvalues in templates

Requesting some help to understand the type deduction of rvalue reference. The non-templated version fails with the following error and I understand the reason.

error: cannot bind non-const lvalue reference of type 'const char*&' to an rvalue of type 'const char*'

With C++11, if I change the function void Firstfun(const Key& key) to void Firstfun(const Key&& key) then it compiles however the templated version works fine with lvalue reference parameter.

As for the templalted version, I thought compiler must have generated function with rvalue reference so checked it with __PRETTY_FUNCTION__ but didn't see it in the output of PRETTY_FUNCTION.

I did come across this discussion where @Anirban mentioned something on these lines.

For wrapper(A());, the type parameter T would still be deduced as A, and the parameter u would be of type A&&, called an rvalue reference to A.

So here are my questions:

  1. What is compiler doing with templated version to make it accept rvalue?
  2. The fix void Firstfun(const Key&& key) for non-templated version, is it valid and acceptable?

Non-templated version

#include <iostream>

namespace somens {

class Firstclass {
public:

    void Firstfun(const char*& key) {
        std::cout << __PRETTY_FUNCTION__ << '\n';
    }
};

class Secondclass {
    Firstclass f_class;

    char* create_buf(){
        char * buf = new char[10]; //buf will be freed elsewhere.
        return buf;
    }

public:
    void Secondfun (){
        f_class.Firstfun(create_buf());
    }

};
}

int main () {
  somens::Secondclass s_class;
  s_class.Secondfun();

}

Output from non-templated version

error: cannot bind non-const lvalue reference of type 'const char*&' to an rvalue of type 'const char*'

Templated version

#include <iostream>

namespace somens {
template<typename Key>
class Firstclass {
public:

    void Firstfun(const Key&  key) {
        std::cout << __PRETTY_FUNCTION__ << '\n';
    }
};

class Secondclass {
    Firstclass<const char*> f_class;

    char* create_buf(){
        char * buf = new char[10]; //buf will be freed elsewhere.
        return buf;
    }

public:
    void Secondfun (){
        f_class.Firstfun(create_buf());
    }

};
}

int main () {
  somens::Secondclass s_class;
  s_class.Secondfun();

}

Output from templated version

void somens::Firstclass::Firstfun(const Key&) [with Key = const char*]

C++/Thrift: Is TThreadedServer::stop() thread-safe?

I'd like to use the TTheadedServer in a separate thread to have control on when to stop/start it. My application needs only 1 controlling thread and one processing thread. I don't expect to have more than one client as I'm using thrift as a relay. TSimpleServer is not thread-safe, so I dropped that option.

I made a little minimal example to check whether it's thread-safe, and used clang's thread-sanitizer to make sure it's thread-safe. Here's the example

std::shared_ptr<MyHandler> handler = std::make_shared<MyHandler>();

int port = 9090;

th::stdcxx::shared_ptr<th::TProcessor>         processor(new HandlerProcessor(handler));
th::stdcxx::shared_ptr<tht::TServerTransport>  serverTransport(new tht::TServerSocket(port));
th::stdcxx::shared_ptr<tht::TTransportFactory> transportFactory(
    new tht::TBufferedTransportFactory());
th::stdcxx::shared_ptr<thp::TProtocolFactory> protocolFactory(new thp::TBinaryProtocolFactory());

ths::TThreadedServer server(processor, serverTransport, transportFactory, protocolFactory);

// start in another thread
std::thread          t(&ths::TThreadedServer::serve, &server);
t.detach();

std::this_thread::sleep_for(std::chrono::seconds(5));

// stop in this thread
server.stop();

std::this_thread::sleep_for(std::chrono::seconds(5));

So what I simply do is start the server with serve() in another thread, then wait for some time, and stop it. I ran this with thread sanitizer, and got a few thread safety warnings. I mention 2 here:

First: thrift/lib/cpp/src/thrift/transport/TServerSocket.cpp:244, at:

interruptableChildren_ = enable;

Second: thrift/lib/cpp/src/thrift/transport/TServerSocket.cpp:654, at:

if (-1 == send(notifySocket, cast_sockopt(&byte), sizeof(int8_t), 0)) {
  GlobalOutput.perror("TServerSocket::notify() send() ", THRIFT_GET_SOCKET_ERROR);
}

So is what I'm doing correct? And is TThreadedServer controller thread-safe? Thread-sanitizer doesn't seem to think so, although the test program works with no problems.

I'm using Thrift 0.12.0.

Is constexpr pointer possible? When should we use it?

I knew that constexpr is used when a variable can be evaluated at compile time.

Now I'm thinking if we could use constexpr on a pointer? For example, constexpr int *p = &i; or int * constexpr j = i;?

dimanche 23 décembre 2018

How to make return type of a function to be same as another function?

there is a question in our study book about object functions. There is a code in c++ and the question wants us to fill the blanks. The code is as below

template <typename Arg, typename Ret> 
class FuncObj {
public:
    typedef Arg argType;
    typedef Ret retType;
    virtual Ret operator()(Arg) = 0;
};

class DivideBy : public FuncObj<int, double> {
protected:
    int divisor;
public:
    DivideBy(int d) {
        this->divisor = d;
    }
    double operator()(int x) {
        return x/((double)divisor);
    }
};

class Truncate : public FuncObj<double, int> {
public:
    int operator()(double x) {
        return (int) x;
    }
};

template < typename Ftype , typename Gtype >
class Compose : public FuncObj <typename Gtype :: argType, typename Ftype :: retType > {
protected:
    Ftype *f; Gtype *g;
public:
    Compose(Ftype f,Gtype g) {
    --------- =f;
    --------- =g; 
    }

    ---------- operator()(____________x) {
        return (_________)((________)(__________)); }
};

The desirable result is

void main() {
    DivideBy *d = new DivideBy(2);
    Truncate *t = new Truncate();
    Compose<DivideBy, Truncate> *c1 = new Compose<DivideBy,Truncate>(d,t);
    Compose<Truncate, DivideBy> *c2 = new Compose<Truncate, DivideBy>(t,d);
    cout << (*c1)(100.7) << endl; // Prints 50.0 
    cout << (*c2)(11) << endl; // Prints 5
}

I really don't know how to complete this code, so what feature or concept of c++ should we use to make this work? If there is a link for further study about this topic please write it down. thanks.