jeudi 28 février 2019

How can `std::error_category` safely be used in static destructors?

Consider a custom error type written using the LLVM system_category implementation for reference:

#include <iostream>
#include <system_error>

struct my_error_category_type : std::error_category {
    char const* name() const  noexcept override { return "name"; }
    std::string message(int i) const noexcept override{ return "message"; }
    ~my_error_category_type() {
        std::cout << "Destroyed the category" << std::endl;
    }
};

std::error_category const& my_error_category() noexcept {
    static my_error_category_type c;
    return c;
}

Now imagine the following simple class that uses std::error_code to handle errors:

std::error_code do_some_setup() {
    return std::error_code(1, my_error_category());
}
std::error_code do_some_cleanup() {
    return std::error_code(2, my_error_category());
}

struct MyObj {
    void method() {
        // this constructs the category for the first time
        auto err = do_some_setup();
        std::cout << err << std::endl;
    }

    ~MyObj() {
        std::cout << "Running cleanup" << std::endl;
        auto err = do_some_cleanup();
        std::cout << err << std::endl;
    }
};

The following code gives alarming output

static MyObj obj;

int main() {
    obj.method();  // remove this line, and the output is fine
}

name:1
Destroyed the category
Running cleanup
name:2

Note how my_error_category_type::message was called on a destructed object!

My questions are:

  1. Is calling message on this destructed object safe?
  2. If not, is there a way to preserve the lifetime of the category? Can I make the object immortal somehow?
  3. Does the standard make any guarantees about the lifetime of the builtin std::system_category() objects and the like? The LLVM implementation I link to above suffers exactly the same problem.

runtime polymorphic invocation of pure virtual function via std::reference_wrapper behaving inconsistently

I present to you this code riddle:

Using this compiler:

harrynh3@bruh:~/test$ g++ --version

g++ (Ubuntu 7.3.0-16ubuntu3) 7.3.0 Copyright (C) 2017 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

...and this compile string:

g++ main.cpp class.cpp -o main -g

...and these files:

class.hpp:

class base {

  public:

    base();

    virtual void f() = 0;
};

class derived : public base {

  public:

    derived( unsigned int id );

    void f() override;

    unsigned int id; 
};

class.cpp:

#include <iostream>

#include "class.hpp"

base::base() {

  return;
}

derived::derived( unsigned int id )
  :
  id( id ),
  base() {

  return;
}

void derived::f() {

  std::cout << "Ahoy, Captain! I am " << id << std::endl;

  return;
}

main.cpp:

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

#include "class.hpp"

int main() {

  unsigned int n_elements;

  std::cout << "enter the number of elements: ";

  std::cin >> n_elements;

  std::cout << std::endl;

  std::vector< class derived > v;

  std::vector< std::reference_wrapper< class base > > base_vector_0;

  std::vector< std::reference_wrapper< class base > > base_vector_1;

  for( unsigned int i = 0; i < n_elements; i++ ) {

    v.emplace_back( i );

    base_vector_0.emplace_back( v[ i ] );
  }

  for( unsigned int i = 0; i < n_elements; i++ ) {

    base_vector_1.emplace_back( v[ i ] );
  }

  std::cout << "sanity check:" << std::endl;

  for( unsigned int i = 0; i < n_elements; i++ ) {

    class base &base = v[ i ];

    base.f();
  }

  std::cout << "case 1:" << std::endl;

  for( unsigned int i = 0; i < n_elements; i++ ) {

    base_vector_1[ i ].get().f();
  }

  std::cout << "case 0:" << std::endl;

  for( unsigned int i = 0; i < n_elements; i++ ) {

    base_vector_0[ i ].get().f();
  }

  return 0;
}

...I get the following output:

harrynh3@bruh:~/test$ ./main
enter the number of elements: 1

sanity check:
Ahoy, Captain! I am 0
case 1:
Ahoy, Captain! I am 0
case 0:
Ahoy, Captain! I am 0
harrynh3@bruh:~/test$ ./main
enter the number of elements: 2

sanity check:
Ahoy, Captain! I am 0
Ahoy, Captain! I am 1
case 1:
Ahoy, Captain! I am 0
Ahoy, Captain! I am 1
case 0:
Segmentation fault (core dumped)

My questions:

  1. Why does this not segfault when the user supplied argument = 1?

  2. Why does this segfault when the user supplied argument > 1?

My short explanation of what the code does:

Creates many objects derived from an abstract base class. Stores references to the objects in containers as std::reference_wrapper around abstract base class reference. Creates the containers of std::reference_wrapper slightly differently. Calls the derived override of pure virtual function via the std::reference_wrappers. Segfaults specifically in the case denoted in the source code above.

I implore the C++ experts... Please help me! This is fascinating and I have no idea why it is happening! I've probably done something dumb.

Why Numbers are getting printed in the form like "12-256" , "13-256" rather than 12,13 etc.?

I'm solving one of the algorithms problem from university to implemet queue using stacks. I've got my logic right i guess but the numbers are getting printed in the form of 12-256, 13-256, 14-256 instead of 12,13,14.

Here's my C++ Code,

#include <iostream>

using namespace std;

class Stack{

private:
    int arr[200];
    int tos = -1;

public:

    bool empty(){
        return (tos == -1)?true:false;
    }

    void push(int element){
        arr[++tos] = element;
    }

    int pop(){
        return arr[tos--];
    }

    void show(){
        if(tos == -1){
            cout<<"stack empty";
        }else{
            for(int i=tos;i>0;i--)
                cout<<arr[i]<<"\t";
        }
    }

};


class Queue{

private:
    Stack s1,s2;


public:
    void enQueue(int x){

        //just using s1 to add new elements
        s1.push(x);
    }

    int deQueue(){

        if(s1.empty())
            throw 'e';

        else{
            int e;
            while(!s1.empty()){
                e = s1.pop();
                s2.push(e);
            }

            cout<<"\nelement to be removed:"<<s2.pop();

            if(s2.empty())
                throw 'f';

            else{
                int e;
                while(!s2.empty()){
                    e = s2.pop();
                    s1.push(e);
                }
            }
        }

    }
};

int main()
{
    try{
        Queue q1;
        q1.enQueue(12);
        q1.enQueue(13);
        q1.enQueue(14);
        q1.enQueue(15);

        cout<<q1.deQueue();
        cout<<q1.deQueue();
        cout<<q1.deQueue();
        cout<<q1.deQueue();
    }catch(char c){
        cout<<"\nstack empty!";
    }

    return 0;
}

Here's my Output.

I'm basically a Python Guy so i'm not able to figure out what's wrong with this code.

I'm new to C++, so please guide me through this.

Thanks in advance!

unable to create FFMpeg filters via c++ application

I am trying to follow ffmpeg filter_audio.c example .

i am constructing the filter graph as below, but not able to get volume level after processing , silence filter working well but not volumedetect filter.

int Filter :: audio_filter_init(AVCodecContext *aCodecctx)
{

        AVCodecContext  *aCodecCtx = aCodecctx;
    char ch_layout[64];
    int err;

    //AVRational time_base = pFormatCtx->streams[audioindex]->time_base; 
        AVRational time_base = aCodecctx->time_base;  
    /* Create a new filtergraph, which will contain all the filters. */
    filter_graph = avfilter_graph_alloc();
    if (!filter_graph) {
        fprintf(stderr, "Unable to create filter graph.\n");
        return AVERROR(ENOMEM);
    }

    /* Create the abuffer filter;
     * it will be used for feeding the data into the graph. */
    abuffer = avfilter_get_by_name("abuffer");
    if (!abuffer) {
        fprintf(stderr, "Could not find the abuffer filter.\n");
        return AVERROR_FILTER_NOT_FOUND;
    }

    abuffer_ctx = avfilter_graph_alloc_filter(filter_graph, abuffer, "src");
    if (!abuffer_ctx) {
        fprintf(stderr, "Could not allocate the abuffer instance.\n");
        return AVERROR(ENOMEM);
    }


    if (!aCodecCtx->channel_layout)
        aCodecCtx->channel_layout = av_get_default_channel_layout(aCodecCtx->channels);


    /* Set the filter options through the AVOptions API. */
    av_get_channel_layout_string(ch_layout, sizeof(ch_layout), 0, aCodecCtx->channel_layout);    
    av_opt_set    (abuffer_ctx, "channel_layout",ch_layout , AV_OPT_SEARCH_CHILDREN);
    av_opt_set    (abuffer_ctx, "sample_fmt",     av_get_sample_fmt_name(aCodecCtx->sample_fmt), AV_OPT_SEARCH_CHILDREN);
    av_opt_set_q  (abuffer_ctx, "time_base",      (AVRational){ 1, aCodecCtx->sample_rate},  AV_OPT_SEARCH_CHILDREN);
    av_opt_set_int(abuffer_ctx, "sample_rate",    aCodecCtx->sample_rate, AV_OPT_SEARCH_CHILDREN);

    /* Now initialize the filter; we pass NULL options, since we have already
     * set all the options above. */
    err = avfilter_init_str(abuffer_ctx, NULL);
    if (err < 0) {
        fprintf(stderr, "Could not initialize the abuffer filter.\n");
        return err;
    }

    silence = avfilter_get_by_name("silencedetect");

    if (!silence) {
        fprintf(stderr, "Could not find the silencedetect filter.\n");
        return AVERROR_FILTER_NOT_FOUND;
    }
    silent_ctx = avfilter_graph_alloc_filter(filter_graph, silence, "silencedetect");
    if (!silent_ctx) {
        fprintf(stderr, "Could not allocate the silencedetect instance.\n");
        return AVERROR(ENOMEM);
    }

    av_opt_set_dict_val (silent_ctx, "duration", (const AVDictionary*)AV_STRINGIFY(5),0);
    av_opt_set_dict_val (silent_ctx, "noise",  (const AVDictionary*)AV_STRINGIFY(-30db),0); 
    err = avfilter_init_str(silent_ctx, NULL);
    if (err < 0) {
        fprintf(stderr, "Could not initialize the silencedetect filter.\n");
        return err;
    }

        std::cout << "volume" << std::endl;
    volumedet = avfilter_get_by_name("volumedetect");
    if (!volumedet) {
        fprintf(stderr, "Could not find the volumedetect filter.\n");
        return AVERROR_FILTER_NOT_FOUND;
    } 
    volume_ctx = avfilter_graph_alloc_filter(filter_graph, volumedet, "volumedetect");
    if (!volume_ctx) {
        fprintf(stderr, "Could not allocate the volumedetect instance.\n");
        return AVERROR(ENOMEM);
    }
    /* Finally create the abuffersink filter;
     * it will be used to get the filtered data out of the graph. */
    abuffersink = avfilter_get_by_name("abuffersink");
    if (!abuffersink) {
        fprintf(stderr, "Could not find the abuffersink filter.\n");
        return AVERROR_FILTER_NOT_FOUND;
    }
    abuffersink_ctx = avfilter_graph_alloc_filter(filter_graph, abuffersink, "sink");
    if (!abuffersink_ctx) {
        fprintf(stderr, "Could not allocate the abuffersink instance.\n");
        return AVERROR(ENOMEM);
    }
    /* This filter takes no options. */
    err = avfilter_init_str(abuffersink_ctx, NULL);
    if (err < 0) {
        fprintf(stderr, "Could not initialize the abuffersink instance.\n");
        return err;
    }
    /* Connect the filters;
     * in this simple case the filters just form a linear chain. */
    err = avfilter_link(abuffer_ctx, 0, silent_ctx, 0);    
    if (err >= 0)
        err = avfilter_link(abuffer_ctx, 0, volume_ctx, 0);
    if (err >= 0)
        err = avfilter_link(volume_ctx, 0, abuffersink_ctx, 0);    
    if (err < 0) {
        fprintf(stderr, "Error connecting filters\n");
        return err;
    }
    /* Configure the graph. */
    err = avfilter_graph_config(filter_graph, NULL);
    if (err < 0) {
        av_log(NULL, AV_LOG_ERROR, "Error configuring the filter graph\n");
        return err;
    }

        return 0;

}



