vendredi 31 mai 2019

How to map char values to int using enum

I am trying to map some chars in a string to some integer values using enum. Please tell where am I going wrong?

enum moves{U,R,D,L};
class Solution {
public:
    bool judgeCircle(string moves) {   

// moves is a string having values like ULLDDRR, ULRD, UULLDDRR 
        int X[] = {0,1,0,-1};
        int Y[] = {1,0,-1,0};

// while iterating the string if a get 'U' , I want it to use as an index 
//with  U representing 0th index, R as index=1 and so on.. as in enum

        int x=0 , y=0;
        enum moves ind;
        for( int i = 0 ; i < moves.length() ; i++ ) {
            ind = moves[i];  // but this line here gives error
            x += X[ind];
            y += Y[ind];
        }

        if(!x && !y)
            return true;
        else
            return false;
    }
};

optimize and speed up processing of code to <=1sec (per test case)

any help with optimizing following code to make it run faster.

Tried making function inline, tried cin.TIE(NULL), tried ios_base::sync_with_stdio(false);

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class gfg
{
public:
bool satisfiable(std::vector<int> a, std::vector<int> b) {
  while (!a.empty()) {
    std::sort(b.begin(), b.end(), std::greater<int>());
    int k = a.back();
    a.pop_back();
    if (k > b.size()) return false;
    if (k == 0) continue;
    if (b[k - 1] == 0) return false;
    for (int i = 0; i < k; i++)
      b[i]--;
  }
  for (std::vector<int>::iterator i = b.begin(); i != b.end(); i++)
    if (*i != 0)
      return false;
  return true;
}

};


int main()
{
    gfg g;
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int r,c,n,cnt=0;
    cin >> n;
    while(cnt<n){
        cnt++;
    cin >> r >> c;
    int x;
      vector<int> a;
      vector<int> b;
    for(int i=0;i<r;i++){
            cin >> x;
          a.push_back(x);
    }

    for(int j=0;j<c;j++){
          cin >> x;
          b.push_back(x);
    }



    if(g.satisfiable(a,b)) cout << "YES\n";
    else cout << "NO\n";
    }

    return 0;
}

Expected : Average 1s or less processing time per test case Actual : Average 2s to 2.5s processing time per test case

In a non-const member function, why is point this non-const, while decltype pointer this is const?

I have a heavily templated class from which I want to use a getter. Following a common convention, I've avoided code duplication like so:

template< typename Foo, typename... Bars >
class Templated
{
...

  constexpr const Foo& get() const 
  { 
    return mFoo;
  }

  constexpr Foo& get() 
  { 
    return const_cast<Foo&>(const_cast<const Templated<Foo, Bars...> *>(this)->get());
  }

However it occurred to me that the second definition gets a bit clunky, especially with a class that has many template parameters. Luckily I figured out after a little messing around that I could simplify this for any generic class template to:

constexpr Foo& get()
{
  return const_cast<Foo&>(const_cast<decltype(this)>(this)->get());

This works because, for some reason, decltype(this) resolves to a const pointer to the class object type, whereas just (this) resolves to a non-const pointer to the class object type. Why in the world is this the case?

Custom comparator for set without overloading operator(), std::less, std::greater

I want a custom comparator for following code. However, I cannot overload operator(), std::less, std::greater. I tried to achieve this using lambdas but gcc won't allow me to use auto as non static member. Any other way to make this work?

#include <iostream>
#include <map>
#include <set>

class Test {
  public:

    // bool operator () (const int lhs, const int rhs) {
    //     return lhs > rhs;
    // };


    using list = std::multiset<int  /*, Test*/>;
    std::map<const char*, list> scripts;
};

int main() {
  Test t;

  t.scripts["Linux"].insert(5);
  t.scripts["Linux"].insert(8);
  t.scripts["Linux"].insert(0);

  for(auto a: t.scripts["Linux"]) {
    std::cout << a << std::endl;
  }

    std::cout << "end";
}

Is it safe to initialize a c++11 function-static variable from a linux signal handler?

2 questions (below) about the C++11 static initialization at [1] in this reference code (this is a complete tested c++11 example program).

#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>

struct Foo {
    /* complex member variables. */
};

void DoSomething(Foo *foo) {
    // Complex, but signal safe, use of foo. 
}

Foo InitFoo() {
    Foo foo;
    /* complex, but signal safe, initialization of foo */
    return foo;
}

Foo* GetFoo() {
    static Foo foo = InitFoo();   // [1]
    return &foo;
}

void Handler(int sig) {
    DoSomething(GetFoo());
}

int main() {
    // [2]

    struct sigaction act;
    memset(&act, 0, sizeof(act));
    act.sa_handler = Handler;
    sigaction(SIGINT, &act, nullptr);

    for (;;) {
        sleep(1);
        DoSomething(GetFoo());
    }
}

Question1: Is this guaranteed safe (no deadlocks etc)? C++11 static initialization involves locks. What if the signal is delivered before/after/during the first call to GetFoo() in main?

Question2: Is this guaranteed safe if a call to GetFoo() is inserted at [2] before the signal handler is installed?

I'm assuming C++11 (g++ or clang) on recent GNU/Linux, although answers for various Unices would also be interesting. (Spoiler: I think the answer is 1:NO and 2:YES but I don't know how to prove it.)

Handle generic parameter with type checking

I am currently trying to implement a type checking over a generic parameter and I have no idea if this is somehow possible without overloading functions and methods, a possibility I would like to avoid. I will try to explain what I'm trying to do below.

I have a class Algorithm that is used as a base to describe several algorithms. Each of them can have their specific parameters as input and output. I could overload the main Run method but I would have to do it for any type I need which can quickly become a long list. So I decided to try doing something like this:

class Algorithm {
public:
  Algorithm();

  GenericParameter* Run(GenericParameter* input);
};

class Alg0 : public Algorithm { ... };
class Alg1 : public Algorithm { ... };
class Alg2 : public Algorithm { ... };

The GenericParameter is type specialized and based on two main classes, a templated TParam class that is uninstanciable. The idea being each specialization of TParam inherits the GenericParameter class:

template <typename T>
class TParam {
public:
  TParam() {
    throw std::runtime_error("Cannot instanciate this object");
  }
  TParam(const T& elmt) {
    throw std::runtime_error("Cannot instanciate this object");
  }
};

class GenericParameter {
protected:
  GenericParameter();
  virtual ~GenericParameter();

  // To create a TParam<T> instance. 
  // Will fail if no specialization.
  template <typename T>
  static GenericParameter* Create(const T& elmt) {
    return new TParam<T>(elmt);
  }
  // To create a TParam<T> instance. 
  // Will fail if no specialization
  template <typename T>
  static GenericParameter* Create() {
    return new TParam<T>();
  }
  // To get the object in the TParam<T> param
  template <typename T>
  static T& Get(GenericParameter* param) {
    TParam<T>* tmp = static_cast<TParam<T>* >(param);
    return tmp->object;
  }
};

template <>
class TParam<TypeA> : public GenericParameter {
public:
  TParam<TypeA>() {};
  TParam<TypeA>(const TypeA& elmt): object(elmt) {};
  TypeA object;
};

template <>
class TParam<TypeB> : public GenericParameter {
public:
  TParam<TypeB>() {};
  TParam<TypeB>(const TypeB& elmt): object(elmt) {};
  TypeB object;
};

Using the Create and Get static methods, I can easily create all kind of parameters, supposing I have specialized the related TParam class.

I used it, it works assuming you know what type you have as input and you should return in the Algorithm inherited classes. But one thing bothers me in the fact the code below compiles and runs:

TypeA aobj();
GenericParameter* aobj_p = GenericParameter::Create(aobj);
TypeB bobj = GenericParameter::Get<TypeB>(aobj_p);

Since I don't do type checking, I can get a TypeB object from a GenericParameter instance while it wraps a TypeA object. I have tried a type checking solution based on an enumeration and a type field in the GenericParameter class but I would like to know if anyone see another possibility for it.

I can provide the implementation of the methods if someone wants it.

I want to play an mp3 file. Is it possible to write a code from scratch?

so i'm trying to play an MP3 file on an LPC1768 uController. I have written a neat software to play wav file. I want to know if it's possible to decode mp3 on the go on LPC1768? If so, could you point me in the right direction. I have knowledge of DSP and encoders/decoder but i'm having issue with decoding mp3 format on PC at least. Please point me in the right direction.

Using Smart Pointers

Am working on a legacy C++ app which has below function,

char* CreateNewString (const char* node)
{
   int len = (int) strlen(node) + 1;
   char * ptr = new char [len];
   strcpy_s(ptr, len, node);
   return ptr;
}

This function is called from many classes in the app and here's an example usage case.

char * nodeID = obj.CreateNewString(process->GetNodeID());

The app calls a different process and get a node ID as char pointer and then it's passed to CreateNewString function to dynamically allocate memory for a new string.

Nowhere in the app after the above call, it's deleting the memory. From what i observe, there's a definite memory corruption here.

I think there're few ways of resolving this issue. But i want to explore using the smart pointers in C++11 first before trying anything else.

What I Tried:

So i came up with below function.

  char* CreateNewString (const char* node) 
  {
       int len = (int) strlen(node) + 1;
       shared_ptr<char> ptr (new char [len](), [](char* p) {delete [] p;});
       strcpy_s(ptr.get(), len, node);
       return ptr.get();
    }

The goal is to keep function signature same, i.e., it returns a char pointer, so that i don't have to make changes at all calling places.

The above is not working as ptr is released as it's declared inside the scope of this function.

My goal is:

  1. Use C++ 11 smart pointers to achieve this with minimum code changes to the existing application.

An alternative way am aware of, dynamically initialize array in calling places itself and then delete it before end of that scope. But I want to explore new C++ features before going back to traditional C++ way.

Is it possible to mock non member functions?

I am writing some for my c++ code. In my productive code, I am using functions to work with shared memory, in particular shm_open. As I see in the ForDumies.md of , the mock class should inherit from a class.

Well, the function shm_open is not a member function of any class, from which I can inherit.

Is it possible to mock such a function?

My objective is to control from my own test the expected return value from the shm_open function, so that I can test my error handling in my productive code.

using declaration in class definition

I found that 'using' keyword can be used in class definition. according to https://en.cppreference.com/w/cpp/language/using_declaration, its used for member function is as follows:

If the name is the name of an overloaded member function of the base class, all base class member functions with that name are introduced. If the derived class already has a member with the same name, parameter list, and qualifications, the derived class member hides or overrides (doesn't conflict with) the member that is introduced from the base class.

an example code is as follows:

#include <iostream>
struct B {
    virtual void f(int) { std::cout << "B::f\n"; }
    void g(char)        { std::cout << "B::g\n"; }
    void h(int)         { std::cout << "B::h\n"; }
 protected:
    int m; // B::m is protected
    typedef int value_type;
};

struct D : B {
    using B::m; // D::m is public
    using B::value_type; // D::value_type is public

    using B::f;
    void f(int) { std::cout << "D::f\n"; } // D::f(int) overrides     B::f(int)
    using B::g;
    void g(int) { std::cout << "D::g\n"; } // both g(int) and g(char) are visible
                                       // as members of D
    using B::h;
    void h(int) { std::cout << "D::h\n"; } // D::h(int) hides B::h(int)
};

int main()
{
    D d;
    B& b = d;

//    b.m = 2; // error, B::m is protected
    d.m = 1; // protected B::m is accessible as public D::m
    b.f(1); // calls derived f()
    d.f(1); // calls derived f()
    d.g(1); // calls derived g(int)
    d.g('a'); // calls base g(char)
    b.h(1); // calls base h()
    d.h(1); // calls derived h()
}

From the above code, I am not sure what is the difference, for instance

using B::f;
void f(int)

and

virtual void f(int)

Is there definite difference for using 'using' keyword in order to override class member function?

How do I reinterpret_cast between any two types?

I would like to re-declare the type of a given variable, but unfortunately reinterpret_cast<> does not help here. This line:

reinterpret_cast<std::vector<double>>(std::string("Hello"));

results in the following compiler error:

invalid cast from type 'std::string {aka std::basic_string<char>}' to type 'std::vector<double>'

Is there a different, clean approach?

Notes:

  • I know that reinterpret_cast<> is not a proper conversion. I really do only want to re-declare the type here. Some code around this line will make sure it is only performed when appropriate
  • Why actually does this line above not work?
  • I am aware of this option, which I think is too messy: *reinterpret_cast(&OldType)

Template Argument Binding

What I want is something like std::bind for functions but for templates. Assume I have a template which needs a template template with a defined set of arguments. Now I have another template which would work but which has more arguments, so I need to convert this complex template into a simpler one with bound arguments.

To do this I created a template which defines an alias template.

If I use this binding template with concrete types this works well. But if I instantiate the binding template with another template argument, gcc and clang assume that the alias is not a template template. I know it becomes a dependent name, but there is nothing like the typename disambiguator for templates.

With icc and msvc this works fine.

template<
    template<typename> typename Template 
>
class ATypeWhichNeedsATemplateTemplate
{
};

template<typename A, typename B>
class AComplexTemplate
{
};

template<
    template<typename...> typename ATemplate 
    ,typename... Args
>
class Binder {
public:
    template<typename T>
    using type = ATemplate<T, Args...>;
};

template<typename T>
class AClassWithBoundTemplate : public ATypeWhichNeedsATemplateTemplate<
    Binder<AComplexTemplate, T>::type
>
{    
};

see on godbolt

clang complains:

<source>:30:5: error: template argument for template template parameter must be a class template or type alias template

    Binder<AComplexTemplate, T>::type

    ^

gcc says something similar:

<source>:31:1: error: type/value mismatch at argument 1 in template parameter list for 'template<template<class> class Template> class ATypeWhichNeedsATemplateTemplate'

 >

 ^
<source>:31:1: note:   expected a class template, got 'Binder<AComplexTemplate, T>::type'

C++ substring searching - JUMPING INTO C++

I'm reading "Jumping Into C++" by Alex Allain. I'm at a chapter on strings and searching strings, and I don't really understand this for-loop. Someone please explain to me how this works. Thanks.

for ( i = input.find( "cat", 0 ); i != string::npos; i = input.find( "cat", i ) )
{
    cat_appearances++;
    i++; // Move past the last discovered instance to avoid
    // finding same string again
}
    cout << "The word cat appears " << cat_appearances << " in the string
    " << '"' << input << '"';
}

Installing ROOT on a mac

I need the data analysis framework ROOT on my mac (macOS mojave 10.14.5) for some coding in c++. After downloading the .dmg from here https://root.cern.ch/content/release-61600 I still get an error when compiling something using stuff from ROOT. I also can't just type in 'root' in the terminal and then use root.

So can someone please tell me how to install ROOT?

I know this is a rather silly question but I'm still a beginner :)

Thank you!

how to match a string with number of patterns embeded?

how can I use regex to match a string like this

3 12 34 56

where, 3 is the number of the following patterns(digits in this case), 12, 34, 56 are the actual digits.

It's easy to use one regex to get the number firstly, then match the string with another regex, but how to use one regex to do it?


tried (\d+)(\s\d+){\1}, but didn't work apparently.


The language is C++11, it could be done with two steps, such as:

  • (\d+)(\s\d+)* to match the number 3 firstly

  • 3(\s\d+){3} to match the string again

However, I'm just trying to find a more concise way to do it, if possible. Thanks!


Similar question here, but may not be the same language.

Regex with backreference as repetition count

Find the largest element of an array in c++

there is an array containing elements from 1 to 10 and any of the element can be repeated you have to find the index of the largest elememt. if there is more than 2 similar largest elements then show the smallest index of those elements. like [2,2,1,0,0] the you will print 0.

jeudi 30 mai 2019

What is the point/function of auto in this template parameter?

The following code is extracted from the accepted answer in C++ std::priority_queue uses the lambda expression

#include <vector>
#include <queue>

auto main()
    -> int
{
    std::priority_queue< int, std::vector<int>, auto(*)(int,int)->bool > pq{
        []( int a, int b )->bool { return a < b; }
        };
}

What is the benefit or significance of using auto as opposed to:

    std::priority_queue< int, std::vector<int>, bool(*)(int,int)> pq{
        []( int a, int b )->bool { return a < b; }
        };
}

I thought the whole point of auto is, well, automatic type deduction. But in this case, ->bool is used which seems to make automatic type deduction moot here. So why not just use bool? Am I misunderstanding something here?

Why i am not able to deep copy a class member

Not able to deep copy one class object to another;

I have a geometry Class object

