lundi 31 juillet 2017

Which mongoDB ODM for C++?

I have recently started developing a project using C++11 and MongoDb, although i have successfully used mongocxx driver to implement the logic, but i was hoping if there is any good ODM like we have MongoEngine in Python for this stuff.

Kindly assist.

shared_ptr reset throws segmentation fault

Tried this program out of curiosity to understand behavior of shared_ptr over raw pointers. I hope the problem could be double delete but here I am facing other:

MyClass *raw_ptr = new MyClass();
shared_ptr<MyClass> sptr1(raw_ptr);
shared_ptr<MyClass> sptr2 = sptr1;
cout << sptr1.use_count() << endl; // prints 2
sptr1.reset(); // occurs Segmentation Fault here

Expected Behavior: reduce the count to 1 and moves control to next line.

signal jammers by coding and what is library

can there be some kind of coding to make a signal jammer with c++ and what is the library and the signals in signal.h are the signals coming out of the laptop or just other signals and how to develop , and also why we need to write in a Xaml file in the code of connecting to the wifi using c++

here is the code i i copied from Ben Hembram

Return from calling function inside lambda

Lambdas are an awesome way to create reusable code inside a function/method without polluting the parent class. They're a very functional replacement for C-style macros most of the time.

However, there's one bit of syntactic sugar from macros that I can't seem to replicate with a lambda, and that's the ability to exit from the containing function. For example, if I need to return while checking the range of a series of ints, I can do that easily with a macro:

const int xmin(1), xmax(5);
#define CHECK_RANGE(x) { if((x) < xmin || (x) > xmax) return false; }

bool myFunc(int myint) {
    CHECK_RANGE(myint);
    int anotherint = myint + 2;
    CHECK_RANGE(anotherint);
    return true;
}

Obviously this is an oversimplified example, but the basic premise is that I'm performing the same check over and over on different variables, and I think it's more readable to encapsulate the check and related exits. Still, I know that macros aren't very safe, especially when they get really complex. However, as far as I can tell, trying to do the equivalent lambda requires awkward additional checks like so:

const int xmin(1), xmax(5);
auto check_range = [&](int x) -> bool { return !(x < xmin || x > xmax); };

bool myFunc(int myint) {
    if(!check_range(myint)) return false;
    int anotherint = myint + 2;
    if(!check_range(anotherint)) return false;
    return true;
}

Is there a way to do this with a lambda? Or am I missing some alternative syntactic sugar?

GNU GCC bug when using both sysroot and c++11?

I'm encountering a very strange issue. I've used Yocto Project to generate me an ARM toolchain/RFS. This in itself may not important since I've since replicated the same issue with a pre-made ARM toolchain (still using the Yocto-generated RFS).

Consider the simple file foo.cpp:

#include <memory>
int main() { return 0; }

I am able to compile it with either --sysroot=... or -std=c++11 flags, but never both.

For example, the following compiles fine:

aarch64-linux-gnu-g++ --sysroot=/opt/sysroots/my_sysroot foo.cpp

This also compiles fine:

aarch64-linux-gnu-g++ -std=c++11 foo.cpp

However, this does not work:

aarch64-linux-gnu-g++ --sysroot=/opt/sysroots/my_sysroot -std=c++11 foo.cpp

The compiler error I get is:

In file included from foo.cpp:2:0:
/opt/marvell/5.2.1/armv8/le/aarch64v8-marvell-linux-gnu-5.2.1_x86_64_20151110/aarch64-linux-gnu/include/c++/5.2.1/memory: In function 'void* std::align(std::size_t, std::size_t, void*&, std::size_t&)':
/opt/marvell/5.2.1/armv8/le/aarch64v8-marvell-linux-gnu-5.2.1_x86_64_20151110/aarch64-linux-gnu/include/c++/5.2.1/memory:117:58: error: cast from 'void*' to 'uintptr_t {aka unsigned int}' loses precision [-fpermissive]
   const auto __intptr = reinterpret_cast<uintptr_t>(__ptr);

Compiler information:

Using built-in specs.
COLLECT_GCC=aarch64-linux-gnu-g++
COLLECT_LTO_WRAPPER=/opt/marvell/5.2.1/armv8/le/aarch64v8-marvell-linux-gnu-5.2.1_x86_64_20151110/bin/../libexec/gcc/aarch64-linux-gnu/5.2.1/lto-wrapper
Target: aarch64-linux-gnu
Configured with: /home/gccbuilder-x86/release/mgcc5.0/src/gcc-src/configure --host=x86_64-linux-gnu --build=x86_64-linux-gnu --target=aarch64-linux-gnu --prefix=/home/gccbuilder-x86/release/mgcc5.0/Release/install/aarch64v8-marvell-linux-gnu-5.2.1_x86_64 --enable-libssp --enable-shared --enable-threads --enable-lto --enable-libgomp --enable-gnu-indirect-function --enable-languages=c,c++ --with-gnu-as --with-gnu-ld --with-pkgversion='Marvell GCC release 20151110-a53c013d' --with-bugurl=mailto:mrvlgccbug@gmail.com --with-sysroot=/home/gccbuilder-x86/release/mgcc5.0/Release/install/aarch64v8-marvell-linux-gnu-5.2.1_x86_64/aarch64-linux-gnu/libc --with-build-sysroot=/home/gccbuilder-x86/release/mgcc5.0/Release/install/aarch64v8-marvell-linux-gnu-5.2.1_x86_64/aarch64-linux-gnu/libc --with-host-libstdcxx='-static-libgcc -Wl,-Bstatic,-lstdc++,-Bdynamic -lm' --with-build-time-tools=/home/gccbuilder-x86/release/mgcc5.0/Release/install/aarch64v8-marvell-linux-gnu-5.2.1_x86_64/aarch64-linux-gnu/bin --enable-poison-system-directories --enable-symvers=gnu --enable-__cxa_atexit --enable-multiarch --enable-linker-build-id --disable-nls --disable-libstdcxx-pch --disable-libcc1 --with-specs='%{funwind-tables|fno-unwind-tables|ffreestanding|nostdlib:;:-funwind-tables}' --disable-multilib
Thread model: posix
gcc version 5.2.1 20151103 (Marvell GCC release 20151110-a53c013d) 

Any insights on how to go about debugging this? I want to determine which party is responsible (GCC, Yocto, Marvell, etc) before attempting to file a bug report.

Force copy (then destroy) on move-only type

Consider the following function of a lock-free work-stealing (de)que:

template<class T>
inline T WorkStealQ<T>::Steal(void)
{
    auto tail{_tail.load(std::memory_order_acquire)};
    if (_head.load(std::memory_order_acquire) <= tail) return T();
    auto task{_tasks[tail & _mask]};
    if (_tail.compare_exchange_weak(tail, tail + 1, std::memory_order_release, std::memory_order_relaxed)) return task;
    return T();
}

But what if T is only moveable but non-copyable? The issue is that the reading of the item from the buffer is a copy operation, and cannot be changed to auto task{std::move(_tasks[tail & _mask])}; because another concurrent operation could also move it, in which case any move constructor which is not read-only but also modifies the original (such as nulling some pointer to a resource) would break the algorithm.

Note that the overall semantics of Steal() do perform only a move from an external point of view, since only one concurrent operation will return with the T that was stored at that location; any others who lose the race would fail the compare_exchange_weak(). Thus, the operation doesn't break the semantics of a moveable only T as far as the user is concerned. Unfortunately, internally it needs to make a temporary shallow copy of T until it determines whether to complete it as a move or give up, leaving it in the buffer (it's basically a two-phase move with a check occurring in the middle).

One way to do this would be make copy constructor and copy assignment private members of T and have a friend WorkStealQ. The problem is what to do in the case of third-party library classes I may want to use as T. Is there any other option in that case than just using pointers to such objects rather than storing them intrusively (and thus getting a performance hit)? I'm assuming memcpy won't work even for a shallow copy in the case of classes with virtual functions.

What is the proper way to manage a vector of unique_ptr's?

If I have a class which is managing a vector of std::unique_ptrs, what is the proper way to manage this resource? I have below a minimum working example. When running this code, however, a segmentation fault occurs. I imagine this is because mains reference to bin get's std::moved in AContainer::addValue, but I don't know for sure and I am not sure how to test that assumption.

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

class AnotherContainer;

class AContainer{
    public:
        void addValue(AnotherContainer& anInt);
        const std::vector<std::unique_ptr<AnotherContainer>>& getVals() const;
    private:
        std::vector<std::unique_ptr<AnotherContainer>> ints;
};

void AContainer::addValue(AnotherContainer& anInt){
    ints.push_back(std::move(std::unique_ptr<AnotherContainer>(&anInt)));
}

const std::vector<std::unique_ptr<AnotherContainer>>& AContainer::getVals() const{
    return ints;
}

class AnotherContainer{
    public:
        AnotherContainer(int val) : myVal(val){};
        int getVal() const{
            return myVal;
        }
    private:
        int myVal;
};

int main(){
    AContainer bin;
    AnotherContainer val1(1), val2(2);
    bin.addValue(val1);
    bin.addValue(val2);
    const std::vector<std::unique_ptr<AnotherContainer>>& vals = bin.getVals();
    std::cout << "vals[0] = " << vals[0]->getVal() << std::endl;
    return 0;
}

How to return an object templated with lambda?

Consider the following code:

class BaseTask {
  // Implementation here
};

class BaseSubtask {
  BaseTask *_pTask;
public:
  explicit BaseSubtask(BaseTask *pTask) : _pTask(pTask) { }
  virtual void Run() = 0;
  // The rest of implementation here.
};

template<typename taFunc> class LambdaSubtask {
  taFunc _f;
public:
  explicit LambdaSubtask(BaseTask *pTask, taFunc&& f)
  : BaseSubtask(pTask), _f(std::forward<taFunc>(f))
  { }
  LambdaSubtask(const LambdaSubtask&) = delete;
  LambdaSubtask& operator=(const LambdaSubtask&) = delete;
  LambdaSubtask(LambdaSubtask&&) = delete;
  LambdaSubtask& operator=(LambdaSubtask&&) = delete;
  virtual void Run() override final { _f(); }
  // The rest of implementation here
};

Because I cannot declare a LambdaSubtask object without specifying its template type argument, and I cannot specify its template type argument because it's a lambda, I try to implement a factory method:

template<typename taFunc> inline LambdaSubtask<taFunc>
MakeLambdaSubtask(BaseTask *pTask, taFunc&& f) {
  return { pTask, std::forward<taFunc>(f) };
}

Unfortunately this gives a compilation error:

copy-list-initialization of LambdaSubtask<lambda_...> cannot use an explicit constructor

With a proper factory method I could get a LambdaSubtask object as follows:

BaseTask task; // Initialization of the task is skipped in the example
auto&& lst = MakeLambdaSubtask(&task, [/* Capture here*/]() {
  // Implementation here
});