below information i am getting in vprintf tb:1/44100 samplefmt:fltp samplerate:44100 chlayout:stereo auto-inserting filter 'auto_resampler_0' between the filter 'src' and the filter 'volumedetect' query_formats: 4 queried, 6 merged, 3 already done, 0 delayed Using fltp internally between filters ch:2 chl:stereo fmt:fltp r:44100Hz -> ch:2 chl:stereo fmt:s16 r:44100Hz Using fltp internally between filters

can someone help to detect volume level

Cannot convert string to char* for argument 1

I am having an issue with my C++ code for converting a string of numbers in base b to another base n. My error is as follows:

cannot convert ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ to ‘char*’ for argument ‘1’ to ‘int base_to_decimal(char*, int)’

I am using g++ to compile and I have been for a while, so I thought at first I knew what the issue was. It says that the method base_to_decimal accepts two arguments: one of type char* and one of type int. So all I should have to do to fix my issue is change the char* argument to a string right? Well I looked and the code for the function in question is:

int base_to_decimal(std::string input_base, int base)

So this method SHOULD be expecting a string, but for some reason when I pass in a string it gets angry at me. If someone could help me figure this out that would be fantastic. I am using g++ 7.3.0 and running all this on Linux Mint 19.1.

How to use templates while separating header and implementation files?

I'm trying to implement a Template while separating the Header and Implementation file.

I'm getting this error when building the project:

error C2955: 'Series': use of class template requires template argument list

Header.h

#ifndef SERIES_H
#define SERIES

template <class T>
class Series {
    private:
        T var;

    public:
        Series(T v);
    };

#endif

Implementation.cpp

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

template <class T>
Series::Series(T v) {
    var = v;
    std::cout << var;
}

Main.cpp

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

int main() {
    Series<int> w(10);
}

The project builds successfully when everything is in one file

What do I need to do to make this work?

Opencv Multithreaded Image Streams

I have several cameras that I'm capturing images for in real-time with a thread for each camera.

I have a pub sub format right now so the saving isn't in real time but the frame capturing is at the rated frame rate for the camera. I decided to separate the image display from the image capture so that the frame capturing is not (potentially) locked by the io. I'm wondering whether opencv's imshow can only be accessed by a single thread at any given time - can I show multiple image streams? At present, I'm getting a seg fault at:

void h::viewImage(std::shared_ptr<CamHandle> cam, //this is a thread
                  bool &cancellation_token,
                  std::shared_ptr<queue<cv::Mat> > q,
                  std::mutex &cancellation_token_mutex,
                  std::shared_ptr<interThread_signalling<bool> > saveSignal) {

  std::string name = "Camera@" + cam->getIPAsString();
  cv::namedWindow(name); //I'm getting a seg fault here
  cv::Size windowSize(cam->width, cam->height);
  cv::Mat im;
  while (!cancellation_token) {
    q->peek(im); //There is a queue of these images from the frame capture thread

    if (cam->show_images == "true") {
      if (!im.empty()) {
        cv::imshow(name, im);
      } 
  }
}

This is the interThread_signalling class:

#include <queue>
#include <mutex>
#include <condition_variable>

template<typename T>
class interThread_signalling {
 protected:
  T signal;
  mutable std::mutex the_mutex;
  std::condition_variable the_condition_variable;

 public:
  interThread_signalling() = default;

  ~interThread_signalling() = default;

  void modify(const T &data) {
    std::unique_lock<std::mutex> lock(the_mutex);
    this->signal = data;
    lock.unlock();
    the_condition_variable.notify_one();
  }

  void peek(T &peeked_value) {
    std::unique_lock<std::mutex> lock(the_mutex);
    if (this->signal == NULL) {
      return;
    } //this will always lag behind by one
    peeked_value = this->signal;
  }

};

Should I be calling the namedWindow command in the main thread - once my program determines how many cameras there are, should I create n namedWindows? How should I be doing this?

How to save incrementally images loaded on a QGraphicsView using QPushButton & OpenCV::imwrite

I prepared this small verifiable .ui in Figure 1 that replicates the issue I have:

small example

I am trying to use the QPushButton "Print Screen Both Images" to incrementally save images on Left and Right of the QGraphicsView into two different folders present on my Desktop, see below Figure 2:

destination_folders

I can take a print screen of either the leftScene or the rightScene by just clicking on their related QPushButton Print Screen Left and Print Screen Right.

However, I am trying for this specific case not to use QFileDialog as I need to silently and incrementally save the images in the two different destination folders as I move on with the right/left arrow.

See below the snipped of code I am using:

mainwindow.h

public:
    void bothPrintScreen(const std::string& pathImg);
private slots:
    void on_bothPrintScreen_clicked(const std::string& imgPath);
private:
    int counterA=0;
    int counterB=0;

mainwindow.cpp

void MainWindow::on_bothPrintScreen_clicked(const std::string& imgPath)
{
    bothPrintScreen(imgPath);
}

void MainWindow::bothPrintScreen(const std::string& pathImg){
    cv::Mat left, right;
    std::string outA = pathImg+"/printScreenA_"+std::to_string(counterA++)+".png";
    cv::imwrite(outA,left);
    std::string outB = pathImg+"/printScreenB_"+std::to_string(counterB++)+".png";
    cv::imwrite(outB,right);
}

I am missing something in the code but I am not sure what exactly.

The compiler is seinding this allocate()/deallocate() error that I don't understand:

compiler_error

Please shed light on this matter.

Is repeatedly calling move with rvalue references necessary?

struct Bar
{    
   Bar(std::string&& val)
    : m_Val(std::move(val)) {} // A

  Bar& operator=(Bar&& _other) { m_Val = std::move(_other.m_Val); }
  std::string m_Val;
}

struct Foo
{
  void Func1(Foo&& param)
  {
     Func2(std::move(param)) // B
  }

  void Func2(Foo&& param)
  {
     m_Bar = std::move(param); // C
  }

  Bar m_Bar;
};

void main()
{
   Foo f;
   std::string s = "some str";
   Bar b(std::move(s));
   f.Func1(std::move(b));
}

Give that you're calling move in main() to invoke the rvalue reference methods, is it necessary in lines A & B & C to repeat an additional call to move()? You already have the rvalue parameter, so is it doing anything different in those lines with vs without?

I understand in Bar's operator= it's necessary because you're technically moving the m_Val rather than _other itself correct?

nofify_all() crashes when the program is closed

I have a very simple C++ program like below. When I close this application, it sometimes crashing while calling notify_all() on the condition variable. Can anybody give me a hint about the reason?

I have checked lots of Q/As on SO, but non of them solved my problem. I work on windows 7 and VS 2013.

    class B;

    class C
    {
    public:
        C(const std::weak_ptr<B>& b) : mB(b)
        {
        }
        virtual ~C() 
        {
        }

        void run()
        {
            while (true)
            {
                std::unique_lock<std::mutex> uLock(mMutex);

                // Wait until some event is happening
                mCondition.wait_for(uLock, std::chrono::seconds(300));

                if (!mStop)
                {
                    //do something here
                }
                else
                {
                    return;
                }
            }
        }


        void start()
        {
            mThread = std::thread(&C::run, this);
        }

        void stop()
        {
            mStop = false;
        }

        void notify()
        {
            mCondition.notify_all();
        }

        void join()
        {
            if (mThread.joinable())
            {
                mThread.join();
            }
        }

        private:
            std::atomic<bool> mStop;
            std::condition_variable mCondition;
            std::mutex mMutex;
            std::thread mThread;
            std::weak_ptr<B> mB;
        };


    class B : public std::enable_shared_from_this<B>
    {
    public:
        B() {}
        ~B()
        {
            if (mC)
            {
                mC->stop();
                mC->notify();
                mC->join();
            }
        }

        // basic methods
        void init()
        {
            mC = std::unique_ptr<C>(new C(shared_from_this()));
            mC->start();
        }

    private:
        std::unique_ptr<C> mC;
    };

    class A
    {
    public:
        ~A(){}

        void init() { pImpl->init(); }

        static std::shared_ptr<A> getInstance(){
            static std::shared_ptr<A> instance(new A);
            return instance;
        }

    private:
        A() : pImpl(std::make_shared<B>()){}
        std::shared_ptr<B> pImpl;
    };


    void main()
    {
        std::shared_ptr<A> a = A::getInstance();
        a->init();

        int x;
        std::cin >> x;
    }

MSVC 19 delete inherited constuctors

Under MSVC 19.16, if class B explicitly inherits from class A the constructors, and also defines his own constructors, the inherited constructors are ignored.

class A {
public:
    A() {}
    A(int x) {}
};

class B : public A {
public:
    using A::A;

    B(double x) : A() {}
};

int main()
{
    B b;                 // error C2512: 'B': no appropriate default constructor available
                         // note: see declaration of 'B'
    return 0;
}

Compiles correctly under gcc. Anyone knows if it is a compiler bug, or something I miss? Thanks.

Linking binaries built with different compilers (gcc, intel, and clang)

I have a code that compromises vastly different languages e.g. Fortran, C, C++, and Python. To be precise my code is a very old Fortran/C++ numerical simulator with in situ libraries used from Paraview/Catalyst. In order to use these, I have to link them to OSMesa or Mesa's Software Galium3D. The thing is I want to use different compilers for these different parts. For now, first runs are working and I build the simulator with Intel Compiler and the rest using GCC.

I wonder should I expect any problem in the future for linking these binaries (statically or dynamically but mostly static) which have been compiled with completely different compilers but all on Linux and the same CPU architecture.

The whole building process is using CMake. So the second part is can I do something in the cmake's build process which inhibits the future hazardous situations?

Cereal serialisation issue for std::chrono with dynamic library

I have a problem with cereal library (http://uscilab.github.io/cereal/).

I have a shared library, and I would like to serialize one of its classes using cereal library. It has a member of time_point from std::chrono

Here is a part of the code of my object in Event.h

    #include <cereal/types/chrono.hpp>
    #include <cereal/types/string.hpp>

    class EventBase
    {
    private:
         std::string m_Id;
         std::chrono::high_resolution_clock::time_point m_StartTime;
    public:
        template<class Archive> void serialize(Archive & archive)
        {
          archive(m_Id, m_StartTime);
        }

The library compiles without a problem. Then I would like to use my library in an executable where I try to serialize one of the object:

    #include <cereal/archives/json.hpp>
    cereal::JSONOutputArchive output(std::cout);
    output(API::Event());

This code does not compile and it is complaining about the missing serialize function for the time_point. If I intend to serialize only the string it compiles.

'openMVG/numeric/numeric.h' file not found

I try to install the openMVG from source by using make and make install. After that, I write the CMakeLists file like the following to link the library.

cmake_minimum_required(VERSION 3.0)
find_package(OpenMVG REQUIRED)
include_directories(${OPENMVG_INCLUDE_DIRS})
add_executable(test main.cpp)
target_link_libraries(test ${OPENMVG_LIBRARIES})

The cmake log information is as the following.

-- The C compiler identification is AppleClang 10.0.0.10001145
-- The CXX compiler identification is AppleClang 10.0.0.10001145
-- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc
-- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++
-- Check for working CXX compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Looking for pthread.h
-- Looking for pthread.h - found
-- Looking for pthread_create
-- Looking for pthread_create - found
-- Found Threads: TRUE  
-- ----
-- OpenMVG Find_Package
-- ----
-- Found OpenMVG version: 1.4.0
-- Installed in: /usr/local
-- ----
-- Configuring done
-- Generating done
-- Build files have been written to: /Users/zsk/Downloads/programming/test_openmvg/build

My code is as the following.

#include <iostream>
#include <openMVG/numeric/numeric.h>

int main()
{
    Mat2X xy ( 2 , 5);
// Defines some data points
    xy << 1, 2, 3, 4,  5, // x
          3, 5, 7, 9, 11; // y

// The base model estimator and associated error metric
    LineKernel kernel ( xy );

    // Call the Max-Consensus routine
    std::vector<uint32_t> vec_inliers;
    Vec2 model = MaxConsensus ( kernel , ScorerEvaluator<LineKernel >(0.3) , &-vec_inliers );
    std::cout << "Finish " << std::endl;
    return 0;
}

I make sure I install the openMVG successfully. I am not very familiar with the compilation of C++ program. It is very strange that I get the following error.

/Users/zsk/Downloads/programming/test_openmvg/main.cpp:2:10: fatal error: 
      'openMVG/numeric/numeric.h' file not found
#include <openMVG/numeric/numeric.h>

c++ repeat N iterations

I can clearly do something like this:

for(int i = 0; i < 10000; i++)
    testIteration();

But is there any std functions which does similar thing in one line? Something like that:

std::repeat(10000, testIteration);

mercredi 27 février 2019

C++ class constructor no matching function for call to

Hi i try to creat one object t of the class Test but i have this error : no matching function for call to ‘testZEG::Test::Test(std::__cxx11::string&, std::__cxx11::string&, std::__cxx11::string&, std::__cxx11::string&)

// test.h

namespace testZEG{
class Test{
    public:
        Test(const std::string& param_1, const std::string& param_2, int param_3);
    private:
        std::string param_1;
        std::string param_2;
        int param_3;
};
}


// test.cpp
namespace testZEG{
    Test::Test(const std::string& param_1, const std::string& param_2, int param_3,)
    : m_param_1(param_1), m_param_2(param_2),m_param_3(param_3) {}
}

//main.cpp

int main(){
    string p1, p2, p3;
    char buffer[256];

    cin.getline(buffer, 255);
    p1= buffer;
    cin.getline(buffer, 255);
    p2= buffer;
    cin.getline(buffer, 255);
    p3= buffer;

    Test t(p1, p2, p3);
}

What is the cause ? How can i fix it ? thank's in advance

Can I create a template (non-type) param class that can take any enum? C++11

Here is a snippet of some example code that does recursion on templates. I am trying to create an algorithm that takes any enum (from 0...n, sequential) and performs an 'algorithm' based on those values using traits (does this recursively by subtracting the largest enum by 1).

#include <iostream>
using namespace std;

enum enum_type : size_t
{
    DEFAULT = 0,
    ONE = 1,
    TWO = 2,
    THREE = 3,
    FOUR = 4,
    MAX = FOUR,
};

template < enum_type F >
struct traits;

template < >
struct traits<ONE>
{
    static void do_something() {}
};

template < >
struct traits<TWO>
{
    static void do_something() {}
};

template < >
struct traits<THREE>
{
    static void do_something() {}
};

template < >
struct traits<FOUR>
{
    static void do_something() {}
};

template < enum_type F, typename TT = traits<F> >
struct attr_engine
{
    static void set()    {
        printf("Number: %lu ", F);

        TT::do_something();

        // get a compile error of trying to subtract an enum to an integer
        constexpr enum_type NEXT_FIELD = static_cast<enum_type>(F - 1);
        attr_engine<NEXT_FIELD>::set();
        return;
    }
};

template < >
struct attr_engine<DEFAULT, traits<DEFAULT>>
{
    static void set()    {
    printf("Reached the end");
    return;
    }
};

int main()
{
   attr_engine<MAX>::set();

   return 0;
}

I would like to create this into a "generic" algorithm that can take any enum (enum_type2 instead of only enum_type, etc.) but I'm not quite sure how to to do this with non-type template params, or it is even possible.

I can't use typename because I'm using a non-type template param.

template < typename F, typename TT = traits<F> >
struct attr_engine

As an alternative, I've considered using a size_t potentially:

template < size_t F, typename TT = traits<F> >
struct attr_engine

But trying to create a generic F that can be deduced into its appropriate trait is something I'm stuck on. I need some new approaches. I'm worried that doing that would cause me to cast the input non-template param which looks messy.

enum enum_type2
{
    DEFAULT_ENUM2,
    ONE_VAL,
    TWO_VAL,
    THREE_VAL,
    FOUR_VAL,
    ENUM2_MAX = FOUR_VAL,
};

int main()
{
   attr_engine<static_cast<sizet>(ENUM2_MAX)>::set();

   return 0;

}

Converting ISO::DateTime to number format

I want to change the date time format to numbers only so that it can be incremented.

Current Implementation is saved as QString 2019-03-13T09:01:22+01:0 Expected result: 201903120858031

what is mean "v.template is

c++ code

template <typename F, typename V, typename R, typename T, typename... Types>
struct dispatcher<F, V, R, T, Types...>
{
    VARIANT_INLINE static R apply_const(V const& v, F&& f)
    {
        if (v.template is<T>())
        {
            return f(unwrapper<T>::apply_const(v.template get_unchecked<T>()));
        }
        else
        {
            return dispatcher<F, V, R, Types...>::apply_const(v, std::forward<F>(f));
        }
    }

    VARIANT_INLINE static R apply(V& v, F&& f)
    {
        if (v.template is<T>())
        {
            return f(unwrapper<T>::apply(v.template get_unchecked<T>()));
        }
        else
        {
            return dispatcher<F, V, R, Types...>::apply(v, std::forward<F>(f));
        }
    }
};

what is mean v.template is<T>() in this c++ prog? i cannot find any "is" function, this v.template is<T>() is system inner function or keyword with v.template get_unchecked<T>().

Random math generator C++

I have to create a program that generates a random math quiz with random operators and numbers. The problems I'm having so far are with: Division - I need for the user to be able to input 2.5 for a question like 5/2. I tried using float and double but I'm not sure I was using them correctly. Looping - My program only asks one question and then quits. Positive Answers - The program also needs to be very simple, not including negative integers anywhere. I get problems like 3 - 6 which equals -3 and I'm not sure how to avoid this. Any advice would help a lot! Sorry for all the questions, I'm very new to C++

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

int main () {
    int a, b, q, answer;
    bool correct = false;

    do {
        srand(time(NULL));
        a = rand() % 21;
        b = rand () % 10;
        char op = "+-*/" [rand() % 4];

        cout << "What is " << a << " " << op << " " << b << "? (q to quit) ";
        cin >> answer;

        switch (op) {
            case '+':
                if (answer == a + b) correct = true;
                break;
            case '-':
                if (answer == a - b) correct = true;
                break;
            case '/':
                if (answer == a / b) correct = true;
                break;
            case '*':
                if (answer == a * b) correct = true;
                break;
        }

        if (correct == true) {
            cout << "Good job!" << endl;
        } else {
            cout << "Incorrect." << endl;
            }

        if (answer = 'q') {
            break;
        }
    } while (answer != 'q');
}

How to convert a vector of integer arrays into a 2D array in C++?

So I have been looking at the following post for converting a vector into an array but this method does not seem to be converting for my use case.

How to convert vector to array

vector<int[256]> table; // is my table that I want to convert

// There is then code in the middle that will fill it

int** convert = &table[0][0] // is the first method that I attempted

convert = table.data(); // is the other method to convert that doesn't work

I belive my understanding of the back end of the data type is where my knowledge falls short. Any help on this would be appreciated

Can't get live video with uEye and OpenCV

i'm using an IDS camera, and I would like to do some video processing but i can't get the video live. I'm using QtCreator (C++) with OpenCV and uEye, the problem is that, i'm getting soms errors.

Here's my code :

`

// camera initialization
int returnedStatus = is_InitCamera(&hCam, NULL);
cout<<"Status Init: "<<returnedStatus<<endl;

// set image size
int imgWidth=792, imgHeight=480;

char *capturedImage = NULL;
int memoryId = 0;

// allocate memory for image capturing
returnedStatus = is_AllocImageMem(hCam, imgWidth, imgHeight, 24, &capturedImage, &memoryId);
cout<<"Status AllocImage: "<<returnedStatus<<endl;

returnedStatus = is_SetImageMem(hCam, capturedImage, memoryId);
cout<<"Status SetImageMem: "<<returnedStatus<<endl;

for(;;){
    // capture frame
    is_CaptureVideo(hCam, IS_DONT_WAIT);
    IplImage* tmpImg;
    tmpImg = cvCreateImageHeader(cvSize(imgWidth, imgHeight), IPL_DEPTH_8U, 3);
   // tmpImg = cvCreateImage(cvSize(imgWidth,imgHeight),CV_8UC3,3);
    tmpImg->imageData = capturedImage;
    cv::Mat mat_img;//(imgWidth, imgHeight,3);
     // To IplImage
    IplImage ipltemp=mat_img;
    cvCopy(&ipltemp,tmpImg);
    // display captured image
    cv::imshow( "Display window", mat_img);
    cv::waitKey(0);

}

`

The error is :

terminate called after throwing an instance of 'cv::Exception' what(): OpenCV(4.0.1-dev) /home/sabrina/Téléchargements/opencv-master/modules/core/src/matrix_c.cpp:185: error: (-5:Bad argument) Unknown array type in function 'cvarrToMat'

Please help me to solve this problem

Thank you

Integer overflow not occuring : they restart from 0

I tried a simple code and found that integers variables are not overflowing instead it seems that latest C++ compiler has introduced a new functionality related to POD datatypes - if the variable crosses its max value, its values are restart from 0:

#include <iostream>
#include <cstdint>
#include <stdexcept>

int main()
{
try
{
for (uint8_t idx = 254 ;  ; idx++)
{
std::cout << unsigned(idx) << std::endl;
}
}
catch(std::overflow_error e)
{
std::cout << "Error" << std::endl;
}
}

When I run the code the exception code is never executed - but is this the desired behavior?

How to remove elements of a vector with a predicate based on another vector

I have two vectors

std::vector<Mat> images;
std::vector<std::string> image_paths;

and would like to filter out the indices in both vectors where the image is empty. This can easily be done on a single vector:

std::remove_if(images.begin() images.end(), [](const Mat& img) { return img.empty(); });

But now I'd like to remove the very same indices on image_paths as well. This can of course be generalized to vectors of arbitrary types or arbitrary predicates. How can I do this most elegantly?

Three sister while loops nested within 3 classes

Problem with starting the program!

Hi, I'm supposed to build a learning engine. This is the first part of it and what it's supposed to do is give me massive numbers so I can hook other programs to it's none existeble numbers. However, I'm having a problem with not being able to launch and to execute the program. I wonder what the problem may be?

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

class A1 {

   void LooP1() {

      int a1 = 2;
      int a2 = 4;
      int a3 = 6;

      while (true) {

          a1 = a1 + a2;
          a2 = a2 + a3;
          a3 = a3 + a1;

          cout << a1 << a2 << a3 << endl;
      }
   }
};

class B1 {

   void LooP2() {

      int a1 = 8;
      int a2 = 10;
      int a3 = 12;

      while (true) {

          a1 = a1 + a2;
          a2 = a2 + a3;
          a3 = a3 + a1;

          cout << a1 << a2 << a3 << endl;
      }
   }
};


class C1 {

   void LooP3() {

      int a1 = 14;
      int a2 = 16;
      int a3 = 18;

      while (true) {

          a1 = a1 + a2;
          a2 = a2 + a3;
          a3 = a3 + a1;

          cout << a1 << a2 << a3 << endl;
      }
   }
};

void main() {

    A1 A;
    A.LooP1;

    B1 B;
    B.LooP2;

    C1 C;
    C.LooP3;

}

Whats the difference between const int const& and const int& in C++?

In c++ i can write const int const* for a constant pointer to an constant int. I can also write const int& for a const reference. So is const int const& a reference to a const int?

Thanks in advance!

Adjacency list representation of a weighted graph

So guys, recently i have been practicing a lot with data structures, graphs and etc. And i encountered a problem with a given code. I am implementing a graph, that is represented with an adjacency list.The problem i stumble across is when i try to implement the solution, using user input. I have tried to do it in many ways but i still stumble across some problems in the program. Because i am using a vector that takes a list of integers, whenever i try to fill the vector with a while loop(for instance) i don't know why, but i can't quite fill it up correctly. And since my mistake starts even from there i don't know how to proceed with the program. If you guys can give me some sort of hint on how i can implement my code to work with user input, or even give me a similar code that i work with i would be really grateful !

This is my code:

const int N = 4;

//purpose of the class is to tell what the weight of the given edge is
class Edge{
   private:
       double weight;
       int vertex_id;

   public:
    //constructor that initializes the weight and vertex id

    Edge(double w, int id)
    {
        weight = w;
       vertex_id = id;
    }

    double getWeight() const
        {
            return weight;
        }

    int getId() const
    {
        return vertex_id;
    }
};

int main()
{
    std::vector<std::list<Edge>> adjList(N); //creating our vector that will store a list of integers

    adjList[0].push_back(Edge(4,1)); //pushing back the first neighbours of our Zero list
    adjList[0].push_back(Edge(2,2)); //pushing back the second neighbours of our Zero list and so on...

    adjList[1].push_back(Edge(4,0));
    adjList[1].push_back(Edge(5,2));

    adjList[2].push_back(Edge(2,0));
    adjList[2].push_back(Edge(5,1));
    adjList[2].push_back(Edge(1,3));

    adjList[3].push_back(Edge(1,2));

    std::vector<std::list<Edge>>::iterator i; //declaring our vector iterator

    int c = 0; //we create a counter(and ofcourse assign zero to it)


    //create the for loop, where the iterator starts at the begining of the vector
    //and ends when the vector (adjList) ends


    //*KEEP IN MIND THAT THE FIRST FOR LOOP ONLY ITERATES THROUGH THE NODES OF THE VECTOR
    for (std::vector<std::list<Edge>>::iterator i = adjList.begin(); i != adjList.end(); i++)
    {

        cout << "Vertices connected to our node: " << c << endl;
        std::list<Edge> li = *i; //this pointer serves the purpose to get the list for each different node

        //NOW THE SECOND FOR LOOP ITERATES THROUGH THE LISTS, THAT EACH NODE CONTAINS
        for (std::list<Edge>::iterator iter = li.begin(); iter != li.end(); iter++)
        {
            cout << " (V = " << (*iter).getId() << " weight= " << (*iter).getWeight() <<")";
        }

        cout << endl; // we end the line between the different nodes of the vector

        c++; //increment our counter
    }

Segfault when stripping .gnu.version section

I'm in the process of rewriting legacy code based on an old Framework with C++11 using thread and chrono libraries. To summarize the library spawns a thread and waits either an event or a delay.

I've written a code sample that works well until I strip the .gnu.version section.

1. Compilation

g++ -std=c++11 test.cpp -o test -pthread -lpthread

2. Execution before strip

$ ./test
>>run()
  run() - before wait()
>>wait()
< wait()
  run() - after wait()
  run() - before wait_until()
  run() - after wait_until()
  run() - before wait()
  run() - after wait()
< run()

3. Strip .gnu.version section

strip -R .gnu.version test

4. Execution after strip

 ./test
>>run()
  run() - before wait()
>>wait()
< wait()
  run() - after wait()
  run() - before wait_until()
Segmentation fault (core dumped)

From what I was able to investigate the segfault occurs in std::condition_variable::.wait_until() when calling the undelaying pthread library.

Here is the code sample :

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

class Task
{
private:
    std::mutex _mutex;
    std::condition_variable _cv;
    std::thread _thread;
    bool _bStop;
    bool _bWait;

    void run()
    {
        std::unique_lock<std::mutex> lock(_mutex);
        std::cout << ">>run()" << std::endl;
        while (!_bStop)
        {
            if ( !_bWait )
            {
                std::cout << "  run() - before wait()" << std::endl;
                _cv.wait(lock);
                std::cout << "  run() - after wait()" << std::endl;
            }
            else
            {
                _bWait = false;
                std::chrono::steady_clock::time_point ts = std::chrono::steady_clock::now()
                                                         + std::chrono::seconds(1);
                std::cout << "  run() - before wait_until()" << std::endl;
                _cv.wait_until(lock,ts);
                std::cout << "  run() - after wait_until()" << std::endl;
            }
        }
        std::cout << "< run()" << std::endl;
    }

public:
    Task():_bStop(false),_bWait(false)
    {
    }

    void start()
    {
        _thread = std::thread(&Task::run,this);
    }

    void wait()
    {
        std::cout << ">>wait()" << std::endl;
        std::unique_lock<std::mutex> lock(_mutex);
        _bWait = true;
        _cv.notify_one();
        std::cout << "< wait()" << std::endl;
    }

    void cancel()
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _bStop = true;
        _cv.notify_one();
    }

    void join()
    {
        _thread.join();
    }
};

int main()
{
    Task t;

    // Start Task thread
    t.start();

    // Sleeping here seems to help produce the error
    usleep(10000);
    t.wait();

    // Wait for Task to process delay
    sleep(5);

    // Stop Task and wait for thread termination
    t.cancel();
    t.join();

    return 0;
}

Is there any good solution to resolve cross-reference between two class in c++?

My use case is following

class Caller
{
  init(){ Callee.init(); }
  callMeByCalle() { //do something }
}

class Callee
{
  init(){ //initialize to receive IPC call from another process }
  onHandlerIPC { //call A class's callMeByCalle() in here }
}

Maybe I can pass the instance of A class when I call init() of Callee. But I think it could cause a cross-reference problem. Is there any formal or famous solution for this situation?

Clean syntax for filling Bitfield structs from function parameters

I must send some data over a network where the package parts are not byte aligned. All packages are 8 byte long and an example package type might look like this:

union Packed
{
    struct
    {
        uint64_t a : 5;
        uint64_t b : 10;
        bool c : 1;
    };
    uint64_t raw;
};

So the first 5 bits are field a the next 10 bits are field b and the last bit is field c. Now I need a send function that can send this and possibly other package types. The function should accept the fields as parameters. The low-level send function accepts a single uint64_t.

My requirements are:

  • An overflow should be detected at compile time
  • The syntax should not be too bulky (subjective, but i will show what i want)

My first attempt

void send_struct(const Packed& packed)
{
    raw_send(packed.raw);
}

int main()
{
    send_struct({1000, 2, true});  // conversion changes value

    Packed packed = {1000, 2, true};  // conversion changes value
    send_struct(packed);
}

The warnings are generated which satisfies my first requirement, but i don't like the syntax: The curly braces look superfluous and manually creating a struct first is cumbersome.

With some warnings enable i even have to use two layers of curly braces, because the struct is nested inside the union.

Second attempt

template <typename ...Args>
void send_var(Args... args)
{
    Packed packed {args...};

    raw_send(packed.raw);
};

int main()
{
    send_var(1000u, 2u, true);
}

Here, i like the syntax, but no warnings are generated, presumably because the bit width is lost somewhere.

Third attempt

struct A
{
    uint64_t data : 5;
};

struct B
{
    uint64_t data : 10;
};

void send_separate(A a, B b, bool c)
{
    Packed packed {a.data, b.data, c};

    raw_send(packed.raw);
}

int main()
{
    send_separate({1000u}, {2u}, true);  // conversion changes value
    send_separate(1000u, 2u, true);  // compile error
}

The first usage is ugly again: too many curly braces and the second one does not compile, because the structs cannot be implicitly constructed with a single value.

Question

How can i implement a function (and Package definition) such that the following function call compiles and shows a warning, because the value 1000 does not fit into 5 bit.

send(1000u, 2u, true);

I actually only care about the call site. The function and union definitions may be more complicated.

Using variables for the function parameters must work, too, of course

uint64_t a, b;
send(a, b, true);  // should generate a warning

send(a & 0x1f, b & 0x3ff, true);  // no warnings

The software will be used on linux only, is compiled with gcc or clang using at lease these warnings: -Wall -Wextra -pedantic plus the flag that allows anonymous structs and unions.

HeCompile Error When compile gRPC that `‘-std=c++11’ is valid for C++/ObjC++ but not for C `

I am trying to compile grpc_python_plugin. I downloaded the latest grpc package in Github. Following the instruction, I went into the grpc directory, and start to compile with

make grpc_python_plugin

, and get the following error:

wcf@wcf-OptiPlex-7060:~/resq/grpc$ make grpc_python_plugin
[C]       Compiling third_party/address_sorting/address_sorting.c
cc1: error: command line option ‘-std=c++11’ is valid for C++/ObjC++ but not for C [-Werror]
cc1: all warnings being treated as errors
Makefile:2972: recipe for target '/home/wcf/resq/grpc/objs/opt/third_party/address_sorting/address_sorting.o' failed
make: *** [/home/wcf/resq/grpc/objs/opt/third_party/address_sorting/address_sorting.o] Error 1
wcf@wcf-OptiPlex-7060:~/resq/grpc$ error: command line option ‘-std=c++11’ is valid for C++/ObjC++ but not for C [-Werror]

Since the Makefile for grpc is so giant, I cannot find any way to solve the problem. Could you share some idea on my problem? Thank you for your time.

mardi 26 février 2019

Using Boost::Beast for CPU-heavy REST APIs, Should I use Async or Sync way to implement them to expect the better latency?

I'm trying to use boost::beast to implement a web service providing some REST APIs. These APIs are CPU-heavy, almost no disk or db I/O. My goal is to optimize for latency with OK throughput. Should I use sync or async way to implement them?

Thanks!

Range based for-loop with &

I haven't found a question that answers the part I'm confused on, and I apologize if someone did answer it.

I'm confused on whats going on in this for-loop, how is it looping through the addresses?

int arr[] = {1,2,3,4,5};
for(const int &arrEntry : arr){
     cout << arrEntry << " ";
}

Acceptable practice with creating objects that are mutually dependent on it's "container" class?

Say I have a class structure that could hold a group of objects, and that the objects that it was containing needed to have access to the container that itself is contained in. Here is an example class structure of what I am talking about:

class Item;
class Container {
private:
    std::vector<Item*> items;
    ....
public:
    void add(Item *newItem) {
        items.push_back(newItem);
    }
    ....
}

class Item {
private:
    int data;
    Container* container;
    ....
public:
    Item(int data, Container* container) {
        this->data = data;
        this->container = container;
        if(container != nullptr) {
            container.add(this);
        }
    }
    ....
}

This would allow me to create an object easily like this:

Container contain;
new Item(1, &contain);
new Item(2, &contain);
new Item(3, &contain);

I could then easily access these objects through the container object, and this would by no means cause a memory leak by freely creating objects like this.

However, is this bad practice to create objects this way? Also, instead of accessing the container directly through a pointer stored in the objects themselves, should I just pass the container as a function parameter for whenever it needs to be used?

Class templates with std::array in separate files [duplicate]

This question already has an answer here:

How do i implement this class in separate files?

class MyClass {
public:
    template<class Type, std::size_t SIZE>                                 
    static void someFunc(std::array<Type, SIZE> &arr, const std::function<bool(Type, Type)> &pred) {
        //...
    } 
};

Here is what i try:

header.h

class MyClass
{   
public: 
    template<class Type, std::size_t SIZE>                                 
    static void someFunc(std::array<Type, SIZE> &arr, const std::function<bool(Type, Type)> &pred); 
};

header.cpp

template<class Type, std::size_t SIZE>                                
void MyClass::someFunc(std::array<Type, SIZE> &arr, const std::function<bool(Type, Type)> &pred) 
{
    //...
}

This stuff can be compiled. But if i try to use this i will see the next compile error:

LNK2019 unresolved external symbol "public: static void __cdecl MyClass::someFunc(class std::array &,class std::function const &)" (??$someFunc@H$04@MyClass@@SAXAAV?$array@H$04@std@@ABV?$function@$$A6A_NHH@Z@2@@Z) referenced in function _main

main.cpp

#include <iostream>
#include <array>
#include "MyClass.h"

int main() 
{
    std::array<int, 5> a{ 1, 2, 3, 4, 5 };
    MyClass::someFunc<int>(a, [](int a, int b) { return true; });
    std::cin.get();
}

constexpr const char* in header file

Is there a reason to not use "constexpr const char*" in header file?

The argument from a colleague is that every translation unit including this header file would have a copy.

My understanding was that since its compile-time constant, not memory is allocated and acts more like a "#define" macro with respect to memory usage. Here is the source,

TestConstExpr.h

  namespace TestConstExpr
  {
    constexpr const char* TIME_FORMAT = "yyyy-MM-dd hh:mm:ss";
    constexpr const int TIME_FORMAT_SIZE = sizeof(TIME_FORMAT) + 1;

    class TestClass
    {
        char arr[TIME_FORMAT_SIZE];
    }
  }

How to implement the Game of Life in parallel using C++ threads?

I have implemented a sequential version of the Game of Life but now I want to parallelize it. I'm trying to learn how to use C++ threads, thread barriers, and maybe even the future library to speed up this implementation. I'm not sure how to go about this. Advice would be greatly appreciated!

Here is my sequential implementation:

GameOfLife.h:

#include <vector>
#include <tuple>
using namespace std;


class GameOfLife {

    public:

        vector<vector<int> > SimulateLife(vector<vector<int> > &board, int life_cycles);

    private:

        vector<vector<int> > board;

        int CheckNeighbors(vector<vector<int> > &board, int row, int col);
        void UpdateBoard(vector<vector<int> > &board, vector<tuple<int, int> > &liveSpots,
                     vector<tuple<int, int> > &deadSpots);
};


//Checks all 8 neighbors of the current cell to see if they are alive
//If they are alive add one to liveNeighbors

int GameOfLife::CheckNeighbors(vector<vector<int> > &board, int row, int col) {
    int liveNeighbors = 0;

    if(board[(board.size()+row-1)%board.size()][(board.size()+col-1)%board.size()] == 1)
        liveNeighbors++;

    if(board[(board.size()+row-1)%board.size()][col] == 1)
        liveNeighbors++;

    if(board[(board.size()+row-1)%board.size()][(board.size()+col+1)%board.size()] == 1)
        liveNeighbors++;

    if(board[row][(board.size()+col+1)%board.size()] == 1)
        liveNeighbors++;

    if(board[(board.size()+row+1)%board.size()][(board.size()+col+1)%board.size()] == 1)
        liveNeighbors++;

    if(board[(board.size()+row+1)%board.size()][col] == 1)
        liveNeighbors++;

    if(board[(board.size()+row+1)%board.size()][(board.size()+col-1)%board.size()] == 1)
        liveNeighbors++;

    if(board[row][(board.size()+col-1)%board.size()] == 1)
        liveNeighbors++;

    return liveNeighbors;
}


//Using the x,y tuples, updates the board with dead
//and alive cells after a life cycle

void GameOfLife::UpdateBoard(vector<vector<int> > &board, vector<tuple<int, int> > &liveSpots,
                         vector<tuple<int, int> > &deadSpots) {

    for(tuple<int, int> t : liveSpots)
        board[get<0>(t)][get<1>(t)] = 1;

    for(tuple<int, int> t : deadSpots)
        board[get<0>(t)][get<1>(t)] = 0;
}


//Loops over every cell for the number of life cycles
//If the cell's value is 2, it will never die (small change to real game)

//If the cell's value is 1, it is currently alive. 
//Check number of alive neighbors to see if it dies or stays alive

//If the cell's value is 0, it is currently dead.
//Check the number of alive neighbors to see if it becomes alive or stays dead

vector<vector<int> > GameOfLife::SimulateLife(vector<vector<int> > &board, int life_cycles) {

    for(int cycles = life_cycles; life_cycles > 0; life_cycles--) {
        vector<tuple<int, int> > liveSpots;
        vector<tuple<int, int> > deadSpots;

        for(int row = 0; row < board.size(); row++) {
            for(int col = 0; col < board.size(); col++) {
                int aliveNeighbors = 0;

                if(board[row][col] == 2)
                    break;

                if(board[row][col] == 1) {
                    aliveNeighbors = CheckNeighbors(board, row, col);
                    if(aliveNeighbors < 2 || aliveNeighbors > 3)
                        deadSpots.push_back(make_tuple(row, col));
                }

                if(board[row][col] == 0) {
                    aliveNeighbors = CheckNeighbors(board, row, col);
                    if(aliveNeighbors == 3)
                        liveSpots.push_back(make_tuple(row, col));
                }
            }
        }

        UpdateBoard(board, liveSpots, deadSpots);
    }

    return board;
}

Main.cc:

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


void print_board(vector<vector<int> > &board) {
    int n = board.size();

    for (int i=0;i<n;i++) {
        for (int j=0;j<n;j++) {
            cout << board[i][j] << " ";
        }
        cout << endl;
    }
}


int main() {
    int n;
    cin >> n;

    vector<vector<int> > board;
    board.resize(n);

    for (int i=0;i<n;i++) {
        board[i].resize(n);
        for (int j=0;j<n;j++) {
            cin >> board[i][j];
        }
    }

    int k;
    cin >> k;

    GameOfLife obj;
    vector<vector<int> > result;
    result = obj.SimulateLife(board,k);
    print_board(result);
}

Broken pipe after writing to socket

In my network library I can do asynchronous writes to the network if I run() and restart() the io_context manually.

I'm now trying to make things scale by adding a thread pool:

.hpp

struct pool : public std::enable_shared_from_this<pool> {
  pool(const pool &) = delete;
  auto operator=(const pool &) -> pool & = delete;
  explicit pool(pool_parameters config, db_parameters params) noexcept;

  asio::io_context m_io_context;

  asio::thread_pool m_workers;

  asio::executor_work_guard<asio::io_context::executor_type> m_work_guard;

  /// \brief Container to hold connections.
  std::vector<std::unique_ptr<dbc::connection>> m_connections;
};

.cpp

pool::pool(pool_parameters config, db_parameters params) noexcept
    : m_config{std::move(config)},
      m_params{std::move(params)},
      m_work_guard{asio::make_work_guard(m_io_context)},
      m_workers{m_config.thread_pool_size} {
  m_connections.reserve(m_config.connection_pool_size);
  asio::post(m_workers, [&]() { m_io_context.run(); });
}

Which manages connections:

.hpp

struct abstract_connection : connection {
  explicit abstract_connection(const std::shared_ptr<pool> &pool) noexcept;

  ~abstract_connection() override;
      packet m_buffer;

      asio::local::stream_protocol::endpoint m_endpoint;

      asio::generic::stream_protocol::socket m_socket;

      asio::io_context::strand m_strand;
    };

.cpp

abstract_connection::abstract_connection(const std::shared_ptr<pool> &pool) noexcept
        : m_params{pool->m_params},
          m_config{pool->m_config},
          m_endpoint{pool->m_config.socket},
          m_socket{pool->m_io_context},
          m_strand{pool->m_io_context} {
      m_socket.connect(m_endpoint);
      m_socket.non_blocking(true);
    }

abstract_connection::~abstract_connection() {
      std::error_code ec;
      m_socket.shutdown(asio::generic::stream_protocol::socket::shutdown_both, ec);
      m_socket.close();
    }

Now comes the confusing park. On the ctor of a concrete connection object I need to do a handshake, along with a handshake on the destructor of the same class. Which does not happen because the socket object seems to be behaving in odd ways:

If I send data asyncrhonously, nothing gets written to the socket and sometimes I get a broken pipe error:

asio::dispatch(m_strand, [&]() {
          m_buffer = write::startup(m_params);
          asio::async_write(m_socket, asio::buffer(m_buffer), [](std::error_code ec, std::size_t len) {});
        });

If I do a synchronous write I get a broken pipe error before I can read from the socket:

std::error_code ec;
        auto startup = write::startup(m_params);
        asio::write(m_socket, asio::buffer(startup), ec);
        if (set_error(ec)) {
          std::cerr << " XXX " << ec.message() << std::endl;
          return;
        }

        m_buffer.reserve(327);
        asio::read(m_socket, asio::buffer(m_buffer), ec);
        std::cerr << ec.message() << std::endl;
        std::cerr << m_buffer.size() << std::endl;

The connection is being done over a unix socket and I have socat sitting between both, so I can see data coming and going, along with the broken pipe messages. Trying to connect to the remote using a third party tool works, with all relevant data appearing in socat, so I believe the problem is in my code.

How can I debug what is going on with the socket?

VS10 C++ Error C2833: 'operator string' is not a recognized operator or type

I am trying to have a custom operator operator ""_exp for Exponent class that I could call the operator like this:

std::cout << 10.5 ** 2._exp << '\n';

My rest of the code:

struct Exponent
{
    long double value;
};

Exponent operator ""_exp(long double exponent)
{
    return exponent;
}

I am using Visual Studio 10 compiler and I get a C2883 error:

Error C2833: 'operator string' is not a recognized operator or type

I have tried:

I've found a list of possible user-defined operators but I couldn't find operator "". https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/ds533389(v%3dvs.100)

Question: Can somebody tell my is it possible to have operator ""_exp" in Visual Studio 2010? Or maybe there is another way to achieve this?

Swap two complex structers - the fastest way to achieve

I need to copy / swap values of one structure to other and believe that swap will be faster than copy - am I correct?

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

class B
{
 public:
  int y;
  std::vector<int> z;
  B(){std::cout << "Called" << std::endl;}
 private:
 int z1;
};

int main()
{
 B b1, b2;
 b1.z.push_back(1);
 std::swap(b1,b2);
 std::cout << b2.z[0] << std::endl;
 b1.z.push_back(1);
 b2 = std::move(b1);
 std::cout << b2.z[0] << std::endl;
 b1.z.push_back(1);
 std::exchange(b1, b2);
 std::cout << b2.z[0] << std::endl;
 b1.z.push_back(1);
 b2 = std::forward<B>(b1);
 std::cout << b2.z[0] << std::endl;
}

The above code does the swaps as expected but I am not sure which is the fastest way - my objective is to copy values (swap if it is faster) of one structure variable to another - in real time the structure will have complex user defined classes.

I understand that similarly there will ways to copy - but which way is the best / safe / fast to copy to destination?

Do I need to take care of some operator / constructor to aid it?

Implement is_array in c++

It's easy to find an item in a vector and we know how. It's also possible to find an item in an array if we know the length of the array. But starting from c++11 with the announcement of std:: end(), it looks like we can get the size of the array by calling its pointer, right?

So this code works:

int arr[] = {1,2,3,4,5};
int needle = 3;

std::find(begin(arr), end(arr), needle);
int* result = find(begin(arr), end(arr), needle);
bool exists = result!=end(arr);

However, if this converted to a function:

bool in_array(int arr[], int needle){
    int* result = std::find(begin(arr), end(arr), needle);
    return result!=end(arr);
}

Will not compile:

error: no matching function for call to ‘begin(int*&)’ int* result = std::find( std::begin(arr), std::end(arr), needle);

The goal is to make a working function to send any type of array to it, just like in_array of Php:

template <typename T>
T in_array(T arr[],T needle){
    T* result = std::find(begin(arr), end(arr), needle);
    return result!=end(arr);
}

Why does this code not work? Does C++ compiler store some kind of a local variable to determine the end of arr?

Question about SFINAE of class template and function template

I try to specialize the template (function or class) for STL containers. The standard I used is c++14.

For the template function, I try the code as following.

template<typename... Args>
using int_t = int;

template<typename T, int_t
<
    typename T::value_type, //has defined the element type
    typename T::iterator, //has defined the iterator
    decltype(std::declval<T>().size()) //has defiend the "size()" function
    //other check...
> = 0>
void container_handler()
{
}

I think that if any type is not existed in "int_t", the template function will not be instantiated, but the compile errors are not happen when I invoke the template function as the following.

container_handler<int>();

However, I get the different result when use the class template.

template<typename... Args>
using int_t = int;

template<typename T , typename = int>
struct ContainerHandler;

template<typename T>
struct ContainerHandler<T, int_t
<
    typename T::value_type, //has defined the element type
    typename T::iterator, //has defined the iterator
    decltype(std::declval<T>().size()) //has defiend the "size()" function
    //other check...
>>
{
};

The above code works, the compile errors is occurred when I instantiates the class template with the type who hasn't defined the special type or function.

ContainerHandler<int> handler1; //compile error
ContainerHandler<int, int> handler2; //compile error
ContainerHandler<vector<int>> handler3; //ok
ContainerHandler<vector<int>, int> handler4; //ok

The "int_t" here can be replaced by "void_t" in c++17. My question is why the SFINAE rule is different of the function template and class template. For the function template, I try another way and it works.

template<typename... Args>
struct type_container
{
    using int_t = int;
};

template<typename T, typename type_container
<
    typename T::value_type, //has defined the element type
    typename T::iterator, //has defined the iterator
    decltype(std::declval<T>().size()) //has defiend the "size()" function
    //other check...
>::int_t = 0>
void container_handler()
{
}

container_handler<int>(); //compile error
container_handler<int, 0>(); //compile error
container_handler<vector<int>>(); //ok
container_handler<vector<int>, 0>(); //ok

I don't know what the difference between use "int_t" and "type_container::int_t".

i need Equivalent java code for this cpp line [on hold]

const float* scoresData = scores.ptr<float>(0, 0, y);

I want a Java equivalent for this cpp statement.

python regex findall convert to c++ regex [duplicate]

This question already has an answer here:

my python code is:

import re
regex1 = r"\[P\] .+? \[\/P\]"
regex2 = r"\[P\] (.+?) \[\/P\]"
line = "President [P] Barack Obama [/P] met Microsoft founder [P] Bill Gates [/P], yesterday."
person1 = re.findall(regex1, line)
person2 = re.findall(regex2, line)
print(person1)
print(person2)

The result is:
person1:['[P] Barack Obama [/P]', '[P] Bill Gates [/P]']
person2:['Barack Obama', 'Bill Gates']

and I want to convert the python code to c++.
my case c++ code is below:

  const std::string s = "President [P] Barack Obama [/P] met Microsoft founder [P] Bill Gates [/P], yesterday.";

  std::regex words_regex("\\[P\\] (.+?) \\[/P\\]+?");
  auto words_begin = std::sregex_iterator(s.begin(), s.end(), words_regex);
  auto words_end = std::sregex_iterator();
  for (std::sregex_iterator i = words_begin; i != words_end; ++i) {
    std::smatch match = *i;
    std::string match_str = match.str();
    std::cout << match_str << '\n';
  }

and the result is:
[P] Barack Obama [/P] [P] Bill Gates [/P] and my question how to remove the [p]and[/p] and I want get the result like person2 above?

lundi 25 février 2019

Pybind11 and std::vector -- How to free data using capsules?

I have a C++ function that returns a std::vector and, using Pybind11, I would like to return the contents of that vector as a Numpy array without having to copy the underlying data of the vector into a raw data array.

Current Attempt

In this well-written SO answer the author demonstrates how to ensure that a raw data array created in C++ is appropriately freed when the Numpy array has zero reference count. I tried to write a version of this using std::vector instead:

// aside - I made a templated version of the wrapper with which
// I create specific instances of in the PYBIND11_MODULE definitions:
//
//     m.def("my_func", &wrapper<int>, ...)
//     m.def("my_func", &wrapper<float>, ...)
// 
template <typename T>
py::array_t<T> wrapper(py::array_t<T> input) {
    auto proxy = input.template unchecked<1>();
    std::vector<T> result = compute_something_returns_vector(proxy);

    // give memory cleanup responsibility to the Numpy array
    py::capsule free_when_done(result.data(), [](void *f) {
        auto foo = reinterpret_cast<T  *>(f);
        delete[] foo;
    });

    return py::array_t<T>({result.size()}, // shape
                          {sizeof(T)},     // stride
                          result.data(),   // data pointer
                          free_when_done);
}

Observed Issues

However, if I call this from Python I observe two things: (1) the data in the output array is garbage and (2) when I manually delete the Numpy array I receive the following error (SIGABRT):

python3(91198,0x7fff9f2c73c0) malloc: *** error for object 0x7f8816561550: pointer being freed was not allocated

My guess is that this issue has to do with the line "delete[] foo", which presumably is being called with foo set to result.data(). This is not the way to deallocate a std::vector.

Possible Solutions

One possible solution is to create a T *ptr = new T[result.size()] and copy the contents of result to this raw data array. However, I have cases where the results might be large and I want to avoid taking all of that time to allocate and copy. (But perhaps it's not as long as I think it would be.)

Also, I don't know much about std::allocator but perhaps there is a way to allocate the raw data array needed by the output vector outside the compute_something_returns_vector() function call and then discard the std::vector afterwards, retaining the underlying raw data array?

The final option is to rewrite compute_something_returns_vector.

Why does the merseen_twister_engine guarantee certain results?

I note the following on cppreference's article for std::mersenne_twister_engine (e.g. std::mt19937):

The 10000th consecutive invocation of a default-constructed std::mt19937 is required to produce the value 4123659995.

The 10000th consecutive invocation of a default-constructed std::mt19937_64 is required to produce the value 9981545732273789042.

Assuming that this interpretation of the standard is accurate, what's the deal? Why do these guarantees exist? Isn't this non-random?

Joining threads while exception is thrown

I am using the C++ 11 std::thread library. Is it valid to join a thread in a destructor while an exception is thrown? The code I have is:

#include <thread>
#include <stdio.h>
#include <exception>
#include <unistd.h>

class the_thread {
private:
    std::thread t;
    bool abort;
public:
    the_thread();
    ~the_thread();

    void run();
};

the_thread::the_thread()
{
    abort = false;
    t = std::thread(&the_thread::run, this);
#if 0
    printf("before detach ...\n");
    t.detach();
    printf("after detach ...\n");
#endif
}

the_thread::~the_thread()
{
    abort = true;

printf("destruct thread container\n");
    if (t.joinable()) {
printf("into join\n");
        t.join();
printf("out of join\n");
    }
}

void the_thread::run()
{
    int i;

    i=0;
    while (!abort) {
        printf("hallo %d\n", i);
        i++;
        std::this_thread::sleep_for(std::chrono::milliseconds(3000));
    }
}

int run_thread_and_throw_exception(void)
{
    the_thread t;

    sleep(5);
    throw std::runtime_error("some expected exception");
}


int main(int argc, char ** argv)
{
    try {
        run_thread_and_throw_exception();
    } catch (const std::runtime_error &e) {
        printf("exception %s caught\n", e.what());
    }

    return 0;
}

When compiling and running with

gcc --version
gcc (Ubuntu 5.4.0-6ubuntu1~16.04.10) 5.4.0 20160609
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

on my Ubuntu 16.04 development machine, this code behaves as expected:

bash$ ./thread_test 
hallo 0
hallo 1
destruct thread container
into join
out of join
exception some expected exception caught
bash$

However when compiling with

arm-linux-gnueabi-g++ -Wall -g -O2 -std=c++11   -c -o main.o main.cpp
arm-linux-gnueabi-g++ -Wall -g -O2 -std=c++11 main.o -o thread_test -lpthread -static

(we need the -static because there is no C++ 11 library on the target) and running it on the target, strange things happen:

bash-on-target# ./thread_test
hallo 0
hallo 1
destruct thread container
into join
terminate called after throwing an instance of 'std::system_error'
  what():  Unknown error 1082172112
Aborted

So it seems that the join in the destructor fails for some reason. Furthermore when trying to detach the thread, the detach fails rightaway:

bash-on-target# ./thread_test
before detach ...
terminate called without an active exception
hallo 0
hallo 0
Aborted

So to repeat my question: is joining threads (and possibly sleeping) while an exception is thrown valid in C++11? Is it possible that there is a bug in the C++ 11 library for ARM that comes with Ubuntu 16.04?

The ARM toolchain is:

bash$ arm-linux-gnueabi-g++ --version
arm-linux-gnueabi-g++ (Ubuntu/Linaro 5.4.0-6ubuntu1~16.04.9) 5.4.0 20160609
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Thanks and best wishes, Johannes

QTableView drag & drop rows not working properly

I am trying to move rows of a QTableView. I build a small MVCE according to this article. I can successfully move rows, however a strange effect happens as soon as I drop the row, see below print screen:

dragDrop_error

A new row5 gets created instead of pushing two to Row0 and three to Row1

So the correct result should be:

Correct

instead I get the following incorrect result:

Incorrect

I have been trying to solve this problem reading this source, which was useful to build and test the model. In addition to that this was useful to understand the parameters to give to the QTableView but did not totally solved the problem. Also from here a small description of the process was useful to read but still my problem persists. Finally I found this interesting source that seems to describe to address Qt::ItemFlags as possible solution but could not properly relate it to a possible solution.

See below the most important part of the code:

main.cpp

#include <QApplication>
#include <QtGui>
#include <QAbstractItemModel>
#include <QTableView>
#include <QListView>
#include <QAbstractItemView>
#include "newmodel.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QStringList numbers;
    numbers << "one" << "two" << "three" << "four" << "five";
    QAbstractItemModel *model = new NewModel(numbers);
    QTableView *tableView = new QTableView;
    tableView->setSelectionMode(QAbstractItemView::ExtendedSelection);
    tableView->dragDropOverwriteMode();
    tableView->setDragEnabled(true);
    tableView->setAcceptDrops(true);
    tableView->setDropIndicatorShown(true);
    tableView->setModel(model);
    tableView->setDefaultDropAction(Qt::MoveAction);
    tableView->show();
    return a.exec();
}

newmodel.cpp

#include "newmodel.h"
#include <QStringListModel>
#include <QDebug>

NewModel::NewModel(const QStringList &strings, QObject *parent)
    : QAbstractListModel(parent)
    , stringList(strings)
{}

int NewModel::rowCount(const QModelIndex &parent) const
{
    return stringList.count();
    Q_UNUSED(parent);
}

QVariant NewModel::data(const QModelIndex &index, int role) const
{
    if(!index.isValid())
        return QVariant();
    if(index.row() >= stringList.size())
        return QVariant();
    if(role == Qt::DisplayRole || role == Qt::EditRole)
        return stringList.at(index.row());
    else
        return QVariant();
}

QVariant NewModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if(role != Qt::DisplayRole)
        return QVariant();
    if(orientation == Qt::Horizontal)
        return QString("Column %1").arg(section);
    else
        return QString("Row %1").arg(section);
}

Qt::ItemFlags NewModel::flags(const QModelIndex &index) const
{
    Qt::ItemFlags defaultFlags = QAbstractListModel::flags(index);

    if(index.isValid())
        return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | defaultFlags;
    else
        return Qt::ItemIsDropEnabled | defaultFlags;
}

bool NewModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if(index.isValid() && role == Qt::EditRole) {
        stringList.replace(index.row(), value.toString());
        emit dataChanged(index, index);
        return true;
    }
    return false;
}

bool NewModel::insertRows(int position, int rows, const QModelIndex &parent)
{
    beginInsertRows(QModelIndex(), position, position+rows-1);
    for(int row = 0; row < rows; row++) {
        stringList.insert(position, "");
    }
    endInsertRows();
    return true;
    Q_UNUSED(parent);
}

bool NewModel::removeRows(int position, int rows, const QModelIndex &parent)
{
    beginRemoveRows(QModelIndex(), position, position+rows-1);
    for(int row = 0; row < rows; ++row) {
        stringList.removeAt(position);
    }
    endRemoveRows();
    return true;
    Q_UNUSED(parent);
}

Qt::DropActions NewModel::supportedDropActions() const
{
    return Qt::CopyAction | Qt::MoveAction;
}

QStringList NewModel::mimeTypes() const
{
    QStringList types;
    types << "application/vnd.text.list";
    return types;
}

QMimeData *NewModel::mimeData(const QModelIndexList &indexes) const
{
    QMimeData *mimeData = new QMimeData();
    QByteArray encodedData;
    QDataStream stream(&encodedData, QIODevice::WriteOnly);
    foreach(const QModelIndex &index, indexes) {
        if(index.isValid()) {
            QString text = data(index, Qt::DisplayRole).toString();
            stream << text;
        }
    }
    mimeData->setData("application/vnd.text.list", encodedData);
    return mimeData;
}

bool NewModel::dropMimeData(const QMimeData *data, Qt::DropAction action,
                                   int row, int column, const QModelIndex &parent)
{
    qDebug() << action;
    if(action == Qt::IgnoreAction)
        return true;
    if(!data->hasFormat("application/vnd.text.list"))
        return false;
    if(column > 0)
        return false;
    int beginRow;
    if(row != -1)
        beginRow = row;
    else if(parent.isValid())
        beginRow = parent.row();
    else
        beginRow = rowCount(QModelIndex());
    QByteArray encodedData = data->data("application/vnd.text.list");
    QDataStream stream(&encodedData, QIODevice::ReadOnly);
    QStringList newItems;
    int rows = 0;
    while(!stream.atEnd()) {
        QString text;
        stream >> text;
        newItems << text;
        ++rows;
    }
    insertRows(beginRow, rows, QModelIndex());
    foreach(const QString &text, newItems) {
        QModelIndex idx = index(beginRow, 0, QModelIndex());
        setData(idx, text);
        beginRow++;
    }
    return true;
}

bool NewModel::dragDropOverwtiteMode() const
{
    return false;
}

Thank you very much for pointing in the right direction and trying to shed light on this matter

No viable overloaded '=' data.end() -1 = '\0'

I'm trying to create a program that filters through speech text, removes any unwanted characters (",", "?", etc., etc." and then produces a new speech where the words are jumbled based on what words follow or precede them. So for example, if you had the Gettysburg Address: "Four score and seven years ago our fathers brought forth on this continent, a new nation conceived in Liberty, and dedicated to the proposition that all men are created equal." My program would take that text, put it into a set of strings. i.e. ["Four","score","and","seven",...."continent,"..."Liberty,"..."equal."] Then it would remove any unwanted characters from each string using c++ .erase and c++ .remove, like "," or "." and capitals. After, you'd have a filtered string like ["four","score","and","seven",...."continent"..."liberty"..."equal."]

After that then the words would be rearranged into a new coherent, funnier speech, like: "Seven years ago our fathers conceived on men...", etc., etc.

That was just so you know the scope of this project. My trouble at the moment has to do with either using my iterator properly or null terminators

   #include <iostream>
    #include <fstream>
    #include <iomanip>
    #include <string>
    #include <set>
    #include <iterator>//iterates through sets
    #include <algorithm>

    using namespace std;

    int main(){
    set<string> speechSet;
    set <string>::iterator itr;//forgot what :: means. Declares iterator as    set
    int sum = 0;
    int x;
    string data;
    ofstream out;
    string setString;

    ifstream speechFile;//declare output file stream object. Unknown type name

    speechFile.open("./MySpeech");

    if(!speechFile){
        cerr<< "Unable to open file " << endl;
        exit(1);
    }

    char unwantedCharacters[] = ".";

    while(!speechFile.eof()){
        speechFile >> data;//speechFile input into data
        for (unsigned int i = 0; i < strlen(unwantedCharacters); ++i) {
            data.erase((remove(data.begin(), data.end(), 
    unwantedCharacters[i]), data.end()));//remove doesn't delete.    
            data.end()-1 = '\0';//Reorganizes
            cout << data << endl;
        }
        speechSet.insert(string(data));
    }


    //go through each string (word) one at a time and remove "",?, etc.
        /*for(itr = speechSet.begin(); itr != speechSet.end(); ++itr){
            if(*itr == ".")//if value pointed to by *itr is equal to '.'
                itr = speechSet.erase(itr);//erase the value in the set and  leave blank
                cout << " " << *itr;//print out the blank
            else{
                cout << " " << *itr;
            }
        }*/

        speechFile.close();
        return(0);

    }//Last line of program. All code must be written above.

I keep getting an error that says error: no viable overloaded '='. At first I thought it might be due to .end() not being a command for a c++ string, but I checked the documentation and it shouldn't be an issue of mismatched data typed. Then I thought it might have to set the iterator itr equal to the end of the data.

iterator itr = data.end() - 1;

and then dereference that pointer and set it equal to the null terminator

itr* = '\0';

That removed the overload error, but I still had another error "use of class template 'iterator' requires template arguments." Any help would be appreciated. Let me know if any more clarification is needed.

How to consume and process AVRO data in GPU efficiently?

Requirement :

  1. I have an application producing AVRO data (around 100 GB per hour).
  2. I want to create another application that would read the generated AVRO data (hourly) and transform the data in GPU

Example class generated by AVRO (not accurate but just to present my case) :

struct XXX {
    std:string s1;
    std:string s2;
    int i1;
    float f1; 
}

struct YYY { 
    typedef XXX x1;
    typedef XXX x2;
    std:string s1;
    int i1;
}

Problem :

  1. After de-serializing an AVRO record, it contains std::string in nested structure
  2. GPU does not support std::string

Question :

Is there a way, to send the deserialized AVRO record to GPU for further processing as it is?

Please bear with me, if the question seems very naive, as I am new to both c++ and GPU programming.

pybind11: return c++ class (with an existing python binding) to python

I am trying to create a wrapper for a c++ method that returns a c++ class(vtkPolyData) which comes from an external c++ library (vtk). The same library has python binding available which is already installed in my python environment. How do you tell pybind that the c++ class (vtkPolydata) and its python variant are the same?

I tried to use this custom type caster macro. but I get TypeError: Unable to convert function return value to a Python type! The signature was : (self: Versa3dLib.skeletonizer, offset distance: float) -> vtkPolyData

which is confusing since it looks like the conversion maps to the correct type but python is unable to interpret it. So I am not sure what's wrong since I don't see anything wrong with the macro either. I noticed that in python vtkPolyData has type vtkCommonDataModelPython.vtkPolyData. is that why the conversion is not done correctly?

Can I avoid copying during the intialization of a std::initializer_list without using raw pointers?

Let's say I have several objects declared locally that I want to iterate over using range-based for syntax. This seems to work well, however, it appears that to put the local objects into the initializer_list, a copy is performed. This is bad news for objects like std::shared_ptr for which (as I understand) incrementing the reference count is an atomic operation. The only way I think this can be avoided is by using raw pointers.

#include <iostream>
#include <memory>

int main() {
    std::shared_ptr<int> ptrInt1 = std::make_shared<int>(1);
    std::shared_ptr<int> ptrInt2 = std::make_shared<int>(2);
    /* in this loop, ptrInt1 and ptrInt2 are copied before they are binded
       to ptrInt, this is ugly since the reference counter needs to temporarily
       increased */
    for(const std::shared_ptr<int>& ptrInt : {ptrInt1, ptrInt2}) {
        std::cerr << *ptrInt << std::endl;
    }
    /* this solution works, but it feels somewhat ugly having to convert my smart
       pointers to raw pointers to avoid the copying, perhaps there is a better
       solution ?? */
    for(const int* rawPtrInt : {ptrInt1.get(), ptrInt2.get()}) {
        std::cerr << *rawPtrInt << std::endl;
    }
    return 0;
}

Is there a way to iterate over a group of locally declared objects without copying them or resorting to using raw pointers?

How to avoid "template parameters not deducible in partial specialization"

I would like to have access to a nested class using templates, and can't figure out how to do it: A sample code:

template <typename T> class mything {
  typedef unsigned key;
  T data;
public:
  template <typename subT> class mysubthing { typedef subT value_type; };
  using subthing = mysubthing<T>;
  using subthing_ro = mysubthing<const T>;
};

template<typename T> struct X; // a container for all value_types

#ifdef MAKE_IT_FAIL
// this should automatically set the X<mything<T>::mysubthing<subT>
template<typename T,typename subT> struct X<typename mything<T>::template mysubthing<subT>> {
  using value_type = subT;
};
#endif

typedef mything<int> intthing;

#ifndef MAKE_IT_FAIL
template<> struct X<mything<int>::subthing> { using value_type = int; };
template<> struct X<mything<int>::subthing_ro> { using value_type = const int; };
#endif

int main(void) {
  intthing t;
  X<intthing::subthing>::value_type data = 1; // a data object
  X<intthing::subthing_ro>::value_type data_ro = 1; // read-only data object

  return 0;
}

This compiles without -DMAKE_IT_FAIL, but of course it completely misses the point about templates, since what I wanted was entered manually. How can I make it work with -DMAKE_IT_FAIL?

Connection pool destructor prevents network communication in destructor of connection objects

I have a connection pool that uses the new thread_pool with 2 threads. I also have 2 connections on my pool. The connection pool is implemented thus:

.hpp

/// \brief Connection pool.
    struct pool : public std::enable_shared_from_this<pool> {
      pool(const pool &) = delete;
      auto operator=(const pool &) -> pool & = delete;
      explicit pool(pool_parameters config, db_parameters params) noexcept;
      ~pool();

      /// \brief Run loop.
      asio::io_context m_io_context;

      /// \brief Used to keep the io_context from running out of work.
      asio::executor_work_guard<asio::io_context::executor_type> m_work_guard;

      /// \brief Thread pool where tasks are asynchronously executed.
      asio::thread_pool m_workers;

      /// \brief Container to hold connections.
      std::vector<std::unique_ptr<dbc::connection>> m_connections;
    };

.cpp

pool::pool(pool_parameters config, db_parameters params) noexcept
    : m_config{std::move(config)},
      m_params{std::move(params)},
      m_work_guard{asio::make_work_guard(m_io_context)},
      m_workers{m_config.thread_pool_size} {
  m_connections.reserve(m_config.connection_pool_size);
  asio::post(m_workers, [&]() { m_io_context.run(); });
}

pool::~pool() {
  std::cerr << "~pool" << std::endl;
  m_work_guard.reset();
  m_workers.join();
  m_io_context.stop();
}

I also have a connection object that does a connection handshake on the constructor and a disconnect handshake on the destructor.

The problem is that by the time the connection is destroyed the pool has already stopped the work guard and so no packets are sent to the remote system.

How can I force the disconnect handshake to be done before the work guard is destroyed? I can add a manual disconnect method to each connection object but I'd like to stick to RAII.

Custom transport protocol over UDP using Boost library

I read that Boost.Asio and Boost.Beast are good libraries for networking in C++. I also understood that I can use a custom transport protocol using raw_sockets. Can I create my own protocol using the boost library that can be used on a client and on a server at the transport layer? If it's possible, which should be the starting point? (I want to implement a RUDP).

I ask this question because I want to know that it can be done before I start learning the library.

How to use C++11 in Qt creator 4.8

I have looked everywhere and the solution to this is to add a line of code to a '.pro' file in my project. I cannot see any such files though! I can see a qbs file, the main.cpp file and a xcode.qbs file.

This is how I started: using a Mac, I installed Qt Creator 4.8 (Clang v5.12) and I created a 'plain C++ project' which uses Qmake.

I am using the {} to initialise a variable but it won't allow me to. I had a similar problem with Eclipse and found a solution. Any help, please?

This is the code I am testing:

#include <iostream>

int main()
 {
   int a{5};
   std::cout << a;
   return 0;
  }

The error code for the line where I define a is: "/Users/xxxxxx/Coding/HelloEarth/main.cpp:5: error: expected ';' at end of declaration"

What should I do?

unordered_map on pair of complex as key fails soon in insert

I have a complex class (class MyComplex) where complex is defined by 2 double variables re and img

I have a function which takes 2 MyComplex objects and does some operations on the same and returns a new MyComplex object.

I wish to keep a cache in the function which first checks if the input has been seen before and if yes return the data from the cache as the calculation is quite expensive in time.

1) Let's define a typedef for the pair of MyComplex

  typedef std::pair<MyComplex, MyComplex> pairOfComplex;

2) An unordered map will need a pair_hash function

 struct pair_hash
{
    //template <class T1, class T2>
    std::size_t operator() (const std::pair<MyComplex, MyComplex> &pairOfComplex) const
    {
        return std::hash<double>()(pairOfComplex.first.re) ^ std::hash<double>()(pairOfComplex.first.im)
            ^ std::hash<double>()(pairOfComplex.second.re) ^std::hash<double>()(pairOfComplex.second.im);
    }
};

3) The actual cache

 std::unordered_map<pairOfComplex, MyComplex, pair_hash> MyCache;

problem: I find that after a few inserts the insert call to the map is failing even though the input is different.

I feel my insert is failing because pair_hash is not proper it seems.

1) What should e an appropriate pair_hash or what strategy should one apply here? 2) Should I change my cache Ds to be something different?