class Geometry
 {
  public:   
     std::string stdstrType;
     bool bValid;

 public:

  Geometry()
    {
       stdstrType = "NO_TYPE";
       bValid = false;

    }

  Geometry( std::string strType , bool bValue )
  {
    stdstrType = strType;
    bValid = bValue;        
  }

 Geometry(const Geometry &g)
{
    stdstrType = g.stdstrType;
    bValid = g.bValid;
}

 ~Geometry()
 {
     qDebug() << "Geometry  destructor called";
 } 

 virtual void draw();
 bool isValid();
 void setValidState(bool bState);
 virtual void Init();
 std::string GetName(); 

}; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// I have a Container class

 class Container
  {
   private:
    std::string stdstrContainerName;
    std::string stdstrPluginType;
    Geometry* Geom;

  public:
    Container();
    Container(std::string, std::string, Geometry* geometry = nullptr);
    Container(const  Container& obj);
    ~Container();
    std::string GetName();
    std::string GetType();
    void SetName(std::string stdstrName);
    Geometry* GetGeometry();
    void SetGeometry(Geometry* Geom);

  };

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 Container::Container(std::string strName, std::string strType, Geometry* 
 geometry) : Geom(geometry)
{
   stdstrContainerName = strName;
  stdstrPluginType = strType;   
}

 Container::Container(std::string strName, std::string strType, Geometry* 
  geometry) : Geom(geometry)
{
  stdstrContainerName = strName;
  stdstrPluginType = strType;

}


 Container::Container(const Container& obj) {
  stdstrContainerName = obj.stdstrContainerName;
  stdstrPluginType = obj.stdstrPluginType;
  Geom = new Geometry;
  *Geom = *obj.Geom;  // This Line gives error
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

since Container object has a data member with Geometry pointer and the scope of geometry object is shorter than the container object so i want to do a deep copy geometry object inside the Container object.

This is the line in copy constructor which gives me error

*Geom = *obj.Geom; // This Line gives error

This is how i Initilize the Container object

 Geometry* geom = new Geometry;
 Container* cont = new Container("Group", "NONE", geom);

AMD Variables in C++ 11

Our organization is moving from pre-standard C++ to C++ 11 (yes we know its 2019) and in the document released about some differences and improvements they are pushing AMD variable types.

Unfortunately I was unable to find anything useful online about these.

What benefit does, say, an AMD_Bool have over bool? (Or any AMD type for that matter)

Is there a reason to change the existing codebase?

Thanks

Why does this acquire and release memory fence not give a consistent value?

im just exploring the use of acquire and release memory fences and dont understand why i get the value output to zero sometimes and not the value of 2 all the time

I ran the program a number of times , and assumed the atomic store before the release barrier and the atomic load after the acquire barrier would ensure the values always would synchronise

#include <iostream>
#include <thread>
#include <atomic>

std::atomic<int>x;



void write()
{


    x.store(2,std::memory_order_relaxed);

    std::atomic_thread_fence(std::memory_order_release);



}

void read()
{

    std::atomic_thread_fence(std::memory_order_acquire);

    // THIS DOES NOT GIVE THE EXPECTED VALUE OF 2 SOMETIMES
    std::cout<<x.load(std::memory_order_relaxed)<<std::endl; 

}

int main()
{

std::thread t1(write);
std::thread t2(read);
t1.join();
t2.join();
return 0;
}

the atomic varible x gives a value of 0 sometimes

Known differences in boost random output from 1.58 to 1.67?

I am working with some legacy code I didn't write that generates random data. The output has changed after it was updated to 1.67 boost from 1.58. Normally reproducible output happens by a fixed seed key. But they are now different between new and old versions.

The boost random distributions used include uniform_int, uniform_real, exponential_distribution and normal_distribution. Does anyone have specific knowledge that one of those or more is now different wrt the boost versions I've mentioned?

I may have to write a simple test prog to ascertain this for sure.

What steps shoul I take when determining the value category of an expression?

I'm rather confused about determiming the value category of an expression. Could you please provide the basic steps that should be taken (what should be analysed) to determing the value category of an expression?

std::map

The following crashes:

  std::map<std::string, int> m1{ {"0", 0}, { "1", 1 }};
  // auto melem = m1["0"]; // OK
  auto melem = m1[0];

Why is that?

C++ std::unique is not showing expected behaviour

I was trying to find if the vector contains duplicates (please don't provide an algorithm to check duplicates.) I came up with this weird behavior. std::unique on vector 1,2,3,1 should make it 1,2,3,1 returning an iterator to 1 but on erasing the iterator returned till the vector.end() I got the same size vector as that of I original vector. Here is the snippet of code depicting the said behavior (available at ideone)

    vector<int> nums2 = {1,2,3,4};  
    vector<int> nums = {1,2,3,1};
    cout << "nums1" << endl;
    vector<int> a(nums.begin(), nums.end());
    auto ip = unique(nums.begin(), nums.begin()+nums.size());
    nums.resize( std::distance(nums.begin(),ip) );
    cout << a.size() <<  " " << nums.size() << endl;

    cout << "Nums2" << endl;
    vector<int> a2(nums2.begin(), nums2.end());
    auto ip2 = unique(nums2.begin(), nums2.begin()+nums2.size());
    nums.resize( std::distance(nums2.begin(),ip2) );
    cout << a2.size() <<  " " << nums2.size();

The actual output is

nums1
4 4
Nums2
4 4

but it should have been

nums1
4 3
Nums2
4 4

callback function is not giving desired output

As per below code snippet shared in coliru link, Each time the user clicks the i’th button, the m_clicks[i] and m_total_clicks should both get incremented. To achieve this, the class MyFrame will register a "on_click-handler" callback with each button. Trying to register button_clicked as the callback doesn’t work.
m_pushbuttons[i].on_click_handler(MyFrame::button_clicked);// Doesn't give expected result

Below is the coliru link for source code. https://coliru.stacked-crooked.com/a/c15865d59b41341f

Here is the expected output based on below test cases for both f1 and f2 objects with print_stats method.

//MyFrame f1(2)
//f1.m_buttons[0].click();
//f1.m_buttons[0].click();
//f1.m_buttons[0].click();
//f1.m_buttons[1].click();
//f1.m_buttons[1].click();

//f1.print_stats();

//MyFrame f2(3);
//f2.m_buttons[2].click();
//f2.m_buttons[2].click();
//f2.m_buttons[2].click();
//f2.m_buttons[1].click();
//f2.print_stats();
// Should print:
// Total Clicks: 4
// Button[0] clicks: 0
// Button[1] clicks: 1
// Button[2] clicks: 3

So basically I need to write a client class so that when instantiated, will create N such buttons (where N is a constructor time parameter). The client class wishes to register a callback to keep track of button clicks but in current implementation, There are couple of issues.

(1) std::vector MyFrame :: m_clicks (2) is initialized statically and initialize value should be same as MyFrame initialized object value instead of static value .

(2) Without declaring static m_total_clicks and m_clicks , Is there any other way to achieve the same.

(3) on line no. 20 ,m_ftr pointer needs to be properly initialized.

Could you suggest any proper design/implementation for this callback implementation.

c++11 list push_back() instanciation fault?

I am adding elements to a c++11 list via push_back(). Before adding an element I am printing out a debug message via cout. When I now remove the cout statement, the values in the element I append to the list with push_back are corrupted. I can test this with googletest.

Following you see the working code. When i comment out the cout statement the values in the last element of the sensor_scan_list get seemingly corrupted. The error lies in my opinion either in the instanciation of the list or in the code of the test. Only the state variable of the current_sensor.state seems corrupted (see below).

When I leave the cout statement in, everything works perfectly fine. It is such a weird issue, has someone a clue why this could happen?

code snippet:

void MessageHandler::processSensorHeader(TelemetryMessageInterface * p_Message)
{
    cout << "DEBUG: sensor header element added\n";
    addSensorHeader(p_Message);
    send_message(encoder->confirm(((SensorHeaderMessage *)p_Message)->getMessageId())); //ACK
}

void MessageHandler::addSensorHeader(TelemetryMessageInterface * p_message)
{
    Sensor new_sensor;

    new_sensor.manufacturerId = ((SensorHeaderMessage *)p_message)->getManufacturerId();
    new_sensor.deviceId = ((SensorHeaderMessage *)p_message)->getDeviceId();
    new_sensor.state |= SENSOR_HEADER_DETECTED;

    sensor_scan_list.push_back(new_sensor);
}

Googletest code:

TEST(MessageHandlerTest, processSensorHeader)
{
TelemetryEncoder * encoder = new TelemetryEncoder();
TelemetryMessageInterface * p_Message;
MessageHandler message_handler;
Sensor current_sensor;

list <Sensor> :: iterator p_List;

p_Message = encoder->encodeSensorHeader(0x0101,0x0202,0x0303); 
//add sensor
message_handler.processSensorHeader(p_Message);

p_List = message_handler.sensor_scan_list.begin();

current_sensor = *p_List;
EXPECT_EQ(current_sensor.deviceId, 0x0303);
EXPECT_EQ(current_sensor.manufacturerId, 0x0202);
EXPECT_EQ(current_sensor.state, 1);

p_Message = encoder->encodeSensorHeader(0x0203,0x0302,0x0403); 
//add new sensor
message_handler.processSensorHeader(p_Message);

current_sensor = *++p_List;
EXPECT_EQ(current_sensor.deviceId, 0x0403);
EXPECT_EQ(current_sensor.manufacturerId, 0x0302);
EXPECT_EQ(current_sensor.state, 1);

p_Message = encoder->encodeSensorHeader(0x0102,0x0202,0x0303);
message_handler.processSensorHeader(p_Message);

current_sensor = *++p_List;
EXPECT_EQ(current_sensor.deviceId, 0x0303);
EXPECT_EQ(current_sensor.manufacturerId, 0x0202);
EXPECT_EQ(current_sensor.state, 1);
}

Sensor class:

class Sensor : public sensor_interface {
public:
Sensor();
virtual ~Sensor();

uint16_t manufacturerId;
uint16_t deviceId;

char name[SENSOR_INFORMATION_LENGTH];

uint8_t state;
};

Googletest output for broken code (cout commented out):

[ RUN      ] MessageHandlerTest.processSensorHeader
../test/inc/test_messageHandler.cpp:77: Failure
  Expected: current_sensor.state
  Which is: '\xC1' (193)
To be equal to: 1
../test/inc/test_messageHandler.cpp:93: Failure
  Expected: current_sensor.state
  Which is: '\xF1' (241)
To be equal to: 1
[  FAILED  ] MessageHandlerTest.processSensorHeader (0 ms)

Best data structure for an N-ary tree

I need to represent a tree with multiple branches per node. What structure should I use? It's for computing chess game states. It explodes exponentially so memory will be a concern. I'm using C++11 but am open to other standards. Also, pruning should be O(1).

Parsing issue when creating class object [duplicate]

This question already has an answer here:

Why is it allowed to write Test object(); Test object{}; in case of deleted constructors?

1.When you write Test object(); it doesn't mean that you create class object in case of deleted constructor, compiler understood a function, thats why when you try to write std::cout << sizeof(object) you will get error ISO C++ forbids applying sizeof to an expression of function type. I can understand that it is not deprecated for back-compatibility, but it could be optimized and fixed in C++11 which is not done.

2.Started from C++11, you can create object with Test object3{}; syntax which is already valid object even though deleted constructor and when you do std::cout << sizeof(object3) the output is 1. In this case it means that operator delete is useless.The same about writing it in private section in old versions.

                        ```About Code```

You can use this style of code when you want to create an aggregation of functions and to have encapsulation. So please don't write in answers for example Why do you use class instead of namespace,etc...

class Test {

    Test() = delete;
    Test(const Test&) = delete;
    Test(Test&&) = delete;
    Test& operator=(const Test&) = delete;

public:
    template<typename T>
    static void func();
private:
    static std::string m_fileName;
};

int main() {

   Test object();  //Compiles as function returning Test object
   Test object2;   //Doesn't compile because of deleted constructor
   Test object3{}; //Compiles and it creates an object even though deleted constructor
   Test object4({}); //Doesn't compile because of deleted constructor
   return 0;
}

C++ creating new operators and overloading the current ones

I am writing code for transposing a matrix as a part of learning C++. What I am doing is operator overloading. But, usually the notation for transposing a matrix is '.

Is ' even an operator? I understand if it is between ' ' you notate a character, and if you use " " you notate a string. But are these operators or not? Can I overload them as individual characters or even as whole?

Can I make new operators in C++ that only work on an object of a specific class? The trick I've used is overloading the known operators like +, -, ^, ... and then with #define I change how the preprocessor processes the text, but in the end I would still override an existing operator and I cannot use any of the special symbols but rather letters.

Does the both object point to the same value in copy constructor

Foo(const  Container& obj);   // Copy Constructor

Foo::Foo(const Container& obj) : Geom (obj.Geom)  {
 // Assign Values In Constructor
  stdstrContainerName = obj.stdstrContainerName;
  stdstrPluginType = obj.stdstrPluginType;  
}

Foo fooToCopy;
 Foo foo;
 foo = fooToCopy;

1) Since i am using pass by reference do the foo and fooToCopy point to the same variable

2) If fooToCopy goes out of scope before foo than will the variable value be destroyed.

Initialize array whose size is a compile-time constant to single value

I have a c-style array whose size is defined by a #define and can change based on compiling options, e.g.

#if LINUX
# define SIZE 4
#else
# define SIZE 5
#endif
static int myArr[SIZE] = { /* ??? */ };

How can I initialize the whole array to a non-zero value, for example all 42?

problem with function template parameter pack

Why does the following fail to compile?

inline Obj init_output_string() { return open_output_string(); }

template<typename... Args>
Obj init_output_string(Args... prev, int last)
{
    Obj port(init_output_string(prev...));
    write_char(port, last);
    return port;
}

int ch1 = ...;
int ch2 = ...;
Obj port = init_output_string(ch1, ch2);

(error is 'init_output_string': no overloaded function takes 2 arguments for MSVC, g++ gives a similar error).

But the following variation does compile

inline Obj init_output_string() { return open_output_string(); }

template<typename... Args>
Obj init_output_string(int first, Args... rest)
{
    Obj port(init_output_string(rest...));
    write_char(port, first);
    return port;
}

int ch1 = ...;
int ch2 = ...;
Obj port = init_output_string(ch1, ch2);

The difference being the order in which the characters are written. I can work around this easily enough, but I'm curious to know what rule my first example is breaking.

No matching function for call to 'std::basic_ofstream

So I was playing around a bit with file ofstream and ifstream and got stuck into a compiler problem that I just simply don't know what it means...

Let's start.

I have the following class:

class FS{
    public:
        string name;
        long long int size;
        long long int freeBlocks;
        long long int usedBlocks = 0;
        int blocksize = 128;
        vector<FS_File> file_list;
        char * ptr;                      //This is a malloc pointer
        void saveTo(ofstream& of); 
        void openFrom(ifstream& inf); 
    };

The problem occurs in the saveTo() function:

void FS::saveTo(ofstream& of){ 
  of.write(&name, sizeof(name)); 
  of.write(&size, sizeof(size));
  of.write(&freeBlocks, sizeof(freeBlocks)); 
  of.write(&usedBlocks, sizeof(usedBlocks)); 
  of.write(&blocksize, sizeof(blocksize)); 
  of.write(&file_list, sizeof(file_list));
  of.write((char *)&ptr, sizeof(ptr));
}

The compiler gives me the next error:

functions.cpp   In member function 'void FS::saveTo(std::ofstream&)':


    [Error] no matching function for call to 'std::basic_ofstream<char>::write(std::string*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ofstream<char>::write(long long int*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ofstream<char>::write(long long int*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ofstream<char>::write(long long int*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ofstream<char>::write(int*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ofstream<char>::write(std::vector<FS_File>*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ifstream<char>::read(std::string*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ifstream<char>::read(long long int*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ifstream<char>::read(long long int*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ifstream<char>::read(long long int*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ifstream<char>::read(int*, long long unsigned int)'

    [Error] no matching function for call to 'std::basic_ifstream<char>::read(std::vector<FS_File>*, long long unsigned int)'

Whenever I try to call the next code:

ofstream outfile;
string filename = curFS.name + ".dat";
outfile.open(filename, ios::binary | ios::out);
curFS.save(outfile);
outfile.close();

I've tried a few things, but nothing has worked...

What does the compiler error means? How can I solve it?

mercredi 29 mai 2019

Exceptions causes crash in application and not caught with sun studio C++ compiled application

I have an application which uses xerces 3.2.1. Everything works fine with sun C++ 5.8. We are moving to the latest compiler, Sun Studio 12.6, C++ 5.15. I compiled xerces and my application. All went well. When I run and throw exceptions from my application, it is not caught in xerces and the application crashes. There are no code changes which are working with the old compiler. Looks like after throwing the exception, the stack do not unwind. This is what I get -

terminate called after throwing an instance of 'xercesc_3_2::ParseException'
t@1 (l@1) signal ABRT (Abort) in __lwp_kill at 0xfa34ec9c
0xfa34ec9c: __lwp_kill+0x0008:  bcc,a,pt  %icc,__lwp_kill+0x18  ! 0xfa34ecac
Current function is CXmpXmlStudioParser::startElement
  421                                           throw ex;
(dbx) bt
current thread: t@1
dbx: can't find definition for symbol 'RefVectorOf<xercesc_3_2::XMLAttr>
  [1] __lwp_kill(0x0, 0x6, 0x0, 0x6, 0xffbffeff, 0x0), at 0xfa34ec9c
  [2] raise(0x6, 0x0, 0x0, 0xfa32e13c, 0xffffffff, 0x6), at 0xfa2e7b58
  [3] abort(0x69d578, 0x1, 0xf71fcce0, 0xffb40, 0xfa3c5518, 0x0), at 0xfa2c29c8
  [4] __gnu_cxx::__verbose_terminate_handler(0x69d5a8, 0x2, 0xf71b25e0, 0x57c800, 0xfdfd2d50, 0xfa3c758c), at 0xf71b58bc
  [5] 0xf71b2234(0xf71b5700, 0x1, 0x8, 0x0, 0x69d5a8, 0xffbfc564), at 0xf71b2234
  [6] std::terminate(0x0, 0x69d5c0, 0xb8b1aabc, 0xbcd4d500, 0x0, 0x0), at 0xf71b22d8
  [7] __cxa_throw(0x69d5c0, 0xfdfd2d18, 0xfddd9a80, 0xbcd4d500, 0x0, 0x69d5a8), at 0xf71b25e0