So basically I want a local variable object of LambdaSubtask type, with template type being a lambda. I want to avoid extra copying of anything. Surely I want to avoid std::function as my benchmarks show it's extremely slow.

Do you know how to implement a proper factory method or get local variable object of LambdaSubtask type in another way?

My compiler is MSVC++2017 with toolset v141 , so C++11/14/17 is partially supported.

C++ programme crashes when compiled

This is my code.After it compiles, the console starts but crashes immediately saying that name.exe has stopped working. warning: extended initializer lists only available with -std=c++11 or -std=gnu++11. \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

#include<iostream>
#include<conio.h>
#include<string> //introducing string classes.
struct cia
{
    std::string name;
    std::string code;
    float balance;
};




int main()
{
   using namespace std;

    cia agent[10] =
    {

     agent[0] =
     {    "wallflower",
         "007860",
         300000
     },

     agent[1] =
     {
         "albus",
         "117861",
         310000
     },

     agent[2] =
     {
         "severus",
         "227862",
         600000
     },

     agent[3] =
     {
         "enigma",
         "337862",
         550000
     },


    };

   string head="\n\t\t\t\t\tCIA";
   string username;
   string pass;


   cout<<head;
   cout<<"\n Welcome To The Most Secure network of Justice.";
   cout<<"Username-; ";
   cin>>username;
   getch();


}

Having issues using CImg to colormap a grey-scale Image

I am using CImg for a few different things in a project and have a grey-scale image that I need to apply a jet_LUT256 color map to. I am not sure if I am on the right path or not. Any guidance would be appreciated.

#include "CImg.h"

using namespace std;
using namespace cimg_library;

int main()
{
    CImg<uint8_t> image("test.jpg");

    // Color mapping using: jet_LUT256

    image.map(jet_LUT256());

    CImgDisplay main_disp(image, "Thank you!");
    while (!main_disp.is_closed())
    {
        main_disp.wait();
    }

    return 0;
}

'thread' is not a member of 'std' in Eclipse Neon with MinGW 6.3 GCC on Windows

I am receiving the error "thread is not a member of std". I have tried every solution that I found online and none have worked so far. I have tried adding -pthread and -std=c++11 to the compiler and linker options and the compiler specs, as well as setting the language standard to ISO C++11. I am using Eclipse neon.3 with minGW 6.3.0-1, and I have updated all of my packages.

The code does run, but I would like to get rid of the error if possible.

Do I need a different version of mingw? Should I just switch to mingw-w64?

Here is my toolchain, for reference:

GCC Assembler

GCC Archiver

GCC C++ Compiler

GCC C Compiler

MinGW C Linker

MinGW C++ Linker

And the simple code that gives this error:

#include <thread>
#include <iostream>

void call_from_thread() {
    std::cout << "Hello!" << std::endl;
}

int main() {
    std::thread t1(call_from_thread);
    return 0;
}

Connecting to Websphere MQ in C# works, but fails in C++ with code 2058 (MQRC_Q_MGR_NAME_ERROR)

I need to write a piece of code to put a message into MQ using C++. When I test it on localhost, using the default port (1414) it works. However, in the actual environment, which uses specific channel definition and different port (1420), it fails with reason code 2058 / MQRC_Q_MGR_NAME_ERROR. There is no problem connecting to the remote MQ using Websphere MQ Explorer. There is also no problem connecting to the same remote server in a C# app to prove connectivity. Any ideas what could be causing it?

Some sample code extract: C++ which fails when .connect() is called...

ImqChannel * pChannel_ = 0;  // Channel definition which is at class level
ImqQueueManager queueManager_;   // Queue Manager, also declared at class level


// extract from the MQHelper::Connect() method... 
int MQClient::Connect() {
   pChannel_ = new ImqChannel;
   pChannel_->setChannelName("CLCHL.QM");
   pChannel_->setTransportType(MQXPT_TCP);
   pChannel_->setConnectionName("10.2.3.4(1420)");
   pChannel_->setModeName("Client");

   queueManager_.setName("QM");
   queueManager_.setChannelReference(pChannel_);

   if (!queueManager_.connect()) {
      // ERROR IS HERE: _lastCompletionCode is 2, _lastReasonCode is 2058
      _lastCompletionCode = queueManager_.completionCode();
      _lastReasonCode = queueManager_.reasonCode();
      return (int)_lastReasonCode;
   }
    // If we get here, we're all good:
   return 0;
}

In C#, there is no such problem: the following code will connect fine..

queueManager = new MQQueueManager("QM", "CLCHL.QM", "10.2.3.4(1420)");

Other info:

  • Server MQ installation is 7.0.1.0 Websphere MQ Explorer version:
  • 7.5.0.1 (no problem connecting here) In the C# app, I am only referencing amqmdnet.dll... all fine.
  • In the C++ app, I have the external dependencies set up for the 26 various mq .h or .hpp files.
  • Also I have included the appropriate libs etc... again - I know it is capable of working as it the same code will work pointing to a localhost queue manager.
  • I am using VS 2017

Any ideas?

C++ variable type conditional

I have two Classes TreeNodeRange(Tree & t) and VertexNodeRange(Vertex & v). Looping over the first is equal to looping over all nodes in a tree whereas looping over the second is equal to looping over all nodes that a children to a given vertex v.

Now depending on user input I would like to either loop over the whole tree or only the subtree that starts at v.

I tried something like this:

const bool only_subtree = to_bool(argv[1]);
typedef std::conditional<only_subtree, VertexNodeRange,TreeNodeRange>::type NodeRange; 

The problem is now that I don't see how I can define an object of type NodeRange. I tried:

Vertex v = tree.get_vertex_by_id(17);
NodeRange get_range = [&](const bool only_subtree, Vertex & v)
    {
        if(only_subtree) return NodeRange(v);
        return NodeRange(tree);
    };
for(auto node : get_range(only_subtree, v)){
    ...
}

The compiler doesn't seem to like this since the constructor NodeRange must be callable with either Vertex or Tree which of course it does not.

It there a way to do this in C++ at all?

Cheers

Why is_heap() not validating the heap created by me though it is valid conceptually

I wrote a heap implementation in C++ and later today I came to know that, there are inbuilt functions in C++11 that can make any range based container a heap.

So out of curiosity I made a vector into heap using my own implementation and used the function make_heap() and then ran is_heap() on both of them.

The one made using make_heap() verified to true, but mine did not, even though it is technically valid.

Source code and screenshots below

Main heapify function

vector<int> heapify(vector<int> nums, string const & type) {
    int n = nums.size();
    for (int i = n - 1; i >= 0; i--) {
        int parent = floor((i-1)/2);

        if (parent >= 0) {
            if (type == "min") {
                if (nums[i] < nums[parent]) {
                    swap(nums[i], nums[parent]);
                }
            } else {
                if (nums[i] > nums[parent]) {
                    swap(nums[i], nums[parent]);
                }
            }
        }
    }
    return nums;
}

Function that builds the heap

vector<int> buildHeap(vector<int> const & nums, string const & type) {
    vector<int> heap;
    int n = nums.size();
    for (int i = 0; i < n; i++) {
        heap.push_back(nums[i]);
        if (!heap.empty()) {
            heap = heapify(heap, type);
        }
    }
    return heap;
}

Remove the top most element

int getTop(vector<int> & nums, string const & type) {
    int n = nums.size();
    if (n < 0) {
        throw string("Size of array is less than 0");
    } else {
        int minElem = nums[0];
        swap(nums[0], nums[n-1]);
        nums.pop_back();
        nums = heapify(nums, type);
        return minElem;
    }
}

Main function

int main()
{
    vector<int> nums = {45, 56, 78, 89, 21, 38, 6, 67, 112, 45, 3, 1};
    vector<int> heap = buildHeap(nums, "min");
    for (int num : heap) {
        cout << num << " ";
    }
    cout << "\n";

    cout << std::is_heap(nums.begin(), nums.end(), greater<int>()) << "\n";
    make_heap(nums.begin(), nums.end(), greater<int>());
    for (int num : nums) {
        cout << num << " ";
    }
    cout << "\n";
    cout << std::is_heap(nums.begin(), nums.end(), greater<int>()) << "\n";
    return 0;
}

Screenshots of output on console and verification on http://ift.tt/1JBWNjW

Output Console

Output verification

Error while subclassing QGridLayout

I'm trying to subclassing QGridLayout for building a widget to set as layout for a QDialog. When I try to do "setLayout(view);" inside the View_currentSpec constructor I have an error from the compiler which says that "view is not declared for this scope". Am I doing something wrong?

class View_currentSpec : public QDialog{
Q_OBJECT
public:
    View_currentSpec(species* spec, std::string sho, QWidget* parent = 0);
private:
    species* currentSpec;
    std::string showType;
};

View_currentSpec :: View_currentSpec(species* spec, std::string sho, 
                                     QWidget* parent)
  : QDialog(parent), currentSpec(spec), showType(sho){

     setWindowTitle("Visualizzazione specie");
     setFixedWidth(500);
     setFixedHeight(500);

     if(View_Species* view = Spec_Selection :: build(currentSpec)){
         if(showType == "show") view -> buildShow();
     }
     setLayout(view);
}

View_Species* Spec_Selection :: build(species* currentSpec){
    if(dynamic_cast<animals*>(currentSpec))
        return new View_Species(currentSpec);
    return nullptr;
}

class View_Species : public QGridLayout{
    Q_OBJECT
public:
    View_Species(species* spec, QWidget* parent = nullptr);

    void buildShow();
protected:
    species* currentSpec;

    QLineEdit* nome_spec;

    virtual void buildSpecView();
};

View_Species :: View_Species(species* spec, QWidget* parent)
    : QGridLayout(parent), currentSpec(spec){
}

void View_Species :: buildShow(){
    buildSpecView();
}

void View_Species :: buildSpecView(){

    QLabel* nome = new QLabel("Nome Specie");

    nome_spec = new QLineEdit();
    nome_spec -> setText("aaa");

    addWidget(nome, 0, 0);
    addWidget(nome_spec, 1, 0);

}

Type agnostic getter methods

I'm writing a client for a system that returns values of natural types in random order (some can be int, others float, others string [well, almost natural]). The problem is, I don't know what type a value will be at compile time.

Since I don't know the type of the value to be returned until after the remote system has been queried, what is the best way to provide a uniform interface that allows a user of the client library to extract the value in the right type?

If querying the remote system once returns a string, I'd like my get_value() to return a string. If an int, make it return an int. Alternatively, how to have the client library call the getter with the right type?

I guess templates with type hinting would be a good way to achieve this?

_GLIBCXX_USE_CXX11_ABI gcc 4.8

we received some libraries (.a) compiled for linux (probably compiled with GCC 6.x).

We are using GCC 4.8 and we are getting the error of the type: undefined reference to std::__cxx11::basic_string when trying to link.

Normally this could be fixed by making sure all units have been compiled with the same _GLIBCXX_USE_CXX11_ABI flag. However if I understood correctly, this was introduced by GCC 5.1 and on.

  1. Is there a way to make this work with GCC 4.8 or do we need to ask the people to recompile the libraries with a different _GLIBCXX_USE_CXX11_ABI?
  2. I guess switch to GCC >= 5.1 we can make this work?

Thanks!

Why the sum of an int and a float is an int?

float d = 3.14f;
int i = 1;
auto sum = d + i;

The sum is 4. Why does this happen?

According to cpp reference, int will be converted to float.

UVA 10062 Wrong Answer

http://ift.tt/2uclKM9

#include<bits/stdc++.h>
using namespace std;
int compare(pair<int, int> a, pair<int, int> b) {
    if(a.first == b.first) return (a.second> b.second);
    if (a.first < b.first) return 1;
    if (a.first > b.first) return 0;
}

int main(){

    string x;
    while(true){
        pair<int , int> freq[150];
        int free[150]={0};
        getline(cin,x);
        if(x=="")break;
        int f =1;
        for(int i = 0 ; i < x.length();i++){
            if(free[int(x[i])])
            {
                freq[free[int(x[i])]].first++;
            }
            else{
                free[int(x[i])]= f;
                freq[f++]= make_pair(1,int(x[i]));
            }
        }
        sort(freq,freq+f,compare);
        for(int i = 1 ; i < f ; i++){
            cout<<freq[i].second<<" "<<freq[i].first<<endl;
        }
        cout<<endl;
    }
}

As simple this problem could be, I don't know why I get the wrong answer. All I did is as follows:

  1. Made two arrays, one to store the frequency along with the value of the char and the other to check what char already existed within the first array to increase the frequency

  2. Sorted using the compare function I created above

  3. Output the array with an extra \n in the end

std::forward and factory that calls std::make_shared

I have code like this...

X* raw = ::new X("abc");
// do something benign to object
std::shared_ptr<X> ptr(raw);

Now consider the same using an object factory...

template<typename T, typename... A>
std::shared_pointer<T> factory(A&&... args) {
    auto ptr = std::make_shared<T>(std::forward<A>(args)...);
    // do something benign to object
    return ptr;
}

std::shared_ptr<X> ptr = factory<X>("abc");    

This is a simplified example, but I'm seeing an unexplained crash when using the factory that appears to be due to a corrupted shared pointer.

I'm not familiar with the innards of std::make_shared, but am wondering if it in turn does something like argument forwarding to placement ::new, and that this chain forwarding is a problem.

Signals and slots with std::vector : lvalue issue

In one of my project, I am trying to use the Qt signals and slots mechanism with a std::vector<bool> as parameter. My project is equivalent to the following minimal code :

class App

// app.h
#ifndef APP_H
#define APP_H

#include <QObject>
#include <QSharedPointer>

#include "emitter.h"
#include "receiver.h"

class App : public QObject
{
    Q_OBJECT
public:
    App(QObject *parent = 0);

};

#endif // APP_H

// app.cpp

#include "app.h"

App::App(QObject* parent): QObject(parent)
{
    Emitter emitter;
    Receiver receiver;

    receiver.attachEmitter(emitter);
    emitter.run();
}

class Emitter

//emitter.h
#ifndef EMITTER_H
#define EMITTER_H

#include <QObject>
#include <vector>
#include "helper.h"

class Helper;

class Emitter : public QObject
{
    Q_OBJECT
public:
    explicit Emitter(QObject *parent = 0);
    void run();
signals:
    void triggered(std::vector<bool> value);
};

#endif // EMITTER_H

// emitter.cpp
#include "emitter.h"

Emitter::Emitter(QObject *parent) : QObject(parent)
{

}

void Emitter::run()
{
    emit triggered(Helper::value());
}

class Receiver

//receiver.h
#ifndef RECEIVER_H
#define RECEIVER_H

#include <QObject>
#include <QDebug>

#include <QSharedPointer>
#include "emitter.h"

class Emitter;

class Receiver : public QObject
{
    Q_OBJECT
public:
    explicit Receiver(QObject *parent = 0);
    void attachEmitter(QSharedPointer<Emitter> emitter);
signals:

public slots:
};

//receiver.cpp
#include "receiver.h"

Receiver::Receiver(QObject *parent) : QObject(parent)
{

}

void Receiver::attachEmitter(QSharedPointer<Emitter> emitter)
{
    connect(emitter.data(), &Emitter::triggered, [this](std::vector<bool> value) {
        qDebug() << "Received value";
    });
}

For some reason, the compiler doesn't like it at all and prints me this stack : Error stack

What do I have to do ? Thank you

std::move(std::array) g++ vs visual-c++

I had some problem implementing the move constructor for an element in my std::array in my project in visual studio 2013.

So I tried making a minimal example in netbeans that I compiled with g++ 5.3.0 .
Only to find that in g++ I could do what I was trying

example g++:

#include <iostream>
#include <array>

using namespace std;

struct A{
    A() = default;
    A(const A&)
    {
        cout << "copy constructed" << endl;
    }
    A(A&&)
    {
        cout << "move constructed" << endl;
    }
};

class B{
public:
    B(array<A, 2>& a)
      : m_a(std::move(a))
    {}
private:
    array<A, 2> m_a;
};

int main(){
    A foo;
    cout << "=========1===========" << endl;
    array<A, 2> a = { { foo, std::move(foo) } };
    cout << "=========2===========" << endl;
    B b(a);
    cout << "=========3===========" << endl;
    array<A, 2> a_second = std::move(a);
    return 0;
}

Output:

=========1===========
copy constructed
move constructed
=========2===========
move constructed
move constructed
=========3===========
move constructed
move constructed

When I tried the (practically) the same code in visual studio 2013 the result was different:

#include "stdafx.h"

#include <iostream>
#include <array>

using namespace std;

struct A
{
    A() = default;
    A(const A&)
    {
        cout << "copy constructed" << endl;
    }
    A(A&&)
    {
        cout << "move constructed" << endl;
    }
};

class B
{
public:
    B(array<A, 2>& a)
        : m_a(std::move(a))
    {
    }
private:
    array<A, 2> m_a;
};

int _tmain(int argc, _TCHAR* argv[])
{
    A foo;
    cout << "=========1===========" << endl;
    array<A, 2> a = { { foo, std::move(foo) } };
    cout << "=========2===========" << endl;
    B b(a);
    cout << "=========3===========" << endl;
    array<A, 2> a_second = std::move(a);
    return 0;
}

Output:

=========1===========
copy constructed
move constructed
=========2===========
copy constructed
copy constructed
=========3===========
copy constructed
copy constructed

How can I use the move constructor in visual c++ and why does visual c++ refuse to use him here?

Reusing a unique_lock in a consumer loop

I stumbled over the following code in Bjarne Stroustrup's "The C++ Programming Language, 4th Edition" on page 119:

queue<Message> mqueue;
condition_variable mcond;
mutex mmutex;

void consumer()
{
    while(true) {
        unique_lock<mutex> lck{mmutex};
        mcond.wait(lck);

        auto m = mqueue.front();
        mqueue.pop();
        lck.unlock();
        // process m
    }
}

There is also a producer thread which pushes Message to the queue and notifies the waiting thread in a loop.

My question is: Is it required to create a new unique_lock in every iteration of the loop? It seems unneccesary to me, because in the next line, mcond.wait(lck), the lock gets unlocked directly after locking it in the line before.

From a performance point of view, couldn't the lck variable just be initialized before the loop starts?

Constant casting in C++ gives 2 different values for the same address [duplicate]

int main()
{
    const int  i = 9;
    const int* p = &i;

    int *c = const_cast<int*>(p);
    *c = 3;
    cout<<"i = "<<i<<endl;
    cout<<"p = "<<p<<endl;
    cout<<"*p = "<<*p<<endl;
    cout<<"c = "<<c<<endl;
    cout<<"*c = "<<*c<<endl;
    cout<<"&i = "<<&i<<endl;


    return 0;
}

Hello all, the previously stated code has an output that doesn't make any sense to me, the output looks like the following C++ code output. My question is, how can you have I have 2 different values in the same memory address? Is it possible? Is there any other case that this might happen in C++? and Can the opposite happen such that compiler moves a value from a specific place in memory and assign it to different place?

Shallow copy of pointers from a map to a vector

I have

map<uint8_t *,MyObject *, lex_compare> my_map;
vector<MyObject *> my_vector;

If I do:

for(auto &pair_el : my_map)
    (pair_el.second)->print();

where print() is a function of the object pointed everything is alright. But I want copy the pointer of map in my_vector (that is empty) (in a shallow way).And I do:

int i=0;
for(auto &pair_el : my_map)
{
    my_vector.push_back(pair_el.second);
    (pair_el.second)->print();
    my_vector[i]->print();
    ++i;
}

but my_vector[i]->print(); goes ,later some execution, in segmentation fault. What could be your problem?

Call method only if pointer is not nullptr

I have an interface class and a pointer that may be nullptr and if it is I just skip the method call:

if (ptr != nullptr)
{
    ptr->SomeMethod();
}

...

if (ptr != nullptr)
{
    ptr->SomeOtherMethod();
}

...

if (ptr != nullptr)
{
    ptr->SomeMethodThatWasntMentionedBefore();
}

I can improve this code readability with the following macro:

#define CALL_IF_NOT_NULLPTR(ptr, method_call) if (ptr != nullptr) { ptr->method_call; };

CALL_IF_NOT_NULLPTR(ptr, SomeMethod());
CALL_IF_NOT_NULLPTR(ptr, SomeOtherMethod());
CALL_IF_NOT_NULLPTR(ptr, SomeMethodThatWasntMentionedBefore());

Is there any way to do the same without macros (C++11 solutions are preferred)?

Error reading characters of string - for a string value in an array

I am trying to make a program that reads lines from a text files about information for a dvd. After feeding information to the custom dvd class, I am going to be printing it. Currently, when using debugger, it shows the below errors for each of the parameters of the custom class. Please help.

Error reading characters of string

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>
using namespace std;

class dvd
{
    string movieName, movieProdComp, movieLeadActor, movieLanguage, renterName;
    string releaseYear, rentDate, returnDate;
public:
    dvd() {};
    dvd(string line) {};
    dvd(string mn, string mpc, string mla, string ml, string rn, string ry, string rd, string retd);
    void print();
};

dvd::dvd(string mn, string mpc, string mla, string ml, string rn, string ry, string rd, string retd) {
    movieName = mn;
    movieProdComp = mpc;
    movieLeadActor = mla;
    movieLanguage = ml;
    renterName = rn;
    releaseYear = ry;
    rentDate = rd;
    returnDate = retd;
}