=>[8] CXmpXmlStudioParser::startElement(this = 0x4caf68, fFormatter = CLASS, name = 0x57c7d8 "data", attributes = CLASS), line 421 in "XmpXmlStudioParser.cpp"
  [9] COtlXmlParseHandler::startElement(this = 0x549e78, name = 0x57c7d8 "data", attributes = CLASS), line 240 in "OtlXmlParseHandler.cpp"
  [10] xercesc_3_2::SAXParser::startElement(this = 0x4c3ff0, elemDecl = CLASS, elemURLId = 1U, elemPrefix = 0x4c71e0 "", , line 990 in "SAXParser.cpp"
  [11] xercesc_3_2::IGXMLScanner::scanStartTagNS(this = 0x4c4e90, gotData = true), line 2640 in "IGXMLScanner.cpp"
  [12] xercesc_3_2::IGXMLScanner::scanContent(this = 0x4c4e90), line 890 in "IGXMLScanner.cpp"
  [13] xercesc_3_2::IGXMLScanner::scanDocument(this = 0x4c4e90, src = CLASS), line 217 in "IGXMLScanner.cpp"
  [14] xercesc_3_2::XMLScanner::scanDocument(this = 0x4c4e90, systemId = 0x497920 "./testDoc.xml"), line 402 in "XMLScanner.cpp"
  [15] xercesc_3_2::XMLScanner::scanDocument(this = 0x4c4e90, systemId = 0x3dffe8 "./testDoc.xml"), line 410 in "XMLScanner.cpp"
  [16] xercesc_3_2::SAXParser::parse(this = 0x4c3ff0, systemId = 0x3dffe8 "./testDoc.xml"), line 617 in "SAXParser.cpp"

Both application and xerces are using the correct libraries while linking and running. Not sure what is wrong. xerces is compiled with the following -

./configure CC=/opt/developerstudio12.6/bin/cc CXX=/opt/developerstudio12.6/bin/CC  CFLAGS="-O -m32"  CXXFLAGS="-O -m32 -std=c++11" LDFLAGS="-std=c++11 -L/opt/developerstudio12.6/lib/compilers/CC-gcc/lib"

Same options for the application used.

Exception is thrown like this -

ThrowXML(ParseException,XMLExcepts::NoError);

class ParseException : public XMLException

The code looks ok because its working with the old compiler. Something to do with C++11 option ? Anything I can try ?

Edit: LD_PRELOAD=/opt/developerstudio12.6/lib/compilers/CC-gcc/lib/libgcc_s.so.1 as some posts said but did not work.

Which C++ standard library functions allocate memory?

It's obvious that the collection classes with their class Allocator = std::allocator<T> parameter explicitly use heap allocations, but which other library functions (or indeed language features) can be expected to allocate memory in a practical implementation.

I know from this post that throw may be expected to (I don't have the spec to hand for the exact terminology) allocate memory for the stack trace, but where else may it occur?


Background: MISRA C++ 18-4-1 says "Dynamic heap allocation shall not be used", yet other rules cover the use of throw (15-0-1/2/3), and yet others (eg 3-4-1) have sample code using std::cout which I would expect to allocate memory.

Does my polymorphism process is causing memory leak

I have a TreeItem class which has a data member with the name Container

class TreeItem
{
 public:    
 void setContainer(const Container &data);

 private:
    QList<TreeItem*> childItems;
    Container itemData;
     TreeItem* parentItem;
 };

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Defination for Set Container

void TreeItem::setContainer(const Container &cont)
 {
   itemData = cont; 
 }

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Defination for Container Class

class Container
 {
  private:
  std::string stdstrContainerName;
  std::string stdstrPluginType;
  Geometry* Geom;

public:
 Container();
 Container(std::string, std::string, Geometry* geometry );
 Container(const  Container& obj);
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Container::Container( std::string strName, std::string strType,  
Geometry* geometry) : Geom(geometry)
{   
  stdstrContainerName = strName;
  stdstrPluginType = strType;
  qDebug() << geometry->isValid();
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// I use my TreeModel class to set the value of Container in the TreeItem object

void  TreeModel::SetContainer(const QModelIndex &index,  Container* Cont)
 {
   TreeItem *item = getItem(index);
   item->setContainer(*Cont);

  }

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// The geometry which is data type to Container class has a virtual function with the name draw

Class Geometry
{
 public:    
     std::string stdstrType;
     bool bValid;

 public:
// Other Functions
 virtual void draw();

}; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// There are other clases which are derived from the Geometry class

 class Sph : public Geometry
  {
   public:
   Sph( float radius , float segments );
  ~Sph();
  void init();
  void CleanUp();
  void draw();

 private:
   float fRadius, fSegments;
   bool isInited;
   unsigned int m_VAO, m_VBO;
   int iNumsToDraw;
   SumShader shader;
   bool isChanged;
};

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// This is the process i am using to set the Container to TreeItem class.

 void WavefrontRenderer::AddSphere()
  {
    QModelIndex index = treeView->selectionModel()->currentIndex();
    QAbstractItemModel *model = treeView->model();
    TreeModel *myModel = qobject_cast<TreeModel*>(model);

    Sph* sphere = new Sph( 0.1 , 32);
   sphere->setValidState(true);
   sphere->stdstrType = "Sphere";
   if (!model->insertRow(index.row() + 1, index.parent()))
      return;

   Container cont("Sphere" , "SPHERE" , sphere );
   QModelIndex child = model->index(index.row() + 1, 0, index.parent());
   model->setData(child, QVariant("Container"), Qt::EditRole);
   myModel->SetContainer(child, &cont);
   delete sphere // This line gives error

}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Everthing works as expected but i have few questions.

1) Since i am creating a new Object "Sph* sphere = new Sph( 0.1 , 32);" but not deleting it does it cause memory leakage.

2) When i tried to delete it after setting it on TreeItem i got Memory error.

OpenCL2.0 runtime compiler not supporting c++11

I am trying to build an OpenCL kernel using OpenCL2.0. I am calling the cl::Program build function and passing the flag -cl-std=CL2.0. The g++ compiler finishes and links with no errors. However, when I run the program, the build function throws an exception (see below). Wanted to see if anyone has seen this before and has a solution. Thank you.

I tried other flags such as -cl-std=c++11, -cl-std=CL2.2, but none of these worked.

[20:03:47.768768][info][Demosaic] CL_FLAGS = -cl-std=CL2.0 -D IMAGE_MAD_INDEXING -D AMD_GPU_ARCH -D DEVICE_WAVEFRONT_SIZE=64 -D WG_SIZE_MAX=256 terminate called after throwing an instance of 'cl::BuildError' [20:03:47.788335][error][Demosaic] Build failed: In file included from /tmp/OCL21460T1.cl:244: /usr/include/CL/cl2.hpp:495:2: error: Visual studio 2013 or another C++11-supporting compiler required

error Visual studio 2013 or another C++11-supporting compiler required

Reading In Chars With Whitespace C++

In C++, I am trying to read in input from a file containing a formatted "table" of chars, some of which are spaces. I then need to transfer the characters, including the spaces, into a 2-D char array, with the characters placed in the same position in the new char array as they were in the input file. I am given a width and a height for the input, and then a "table" of chars, with (2 * h) + 1 rows and (2 * w) + 1 columns. I keep having problems with reading in this input into a char array. Can anybody show me how to correctly do this? I have included sample input below. For example, my_chars[0][0] would be '+', and my_chars[1][1] would be ' ', meaning space character.

5 3
+-+-+-+-+-+
|         |
+-+ +-+ + +
|     | | |
+ +-+-+ + +
| |     |  
+-+ +-+-+-+

Here is one piece of code that I tried, but does not work:

int H = 2 * h + 1;
int W = 2 * w + 1;
for (int i = 0; i < H; i++) {
    string line;
    getline(fin, line);
    for (int j = 0; j < W; j++) {
      my_chars[i][j] = line[j];

Looping through linked lists

So basically, what I'm trying to do is going through all the nodes and verify if node.value is <= cost. If it is I need to remove that node and in the end I want to store the nodes that weren't remove in a new struct. I'm not sure how exactly am I supose to do this.

This struct can be an example:

struct node {
    int value;
    node * next;
}

I'm going through all the nodes and remove only the ones that doen't have the required.

node * verify_money(node * head, int cost)
{

    node * iterator = head;

    while(iterator != NULL){
       if(iterator.value <= cost) {  
           /*remove this node*/
       }
       iterator = iterator.next;
    }

return /*struct without nodes removed)/*

}

I want to get the remaining nodes.

How to clearly see variables during debbuging when we work with Vectors or Maps on RAD Studio

I am working with different data structure such as vectors, map and multimap. Is there a way to format the debug window of local variables in order to properly see what does these structures contain?

Another question on std::forward: behind the scenes

First of all excuse me for my english very poor and simple.

I'm experimenting with Perfect Forwarding and I found that std::forward needs two overload:

Overload nr. 1:

template <typename T>
inline T&& forward(typename 
std::remove_reference<T>::type& t) noexcept
{
    return static_cast<T&&>(t);
}

Overload nr.2:

template <typename T>
inline T&& forward(typename 
std::remove_reference<T>::type&& t) noexcept
{
    static_assert(!std::is_lvalue_reference<T>::value,
              "Can not forward an rvalue as an lvalue.");
    return static_cast<T&&>(t);
}

Now a typical scenario for Perfect Forwarding is something like

template <typename T1>
void wrapper(T1&& e1)
{
    wrapped(forward<T1>(e1));
}

Of course you know that when wrapper is instantiated, T depends on whether the argument passed to func is an lvalue or an rvalue. If it's an lvalue of type U, T is deduced to U&. If it's an rvalue, T is deduced to U.

In any case - in the scope of wrapper - e1 is an LValue, therefore is always used the first overload of

std::forward

Now my question:

can you show me a valid scenario in which the 2nd overload is used (and is needed)?

Thank you for your time and, again, forgive my english.

Overloads of std::isnan and std::isinf for integral types

Cppreference mentions the overloads of std::isnan and std::isinf (and maybe others) for integral types. This makes the following call unambiguous:

std::isnan(1);

However, I cannot find any such overloads mentioned in the C++ Standard. I checked C++11 and the current draft, and there are only overloads for float, double, and long double.

As for compiler behavior, GCC and Clang both compile the code, but MSVC does not. Who is right? Where did the integral overload on cppreference come from?

How to initialize dynamic array in constructor using initializer_ist?

I am trying to initialize the dynamic array in the constructor using initialize_list in C++. How can I achieve this?

#include <cstdlib> 
#include <initializer_list>
#include <iostream>
#include <utility>

using namespace std;

class vec {
private:
    // Variable to store the number of elements contained in this vec.
    size_t elements;
    // Pointer to store the address of the dynamically allocated memory.
    double *data;

public:
    /*
      * Constructor to create a vec variable with the contents of 'ilist'.
    */
    vec(initializer_list<double> ilist);
}

int main() {
    vec x = { 1, 2, 3 };  // should call to the constructor 
    return 0;
}

base64 encode and decode snippet in c++11 using poco library

Anyone have a freely available base64 encoding and decoding code snippet in c++11 using Poco library? if so please share the example how to use it.

mardi 28 mai 2019

Why i am not able to cast pointer to the class structure

I have a Geometry class

  class Geometry
  {
  public:   
   std::string stdstrType;
   bool bValid;
   public:

    Geometry()

 Geometry( std::string strType , bool bValue )

 Geometry(const Geometry &g)

 ~Geometry()        
    virtual void draw();
    bool isValid();
    void setValidState(bool bState);
    virtual void Init();
    std::string GetName();  
 };

Which is the base class for geometry objects like in this case for sphere class

class Sph : public Geometry
 {
  public:
  Sph( float radius , float segments );
  ~Sph();
  void init();
  void CleanUp();
  void draw();

 private:
   float fRadius, fSegments;
    bool isInited;
    unsigned int m_VAO, m_VBO;
    int iNumsToDraw;
    SumShader shader;
    bool isChanged;
};

I have a Tree structure holding different Container objects and geometry is a data type in the Container object.

 class Container
   {
     private:
      std::string stdstrContainerName;
      std::string stdstrPluginType;
       Geometry Geom;
    }

Since each item in the tree can hold a circle sphere or rectangle so i would like to Use the draw function of geometry to draw the Geometry object types. For this when i try to cast any Geometry Object type to Geometry i get a Error.

Geometry *geom = new Geometry;
geom = &sphere;
Container cont("Sphere" , "SPHERE" , *geometry );   
myModel->SetContainer(child, cont);

1)Is this the Correct Approach .

2) How can i cast the Geometry Objects to the Geometry Pointer.

what is good solution from template pointer: *(T*) to C++ type casting?

I'd like to convert C style template pointer: *(T*)(&buf[index]) to c++ type casting in bytebuffer code.

code in https://github.com/RamseyK/ByteBufferCpp/blob/master/src/ByteBuffer.hpp#L170

template<typename T> 
T read(uint32_t index) const {
    if (index + sizeof(T) <= buf.size())
        return *((T*) &buf[index]); //C Style Cast
    return 0;
}

My solution: C++ Type cast

return *(reiterpret_cast<T*>(&buf[index])); //C++ Style Cast

Is this good solution?

Or other good solutions with c++11?

Set the maximum size for a boost priority queue

I am trying to find top n items of a list that gets populated dynamically. I thought priority-queue would be a good way to go about this. Since I need only top n, there is no point in storing anything more than the 'n' items required for my calculation. I am unable to find anything in the boost library that seems to be able to set the limit for the priority queue

I tried using the reserve(element_count) function. The doc said that the function is used to "reserve space for the element_count elements". But that did not work the way I thought it would

This is some sample code that I am writing. This is NOT THE USE CASE though.

int main()
{
        int maxSize = 2; // Priority Queue (pq) is expected to hold a maximum of 2 elements at any time
        boost::heap::priority_queue<int> pq; // Declaration
        pq.reserve(maxSize); // I assumed this would reserve space only for 2 elements and anything more would over write the existing ones based on comparison
        pq.push(3);
        pq.push(2);
        pq.push(1); // Push should fail
        cout << "Size = " <<pq.size() << " Max Size = " << (int)pq.max_size(); 
        for (int i=0; i<maxSize; i++)
        {
                int a = pq.top();
                pq.pop();
                cout << a <<"\n";
        }
        return 0;
}

I expected the result to be:
Size = 2 Max Size = 2
3
2

But what I get is:

Size = 3 Max Size = -1
3
2

What am I missing?

How to index and clear properly a multidimensional vector

I am working on a piece of code that reads data from files and should save this data in a multidimensional vector. The data is stores in three columns in each file and I am saving the data from each file in a 2D vector. Then, I need to store the data from all the files into a 3D vector, in which the third index represents the number of files.

I am not sure I am doing this in the proper way and I would like some guidance. When I print the content of the vector _data, I expect it to print in each iteration of the loop only the data of the j-th file, instead it prints all of the data.

Should I clear _data after each file is read? And if so, how do I clear _data?

Thanks.

    vector< vector<double> > data(3);
    vector< vector< vector<double> > > _data;
    for (int i = 0; i < channels.size(); ++i){
        ifstream ifs(channels.at(i));
        if(!ifs){
            cerr << "File could not be found." << endl;
            exit(1);
        }
        else if(ifs.is_open()){
            string line;
            getline(ifs,line);
            while(ifs.good()){
                istringstream iss (line);
                double x;
                double y;
                double err;
                iss >> x >> y >> err;
                data[0].push_back(x);
                data[1].push_back(y);
                data[2].push_back(err);
                getline(ifs,line);
            }
            _data.push_back(data);
    }

    for ( int j = 0; j < channels.size(); ++j){
        for ( int i = 0; i < data[0].size(); ++i){
            cout << _data[j][0][i] << '\t' << _data[j][1][i] << '\t' << _data[j][2][i] << endl;
        }
        cout << "---------------" << endl;
    }

How to define a static generic member

I get this error when trying to compile the program:

minpriorityqueue.cpp:4:36: error: expected expression std::map <MinPriorityQueue<G>::node*,int> MinPriorityQueue<G>::positions = ;

and it has the '^' symbol under the comma

// graph.h
#include "minpriorityqueue.h"
#include "node.h"
#include "edge.h"
class Traits {
    public:
        typedef char N;
    typedef int E;
};

template <typename Tr>
class Graph {
    public:
        typedef Graph<Tr> self;
        typedef MinPriorityQueue<self> min_priority_queue;
        typedef Node<self> node;

        struct u {
            node* n;
            E key;
            struct u* parent;
            u(node* n) : n(n), key(INT_MAX), parent(nullptr) {}
        };
        typedef struct u U;

    self MST_Prim(node* r) {
        // some code
        min_priority_queue::heapDecreaseKey(V, v, weight(u->n,v->n));
        // more code
        self MST;
        // and more code...
        return MST;
    }
};

// minpriorityqueue.h
template <typename G>
class MinPriorityQueue{
    private:
        typedef typename G::U U;
        typedef typename G::E E;
        typedef typename G::node node;
        static std::map<node*,int> positions;
    public:
        static void heapDecreaseKey(std::vector<std::pair<node*, U*> >& A, U* n, E key) {
            // implementation
        }
};

// minpriorityqueue.cpp
#include "minpriorityqueue.h"

template<typename G>
std::map<MinPriorityQueue<G>::node*,int> MinPriorityQueue<G>::positions = ;

I already tried defining positions without MinPriorityQueue<G>:: before node and it gives me another error. I also tried using typename MinPriorityQueue<G>:: and get the following:

Undefined symbols for architecture x86_64:
"MinPriorityQueue<Graph<Traits> >::positions", referenced from:

I've been trying to solve this problem for almost a day and couldn't find anything close to this.

Counting the max of elements based on stack operations c++

You are given a stack of N integers. In one operation, you can either pop an element from the stack or push any popped element into the stack. You need to maximize the top element of the stack after performing exactly K operations. If the stack becomes empty after performing K operations and there is no other way for the stack to be non-empty, print -1.

I'm dynamically allocating the memory and then releasing the memory. I am unable to understand why I'm facing this issue.

#include "pch.h"
#include<iostream>
using namespace std;
int main()
{
int n, x, max;
cin >> n;
cin >> x;
int* arr = new int[n];
    //Storing the values from the last, since the first element represents 
    //top of the stack, so the first element would be latest element which 
    //will be pushed into the stack
for (int i = n; i > 0; i--)
{
    cin >> arr[i];
}
max = arr[n];
    //Finding the max by iterating from the last position to the no of 
    //stack operations performed.
for (int i = n; i >= x; i--)
{
    if (arr[i] > max)
    {
        max = arr[i];
    }
}
cout << max;
delete arr;
return 0;
}

Input :
6 4
1 2 4 3 3 5
Expected Output : 
4



Error Message : Debug Error ! Program :- Heap Corruption detected : after 
normal block c#2368 at 0x01d21e30. CRT detected that the application wrote 
memory after end of heap buffer.

C++ class exceptions overriding const char* what() const throw () method

I'm having some difficulties learning exceptions in c++. I have a simple class named Clothing and a custom exception class named WrongClothingSize. I want the exception class to throw something like "WrongClothingSize exception! Size is unacceptable, Size: xxx" in the console, when i try to make a Clothing object of a non-existing size (example: male clothing size: 95) in the main file. I will also include some details in TODO comments in parts of my code. Thank you for your time!

Clothing.cpp

//TODO add throw where necessary
Clothing::Clothing() :
        name("unknown"), gender(0), size(0), price(0) {

}

Clothing::Clothing(string name, int gender, int size, double price) :
        name(name), gender(gender), size(size), price(price) {

}

Clothing::Clothing(const Clothing &object) :
        name(object.name), gender(object.gender), size(object.size), price(
                object.price) {
}

Clothing::~Clothing() {

}

int Clothing::getSize() {
    return size;
}

void Clothing::setSize(int c) {
    size = c;
}

WrongClothingSize.h

class WrongClothingSize: public std::exception {
public:
    WrongClothingSize();
    const char* what() const throw () { //abstract function from exception header
        return msg.c_str();
    }
    virtual ~WrongClothingSize();
    /*TODO check if size of clothing is acceptable (correct)
     * Example:
     * bool Clothing::isSizeValid(int gen, int siz) {
    if (gen == 0){
        if (siz == 46 || siz == 48 || siz == 50 || siz == 52 || siz == 54 || siz == 56)
            return true;
    }
    else if (gen == 1){
        if (siz == 32 || siz == 34 || siz == 36 || siz == 38 || siz == 40 || siz == 42 || siz == 44 || siz == 46 || siz == 48 || siz == 50 || siz == 52 || siz == 54)
            return true;
    }
    return false;
}
     */
private:
    const std::string msg;
};


WrongClothingSize.cpp

#include "WrongClothingSize.h"

WrongClothingSize::WrongClothingSize() :
        msg("Wrong Clothing Size!") {

}

WrongClothingSize::~WrongClothingSize() {
    // TODO Auto-generated destructor stub
}

Clarification on calling srand

I'm wondering why it's advantageous to seed srand at the beginning of the program, instead of where I use it.

I generate pseudo-random numbers when seeding srand at the beginning of my program but I get the numbers all the same when I seed srand inside the function I call to generate the numbers

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

int rng()
{
    const int SIZE = 10;
    int rng[10];
  srand(time(NULL));
    for (int i = 0; i < 10; i++)
    {
        rng[i] = rand() % 128 + 1;
        return rng[i];
    }

}

int main()
{
    int array;
  //srand(time(NULL)); If i put it here i get actual random numbers
    cout << "Welcome to the program";
    cout << "\nthis is your rng\n";
    for (int i = 0; i < 10; i++)
    {
        array = rng();
        cout << array << endl;
    }

    return 0;
}

When I run the program all of the numbers are the same, but when I delete the seeding from in the rng function and uncomment the srand in the main module the numbers are pseudo-random which is what I want. Im wondering why though. I've looked into it and heard that im seeding srand with a time and when I run that function the loop iterates so fast that all of the numbers are generated with the same seed value so they're all the same, but I'm wondering what's the difference from that and having srand(time(NULL)) in main because either way doesn't the function generate the numbers so fast they'll be at the same seed value anyway? It doesn't appear that way because of the different output but im curious, why?

How to use boost::aio::async_connect with lambda

I want to reliaze how to use boost::aio::async_connect with lambda. Boost version 1.68

It's really strange that I could use std::bind but not lambda. If I use std::bind, it work. But when I use lambda, it buillt failed, and said "IteratorConnectHandler type requirements not met.

std::bind version (worked)

void SslClient::connect(boost::asio::ip::tcp::resolver::results_type results) {
    auto sp = shared_from_this();
    boost::asio::async_connect(ws->next_layer().next_layer(),
        results.begin(),
        results.end(),
        std::bind(
            on_connect,
            std::placeholders::_1)

    );
}

lambda version (not worked)

void SslClient::connect(boost::asio::ip::tcp::resolver::results_type results) {
    auto sp = shared_from_this();
    boost::asio::async_connect(ws->next_layer().next_layer(),
        results.begin(),
        results.end(),
            [&, sp](boost::system::error_code ec) {
               if (ec) {
                   return;
               }
               ws->next_layer().async_handshake(boost::asio::ssl::stream_base::client,
                                                [&, sp](boost::system::error_code ec1) {
                                                    handShake(ec);
                                                });
        }


    );
}


So how to use lambda here?

Why is this result?

Is that about stack? i think the last *p++ is undefined.*p++ means *(p++) or *p;p++;?

void test123()
{

    char s[] = "123", * p;
    p = s;
    // 1 2 3
    cout << *p++ << endl;
    cout << *p++ << endl;
    cout << *p++ << endl;

}
void test321()
{
    char s[] = "123", * p;
    p = s;
    //321
    cout << *p++ << *p++ << *p++ << endl;

}
int main(void)
{
    cout << "123:" << endl;
    test123();
    cout << "123:" << endl;
    test321();
    cout << "hello world" << endl;
    return 0;
}

i think the result is undefined

cmake building external library from github submodule

I am trying to build a sample c++ project with cmake which depends on the external Pisatche library hosted in github. Installation guide list the following steps:

git clone https://github.com/oktal/pistache.git
git submodule update --init

cd pistache
mkdir -p {build,prefix}
cd build
cmake -G "Unix Makefiles" \
    -DCMAKE_BUILD_TYPE=Release \
    -DPISTACHE_BUILD_EXAMPLES=true \
    -DPISTACHE_BUILD_TESTS=true \
    -DPISTACHE_BUILD_DOCS=false \
    -DPISTACHE_USE_SSL=true \
    -DCMAKE_INSTALL_PREFIX=$PWD/../prefix \
    ../
make -j
make install

I would like to install this library from inside cmake and then link it to my executable. Any ideas how to do it?

How to switch templates in C++11 at runtime?

I created a Socket Wrapper. It can be instantiated with two templates:

Socket<asio::ip::udp>
Socket<asio::ip::tcp>

In a Singleton class I want to instantiate one of the two, but I get a runtime parameter which makes the choice. How do I instantiate one of the tow at runtime?

I'm aware of boost::variant, is there a way without?

lundi 27 mai 2019

Return a list of non const pointers by const reference to a list of const pointers

I'm facing this problem where one of my objects has a list of shared_ptrs to some object. so the type is like this list<shared_ptr<some_object>>. But the interface I'm implementing demands that this list be returned from a function with the following signature

const list<shared_ptr<const some_object>>& getObjList().

The compiler won't let me return my list since list<shared_ptr<const some_object>> and list<shared_ptr<some_object>> are not convertable to each other. Is there anyway I can return the required list without having to make a copy whose elements are shared_ptr<const some_object>?

The different between libwebsockets and lwip

What is the different between libwebsockets and lwip? What are the differences in the places they apply?

Using int and nullptr as default parameters is not working [duplicate]

This question already has an answer here:

I am using MSVC2015 compiler in QtCreator.

A class constructor takes two default parameters

class EditorChannel : public QObject
{
    Q_OBJECT
public:
    explicit EditorChannel(int localPort = 31415, QObject *parent = nullptr);
    ...
}

When I try to create an object with one (pointer) parameter like this:

editorChannel = new EditorChannel(this);

I am getting this error:

error: C2664: 'EditorChannel::EditorChannel(const EditorChannel &)': cannot convert argument 1 from 'MyObject *const ' to 'int'

As I know nullptr is not convertable to int. Why compiler cannot resolve constructor's default parameters int and nullptr?

Right now I have one more constructor with one parameter, but it's strange to me that above constructor is not working.

How the insert() function in STL containers works

I am trying to make my own versions of the STL containers (for practice in C++) and I do not fully understand how the insert function works. I understand how to properly call and use the function, but I do not comprehend how to implement my own version of the function. How exactly does the insert function work under the hood. I am referring to the instances of the insert function that take an iterator as one of their parameters.

Pass a function with multiple parameters as an argument

I would like to call a function with multiple parameters as an argument of another function. The assignment asks to pass the counted value(which just so happens to be the same value that is returned from the type integer read_Events function ) as an argument of another function. Although I could just call the function and store it and pass it, I figured it might be a little cleaner to pass the whole function as an argument.

This is for a project for a previous class that I am revising for learning purposes. So far I've tried to store the address of function 2 into a pointer and pass the pointer storing the address of function 2 as an argument of function 1. I've also tried to pass the entirety of function 2 an argument of function 1.

#include<iostream>
#include<conio.h>
#include<string>
using namespace std;
struct Date {
    int month;
    int day;
    int year;
};
struct Time {
     int hour;
     int minute;
};
struct Event {
    char desc[80];
    Date date;
    Time time;
};

int read_Events(Event* Eptr[50], int MAX);
void display(Event* Eptr[50],int(*read_events)(Event , int )) //1. can i 
do this?;
int main() {
    Event* Eptr[50];
     int *Fptr = &read_Events;//#2 Is this possible? (function address 
to pass as arugement in display function)

    _getch();
    return 0;
}

int read_Events(Event* Eptr[50], int MAX) {
    bool repeat = true;
    char ans;
    char slash;
    char colon;
    int i = 0;

    while (repeat && i < MAX) {
        cout << "\nWould you like to add a new event [y/n]? ";
        cin >> ans;

        if (ans == 'Y' || 'y') {
            Eptr[i] = new Event;
            repeat = true;

            cout << "\nEnter description: ";
            cin.clear();
            cin.ignore(256, '\n');
            cin.getline(Eptr[i]->desc, sizeof(Eptr[i]->desc));

            cout << "\nEnter Date(MM/DD/YYYY): ";
            cin >> Eptr[i]->date.month >> slash >> Eptr[i]->date.day >> 
slash >> Eptr[i]->date.year;

            cout << "\nEnter time(HH:MM): ";
            cin >> Eptr[i]->time.hour >> colon >> Eptr[i]->time.minute;
        }
        else {
            repeat = false;
            return i;
        }
            i++;
        }
        return i; //returning number of events
}

It seems as if what I have done so far is not syntactically correct.

Why does std::array not have an operator()?

With C arrays, it's been the case that simply naming an array has the same effect as writing &foo[0] for something approaching 50 years.

When converting from C style arrays to std::array<> in a project I'm working on, the vast majority of "error"s that appeared were due to the above property of C arrays.

In all cases, the solution was trivial, just append .data(). However it occurred to me that a carefully crafted operator() ought to directly solve this issue.

Is there any good reason this operator doesn't exist?

What's wrong with protected members and what's the alternative?

I've been recently told that protected members are bad and after doing some reading it seems that it is indeed the consensus. So what should I do instead?

Let's say I'm working on a set of Widget classes and each and every widget is supposed to have a number of common attributes (e.g. foo, bar and baz). I could define the base class as follows:

class Widget
{
public:
    virtual ~Widget() = default()

    Foo foo() const;
    Bar bar() const;
    Baz baz() const;

    virtual void someInterfaceMethod() = 0;

protected:
    Foo m_foo;
    Bar m_bar;
    Baz m_baz;
};

Widget::foo() { return m_foo; } // etc.

What's so bad about it and what is a better way to implement it? Should I make Widget an inteface only class and then define those members in each and every derived widget? Should I make them private and use get() & set() methods in the constructor of derived class instead? Should I make them private and change Widget constructor to take them as arguments? What if they can't be fully initialized until after construction.

Regex segmentation fault

I have a regex that fires segmentation fault error. After some tests I noticed that [\s\S]*\s+ part of regex is making problems if string is larger than 15 KB, so sometimes it works but sometimes it crashes.

Here is the C++ code compiled with g++ (gcc v. 6.3.0)

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

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

    std::regex regex(
            R"([\s\S]*\s+)",
            std::regex_constants::icase
    );

    std::ifstream ifs("/home/input.txt");
    const std::string input(
            (std::istreambuf_iterator<char>(ifs)),
            (std::istreambuf_iterator<char>())
            );

    std::cout << "input size: " << input.size() << std::endl;

    bool reg_match = std::regex_match(input, regex);

    std::cout << "matched: " << reg_match << std::endl;

}

how to find sum of the absolute differences of one element from all the remaining elements of an array?

this has to be done in complexity less than O(n²) we have an array a[4]={1,2,3,4}. we need to find the absolute differences of all the individual elements with the rest of the elements of the array i.e,

for a[0]->|1-2|+|1-3|+|1-4|=6

for a[1]->|2-1|+|2-3|+|2-4|=4

for a[2]->|3-1|+|3-2|+|3-4|=4

for a[3]->|4-1|+|4-2|+|4-3|=6

and the output we get will be {6,4,4,6}

I did this piece using 2 for loops, but the time complexity becomes O(n²).

SFINAE Template Specialization in Separate Source File

I am working maintenance on a program with a bunch of different structures that are fundamentally similar. I want to write a template method that utilizes SFINAE to enable calling this method from the client. When I define the template specialization inline, everything works as expected. However, when I try to move the template definition into a separate compilation unit, I run into issues. I am trying to move the template implementation into a separate file in order to enable using forward declarations for most of the dependent classes. The following is an example of what I am attempting to achieve:

// Impl.h
#pragma once

struct A {
    struct {
        int value;
    } valueA;
};

struct B {
    struct {
        int value;
    } valueB;
};

template<typename T>
int GetValue(T const &value);

// Impl.cpp
#include "Impl.h"
#include <type_traits>

using std::enable_if_t;
using std::remove_reference_t;

template<typename T, typename U, U(T::*Value)>
static inline int GetValueImpl(T const &value) {
    return (value.*Value).value;
}

template<typename T>
enable_if_t<T::valueA, int> GetValue(T const &value) {
    static constexpr auto T::*const Value = &T::valueA;
    typedef remove_reference_t<decltype(value.*Value)> ValueType;
    return GetValueImpl<T, ValueType, Value>(value);
}

template<typename T>
enable_if_t<T::valueB, int> GetValue(T const &value) {
    static constexpr auto T::*const Value = &T::valueB;
    typedef remove_reference_t<decltype(value.*Value)> ValueType;
    return GetValueImpl<T, ValueType, Value>(value);
}

template<> int GetValue(A const &); // C2912 here
template<> int GetValue(B const &); // C2912 here

I am using VS2017u2, and am getting error C2912: explicitt specialization 'int GetValue(const A &)' is not a specialization of a function template. Does anyone know how to make this work with the definitions in a separate compilation unit?

Volatile cast inside of while loop

I noticed that unless I use something like a Sleep(1) inside of my while loop, it will never break.

while (*Ns::Gl::G == nullptr) Sleep(1); // Works

while (*Ns::Gl::G == nullptr); // Doesn't work

After some research I would think it's because *Ns::Gl::G is changed by another thread or process, this seems likely in my scenario.

So, I tried to do something amongst the lines of:

while (*(volatile TYPE **)&*Ns::Gl::G == nullptr); amongst a lot of other variants of that, and all to no avail.

The way Ns::Gl::G is defined is amongst the lines of:

namespace Ns { struct Gl final { static TYPE** G }; TYPE** Gl::G;}

Does anyone have an idea of how I can turn *Ns::Gl::G into volatile inside of the while loop? MemoryBarrier() works but I'd highly prefer to use the volatile keyword.

TL;DR - volatile cast inside of while loop isn't working due to compiler optimizations~

How to concatenate string in _bstr_t and wchar_t?

I have _bstr_t string and I have wchar_t and one unsigned int variables which I want to put to the string...

_bstr_t strCnn("Driver={SQL 
Server};Server=some_host,some_port;Database=some_db;User 
ID=some_user;Password=some_psw;");

wchar_t *host,
unsigned int port,
wchar_t *user,
wchar_t *password,

These 4 variables I pass to the function which does connection. Can you please guide me how to insert them to connection string. Thank you.

Does a thread synchronize with with the previous thread with same id?

In C++11 there is std::this_thread::get_id() I can use to obtain an std::thread::id identifier of my thread. The standard says:

30.3.1.1

  1. An object of type thread::id provides a unique identifier for each thread of execution and a single distinct value for all thread objects that do not represent a thread of execution (30.3.1). Each thread of execution has an associated thread::id object that is not equal to the thread::id object of any other thread of execution and that is not equal to the thread::id object of any std::thread object that does not represent threads of execution.
  2. thread::id shall be a trivially copyable class (Clause 9). The library may reuse the value of a thread::id of a terminated thread that can no longer be joined.

My question is precisely about the case in which a new thread B, has the same id as an old thread A: will the thread B "see changes made by" thread A?

To be more specific consider this scenario:

Thread A does:

owner.store(std::this_thread::get_id()); //store A's 'id'
...some work...
owner.store(std::thread::id(),std::memory_order_relaxed); // clear

Thread B does:

assert(owner.load(std::memory_order_relaxed) != std::this_thread::get_id());

Will this assert hold?

The owner.load in Thread A and last owner.store in Thread B are intentionally "relaxed", as so there is no obvious "synchronize with" relation between the two, other than the one supposed in my question.

Why the declaration with equal operator is Error when I declare copy initializer is deleted

the class A is declare as follow:

class A {
public:
    A() {
        cout<<"A()"<<'\n';
    }
    A(int i) {
        cout<<"A(int i)"<<'\n';
    }
    A(const A& a_) {
        cout<<"A(const A& a_)"<<'\n';
    }
};

when I initialize 'A' by an integer with equal operator:

int main() {
    A a = 123;
    return 0
}

then it only output: "A(int i)" so I guess it only invoke A::A(int i) and the copy constructor is never used in this situation.

But when I declare "A::A(const A& a_) = delete",the codes as follow:

class A {
public:
    A() {
        cout<<"A()"<<'\n';
    }
    A(int i) {
        cout<<"A(int i)"<<'\n';
    }
    A(const A& a_) = delete;
};
int main() {
    A a = 123;
    return 0;
}

the compiler issues an error: "Copying variable of type 'A' invokes deleted constructor".

so my question is why the copy constructor can't be deleted even it's not invoked in this situation

C++14: auto return type of a function which can return an object of sibling

I have two classes which are inheriting from class Base

class Derived_1:public Base
{
  public:
     getSomeFunc();
};

class Derived_2:public Base
{
  public:
     getSomeFunc();
};

Now what I want to write a function which takes base class pointer object and after dynamic casting finding the appropriate child and returns it so that we can call right version of getSomeFunc()

I tried to write

auto getChild(Base* ptr)
{
  Derived_1 * p = dynamic_cast<Derived_1*>(ptr)
  if(p)
  {
    return p;
  }
  else
  {
      Derived_2 * q = dynamic_cast<Derived_2*>(ptr)
      if(q)
      {
        return q;
      }
     else
     { 
        // some handling to avoid bugs!!
     }
  }

But It does not get compiled. Any way to serve my requirement.

Edit ----------------------------------
Error from compiler is - incorrect deduction of 'auto'. Compile is gcc

Structure init fails with C2280

I have a problem with structure init. It fails with compiler error C2280.

I have a structure like this

struct myStruct final
{
    myStruct() = default;

    int val1;
    int val2;
    bool val3;
    string name;

    myStruct(int _val1, int _val2, bool _val3, string _name) :
    val1(_val1), val2(_val2), val3(_val3), name(_name) {}
};

Then i want to init struct this way

myStruct ms;

This fails with error C2280 - attempting to reference a deleted function.

Dynamic Allocation for a Struct with template

I have a code, which is an implementation of doubly linked list.

template<class T>
struct Node{
    T value;
    struct Node * next_;
    struct Node * prev_;
};

template <class T>
class Dex
{
  public:
    struct Node<T> * head = (struct Node<T> *)calloc(1, sizeof(struct Node<T>));
    struct Node<T> * tail = (struct Node<T> *)calloc(1, sizeof(struct Node<T>));
    struct Node<T> * current = (struct Node<T> *)calloc(1, sizeof(struct Node<T>));

When I compile this, I receive the following error:

[Error] there are no arguments to 'calloc' that depend on a template parameter, so a declaration of 'calloc' must be available [-fpermissive]

I've tried malloc, new etc. But I want to stick to calloc() for this one. Any other method to allocate memory is appreciated, as long as it works and won't throw any SIGSEV.

I expect the code to compile successfully, and be able to initialize a (struct Node *) pointer without having to deal with memory problems.

thread_local global variables give linker error: undefined symbols

I am trying to build a shared object (.so) on AIX, using the IBM xlclang++ compiler (v16.1). The .so uses C++11 concurrency, and I have defined some global variables as thread_local. The linker gives Undefined symbol errors for those variables (and for another symbol).

This code compiles, links, and runs fine on Windows (as a DLL), both when using MS Visual C++ 2019 and clang++ (v9.0.0).

By the way, there are also some thread_local static variables inside a function. (See DoSomething below.) The linker does not complain about those. (It did so before I added the compiler/linker options -qthreaded and -qtls=global-dynamic.)

// --- In GlobData.h: ---
extern thread_local bool GLOB_bTracingEnabled;

// --- In GlobData.cpp: --- (Error: Undefined symbol)
thread_local bool GLOB_bTracingEnabled;

// --- In Calculations.cpp: --- (No problem)
int DoSomething() {
    thread_local static int _staticVar;
    // ...
}

#--- In makefile: ---
INCL1=.
CCC=/opt/IBM/xlC/16.1.0/bin/xlclang++
CCFLAGS1=-q64 -qrtti -qthreaded -qtls=global-dynamic -qmkshrobj -bE:MyDLL.exp -DNDEBUG -I$(INCL1)
CCFLAGS=$(CCFLAGS1) -c
LD=/opt/IBM/xlC/16.1.0/bin/xlclang++
LDFLAGS=$(CCFLAGS1)
LIB_FILE=mydll.so
SOURCEDIR1=.
OBJ_FILES=StdAfx.o GlobData.o Calculations.o
VPATH=$(SOURCEDIR1)
.SUFFIXES: .cpp .o

#Make all:
all :: $(LIB_FILE)

#Compile rule:
.cpp.o:
    $(CCC) $(CCFLAGS) -o$@ $<

#Link rule:
$(OUTDIR)/$(LIB_FILE) : $(OBJ_FILES)
    $(LD) $(LDFLAGS) -o $@ $(OBJ_FILES) 
    strip -t -X64 $@

Link errors:

ld: 0711-317 ERROR: Undefined symbol: .ZTH20GLOB_bTracingEnabled
ld: 0711-317 ERROR: Undefined symbol: .__pt_atexit_np
ld: 0711-345 Use the -bloadmap or -bnoquiet option to obtain more information.

Write a function ASTERISK in C++ Programming

I did a coding that accepts an integer from the user, and output the corresponding number of asterisks. For example:

Please enter a number: 10
* * * * * * * * * * 

I must use function concept to complete the coding only. I managed to get the correct number of asterisks but the '0' at the back just won't disappear.

#include<iostream>
using namespace std;

int NUMBER, i; 
int ASTERISK (int NUMBER);
int main ()

{
    cout << "Enter a number: " ;
    cin >> i ;
    cout << ASTERISK (i); 
    return 0;
}

int ASTERISK (int NUMBER){
    int ANSWER;
    for (NUMBER=1; NUMBER<=i; NUMBER=NUMBER+1){
        cout << "* " ;
    }
    return ANSWER;
}

Which is the best way to yield thread?

Program language: C++ 11
I use pipeline threads mode to deal data.
One thread generate data.
One thread process data.
While no data to deal, which is the best way to yield thread?
Now I use

std::this_thread::sleep_for(100ms); 

  1. I wonder if there is a better way to yield?
  2. If sleep is well enough, how long time to sleep is better?

Real-world portability of equal-rank unsigned to signed conversion

Take the following code

#include <iostream>

int main() {
    unsigned char i = 128;
    signed char j = i;
    std::cout << static_cast<int>(j) << '\n';
}

compiling on GCC, this produces -128 as most programmers would naturally expect (when assuming CHAR_BIT == 8, which is a safe assumption in 2019). Now, I am fully aware that the initialisation signed char j = i; invokes implementation-defined behaviour in C++ standards before C++20.

My question: Realistically speaking, does anybody know of a semi-interesting compiler implementation of C++ that does not just do the obvious thing (i.e. a no-op in the above case). By semi-interesting, I mean compilers I can realistically encounter, not some prototype Unisys C++ compiler from 1985 for an obscure 43-bit architecture that only the DoD has access to. GCC documents the above behaviour in its documentation, Clang doesn't, but the observable behaviour is the same. My feeling is that there are none, and that this conversion, while formally implementation-defined behaviour, is portable in practice.

Custom allocators as alternatives to vector of smart pointers?

This question is about owning pointers, consuming pointers, smart pointers, vectors, and allocators.

I am a little bit lost on my thoughts about code architecture. Furthermore, if this question has already an answer somewhere, 1. sorry, but I haven't found a satisfying answer so far and 2. please point me to it.

My problem is the following:

I have several "things" stored in a vector and several "consumers" of those "things". So, my first try was like follows:

std::vector<thing> i_am_the_owner_of_things;
thing* get_thing_for_consumer() {
    // some thing-selection logic
    return &i_am_the_owner_of_things[5]; // 5 is just an example
}

...

// somewhere else in the code:
class consumer {
    consumer() {
       m_thing = get_thing_for_consumer();
    }

    thing* m_thing;
};

In my application, this would be safe because the "things" outlive the "consumers" in any case. However, more "things" can be added during runtime and that can become a problem because if the std::vector<thing> i_am_the_owner_of_things; gets reallocated, all the thing* m_thing pointers become invalid.

A fix to this scenario would be to store unique pointers to "things" instead of "things" directly, i.e. like follows:

std::vector<std::unique_ptr<thing>> i_am_the_owner_of_things;
thing* get_thing_for_consumer() {
    // some thing-selection logic
    return i_am_the_owner_of_things[5].get(); // 5 is just an example
}

...

// somewhere else in the code:
class consumer {
    consumer() {
       m_thing = get_thing_for_consumer();
    }

    thing* m_thing;
};

The downside here is that memory coherency between "things" is lost. Can this memory coherency be re-established by using custom allocators somehow? I am thinking of something like an allocator which would always allocate memory for, e.g., 10 elements at a time and whenever required, adds more 10-elements-sized chunks of memory.

Example:
initially:
v = ☐☐☐☐☐☐☐☐☐☐
more elements:
v = ☐☐☐☐☐☐☐☐☐☐ 🡒 ☐☐☐☐☐☐☐☐☐☐
and again:
v = ☐☐☐☐☐☐☐☐☐☐ 🡒 ☐☐☐☐☐☐☐☐☐☐ 🡒 ☐☐☐☐☐☐☐☐☐☐

Using such an allocator, I wouldn't even have to use std::unique_ptrs of "things" because at reallocation time, the memory addresses of the already existing elements would not change.

As alternatives, I can only think of referencing the "thing" in "consumer" via a std::shared_ptr<thing> m_thing, as opposed to the current thing* m_thing but that seems like the worst approach to me, because a "thing" shall not own a "consumer" and with shared pointers I would create shared ownership.

So, is the allocator-approach a good one? And if so, how can it be done? Do I have to implement the allocator by myself or is there an existing one?

How to iterate over a map string keys with unique_ptr's as values?

This is a follow up question on this one.

I am using the dlopen and dlclose functions to load/unload a shared library. (They both return void*).
I am saving the dlopen handle inside a dictionary.
Every time an element is erased from the map, dlclose function should be called automatically.

This is what I have:

auto closeFunc = [](void* vp) {
  dlclose(vp);
};
using HandlePtr = std::unique_ptr<void, decltype(closeFunc)>;
std::map<std::string, HandlePtr> handles;

HandlePtr handle(dlopen(path.c_str(), RTLD_LAZY), closeFunc );
handles[nameStr] = std::move( handle );

My issue is when I want to iterate over the keys of the map (strings) and print them, it forces me to take the address:

vector<string> loadedLibraries;

for(auto& kv: handles) {
    loadedLibraries.push_back(kv.first);
}

return loadedLibraries;

Because of this it will clear my map when loadedLibraries goes out of scope.
If I don't take the reference I have a compilation error "using a deleted function".

I am kinda confuse by this. What is the proper way to retrieve the keys from the map ?

Extract m-n range of bits from data

I have a 16 byte data with me. I need to extract and print different fields of data from that like fist 3 bits, next 11 bits, next 7 bits etc..

Segmentation fault when passing big integers as values in vector

Getting segmentation fault(Core Dumped) when big integers are passed.It works fine for smaller inputs.

Replaced int with long int and also tried to declare the variables globally,But still the same error. Here is the function:

vector<long long int> circularArrayRotation(vector<long long int> a, long long int k, vector<long long int> queries) {
    vector <long long int> b;
    std::vector<long long int> result(queries.size());

    b=a;
    for(long long int j=0;j<k;j++)
    {
        for(long long int i=0;i<a.size();i++)
            a[i]=b[(a.size()+i-1)%a.size()];
        b=a;
    }

    for(long long int k=0;k<queries.size();k++)
        result[k]=a[queries[k]];
    for(long long int i=0;i<result.size();i++)
            cout<<result[i]<<endl;

    return result;

}