void dvd::print() {
    cout << "Movie:" << movieName << endl;
    cout << "Production:" << movieProdComp << endl;
    cout << "Starring:" << movieLeadActor << endl;
    cout << "Language:" << movieLanguage << endl;
    cout << "Rented By:" << renterName << endl;
    cout << "Released:" << releaseYear << endl;
    cout << "Rent Date:" << rentDate << endl;
    cout << "Return Date:" << returnDate << endl;
}

int main() {
    string filepath = "C:\\Users\\SuperUser\\Google Drive\\COMP306\\TMA2\\test.txt";
    string line;
    ifstream file(filepath);
    string arrayDvd[10][8];
    if (file.is_open())
    {

        int i = 0;
        int c = 0;
        int n = 0;
        while (getline(file, line))
        {   
            arrayDvd[n][c] = line;
            i++;
            c++;
            if (i > 7)
            {
                n++;
                c=i = 0;
            }           
        }
    }

    for (int n = 0; n <= 9; n++) 
    {
        //this is where the error shows.
        dvd dvdS[] = { arrayDvd[n][0], arrayDvd[n][1], arrayDvd[n][2], arrayDvd[n][3], arrayDvd[n][4], arrayDvd[n][5], arrayDvd[n][6], arrayDvd[n][7] };
    }
}

What happens when a copy of shared_ptr is made?

I want to understand how the reference count of the managed object in a shared_ptr is affected when a shared_ptr is assigned to another.

I came across the following statement in C++ primer, 5th edition, that:

For example, the counter associated with a shared_ptr is incremented when ... we use it as the right-hand operand of an assignment... The counter is decremented when we assign a new value to the shared_ptr...

As an example its shown there:

auto p = make_shared<int>(42); // object to which p points has one user

auto q(p); // p and q point to the same object
           // object to which p and q point has two users

auto r = make_shared<int>(42); // int to which r points has one user
r = q; // assign to r, making it point to a different address
       // increase the use count for the object to which q points
       // reduce the use count of the object to which r had pointed
       // the object r had pointed to has no users; that object is automatically freed

When I run a similar code, the above is not my observation:

Code:

#include<iostream>
#include<memory>

int main()
{
  std::shared_ptr<int> sh1 = std::make_shared<int>(1);
  std::shared_ptr<int> sh2 = std::make_shared<int>(2);

  sh2 = sh1;

  std::cout << "sh1 use count: " << sh1.use_count() << std::endl;
  std::cout << "sh2 use count: " << sh2.use_count() << std::endl;

  return 0;
}

Output:

sh1 use count: 2

sh2 use count: 2

How can the use_count of sh2 also 2? Should not it be 0 as per the mentioned text above? Am I missing something here?

What is the type of a pointer to a 2D array?

I know that the following is not correct:

int arr[2][3] = {}; //some array initialization here
int** ptr;
ptr = arr;

But I am quite surprised that the following lines actually work

int arr[2][3] = {}; //some array initialization here
auto ptr = arr;
int another_arr[2][3] = {}; //some array initialization here
ptr = another_arr;

Can anyone possibly explain what is the type assigned to ptr in the second block of code, and what happened underneath?

dimanche 30 juillet 2017

Understanding stringstream

I have never used stringstream before and was given a sample code but with no explanation of what was happening in the code. If someone could explain each line's purpose that would be great. I have looked in multiple places but cant seem to pin down the second line.

#include <sstream> // i know this line includes the file

stringstream    ss(aStringVariable);// this line in particular 

ss >> aVariable;

getline(ss, stringVariable2HoldValue, ‘|’);

How qml call static method from c++

What I done:

validator.h:

class UTILSSHARED_EXPORT Validator: public QObject {
    Q_OBJECT
public:
    Validator(QObject *parent = 0);
    ~Validator();
    Q_INVOKABLE static bool validateMobile(const QString target);

};

main.cpp:

qmlRegisterUncreatableType<Validator>("CT.Utils", 1, 0, "ValidatorKit", "It just a kit");

qml:

import CT.Utils 1.0
ValidatorKit.validateMobile("112344")

But unfortunately, I got an error that said: TypeError: Property 'validateMobile' of object [object Object] is not a function

So, how can I expose static method to qml correctly?

Could anybody help me? Thanks a lot.

Why c++11 thread crash?

Look the code:

#include <iostream>
#include <thread>

using namespace std;

void task(int index){
    cout<<index<<endl;
}

int main()
{
    thread t1(task,1);
    thread t2(task,2);
    t1.join();
    t2.join();
    return 0;
}

The most time, the program runs normally, but sometimes it crashs? Why does it crash?

How to convert from a web::json::object to a map of strings

I have a json object, where one of the values is a python dictionary, that I'm sending to C++ as JSON.

I was trying to save the value as a std::map<string, string> which I thought would represent the data correctly.

There is a method in this, that can convert the Web JSON object into a json object json::object& web::json::value::as_object.

But there is no further method to convert that into a map of strings. Is the only option to iterate over every one of the values in the JSON object and make the map that way?

c++ Exception thrown: read access violation as 0xDDDDDDDD on VS2015

im trying to build a snake game, and it works just fine, until i gameover, for some reason i get access violation right after the program ends, referring to this->actualState->

here is the code for the cpp file with working on actualState:

#include "Game.h"
using namespace sf;

Game::Game()
    :actualStateID(END)
{
    ContextSettings settings;
    settings.antialiasingLevel = 8;
    window.create(VideoMode(SCRN_WIDTH, SCRN_HEIGHT), "Snake", Style::Close, settings);
    window.setFramerateLimit(60);
    window.clear();
    window.display();

    if (!font.loadFromFile("data/font.ttf"))
    {
        //MessageBox(NULL, "Font not found! Chceck data folder!", "ERROR", NULL);
        return;
    }

    actualStateID = MENU;
}


Game::~Game()
{
}

void Game::runGame()
{
    actualState = new MenuState(MENU, window, font);
    actualState->init();

    while (actualStateID != END)
    {
        if (actualStateID != actualState->getSTATE_ID())
            changeState();

        handleState();
    }
    window.close();
}

void Game::changeState()
{
    delete actualState;

    switch (actualStateID)
    {
    case MENU:
        actualState = new MenuState(MENU, window, font);
        break;
    case PLAY_STATE:
        actualState = new PlayState(PLAY_STATE, window, font);
        break;
    case FAILURE:
        //Image screenShot = window.capture(); //DEPRECATEDDDDDD
        //Image screenShot = Texture.update(window);

        //actualState = new FailureState(FAILURE, window, font, screenShot);
        break;
    }

    actualState->init(); //error line!!
}

void Game::handleState()
{
    actualStateID = actualState->handleEvents(event);
    actualState->update();
    actualState->render();
}

i manage to track the exeption to line 63, but i dont seem to get it to work, srry im pretty new to c++ and sfml

here goes the state.cpp file as well as the detailed error(is there any more detail in VisualStudio?): error image with state.cpp thank you in advance

C++ pass variadic template argument as reference to std::thread via perfect forwarding

Consider this simple variadic template function that spawns a thread and forwards the args to the thread function. Why do I get a template substitution failure on the thread constructor here?

std::thread t;

void test3(int& a)
{
    a = 10;
}

template<class ...Args>
void test(Args&&... args)
{
   t = std::thread(test3, std::forward<Args>(args)...);
}

int main()
{
    auto timer = 2s;

    int a = 1;
    test(a);
    std::this_thread::sleep_for(timer);
    std::cout << a << std::endl;
    t.join();
}

Compiler output:

template argument deduction/substitution failed:
/opt/wandbox/gcc-head/include/c++/8.0.0/bits/invoke.h: In substitution of 
'template<class _Callable, class ... _Args> constexpr typename 
std::__invoke_result<_Functor, _ArgTypes>::type std::__invoke(_Callable&&, 
_Args&& ...) [with _Callable = void (*)(int&); _Args = {int}]':
/opt/wandbox/gcc-head/include/c++/8.0.0/thread:233:29:   required by 
substitution of 'template<long unsigned int ..._Ind> decltype 
(std::__invoke(_S_declval<_Ind>()...)) std::thread::_Invoker<std::tuple<void 
(*)(int&), int> >::_M_invoke<_Ind ...>(std::_Index_tuple<_Ind1 ...>) [with 
long unsigned int ..._Ind = {0, 1}]'
/opt/wandbox/gcc-head/include/c++/8.0.0/thread:240:2:   required from 
'struct std::thread::_Invoker<std::tuple<void (*)(int&), int> >'
/opt/wandbox/gcc-head/include/c++/8.0.0/thread:127:22:   required from 
'std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)
 (int&); _Args = {int&}]'
prog.cc:23:14:   required from 'void test(Args&& ...) [with Args = {int&}]'
prog.cc:43:11:   required from here
/opt/wandbox/gcc-head/include/c++/8.0.0/bits/invoke.h:89:5: error: no type 
named 'type' in 'struct std::__invoke_result<void (*)(int&), int>' 

When I wrap the forwarding of the arguments with a std::ref like this:

std::thread(test3, std::ref(std::forward<Args>(args)...));

It works. Aren't the arguments supposed to be perfectly forwarded in the first place?

Cannot Return Values When Passing Function by Reference To TBB Task

I'm getting my feet wet with Intel TBB and am trying to figure out why I cannot populate a vector passed in by reference to a TBB Task when I also pass in a function by reference.

Here is the code:

// tbbTesting.cpp : Defines the entry point for the console application.

#include "stdafx.h"

#include "tbb/task.h"

#include <functional>
#include <iostream>
#include <random>

#define NUM_POINTS 10


void myFunc(std::vector<double>& numbers)
{
   std::mt19937_64 gen;
   std::uniform_real_distribution<double> dis(0.0, 1000.0);

   for (size_t i = 0; i < NUM_POINTS; i++)
   {
      auto val = dis(gen);
      std::cout << val << std::endl; //proper values generated
      numbers.push_back(val);  //why is this failing?
   }

   std::cout << std::endl;

   for (auto i : numbers)
   {
      std::cout << numbers[i] << std::endl; //garbage values
   }
}


class TASK_generateRandomNumbers : public tbb::task
{
public:
   TASK_generateRandomNumbers(std::function<void(std::vector<double>&)>& fnc, 
std::vector<double>& nums) : _fnc(fnc), _numbers(nums) {}
   ~TASK_generateRandomNumbers() {};

   tbb::task* execute()
   {
      _fnc(_numbers);
      return nullptr;
   }

private:
   std::function<void(std::vector<double>&)>& _fnc;
   std::vector<double>& _numbers;
};


class Manager
{
public:
   Manager() { _numbers.reserve(NUM_POINTS); }
   ~Manager() {}

   void GenerateNumbers()
   {
        _fnc = std::bind(&myFunc, _numbers);
        TASK_generateRandomNumbers* t = new(tbb::task::allocate_root()) 
        TASK_generateRandomNumbers(_fnc, _numbers);
        tbb::task::spawn_root_and_wait(*t);
   }

   auto GetNumbers() const { return _numbers; }

private:
   std::function<void(std::vector<double>&)> _fnc;
   std::vector<double> _numbers;
};



int main()
{
   Manager mgr;
   mgr.GenerateNumbers();
   auto numbers = mgr.GetNumbers(); //returns empty
}

When the execute method performs the operation, I can get values when passing the vector by reference.

When the execute method has to call a function, I get garbage data printed to the console (push_back failing?) and I get an empty container on return.

Can anyone see what I'm missing? Thanks.

Tempate defined by return value of lambda

Let it be a template with requirement of such behavior:

template<typename MyActionLambda>
void enumerateChildrenByTag(QDomNodeList& list, const QString& tag, MyActionLambda action )
{
    for(int i = 0; i < list.size(); i++) {
        QDomElement el = list.item(i).firstChildElement(tag);
        while(!el.isNull())
        {
            if( typeid(decltype(action(el))) == typeid(SomeType) )
            {
                    auto res = action(el)
                    // do something with res
            }
            else
                    // do something with action(el)

            el = el.nextSiblingElement(tag);
        }
    }
}

this obviously would be impossible in way it is written for lambda to have void return type, because both branches of if() should be legal. Is there a simpler way to resolve this except making declspec as a default value of template parameter and specialize two templates?

Entries(

I want save values in a map if an hash function return a value that isn't already contained in the map. The data structure is:

map<uint8_t* , MyObject* , lex_compare> mymap;

where uint8_t* point to un array of 128 bit (uint8_t hash_value[16]) that contain the hash function applied to a field of class MyObject. I use lex_compare for a personalized comparison:

struct lex_compare {
bool operator() (const uint8_t *hash1, const uint8_t *hash2) const {
    /*for(int i=0 ; i<16 ; i++)
             {
                 cout<<(unsigned int)hash1[i]<<" ";
             }
             cout<<endl<<endl;
             for(int i=0 ; i<16 ; i++)
             {
                 cout<<(unsigned int)hash2[i]<<" ";
             }
    int m=memcmp(hash2,hash1,16);
    cout<<"m is è"<<m<<endl;*/
    return memcmp(hash2,hash1,16); //compare 16 byte.
    }
};

To ensure insertion only if an hash value is not already contained in the map I use:

while(mymap.size()<R)
{
myObject *temp_o  = new myObject(parameters);
uint8_t hash_result = my_hash_function(myObject->return_field()) // return_field is a specific field of myObject 
mymap.insert(make_pair(hash_result,temp_o));
}

But only one element is inserted in mymap, thus I go in endless loop. Why? I can not explain it. Look at lex_compare I saw that this function return always zero value (because is called on 2 equals elements). May be is a trivial problem, but I'm not able to see it

Editing array with std::async

The idea was to perform operations on each element of array in parallel. I come up with the following:

struct dataContainer
{
    int value;
    bool flag;
    dataContainer()
        : value(1)
        , flag(true)
    {}
};


int main()
{
    std::vector<dataContainer> arrData;
    arrData.resize(10);

    {
        std::vector<std::future<void> > results;
        std::for_each(arrData.begin(), arrData.end(), [&results](dataContainer& tData) {

            results.emplace_back(std::async(std::launch::async, [](dataContainer& ttData) {
                ttData.value++;
                ttData.flag = false;
            }, tData));
        });
    }

    return 0;
}

However, lambda called by std::async doesn't perform operations on elements of arrData. Actually, I don't understand what is happening. It appears that operations are performed on local copy of dataContainer.

So the question is what is happening, and how can I perform operations on array elements in this manner?

"Error: void value not ignored as it ought to be" - Understanding the error and trying to overcome it

Following is my code snippet.The error occurs in the display_results() method.

    class results
    {
    public:
        bool majority;
        int major_element = 0;

    void show_results()
        {
            if (majority)
            {
                cout<<"Majority found "<<major_element;
            }

            else
                cout<<"No majority element found";
        }
    };
void display_results(results* p, int number_of_testcases)
    {
        for(int i = 0; i<number_of_testcases;i++)
        {
          //Error occurs in next line  
         *p[i].show_results();
        }
    }

Can anyone explain me why is this happening?

How can you insert the return value of a lambda in a vector?

I am trying to use a lambda for a frequently occurring vector insertion to prevent calling an equivalent function:

std::vector<vector<double>> A
A.push_back(
            //*
            someFunction(lots, of, parameters, to, deal, with)
            //*/
            /*
            [&]() -> vector<double> 
            {
                //body identical to that of someFunction        
            }
            //*/
           );

The return and body of someFunction is identical to that of the lambda.

  • Is there something wrong with the syntax?
  • Is this even worth the effort (considering the reduced readability) or is the effect going to be identical?

How to compile "#include

i am having trouble while compiling with the header "#include" in codeblocks!!! Would appreciate any help on how to sucessfully compile with the header!!!

how can I parse a string of integers(signed numbers with range of int) in c++? [duplicate]

This question already has an answer here:

I have seen old solution, want to see a new way if there is one using c++11 or c++14.

Following are the two solutions that I have found.

#include <string>
#include <sstream>

int main() {
    std::string s = "100 123 42";
    std::istringstream is( s );
    int n;
    while( is >> n ) {
         // do something with n
    }
}


#include <sstream>
#include <vector>
#include <string>

std::string myString = "10 15 20 23";
std::stringstream iss( myString );

int number;
std::vector<int> myNumbers;
while ( iss >> number )
  myNumbers.push_back( number );

How can I setup CPLEX 12.7.1 in XCode 8.3.3 for a C++ code?

I am trying to link CPLEX to XCode for a C++ project. Currently I am using one of the examples provided in the CPLEX package, to ensure any bugs in my code don't affect the setup.

I have followed all of the steps in the following tutorial: http://ift.tt/1p0oCJZ however, I still receive the error message:

ld: library not found for -lcplex clang: error: linker command failed with exit code 1 (use -v to see invocation)

I have so far been unable to find any tutorials with any additional steps, or a tutorial with the most up-to-date versions of either software.

Any help with this would be hugely appreciated.

change positive numbers of array into their negative alternative with bitwise operations

I am trying change positive elements of array into their negative alternative with bitwise operations.I wrote this but its not working. I can't understand why. Can someone help me? thanks!

#include <iostream>
using namespace std;
#define n 5
void shecvla(int x)
{
  int k = sizeof(int) * 8, m = 1;
  for (int i = 0; i < k; i++)
    m <<= 1;
  if ((x & m) == 0)
    ~(x) + 1;
}

void alternativa(int a[], int k)
{
  for (int i = 0; i < k; i++)
    shecvla(a[i]);
}

void orobiti(int s)
{
  unsigned int m = 1;
  int k = sizeof(int) * 8;
  for (int i = 0; i < k - 1; i++)
    m <<= 1;
  for (int i = 0; i < k; i++) {
    if ((s & m) != 0)
      cout << 1;
    else
      cout << 0;
    m >>= 1;
  }
  cout << endl;
}

void print(int a[], int k)
{
  for (int i = 0; i < k; i++)
    orobiti(a[i]);
}

main()
{
  int a[n];
  for (int i = 0; i < n; i++)
    cin >> a[i];
  print(a, n);
  alternativa(a, n);
  cout << endl;
  print(a, n);
  for (int i = 0; i < n; i++)
    cout << a[i] << " ";
  system("pause");
  return 0;
}

samedi 29 juillet 2017

getting linking Error while creating a flyweight_pattern

#include <iostream>
#include <map>
#include <string>
#include <cstdlib>

using namespace std;

class Shape 
{
public :
    virtual void draw()=0;
    virtual ~Shape(){}
};

class Circle : public Shape
{
   string color;
   int x;
   int y;
   int radius;
public:
  Circle(string color){
      color = color;        
   }

    void setX(int x) {
       x = x;
   }

    void setY(int y) {
      y = y;
   }

    void setRadius(int radius) {
      radius = radius;
   }
    void draw() {
     cout << "color :" << color << x << y ; 
   }
};

class ShapeFactory {
public:
    static map<string, Shape*> circlemap;
    static Shape* getcircle(string color)
    {
        Shape *mcircle;
        mcircle = circlemap.find(color)->second;
        if(mcircle == nullptr) {
         mcircle = new Circle(color);
         circlemap[color] = mcircle;
        // circlemap.insert(std::make_pair(color,mcircle));
        }
        return mcircle;
    }

};

class Flyweightpattern
{
public:

    static string getRandomColor(string colors[]) {
      int m_rand = rand() % 5; 
      return colors[m_rand];
   }
    static int getRandomX() {
      return (int)(rand() % 100);
   }
    static int getRandomY() {
      return (int)(rand() % 100);
   }

};

int main()
{
    string colors[] = { "Red", "Green", "Blue", "White", "Black" };

      for(int i=0; i < 20; ++i) {
         Circle *circle = dynamic_cast<Circle *>(ShapeFactory::getcircle(Flyweightpattern::getRandomColor(colors)));
         circle->setX(Flyweightpattern::getRandomX());
         circle->setY(Flyweightpattern::getRandomY());
         circle->setRadius(100);
         circle->draw();
      }

      getchar();
      return 0;
   }

I am getting the linking error during run is below :

flyweight_pattern.obj : error LNK2001: unresolved external symbol "public: static class std::map,class std::allocator >,class Circle *,struct std::less,class std::allocator > >,class std::allocator,class std::allocator > const ,class Circle *> > > ShapeFactory::circlemap" (?circlemap@ShapeFactory@@2V?$map@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@PAVCircle@@U?$less@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@2@V?$allocator@U?$pair@$$CBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@PAVCircle@@@std@@@2@@std@@A)

I have a map in the ShapeFactory class and tried to creating filling the map in the class itself but still not able to resolve the problem.

System design for a client server architecture

I am trying to design and implement a solution for the following problem I am facing in one of my projects.

There are n (say 30) clients that send me data points of the form {timestamp, object}, where ‘timestamp’ comes in strictly ascending order.

I (server) need to listen for them and process the aggregated data from all clients for each time stamp in the following cases:

  1. I hear from all 30 clients for a single timestamp.
  2. I time out waiting to hear from a subset of the clients. This time out starts after I receive data for a time stamp for the first time.
  3. A subset of clients send data of timestamp higher than the one I need to process for (in this case I should process before the time out for whatever data I aggregated).

Is there a better way than maintaining bitmap of 30 clients for each timestamp, using background threads to continuously check the bitmaps and receive messages from forked listener process if higher timestamp is seen for any client? I would like something that is fast because the amount of data to be received in one hour is around 200 GB.

Any suggestions are appreciated, I don't have much experience in C++ systems programming. Can ZeroMQ or Apache Kafka be used here? I don't know much about any of them, I am willing to learn and implement; I just need some guidance. Please comment if you need any more details about anything, I apologise for missing anything.

Invoking a pure virutal method within a thread

I have the requirement of invoking a pure virtual method implementation when spawning a thread from within a based class method as shown below.

#include <iostream>

class Foo {
  private:
    std::thread tr;

  public:
    virtual void baz() = 0;
    void foo() {
      this->tr = std::thread([=] { this->baz(); });
    }

};

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

};

Main class...

#include <thread>
#include "test.hpp"

int main(int argc, char* argv[]) {
  Bar b;
  b.foo();
}

But it fails with the message

terminate called without an active exception

pure virtual method called

The message "pure virtual method called" appears only in some of the failure messages. What am I doing wrong? Is it something related to Bar or the thread getting improperly destructed?

Is it possible to combine c++ with any language?

I heard from a book (Professional C++) that c++ can be combined with like many languages, close to all by using "extern"

for example

extern "Lua" {
     //Some code in Lua
};

extern "Python" {
     //Some code in Python
};

extern "C" {
     //Some code in C
};

int main(int argc, char* argv[]){
     //Some C++ code
     return 0;
}

Now I know that you can combine C and ASM with c++, but like I said before can we use a lot more other languages like Lua Python PHP etc.

Or does it only work with languages that are dependent on C/C++?

Delete Duplicate Members of N-Dimensional Vector

Recursive templates are still quite confusing to me, and I don't feel like I'm using them as well as I should be. For example, I tried to use recursive templates to write a function that will remove all duplicate members of an n-dimensional vector, and I believe that I have some code that works. However, I'm almost confident that there's a better way to do this:

  template <typename T>
  void remove_if_duplicate(std::vector<T>& vec, bool at_end)
  {
    static std::set<T> seen;
    if(!at_end)
    {
      auto newEnd = std::remove_if(vec.begin(), vec.end(), [=](const T& value)
      {
        if(seen.find(value) != std::end(seen))
          return true;

        seen.insert(value);
        return false;
      });
      vec.erase(newEnd, vec.end());
      std::cout << "\n\nhere: " << at_end << "\n\n";
    }
    if(at_end) {seen.clear();}
  }

  template <typename T>
  void remove_if_duplicate(std::vector<std::vector<T>>& v, bool at_end)
  {
    if(!at_end)
    {
      for(unsigned int i = 0; i < v.size(); i++)
      {
        remove_if_duplicate(v[i], at_end);
      }
    }
    if(at_end) {remove_if_duplicate(v[0], at_end);}
  }

template <typename T>
void remove_duplicates(std::vector<std::vector<T>>& v)
{
  remove_if_duplicate(v, false);
  remove_if_duplicate(v, true);
}

See an example here: http://ift.tt/2v80T10

Notice how I declare the set variable "seen" as a static variable of the base function. I have do this so that I still have access to previous items that I have "seen" before even when iterating through multidimensional vectors. I cannot declare the "seen" variable inside the second function because the base type that the multidimensional vectors is templated on is unknown at that point (and then the case of a single-dimensional vector wouldn't work either). So then I have to pass booleans into these functions in order to decide when to actually clear the static set variable so that I can use this function again for other n-dimensional vectors.

While it seems to work so far and is giving me the behavior I want, I'm not sure if any unexpected bugs will appear as a result of my poor implementation. I think that the way that I have done this here is far from ideal, and I'm sure there's a better, more efficient way. How would you do it differently?

no Output while preorder traversing the Tree

I'm a rookie programmer.I made a program on insertion and preorder traversal in a binary search tree. But the problem is that the preorder traversal function is not printing anything. when I try to traverse the tree, nothing is printed. I tried fixing the problem but unfortunately, I was not able to fix it...please help.....

 #include<iostream>
 #include<stdio.h>
 using namespace std;
 struct node
 {
     int data;
     struct node* left;
     struct node* right;
 };

 void insert(struct node * root,int k)
{
struct node *n,*pre;
n=(struct node *)malloc(sizeof(struct node));
n->left=NULL;
n->right=NULL;
n->data=k;
if(root==NULL)
 root=n;
else
 {
 pre=root;
 while(pre!=NULL)
 {
    if(k<pre->data)
    {  
        if(pre->left==NULL)
          {
           pre->left=n;
          }
        pre=pre->left;
    }
    else if(k>pre->data)
    {
        if(pre->right==NULL)
          {
             pre->right=n;
          }
        pre=pre->right;
    }

 }

  }
 }
 void traversal(struct node * root)
 {
 if(root!=NULL)
 {
    cout<<root->data<<endl;
    traversal(root->left);
    traversal(root->right);
 }

 }

 int main()
 {
   struct node *root=NULL;
   int i,data;
   while(1)
   {
     cout<<"1.Enter into tree"<<endl;
     cout<<"2.traverse"<<endl;
     cout<<"3.exit"<<endl;
     cin>>i;
     switch(i)
     {
        case 1:cout<<"input a number:";
               cin>>data;
               insert(root,data);
               break;
        case 2:cout<<"The elements of the tree:"<<endl;
               traversal(root);
               break;
        case 3:cout<<"Exiting.... || bye!";
               exit(0);      
               break; 
    }
   }
  }

How should I iteratively filter data from big vectors without repeating checks?

I am trying to filter some data in the following scenario: I have a bunch of vector<double> representing n-dimensional points. They can be distinguished into UpperLevel (UL) points x and LowerLevel (LL) points y_i.

There is a single upper level problem and an upper level function f(x), corresponding to a set of UL points (stored in vector<vector<double>> UL_Points) and multiple lower level problems (LLPs) and lower level functions g_i(x,y_i), each corresponding to one set of LL points of varying dimensionalities.

For each UL point I evaluated the UL function for all points and created a std::multimap<double, vector<double> *> UL_Candidates ordering the UL points by their function value. (Low is good)

Now my task is to select a few LL points in such a way that they 'eliminate' a large number of preferably good UL points.

An UL point x is eliminated if there exists any LL point y_i such that the corresponding LL function g_i(x,y_i) is positive.

Since f and the g_i are continuous functions I am using the heuristic to check each UL point of the multimap from lowest to highest against consecutive points in the lower levels. Once I found a violation, g_i(x,y_i) > 0 I keep going until I find a decrease in g_i, and select the previous point y_i that caused the local maximum.

Once a point y_i is selected I do not need to check it again.

Below I posted two implementations:

  1. Uses a std::vector<std::list> to keep track of the indices of LL points in each LLP. If a LL point is selected it deletes the corresponding index.

  2. Directly deletes the LL points (which are stored in a vector<vector<vector<double>>> LL_Points_ of size data.nLLPs).

To my surprise version 2 is more than twice as fast as version 1. I previously tried another version with a forward list, was slightly faster than version 1 but still way slower than version 2.

Due to the required reordering I assumed the deletion of the vectors would be significantly slower, permitting the extra overhead of creating and maintaining the list but it seems I am wrong...

Another possiblility could be that my limited programming experience is causing me to do something stupid, or overlook something elementary, so by all means please enlighten me!

auto minNumPoints(5);
auto maxNumRuns(5); // Runs without a cut

//*/DEBUG:
t1 = std::chrono::steady_clock::now();
//*/
auto UL_Iter = UL_Candidates.begin();
auto UL_End = UL_Candidates.end();
vector<list<vector<double> *>> LL_Pointers(data.nLLPs);
for(auto LLP(0); LLP < data.nLLPs; ++LLP) {
    for(int p = 0; p < data.nLL_Points_[LLP]; ++p) {
        LL_Pointers[LLP].push_back(&LL_Points_[LLP][p]);
    }
}

std::multimap<double, vector<double> *> LL_Candidates1;
auto run(1);
double last = -INFINITY;
while(LL_Candidates1.size() < minNumPoints && run <= maxNumRuns) {
    for(auto LLP(0); LLP < data.nLLPs; ++LLP) {
        auto LL_Pointer = LL_Pointers[LLP].begin();
        auto LL_End = LL_Pointers[LLP].end();
        while (++LL_Pointer != LL_End) {
            tester.defineLL_Constants(LLP, *UL_Iter->second, **LL_Pointer);
            auto current = tester.test(LLP + 1);
            if(last > 0 && last > current) { // We've got a new cut...
                LL_Candidates1.emplace(
                                       (maxObjective - UL_Iter->first)/
                                       (maxObjective - minObjective),
                                       std::move(*(--LL_Pointer))
                                      );
                LL_Pointers[LLP].erase(LL_Pointer);
                last = -INFINITY;
                run = 0;
                if(++UL_Iter == UL_End) goto END1;
            }
            else {
                last = current;
            }
        }
        if(last > 0 && LL_Pointer != LL_End) { // positive local maximum at a boundary
            LL_Candidates1.emplace(
                                   (maxObjective - UL_Iter->first)/
                                   (maxObjective - minObjective),
                                   std::move(*(--LL_Pointer))
                                  );
            LL_Pointers[LLP].erase(LL_Pointer);
            last = -INFINITY;
            run = 0;
            if(++UL_Iter == UL_End) goto END1;
        }
    }
    if(run++ && ++UL_Iter == UL_End) goto END1; // increment if no cut
    // We checked all of the LL_Points_ at least once
}
END1:// All UL_Candidates (and thus all UL_Points) are infeasible


//*/DEBUG:
t2 = std::chrono::steady_clock::now();
duration = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();
cout << "LL-evaluation1: " << duration/1e6 << endl;
//*/

//*/DEBUG:
t1 = std::chrono::steady_clock::now();
//*/

UL_Iter = UL_Candidates.begin();
UL_End = UL_Candidates.end();
std::multimap<double, vector<double> *> LL_Candidates2;
auto toDelete = vector<size_t>();
toDelete.reserve(maxNumRuns);
run = 1;
last = -INFINITY;
while(LL_Candidates2.size() < minNumPoints && run <= maxNumRuns) {
    for(auto LLP(0); LLP < data.nLLPs; ++LLP) {
        for(auto p(0); p < data.nLL_Points_[LLP]; ++p) {
            tester.defineLL_Constants(LLP, *UL_Iter->second, LL_Points_[LLP][p]);
            auto current = tester.test(LLP + 1);
            if(last > 0 && last > current) { // We've got a new cut...
                LL_Candidates2.emplace(
                                       (maxObjective - UL_Iter->first)/
                                       (maxObjective - minObjective),
                                       std::move(&LL_Points_[LLP][p-1])
                                      );
                toDelete.push_back(p-1);
                last = -INFINITY;
                run = 0;
                if(++UL_Iter == UL_End) goto END2;
            }
            last = current;
        }
        if(last > 0) { // We had positive local maximum at a boundary
            LL_Candidates2.emplace(
                                   (maxObjective - UL_Iter->first)/
                                   (maxObjective - minObjective),
                                   std::move(&LL_Points_[LLP].back())
                                  );
            toDelete.push_back(data.nLL_Points_[LLP]-1);
            last = -INFINITY;
            run = 0;
            if(++UL_Iter == UL_End) goto END2;
        }
        if(!toDelete.empty()) {
            auto deleted(0);
            for(auto index : toDelete) {
                LL_Points_[LLP].erase(LL_Points_[LLP].begin() + index - deleted++);
            }
            data.nLL_Points_[LLP] -= deleted;
            data.nLL_Points -= deleted;
            toDelete.clear();
        }
    }
    if(run++ && ++UL_Iter == UL_End) goto END2; // increment if no cut
// We checked all of the LL_Points_ at least once
}
//*/
END2:// All UL_Candidates (and thus all UL_Points) are infeasible
//*/DEBUG:
t2 = std::chrono::steady_clock::now();
duration = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();
cout << "LL-evaluation2: " << duration/1e6 << endl;
//*/

segmentation fault (core dumped) pointer struct data type

i am trying to create a tree using struct in C

#include<stdio.h>
#include<stdlib.h>

struct node{
  int data;
  struct node * next, * left, * right;
};

struct node * createtree(int data){
  struct node * kosong = (struct node*)malloc(sizeof(struct node*));
  kosong->data = data;
  kosong->left = kosong->right = NULL;
  return kosong;
}

void printtree(struct node * tree){
  if(tree == NULL) return;
  printtree(tree->left);
  printf("%d ",tree->data);
  printtree(tree->right);
}

int main(){
  struct node * pohon = NULL;
  pohon = createtree(1);
  pohon->left = createtree(2);
  pohon->right = createtree(3);
  pohon->left->left = createtree(4);
  pohon->left->right = createtree(5);
  printtree(pohon);
}

whenever i compile it gets segmentation fault. Then i try to delete the * next pointer and it compiles & run successfully. I know tree does not need the * next pointer , but i dont see why it wont compile just because of another same pointer. Appreciate your help.

convert custom hex code to string in c++

I'm trying to write simple encryption, please take look at below code I expecting it return

hello

by map with mapOfWords array

How to write decode function so, it return string as I'm expecting

#include <iostream>
#include <string>
#include <map>

using namespace std;

std::string decode(const std::string& input) {
    std::map<std::string, std::string> mapOfWords;
    mapOfWords["d2"] = "h";
    mapOfWords["a3"] = "e";
    mapOfWords["c2"] = "l";
    mapOfWords["72"] = "l";
    mapOfWords["84"] = "o";

    std::string result = input;
    return result;
}

int main(int argc, char** argv) {
    std::string sot = decode("\xd2\xa3\xc2\x72\x84");
    std::cout << sot << std::endl;

    return 0;
}

How to access member funtions of a derived Template class if we have a base* class

I have a template class derived from a base class.

Also in main, I have a vector container which contains various types of the derived class. Without knowing the type of the Derived class, how can I access its member functions in main?

Template specializition could be a good solution to this problem. But, how can I do that?

class Base{ // The base class of a template class
public:
    Base(){}
    virtual ~Base(){}
};

template <typename T>
class Derived : public Base{ // The template class,
                             // derived from the base class.
    T data;
public:
     Derived(){}
    ~Derived(){}

       T  get()       { return data; }
     void set( T val) { data = val;  }
};

int main() {

    vector <Base*> myObject;
    // I have different types of Derived class
    // in a vector conteiner.

    Derived<int>  *D1=new Derived<int>;
    Derived<float>*D2=new Derived<float>;
    Derived<char> *D3=new Derived<char>;

    myObject.push_back(D1);
    myObject.push_back(D2);
    myObject.push_back(D3);

    for (int i=0;i<myObject.size();i++){
         // myObject[i]->set(4);  Error! : myObject is a vector of <Base*>
         // myObject[i]->get();   Error! : not a vector of <Derived*>
    }

  return 0;
}

Code out of range. How can this vector be allocated dynamically?

I'm fairly new to c++ and started writing a small poker game to help me get some more experience with vectors. I'm getting a runtime error in the second function, which is really no surprise after reading the post below and discovering I was misunderstanding the behavior of the reserve() class member. I believe I could probably remedy this with resize() but I was hoping for some creative input on a way that I could re-construct this function to allocate dynamically. The difficulty I'm having with the dynamic allocation is that I am trying to make the deal function distribute cards to each player as in a real card game (yes I realize that this is somewhat statistically superfluous). I could do this with pointer math in c fairly easily, and I think I could fix this by statically allocating some of these vectors, but I would prefer to utilize c++ as elegant and efficient as possible. Any suggestions on a way to do this dynamically?

Choice between vector::resize() and vector::reserve()

#include <cassert>
#include <algorithm>
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <vector>

const int __handSize__ = 5;

class Hand {
public:
    std::vector<int> held;
    std::vector<int> played;
};

std::vector<int> shuffle() {
    std::vector<int> deck;
    for( int i = 0; i < 52; i++ ){
        deck.push_back( i );
    }
    std::random_shuffle(deck.begin(), deck.end());
    assert( 52 == deck.size() );
    return deck;
}

std::vector<Hand> deal( int nPlayers, std::vector<int> &deck ) {
    std::vector<Hand> playerHands;
    playerHands.reserve( nPlayers );
    for( int i = 0; i > __handSize__; i++ ) {
        for( int j = 0; j < nPlayers; j++ ) {
            playerHands.at(j).held.push_back( deck.back() );
        }
    }
    return playerHands;
}

int main() {
    srand(time( NULL ));
    std::vector<int> deck = shuffle();
    std::vector<Hand> hand = deal( 3, deck );
    std::cout << hand.at(1).held.at(1) <<std::endl;

}

how to use unnamed non-type parameters for a template

I am reading a text book on meta programming. It mentions that typically non-type template parameters should named as UPPERCASE, and this could result in naming conflict with macro names. One way to resolve this is to avoid naming the non-type template as illustrated below. My question, if the parameter does not have a name, how can it be used in the coding? Would I just use a literal in its place?

example:

template <typename A, bool = false>
class test

What is a good datastructure for runtime efficient filtering in C++?

I have a std::vector<std::vector<double>> samples of representing a list of sampling points in an n-dimensional vector space. I want to evaluate these points with a function and select those with the highest score, but since samples is the result of a cartesian product routine (i.e. the set of all possible combinations of each one-dimensional sampling) it is quite large in general (nSamplesPerDimension^nDimensions).

Therefore I want to prepend a filtering process to the rigorous evaluation of all points which preselects a smaller number of hopefully 'good' candidates (fixed number, e.g. 1e6).

Note that following this filtering, I still need to evaluate the candidates!

My current approach is to use std::multimap<double, vector<double> *> candidates mapping score to candidates, populate this map during the filtering, reorder the points according to the rigorous evaluation and select the best 100 or so.

The issue is, that the filtering procedure uses a non deterministic approach that only gives a very moderate hint to the final score obtained by evaluating a candidate std::vector<double>, therefore the real score might be quite different than the temporary one obtained during filtering, requiring a reordering of the map.

Also, due to the score being used as a key I need to delete the entry corresponding to the temporary key and reinsert with the real score.

Last but not least: I am mainly interested in runtime efficiency (I hope from the numbers up there you see that this is not falling into the category of premature optimization). While memory obviously is an issue as well, I will try to incorporate the filtering during the creation of the samples, i.e. preventing some of the samples to be generated in the first place.

  • This seems to me like a pretty standard workflow, are there any best practices for it?

  • Does it make sense to use different containers for filtering and evaluation (possibly with some algorithm for selecting the k best afterwards)?

Does const and & in std::function ignored?

Why does this code compile?

std::function<void(const int&)> f = [](int a)
{

};

Aren't int and const int& different types?

Better constant definition approach

While exploring SQLite source code for learning purposes I found this in many places within the source code;

#define SQLITE_LOCK_NONE          0
#define SQLITE_LOCK_SHARED        1
#define SQLITE_LOCK_RESERVED      2
#define SQLITE_LOCK_PENDING       3
#define SQLITE_LOCK_EXCLUSIVE     4

#define SQLITE_IOCAP_ATOMIC                 0x00000001
#define SQLITE_IOCAP_ATOMIC512              0x00000002
#define SQLITE_IOCAP_ATOMIC1K               0x00000004
#define SQLITE_IOCAP_ATOMIC2K               0x00000008
#define SQLITE_IOCAP_ATOMIC4K               0x00000010

Is this standard in modern C++ (C++11, 14, 17) or are there different ways to do this in modern C++?

how to put a new line inside a string in c++

i was thinking if it is possible to make a string in c++ which contains data in it like , i dont want to make a string of strings or an array of strings suppose i have a string mv
mv =
"hello
new
world "
hello , new and world are in different lines .now if we print mv then hello , new and world should come on different lines.

i was also thinking in respect to competitive programming if concatenate all the answers of queries in a single string and then output the answer or cout all the queries one by one, will be there a time difference in both the outputs

Why I am getting Compile Error?

I am coding for a contest and I got compile error for this code but when I use some other ide I got correct output.I am using C++ language for my code. I used http://ift.tt/2vg9XkT IDE. Please help me. code

#include <iostream>
#include <algorithm>
std::string decryptRailFence(std::string cipher, int key)
{
    char rail[key][cipher.length()];

    for (int i=0; i < key; i++)
        for (int j=0; j < cipher.length(); j++)
            rail[i][j] = '\n';
    bool dir_down;

    int row = 0, col = 0;

    for (int i=0; i < cipher.length(); i++)
    {
        // check the direction of flow
        if (row == 0)
            dir_down = true;
        if (row == key-1)
            dir_down = false;

        // place the marker
        rail[row][col++] = '*';
        dir_down?row++ : row--;
    }
    int index = 0;
    for (int i=0; i<key; i++)
        for (int j=0; j<cipher.length(); j++)
            if (rail[i][j] == '*' && index<cipher.length())
                rail[i][j] = cipher[index++];

    std::string result;

    row = 0, col = 0;
    for (int i=0; i< cipher.length(); i++)
    {
        // check the direction of flow
        if (row == 0)
            dir_down = true;
        if (row == key-1)
            dir_down = false;

        // place the marker
        if (rail[row][col] != '*')
            result.push_back(rail[row][col++]);

        // find the next row using direction flag
        dir_down?row++: row--;
    }
    return result;
}

//driver program to check the above functions
int main()
{
    int key;
    char c = 'X';

    std::string str1;
    //Now decryption of the same cipher-text
    std::cin>>key;
    std::cin>>str1;
    std::string s= decryptRailFence(str1,key);

    char endch = s.back();

    if(endch == c)
    {
        s.erase(std::remove(s.begin(), s.end(), c), s.end());
    }
    std::cout<<s<<std::endl;
    return 0;
}

Input

5

WTXHUTXAOHXTBIXAS

Output

WHATABOUTTHIS

While using their compiler i get compile time error

vendredi 28 juillet 2017

Operating on slices of Cube in armadillo

I am trying to get used to armadillo linear algebra library for c++ and I cannot figure out hot to operate on slices(matrices) of a cube. Whenever I try to operate on a slice, the program compiles but does not give any output, not even the outputs of statement before the slice operation. Here's the code:

#include <armadillo>
#include <iostream>
using namespace arma;
using namespace std;

int main()
{

Cube<double> A(3  , 5 ,1, fill::randu);

Cube<double>B(5,3,1,fill::randu);
Mat<double>x  =A.slice(0);
Mat<double>y = B.slice(0);
cout << x << "\n" << y << endl;
cout << x*y << endl; //code works fine if this line is removed
}

the problem is that the code works fine if the last line is removed. Why does this happen? Is there a better way to operate on matrices inside a cube ?

Out-parameters and move semantics

Consider a case of a lock-free concurrent data structure where a pop() operation needs to return an item or false if the cointainer is empty (rather than blocking or throwing). The data structure is templated on a user type T, which can potentially be large (but also could be lightweight, and I want things to be efficient in either case). T has to be at least movable, but I don't want it to have to be copyable.

I was thinking that the function signature would be bool DS<T>::pop(T &item) so the item is extracted as an out-parameter rather than return value (which instead is used to indicate success or failure). However, how do I actually pass it out? Assume there's an underlying buffer. Would I do item = std::move(_buff[_tail])—does it make sense to move into a reference out-parameter? A downside is that the user would have to pass in a default-constructed T, which goes a bit against effective RAII because the result is an object that hasn't actually initialized its resources if the function fails.

Another option is returning an std::pair<bool, T> rather than using an out-parameter, but there again needs to be a default-constructible T which holds no resource in the case of failure, for the return std::make_pair(false, T).

A third option would be returning the item as std::unique_ptr<T>, but this incurs useless overhead in the case of T being a pointer or another lightweight type. While I could store just pointers in the data structure with the actual items stored externally, that incurs not just the penalty of additional dereferences and cache misses, but also removes the natural padding that items stored directly in the buffer add and help minimize producer and consumer threads from hitting the same cache lines.

Why move semantics has the same behavior as shallow copy in dynamic mem allocation?

In the classes dealing with dynamic mem allocation, shallow copy basically causes the program to delete a resource twice. In move operations, the original pointer no longer points to the resource, So But why the same behavior occurs in move semantics? e.g:

#include <utility>
#include <cstring>
using namespace std;
class MyString
{
    char* cstr;
 public:
    MyString(const char* arg)
    : cstr(new char[strlen(arg)+1])
    {
        strcpy(cstr, arg);
    }
    MyString(MyString&&) = default;
    MyString& operator=(MyString&&) = default;
    MyString(const MyString&) = delete;
    MyString& operator=(const MyString&) = delete;
    ~MyString()
    {
        delete[] cstr;
    }
};

int main()
{
    MyString S1{"aaa"};
    MyString S2 = move(S1); // error

}

I've tried with 3 different compilers and i got the same results.

All sequences in range n-m of given length

Given a range, for example 5 through 10 I need a way to find all the possible combinations of numbers in that range of a given length, formula should be as efficient as possible.

A basic example:

Given range 1-3 and length 2 then (1,1)(1,2)(1,3)(2,1)(2,2)(2,3)(3,1)(3,2)(3,3).

passing std::shared_ptr> by reference to a function

I am trying to understand the use of shared_ptrs. The simple code below

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

void funct(std::shared_ptr<std::vector<double>> & H){
    H->push_back(1.00); 
}

int main()
{
std::shared_ptr<std::vector<double>> H;
funct(H);
return 0;
}

gives me a segmentation fault which I can't seem to understand. What am I doing wrong here?

C++: When to process packets efficiently?

Short Question: What obvious mistake (misunderstanding?) am I making with the use of std::is_pointer and/or std::is_array within SafeQueue::clear()? The intent is to check for queue of pointers, then check if pointers happen to be unsigned char* or char* arrays.

This is in C++11, wrapping the std::queue class to bring something approaching thread safety.

#ifndef SAFEQUEUE_H
#define SAFEQUEUE_H

#include <queue>
#include <mutex>
#include <type_traits>

template <typename T>
class SafeQueue
{
    public:
        SafeQueue() = default; // default ctor
        SafeQueue(const SafeQueue&) = delete; // disable copy
        SafeQueue& operator=(const SafeQueue&) = delete; // disable assignment

        bool empty() const
        {
            std::unique_lock<std::mutex> ulock(m_mutex);
            return m_queue.empty();
        }

        T& front() // never called without empty() or size() > 0 check
        {
            std::unique_lock<std::mutex> lock(m_mutex);
            if(!m_queue.empty()) { return m_queue.front(); }
        }

        void clear()
        {
            std::unique_lock<std::mutex> lock(m_mutex);
            if(m_queue.empty()) { return; } // quick exit

            bool isPointers = (std::is_pointer<T>::value) ? true : false; // always returns true on class objects
            if(isPointers)
            {
                //bool isarray = std::is_array<T>::value ? true : false; // always returns true on class objects
                bool isarray = (std::is_same<unsigned char*, T>::value || std::is_same<char*, T>::value) ? true : false; // also returns true always
                while(!m_queue.empty())
                {
                    if(isarray) { delete[] m_queue.front(); m_queue.front() = nullptr; }
                    else { delete[] m_queue.front(); m_queue.front() = nullptr; }
                    m_queue.pop();
                }
            }
            else { std::queue<T>().swap(m_queue); }
        }

        void pop()
        {
            std::unique_lock<std::mutex> lock(m_mutex);
            if(!m_queue.empty()) { m_queue.pop(); }
        }

        unsigned int size() const
        {
            std::unique_lock<std::mutex> lock(m_mutex);
            return m_queue.size();
        }

        void push(const T& item)
        {
            std::unique_lock<std::mutex> lock(m_mutex);
            m_queue.push(item);
        }

    protected:
        mutable std::mutex m_mutex;
        std::queue<T> m_queue;
};

#endif // SAFEQUEUE_H

Can you make a computed goto in C++

Fortran has a computationally efficient called a 'computed goto'. The construct uses an index into a branch table to perform a direct goto. If I remember correctly the syntax is:

go to index (lable1, lable2, ...)

where the index is used to reference a code pointer (label) in the parenthesized list.

I have a case where a computed goto is a better solution than a switch statement and would like to construct one but can't figure out how.

Now before the jibes and slings arrive, it is possible for the compiler to optimize a computed goto, but I have no guarantee that it will.

static_assert fails when test condition includes constants defined with const?

I'm reading Bjarne Stroustrup's book, "The C++ Programming Language" and I found an example explaining that static_assert. What I understood is that static_assert only works with things that can be expressed by constant expressions. In other words, it must not include an expression that's meant to be evaluated at runtime.

The following example was used in the book (I did sone changes in the code. But I don't think that should change anything that'd produced by the original example code given in the book.)

#include <iostream>

using namespace std;

void f (double speed)
{
    constexpr double C = 299792.468;
    const double local_max = 160.0/(60*60);
    static_assert(local_max<C,"can't go that fast");
}

int main()
{
        f(3.25);
    cout << "Reached here!";
    return 0;
}

The above gives a compile error. Here's it compiled using ideone: http://ift.tt/2eV5woW The exact code from the book example:

constexpr double C = 299792.458;
void f(double speed)
{ 
    const double local_max = 160.0/(60∗60);
    static_assert(speed<C,"can't go that fast"); // yes this is error
    static_assert(local_max<C,"can't go that fast");
 } 

Why does the compiler search for type,allocator instead of type&?

I'm trying to write a basic function to write a vector of array-like elements to a CSV file:

template <typename T>
void writeCSV(std::string filename, std::vector<T>& mat)
{
    std::ofstream outfile(filename);

    for (std::vector<T>::iterator it = mat.begin(); it != mat.end(); ++it)
    {
        outfile << *it << std::endl;
    }
}

which is used for types for which I have overloaded the << operator as:

std::ostream &operator<<(std::ostream &os, Point2D const &m) {
    return os << m.x << "," << m.y;
}

I use the function as:

std::vector<Point2D> points = complicated_function();
writeCSV<Point2D>("file.csv", points);

This compiles & works just fine in VS2015, but fails when I try to use the exact same code in Simulink (using vs15 as compiler), with the error:

error C2664: 'void csv::writeCSV<Point2d>
(std::string,std::vector,std::allocator>> &)': cannot convert argument 2 from 'std::vector' to 'std::vector,std::allocator>> &'
    with
    [
        _Ty=point_t
    ]

(For some reason, the developer in charge of complicated_function typedef'd all the base types, and point_t is an alias for Point2D.)

My first question is: what am I doing wrong? Additionally, why is the compiler trying to find an allocator?

Second question: when debugging, I tried to pass mat by copy instead of reference:

void writeCSV(std::string filename, std::vector<T> mat)

In this case, the code does not compile at all in VS, with the following error:

Error C2679 binary '<<': no operator found which takes a 
right-hand operand of type 'std::vector<T,std::allocator<_Ty>>' 
(or there is no acceptable conversion)  

However, when I explicitly take care of the overloading by defining by hand

void writeCSV(std::string filename, std::vector<Point2D> mat)

everything works fine, although from my (limited) understanding of templates, this should be almost equivalent since the compiler is supposed to generate one function for each T it encounters. What am I missing?

Thanks.

Filter a list of values at compile time with gnu++11 and no stdlib (Arduino environment)

I'm working on an Arduino project, which means the C++ dialect is currently the gnu++11 superset of C++11, and stdlib is not available (no tuples, no arrays, no nothing; namespace std is just empty!).

For optimization reasons (the CPU has 16K of FLASH, 2K of RAM and this particular low-voltage version runs at 8MHz) I want the compiler to pre-compute as much as possible to provide runtime code, especially the interrupt service routines, with "friendly" data.

Now what I would like to do is the following:

given a list of (unique) integers, I want to extract the values that match an arbitrary filter. Then I want to build an index table that will allow to reach the filtered elements through their initial indices

For instance 2,10,4,7,9,3 with the filter value < 8 could yield the filtered list 2,4,7,3 and the index table 0,-1,1,2,-1,3.
The order of the elements in the filtered array does not matter as long as the index table remains consistent.

The initial list would be given by a plain #define, and the results would be in constant arrays, e.g:

#define my_list 2,10,4,7,9,3

constexpr bool filter (int value) { return value < 8; }

const int    filtered_list [] = filter_list <filter>(my_list);
const size_t filtered_index[] = filter_index<filter>(my_list);

The question is, how to implement these filter_list and filter_index templates with barebone C++11 and no stdlib, if at all feasible?

I don't care about error handling, the abnormal cases like empty lists or duplicate values are already taken care of. I'd rather like to see the simplest possible implementation, even if some assumptions are made about data validity.

I would prefer to have a self-contained C++ source. On the other hand, if what Python could achieve in a couple dozen lines requires pages of cryptic templates, including the rewriting of std::array and std::tuple, I'd rather write some external preprocessor.