vendredi 30 juin 2017

Sorting multiple vectors in single sort call C++

This answer demonstrates how to efficiently obtain an indices vector using std::sort on a vector of values using the nice new-ish C++11 functionality (there's also a variety of duplicates of that question as well). It also hints that you can obtain the double output of both the sorted vector and the sorted indices by "using an extra vector." However, the only way I can achieve this is by calling std:sort a second time. I'm working with arrays with lengths of tens, maybe hundreds, of thousands of elements trying to focus on efficiency. Is it possible to obtain both the sorted vector and the indices of the sort from a single call to std::sort?

More generally, my question is: can one sort multiple vectors with a single sort call? The assumption is the sorting order is based on only one of the supplied vectors.

What I've come up with in the meantime is this (a slight modification to the code in the linked answer), but as you can see, it requires a call to std::sort for each vector being sorted, even though they are all to be ordered according to the sorting of a single vector:

#include <numeric>
#include <algorithm>

using std;

void sort_vectors(vector<size_t> idx, vector<double> &v) {

  // sort indexes based on comparing values in v
  sort(idx.begin(), idx.end(),
       [&v](size_t i1, size_t i2) {return v[i1] < v[i2];});

  // Sort the actual vector
  sort(v.begin(), v.end());

  return idx;
}

How to prevent constructor from creating object when exception is thrown

When a constructor throws an exception, how can I prevent the object from being created?

In the example below, I create a Month() class, for which legal values of the int month_ property are in the range of 1 to 12. I instatiate December, or dec, with integer value 13. The exception is thrown, as it should be, but the object is still created. The destructor is then called.

How do I abort creation of a class instance upon a thrown exception?

OUTPUT

-- Month() constructor called for value: 2
-- Month() constructor called for value: 6
-- Month() constructor called for value: 13
EXCEPTION: Month out of range
2
6
13
-- ~Month() destructor called.
-- ~Month() destructor called.
-- ~Month() destructor called.
Press any key to exit

Minimal, complete, and verifiable example

#include <iostream>
#include <string>

class Month {
public:
    Month(int month) {
        std::cout << "-- Month() constructor called for value: " << month << std::endl;
        try {
            if ((month < 0) || month > 12) throw 100;
        } catch(int e) {
            if (e == 100) std::cout << "EXCEPTION: Month out of range" << std::endl;
        }
        month_ = month;
    }
    ~Month() {
        std::cout << "-- ~Month() destructor called." << std::endl;
    }
    int getMonth()const { return month_; }
private:
    int month_;
};

int makeMonths() {
    Month feb(2), jun(6), dec(13);
    std::cout << feb.getMonth() << std::endl;
    std::cout << jun.getMonth() << std::endl;
    std::cout << dec.getMonth() << std::endl;
    return 0;
}

int main() {
    makeMonths();
    std::cout << "Press any key to exit"; std::cin.get();
    return 0;
}

Android : NDK vs CMAKE optimizations

I recently switched my Android/Application mk file to a CMakeLists.txt file.

A good portion of the code is native in c/c++ (hence why cmake's debugging ability is required).

Now though, I am comparing the two builds, and the one built with ndk is much faster ...

I have added in the "-Os" flag to the

externalNativeBuild {
    cmake {
        arguements "-Os"
    } 
}

block inside the build.gradle file.

My question is what is the differences of compilation here ?? What about ndk-build and cmake is different that would cause this ??

I feel as if this is a dumb question with a quick answer

Why don't you have to implement the constructor of class with a list of objects as data member?

Basically imaging that I have a class A and a class B.

Class A has several data members and class B has a list of A as a data member.

So basically I have my class A constructor by default and there I initialize all the data members like:

A::A(){
this->a = int();
this->s = string();
}

And a private data member of the class B is:

std::list<A> Alist;

One guy at work told me that I don't need to initiate the Alist variable because the compiler will do it automatically.

Normally I do the following:

B::B(){
this->Alist = std::list<A>();
}

Because supposing that for example I have a A object as data member of the class B. In order to create B variable I should make the constructor like:

this->avar = A();

So, Why shouldn't I code the constructor if the data member is a variable? I can't see an explanation.

Thanks.

C++ Limit typedef to numbers

What I mean is this, I have a function in c++ where I want to deposit money into an account. This function should be able to accept floats, doubles, integers, etc. as these are all valid forms of an input, as all I need is a number to deposit.

Thus, I declared:

template <typedef type>
void Deposit(type t) {...}

Now the only issue I have is this: theoretically, a user of this class down the road could pass a char or string to this function and have unintended consequences of doing so. How would I go about restricting type to integers, floats, doubles and shorts? Is it possible to restrict this within the function definition so that others, when programming with this function get a compiler/linter error rather than having to use try{...} catch(...){...}?

how to print the user defined point set information

I have created a set of points(user defined) by overriding < operator. I'm unable to print the set elements.Thanks in advance.

here's the program

#include<bits/stdc++.h>
using namespace std;
class point 
{
double x,y;
public:
point(double x=0,double y=0):x(x),y(y){}
bool operator <(point &p)const
{
  if(x!=p.x && y!=p.y)
  return true;
  return false;
}
friend void show(set<point> &s);
};
void show(set<point> &s)
{
for(auto xx=s.begin();xx!=s.end();xx++)
cout<<(*xx).x<<" "<<(*xx).y<<endl;
}
int main()
{
set<point> s;
for(int x=0;x<10;x++)
s.insert(x,x);
show(s);
return 0;
}

how to write this in vs12?

I'm reading post "64bit" on The AdaptiveRisk Blog, where the sample code has a line can't be compiled in visual studio 2013:

/*!
@brief Helper to determine whether there's a key_type for T.
@sa http://ift.tt/2suequp
*/
template<typename T>
struct has_mapped_type
{
private:
  template<typename C> static char test(typename C::mapped_type*);
  template<typename C> static char(&test(...))[2];
public:
  static constexpr bool value = sizeof(test<T>(0)) == 1;
};

Here static constexpr bool value = sizeof(test<T>(0)) == 1; using constexpr could not be compiled. Simply removing constexpr doesn't work, VS reports error C2864:

'nlohmann::`anonymous-namespace'::has_mapped_type::value' : a static data member with an in-class initializer must have non-volatile const integral type

Is there a way to rephrase it so that VS 2013 could compile?

Is std::is_same

I've inherited some code that looks like this:

///
/// A specializable function for converting a user-defined object to a string value
///
template <typename value_type>
std::string to_string(const value_type &value)
{
    static_assert(!std::is_same<value_type, value_type>::value, "Unspecialized usage of to_string not supported");
    return "";
}

///
/// A specializable function for converting a user-defined object from a string to a value
///
template <typename return_type>
return_type from_string(const std::string &source)
{
    static_assert(!std::is_same<return_type, return_type>::value, "Unspecialized usage of from_string not supported");
}

!std::is_same<value_type, value_type>::value seems overly verbose.

Should I change these statements to static_assert(false,"...")?

I'm not sure if it was expressed this way to handle some kind of edge case, or if false is indeed equivalent.

Is std::is_same<t,t>::value always true?

Can anyone explain how the c++ code below works?

The thing is I usually would use a for loop to handle this kind of thing but this method seems to be much more efficient. I apologize in advance for this question, but the documentation on cplusplus was a bit hard to comprehend for me given I am quite new at c++

 std::string no_space(std::string x)
{
    x.erase(std::remove(x.begin(), x.end(), ' '), x.end());
    return x;
}

Avoid cast while comparing enum class with int

I finally convinced my co-worker to use enum class instead of the old enum.

However, when comparing int to a enum class value a cast is necessary now. At least IntelliSense says so:

enter image description here

Because of that unecessary cast (since the underlying type is int) she now wants to stay with the old enum...

Please help me out with arguments in that discussion. Maybe there is a technical way to avoid the cast?

Statically assert that variadic template's nested value is unique

I have a class that receive variadic templates of the same type. Each of these types have a nested value that should be unique:

template <SomeEnum _se, int _val>
struct Pack
{
  enum {val_se = _se};
  enum {val = _val};
};

int main()
{
  TypeMe<Pack<A_SE, 1>, Pack<B_SE, 2>, Pack<C_SE, 3>> tm_abc; // OK
  TypeMe<Pack<A_SE, 1>, Pack<B_SE, 2>, Pack<A_SE, 3>> tm_aba; // Should fail (first and last Pack are templated with A_SE)

  (void)tm_abc;
  (void)tm_aba;
  return (0);
}

The entire test code :

#include <cstdio>

template <typename ... ArgPacks>
class TypeMe
{
public:
  TypeMe();
private:
  template <typename ... APs>
  void cycleAPs();

  template <typename AP>
  void cycleAP();
};

template <typename ... ArgPacks>
TypeMe<ArgPacks...>::TypeMe()
{
  // Maybe the static assertion should go here
  cycleAPs<ArgPacks...>();
}

template <typename ... ArgPacks>
template <typename ... APs>
void TypeMe<ArgPacks...>::cycleAPs()
{
  int _[] = {0, (cycleAP<APs>(), 0)...};
  (void)_;
  return ;
}

template <typename ... ArgPacks>
template <typename AP>
void TypeMe<ArgPacks...>::cycleAP()
{
  printf("SomeEnum = %d, Val = %d\n", static_cast<int>(AP::val_se), AP::val);
  return ;
}

enum SomeEnum
{
  A_SE,
  B_SE,
  C_SE,
  MAX
};

template <SomeEnum _se, int _val>
struct Pack
{
  enum {val_se = _se};
  enum {val = _val};
};

int main()
{
  TypeMe<Pack<A_SE, 1>, Pack<B_SE, 2>, Pack<C_SE, 3>> tm_abc; // OK
  TypeMe<Pack<A_SE, 1>, Pack<B_SE, 2>, Pack<A_SE, 3>> tm_aba; // Should fail (first and last Pack are templated with A_SE)

  (void)tm_abc;
  (void)tm_aba;
  return (0);
}

Is there a way, in C++0x, to check at compile time that each of the Pack::val_se are different ? or with C++11 ?

Thanks for reading

Custom allocator compatibilty

Given the following function signature

void foo(std::vector<int> &bar);

and a custom allocator CustomAlloc, calling foo with a instance of std::vector<int, CustomAlloc> results in

could not convert ‘bar’ from ‘std::vector<int, CustomAlloc<int, [...] >}’ to ‘std::vector<int>’

I am no C++ template guru and please do correct me if I am wrong but my understanding is that std::vector<int> default to std::vector<int, std::allocator<int> > (gcc 7.1.1.-3) and hence defines a completely unrellated type.


This beeing said I am trying to find some solutions to make foo callable using std::vector<int, CustomAlloc> and came with the following.

template<typename Allocator>
void foo(std::vector<int, Allocator> &bar);

I dislike how the allocator specification propagates templates, but I guess that is how the STL works.

So my question is, how would you solve this problem given that foo specically operates on int?

PS: Apologies for the bad title I just couldn't find a good one

restrict function parameters to certain enum values

Here's my first attempt -

#include <iostream>
using namespace std;

enum class props {
    left, right
};

template<typename T>
auto allowLeftOnly(T p) -> decltype((p==props::left), void())
{
    cout << "Wow!";
}

int main() {
    props p1 = props::left;
    props p2 = props::right;
    allowLeftOnly(p1);
    // allowLeftOnly(p2);  // should fail to compile
}

what I want from allowLeftOnly function is to accept only props::left or others that I explicitly specify as parameters and fail to compile for others. Is that possible?

Reset a derived class object

I'd like to achieve something like this below:

class A {
public:
    virtual void reset() {
    // 1). if there's no override to this function,
    // then whatever derived from A should get reset
    // to its constructed state, e.g. if B derives from
    // A, then *this = B();
    // 2). if there is an override to reset in the derived 
    // class, call the reset in the derived class
    }
};
class B: public A {
public:
    B() { std::cout<<"reset B"<<std::endl; }
    // no override of reset() here
}; 
class C: public A {
public:
    void reset() override {
        std::cout<<"reset C"<<std::endl;
    }
};

N.B. A doesn't know which class will derive from it, but whoever derive from it, if there is no reset() override in that derived class, calling A::reset() should reset the derived class object to its constructed state, i.e.

A* a = new B();
a->reset(); // -> this equals to *a = B();

However, if there is an override of reset() in the derived class, calling A::reset() should call the overridden reset(), i.e.

A* a = new C();
a->reset(); // -> this should call C::reset()

Error : unknown type name 'FeatureTracks'

I had made an structure for feature tracks:

struct FeatureTracks{
    std::vector<std::vector<cv::Point2f> > tracks;
    std::vector<size_t> offset;
};

Then making a function to call it:

void genTrackMatrix(const std::vector<cv::Mat>& images, FeatureTracks& trackMatrix, int tWindow,  int stride);

But the function calling is giving an error:unknown type name 'FeatureTracks'

Please help me out. Thanks in advance.

Insert a map into other map with a unique type key (2)

hello guys i am new to maps in C++ i am having a question regarding copying a particular type map to another map of same kind the details are shown below I initially declared a map like this

map<string,int> objmap,obj_porcess ;
 for(int i = 0; i < 10; i++) {
 objmap ["process"+to_string(i)]=i+10//some processing the to_string is just in case but i have strings with names for all 10 values
 }

like

objmap["process_today"]=1;
objmap["process_yesterday"]=-1;
objmap["process_tommorow"]=2;

now i want to define some thing like this just my key word should be added with the process and remaining all can be same for all the keys from obj_process

obj_process["today"]=objmap["process_today"] ;

instead of defining all 10 can i have a simple code cause in here i took an example of 10 but i have like 200 set of different strings in the key of map i already asked a qn for exact opposite one this was my previous qn now when i try its vice versa i got an issue hope i find some help

c++11 threads: unable to stop thread

I'm learning to use threads in c++11 (I've mostly used threads via some framework but not directly).

Here's a simple class that runs the run() method in a new thread. The start()/stop() method are used for controlling the threads lifecycle:

#include <thread>
#include <mutex>
#include <iostream>
#include <memory>
#include <atomic>
#include <unistd.h>

using namespace std;

class ThreadTest
{
public:
    ThreadTest() : _run(false), _t(nullptr) {}
    void start()
    {   
        lock_guard<mutex> g(_mutex);
        cout << "Starting new thread..." << endl;
        _run = true;
        if (!_t) {
            _t.reset(new thread(&ThreadTest::run, this));
        }
    }

    void stop()
    {   
        lock_guard<mutex> g(_mutex); 
        cout << "Stopping thread..." << endl;
        _run = false;
        if (_t) {
            _t->join();
            _t.reset(nullptr);
        }
    }

    void run()
    {   
        while(true) {
            lock_guard<mutex> g(_mutex);
            if (!_run) {
                return;
            }
            cout << "Running every sec" << endl;
            sleep(1);
        } 
   }

private:
    atomic<bool> _run;
    unique_ptr<thread> _t;
    mutex _mutex;
};

int main()
{
    ThreadTest t;
    t.start();
    cout << "Sleeping for 2 secs..." << endl;
    sleep(2);
    cout << "Done" << endl;
    t.stop();
    return 0;
}

Sample output:

Starting new thread...
Sleeping for 2 secs...
Running every sec
Running every sec
Done
Running every sec
Running every sec
Running every sec
Running every sec

The problem is that the thread does NOT stop after calling stop()! On debugging I found that its stuck in this function trying to acquire the lock _mutex and therefore the _run variable is not set to false yet. I know that since _run is an atomic, I dont strictly need locks here, but I'm trying to understand the usage of locks here.

Shouldn't the mutex be acquired whenever the while loop of run() loops again?

For the life of me I can't explain this trivial issue! :/

what is the name of this new c++ syntax? [duplicate]

This question already has an answer here:

I just saw a new C++ syntax like:

x = "abc"s;

From context I guessed that this means x was assigned a string "abc", I would like to know the name of this new syntax, and is there any similar syntax in C++1z?

what kind of database technique i should use to store and access the data in an offline application developed using QT framework?

I am developing an off-line question answer application using QT.i wanted to know how can i store and access my data which is questions & answers and some images.which database technique i should use? and please give a coding example for storing and accessing off-line data in qt if possible.

jeudi 29 juin 2017

Previous Object becomes NULL after TlsSetValue

In my C++ dll I am using Thread local storage to store and retrieve thread specific information.

The thread specific info gets packed in a object pInfo. I am allocating once in DLL attach and then using storing the pInfo for each thread using TlsSetValue.

PInfo *pInfo = TlsGetValue(tlsIndex);
if(pInfo == NULL)
{
   pInfo = new PInfo();
   errCheck = TlsSetValue(tlsIndex, pInfo);
}

After some function callbacks and filling the pInfo. In a particular point i push this pInfo (a pointer) to a static vector (which is defined as below).

vector<PInfo*>* swapBucket;

Using swapBucket->push_back(pInfo); i push this object . After pushing this , i need to refresh the existing TLS index storage. So i am assigning NULL to existing TLS index.

errCheck = TlsSetValue(tlsIndex, NULL);

After setting this, i verify whether the lastly inserted pInfo in the swapBucket is valid. But surprisingly it is NULL.

       if(swapBucket->size() > 0)
        {
            if(swapBucket->back() == NULL)
            {
                fileLogObj->WriteLog("[WARNING]","Last Element is NULL",2);
            }
        }

This does not happens all the time. Only some times it happens. (May be once in 5000 times - Sometime it never happens). Most of the time whatever object i push into the vector remains same(even after refreshing with TlsSetValue). Why the pushed object to vector becomes NULL.? (I am not deleting the object too - After some processing with those vector objects i delete those pInfos)

2 Dimension Passing (missing subscript, unknown size)

I am constantly getting a missing subscript and unknown size problem. So, I am guessing this is a beginner problem but I can't get my head around it. How do I get my function to work and outputted to the screen?

I am trying to have two columns be filled with numbers. Column[0] is inputted by rand() and then have Column[1] be converted into a new number through an equation. I am expecting 1-20 rows to be inputted.

void arrayProgram(double ma[][1], int xSize);

double ma[1][1];
arrayProgram(ma, 1);


void arrayProgram(double ma[][1], int xSize)
{

    int i = 0;

    for (i = 0; i < xSize; ++i)
    {
        ma[i][0] = rand();
        ma[i][1] = (ma[i][0] * (20 / 25.0) + 64);
    }

}

C++ QueryInterface implementation using std::shared_ptr<>

I'm looking to write a small bit of C++11 re-usable code to provide similar functionality seen in COM/ATL's IUnknown. Specifically, I'm interested in the QueryInterface() functionality.

A have a few requirements in mind:

  1. Do not rely on RTTI. This rules out dynamic_cast<> (this is not out of personal choice!)
  2. Remove possible coding mistakes by making use of std::shared_ptr<> instead of raw pointers. Shared ptr also provides useful in-built functionality like custom deleters.
  3. Use enum ids to refer to interfaces.
  4. Cross platform is a must.

Some code provided by Alexandre in another SO question has given me some ideas. Nonetheless, what I am keen to try achieve is return a std::shared_ptr object from the query interface method.

I have started to write some code (see below) to demonstrate what I'm trying to achieve. I appreciate that it is not complete.

Trying to flesh this out, I quick ran into all sorts of problems related to type-casting. The code soon felt 'hackish'.

#include <iostream>
#include <memory>
#include <map>

//////////////////////////////////////////////////////////////////////
enum iid
{
    IID_ANONYMOUS       = 0,
    IID_FOO             = 1,
    IID_BAR             = 2,
};

//////////////////////////////////////////////////////////////////////
class abstract_anonymous
{
public:

    virtual ~abstract_anonymous() {}

    // Return 0 if succesful.
    template <class INTERFACE>
    bool query_interface(const iid id,
                         std::shared_ptr<INTERFACE> &inout_apObj)
    {
        // Magic here.
    }

protected:

    virtual std::map<iid, zzzzzzzzzz >  &interfaces_map() const = 0;
};

//////////////////////////////////////////////////////////////////////
class anonymous_base_impl // : public std::enable_shared_from_this<abstract_anonymous>
{
public:

    anonymous_base_impl()
    {
        add_interface(IID_ANONYMOUS, xxxxxxxxxxxx );
    }

    ~anonymous_base_impl() = default;



protected:

    void add_interface(const iid id, yyyyyyyyyyy )
    {
        m_mapInterfacs.emplace({id, yyyyyyyyyyy});
    }

    std::map<iid, zzzzzzzzzz >  &interfaces_map() const override
    {
        return m_mapInterfacs;
    };

private:

    std::map<iid, zzzzzzzzzz >     m_mapInterfacs;
};

Any tips/suggestion would be much appreciated.

C++ linker error when calling template function that is defined in header

I'm getting a linking error when calling a template function, but the linker error does not seem to point to the template function. It seems to point to the shared pointer in the function. My class with the template function:

class Blackboard {
    public:
    template<class T>
    bool setValue(std::string key, T* value) {
        std::shared_ptr<T> ptr(T);
        boost::any v = ptr;
        auto it = map.insert(std::pair<std::string, boost::any>(key, v));
        return it.second;
      }
}

Most similar questions say put all implementation in the header, which I have done. The linking error happens in the class that calls this function. Example class that calls blackboard:

class Example {
    void foo(Blackboard* blackboard) {
        int* i = new int;
        *i = 0;
        blackboard->setValue<int>("some key", i);
    }
}

The error:

Error LNK2019 unresolved external symbol "class std::shared_ptr<int> __cdecl ptr(int)" (?ptr@@YA?AV?$shared_ptr@H@std@@H@Z) referenced in function "public: bool __cdecl BehaviorTree::Blackboard::setValue<int>(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,int *)" (??$setValue@H@Blackboard@BehaviorTree@@QEAA_NV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@PEAH@Z)

Both the Blackboard class and Example class are part of a visual studio static lib project. The linking error occurs when compiling a program using the static library.

I'm having difficulty finding a solution to this problem, so any help would be appreciated!

Calling another class` member functions via smart pointers

In a program I'm writing I have a class that creates and handles some threads. After construction, an instance of this will be given an object of another class that the threads will be able to call member functions of.

I've gotten this to work with raw pointers (just replace the smart pointers), but since I have access to smart pointers, I tried to use them instead. Although without much progress .

Some searching led me to use shared_ptrs, so here's what I'm trying to do:

Obj.hpp:

#pragma once

#include "Caller.hpp"

class Caller;

class Obj : std::enable_shared_from_this<Obj> {
public:
    Obj(Caller &c);

    void dothing();
};

Caller.hpp:

#pragma once

#include <memory>

#include "Obj.hpp"

class Obj;

class Caller {
public:
    void set_obj(std::shared_ptr<Obj> o);

    std::shared_ptr<Obj> o;
};

main.cpp:

#include <iostream>
#include <memory>

#include "Caller.hpp"
#include "Obj.hpp"

void Caller::set_obj(std::shared_ptr<Obj> o)
{
    this->o = o;
}

Obj::Obj(Caller &c)
{
    c.set_obj(shared_from_this());
}

void Obj::dothing()
{
    std::cout << "Success!\n";
}

int main()
{
    Caller c;
    auto obj = std::make_shared<Obj>(c);

    c.o->dothing();
}

Running this code leads to a throw of std::bad_weak_ptr, but I don't understand why. Since obj is a shared_ptr, shouldn't the call to shared_from_this() be valid?

Compiled with g++ main.cpp with gcc 7.1.1.

Storing an std::thread in C++11 smart pointer

In C++ 11 & above what are the advantages or disadvantages when storing an std::thread as a member of class directly like so:

std::thread my_thread;

As opposed to storing a std::shared_ptr or std::unique_ptr to the thread like so:

std::shared_ptr<std::thread> my_thread_ptr;

Is any of the code options better than other? Or it doesn't matter, just 2 separate ways of handling the thread object.

"this" captured by lambda is incorrect. GCC compiler bug?

For the last few days, I have been debugging a weird issue involving lambdas in C++. I have reduced the problem down to the following symptoms:

  • The this pointer gets corrupted inside a lambda (note: this is always captured by copy, so the lambda should get it's own this pointer, which points to the App object)
  • Only occurs if a std::cout print statement is present, and called before the lambda is created. The print statement can be seemingly completely unrelated (e.g. print "Hello!"). printf() also exhibits the same behaviour.
  • Only occurs when cross-compiling
  • Compiles and runs fine with standard compiler for x86 architecture (see example at http://cpp.sh/9ru5k)
  • If I create the lambda on the heap (and save a pointer to it inside the App object), the bug does not occur

The following is the simplest, compilable code example I could come up with which causes the problem.

#include <iostream>
#include <functional>

class App {

public:

    std::function<void*()> test_;

    void Run() {

        // Enable this line, ERROR is printed
        // Disable this line, app runs o.k.
        std::cout << "This print statement causes the bug below!" << std::endl;

        test_ = [this] () {
            return this;
        };

        void* returnedThis = test_();
        if(returnedThis != this) {
            std::cout << "ERROR: 'this' returned from lambda (" << returnedThis << ") is NOT the same as 'this' (" << this << ") !?!?!?!?!" << std::endl;
        } else {
            std::cout << "Program run successfully." << std::endl;
        }

    }
};

int main(void) {
    App app;
    app.Run();
}

When running on the target device, I get the following output:

This print statement causes the bug below!
ERROR: 'this' returned from lambda (0xbec92dd4) is NOT the same as 'this' 
(0xbec92c68) !?!?!?!?!

If I try and dereference this corrupted this I usually get a seg fault, which is how I discovered the bug in the first place.

The compiler settings are:

arm-poky-linux-gnueabi-g++ -march=armv7-a -marm -mfpu=neon -std=c++14 \
-mfloat-abi=hard -mcpu=cortex-a9 --sysroot=/home/ghunter/sysroots/cortexa9hf-neon-poky-linux-gnueabi \
-O2 -pipe -g -feliminate-unused-debug-types

The linker settings are:

arm-poky-linux-gnueabi-ld --sysroot=/home/ghunter/sysroots/cortexa9hf-neon-poky-linux-gnueabi \
-Wl,-O1 -Wl,--hash-style=gnu -Wl,--as-needed

The version of the compiler is:

~$ arm-poky-linux-gnueabi-g++ --version

arm-poky-linux-gnueabi-g++ (GCC) 6.2.0
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Could this a compiler bug?

Is use count on `const std::shared_ptr<...>' mutable?

I'm trying to adapt some pre-existing code to make use of std::shared_ptr<...>. It is a `message passing system' so the basic context is:

Public Method:

void writeReport(std::shared_ptr<const ReportBase> pReport) {
  /* This is a public method for writing a report. I might do
     additional stuff in here but end by forwarding to the
     private method. */
  writeReport_(pReport);
}

Private Method:

void writeReport_(std::shared_ptr<const ReportBase> pReport) {
  if( certain conditions )
    processReport_(pReport);

  writeBytes_(serialize(pReport));
}

Processing Method:

void processReport_(std::shared_ptr<const ReportBase> pReport) {
  processReportImpl(pReport);

  if( certain other conditions )
    reportDeque_.push_back(pReport);
}

Of the above pseudo-code, for example, processReport_(...) might be the only method which, under certain conditions, would want to actually store the record. The other methods are simply interested in the contents of the object pointed to. So, were it not for the need to sometimes copy the shared_ptr in processReport_(...) (i.e., 'store' the record), I would simply pass const ReportBase * to all my nested functions and avoid the overhead of pass-by-value (i.e., use count increments).

So, I want to pass std::shared_ptr<const ReportBase>& (and maybe && where appropriate) but want to preclude some rogue nested method from actually modifying what the pointer points to. So I think I want to pass const std::shared_ptr<const ReportBase>& to prevent that...

... but, again, in processReport_(...) I'll sometimes want to make a copy to store the record.

Which finally leads me to the question(s)... is use count on a std::shared_ptr mutable? Why can (or can't) I do a copy assignment on a const std::shared_ptr<...> to a std::shared_ptr<...>? Does the const make the entire control block of the shared_ptr const? Or does the leading const only apply to the raw pointer value?

And if someone wants to answer tangentially 'don't worry so much about passing by value into nested functions' or 'I have a completely different approach for you' then I'd be interested to hear that too.

From VS2013 to VS2017 std::async does not start a new thread

I updated my Visual Studio from 2013 to 2017. Compiling was fine but it seems like that the std::async call didn't open a new thread. (I cant see a new one in the thread-window while debugging. Also it looks like the thread which calls the the async function does the job...)

That is my function call:

std::async(std::launch::async, myfunction, this); 

I didn't change anything in my code and in VS2013 was everything working fine.

Any Idea? Google can't tell me a lot about this but maybe i have the wrong keywords. So keywords would also help!

Thank you

Passing std::vector of float values to a function changes values a bit

I have a very simple little function that is supposed to verify the values in the passed vector:

bool Verify( std::vector<std::pair<float, float>> const & source) {
    // The lookup table must be changing linearly on input
    float delta_x{};
    for (unsigned i = 1; i < source.size(); i++) {
        auto input_delta = std::abs(source[i].first - source[i-1].first);
        if (i == 1) {
            delta_x = input_delta;
        } else {
            std::cout << "LUT"
              << "Expected step: '" << std::setprecision(10) << delta_x << "'."
              << " measured step[" << i << "]: '"
              << std::setprecision(10) << input_delta << "'"
              << (input_delta-delta_x)
              << ":" << source[i].first << "-" << source[i-1].first << std::endl;
        if (delta_x != input_delta) {
            return false;
        }
     }
  }

  return true;
}

It seems fairly straightforward. However, it fails. When I pass a simple vector like this:

    std::vector<std::pair<float, float>>kDecodeLut{
  {  -1.326, 101.3974},
  {   6.174, 96.0049 },
  {  13.674, 91.5644 },
  {  21.174, 87.5549 },
  {  28.674, 83.7873 },
  {  36.174, 80.1683 },
  {  43.674, 76.6441 },
  {  51.174, 73.1802 },
  {  58.674, 69.7524 }};

The values that the Verify method sees are not exactly the same as in the vector. Here is the printout:

LUTExpected step: '7.5'. measured step[2]: '7.5'0:13.67399979-6.173999786
LUTExpected step: '7.5'. measured step[3]: '7.5'0:21.17399979-13.67399979
LUTExpected step: '7.5'. measured step[4]: '7.5'0:28.67399979-21.17399979
LUTExpected step: '7.5'. measured step[5]: '7.5'0:36.17399979-28.67399979
LUTExpected step: '7.5'. measured step[6]: '7.5'0:43.67399979-36.17399979
LUTExpected step: '7.5'. measured step[7]: '7.5'0:51.17399979-43.67399979
LUTExpected step: '7.5'. measured step[8]: '7.5'0:58.67399979-51.17399979

It appears as if there was some number conversion from the original kDecodeLut vector to the internal variable inside Verify.

Was there really some sort of conversion? I didn't intend for the kDecodeLut vector to be copied or modified in any form. What else can explain this behavior?


Edit: I've added the code to print the values before calling Verify and they come out as expected.

 for (unsigned i = 1; i < kTiltWingDecodeLut.size(); i++) {
  std::cout << "LUT"
            << ":" << kTiltWingDecodeLut[i].first << "-" << kTiltWingDecodeLut[i-1].first << std::endl;
}
Verify(kTiltWingDecodeLut);

Here is the output

LUT:6.174--1.326
LUT:13.674-6.174
LUT:21.174-13.674
LUT:28.674-21.174
LUT:36.174-28.674
LUT:43.674-36.174
LUT:51.174-43.674
LUT:58.674-51.174
LUTExpected step: '7.5'. measured step[2]: '7.5'0:13.67399979-6.173999786
LUTExpected step: '7.5'. measured step[3]: '7.5'0:21.17399979-13.67399979
LUTExpected step: '7.5'. measured step[4]: '7.5'0:28.67399979-21.17399979
LUTExpected step: '7.5'. measured step[5]: '7.5'0:36.17399979-28.67399979
LUTExpected step: '7.5'. measured step[6]: '7.5'0:43.67399979-36.17399979
LUTExpected step: '7.5'. measured step[7]: '7.5'0:51.17399979-43.67399979
LUTExpected step: '7.5'. measured step[8]: '7.5'0:58.67399979-51.17399979

How to properly seed a 64 bit random generator with time [duplicate]

This question already has an answer here:

I would like to generate 64 bit integers using the standard c++ std::mt19937_64 without manually seeding it. When defining the seed though, this question occurred to me: is there a proper way of seeding such a random generator using the current time (eg. producing a number based on the current time point, that is at least as big as a 64 bit int)? Something like counting milliseconds from the Unix epoch? Is there an easy way to achieve this?

Taking unknown numbers count to array from user

How can I get numbers from user and place it into array, without knowing how many numbers will he input? And then, how can I for example take last 5 numbers from that array?

Struct Variable Query

#include<bits/stdc++.h>
using namespace std;
typedef struct trie
{
    int arr[26];
    bool isleaf;
    trie(int isleaf)
    {
        this->isleaf=9;
        cout<<isleaf<<endl;
        isleaf=false;
        cout<<isleaf<<endl;
        cout<<this->isleaf<<endl;
    }
}* tr;
//void inser(s)
int main()
{
   tr k=new trie(3);
   cout<<k->isleaf;
}

Works Fine and outputs 3 0 1 1

But in

#include<bits/stdc++.h>
using namespace std;
typedef struct trie
{
    int arr[26];
    bool isleaf;
    trie(int isleaf)
    {
        cout<<isleaf<<endl;
        isleaf=false;
        cout<<isleaf<<endl;
        cout<<this->isleaf<<endl;
    }
}* tr;
//void inser(s)
int main()
{
   tr k=new trie(3);
   cout<<k->isleaf;
}

I get 3 0 68 68

I understand that it is uninitialized but still why 68?

If use a normal bool either in global or inside function and print it without initializing i get 0,then why not here?

And can somebody also point out some good source to clear doubts about such variable declarations , public and private concepts , and OOPS, difference between structs and classes etc.

Clang returns different compiler errors for system include files

main.cpp:

#include "test.h"
void main () {narrowingConversion ();}

include/test.h:

void narrowingConversion () {int i = 1; char a[1] = {i};}

Clang compiles the above code successfuly when including the include folder as a system folder:

clang++ -std=c++0x -isystem./include main.cpp

But clang fails when the folder is included normally:

clang++ -std=c++0x -I./include main.cpp

./include/test.h:1:54: error: non-constant-expression cannot be narrowed from type 'int' to 'char' in initializer list [-Wc++11-narrowing]

How to write a destructor for a class which includes a map

I have a class like:

class CPR_data{
public:
    /*some functions*/
private:
    map<int,double*> data;    //saving data
};

In the file main.cpp, I add data into the class as following:

double *data_ = new double[n_var];
auto insert_flag = data.insert(make_pair(n,data_));

I used the default destructor but it seems a Memory Leak. Do I need to delete all the arrays manually in the destructor?

How to build a c++ library for Android?

Hi I have a C++ static library built for Linux: say libmyutil.a It uses rpclib. Now I wanted to build libmyutil.a so that Android apps can use it. rpclib requires C++-14. Apart from rpclib, rest of libmyutil.a requires C++-11. Could someone suggest me how should I build my libmyutil.a for Android. As per my understanding, I have to build rpclib for Android first; and then build libmyutil.a. I have installed latest Android SDK & NDK.

Thanks in advance!
Shakthi

template template parameter causing compiler error in clang

I have a template that is compiling fine in MSVC (2017) but fails in clang (4.0):

#include <type_traits>

template <template <typename U, U, U> class, typename, typename>
struct meta_zip;

template <template <typename U, U, U> class OP, typename TA, TA... As, typename TB, TB... Bs>
struct meta_zip<OP, std::integer_sequence<TA, As...>, std::integer_sequence<TB, Bs...>>
{
    using common_type = typename std::common_type<TA, TB>::type;

    using type = std::integer_sequence<common_type, OP<common_type, As, Bs>::value...>;
};

template <template <typename U, U, U > class OP, typename A, typename B>
using meta_zip_t = typename meta_zip<OP, A, B>::type;

The compiler error in clang is:

template template argument has different template parameters than its corresponding template template parameter
struct meta_zip<OP, std::integer_sequence<TA, As...>, std::integer_sequence<TB, Bs...>>
                ^

I'm reasonably new to templates and don't know how to rework OP to make it work. I've tried OP<U, U, U> but that doesn't seem to help.

looking for explanation for a stack corrupting bug

The following problem is distilled from a huge project and the most minimal example of the problem I was able to come up with.

I know, deriving from std::string is bad, and it already is changed in our code base, but I am trying to understand what is happening under the hood here.

The code crashes on Visual C++ 2017 (ver 15.2) in release-mode only (with speed optimization).

// my_string.h

#pragma once

#include <string>

struct my_string :
    public std::string
{
    my_string( const std::string_view& str );
    ~my_string();

    template <typename T>
    my_string& arg( T );
};

template <typename T>
my_string& my_string::arg( T )
{
    return *this;
}


// my_string.cpp

#include "my_string.h"
#include "my_string_view.h"

my_string::my_string( const std::string_view& str ) :
std::string( str.data(), str.size() )
{}

my_string::~my_string()
{}


// my_string_view.h

#pragma once

#include "my_string.h"

#include <string>

struct my_string_view : public std::string_view
{
    my_string_view( const std::string_view::value_type* val ) :
        std::string_view( val ) {}

    template <typename... PARAMS>
    my_string arg( PARAMS&&... prms ) {
        return my_string( *this ).arg( std::forward<PARAMS>( prms )... );
    }
};


// main.cpp

#include "my_string_view.h"

#include <string>
#include <vector>

template <typename T>
struct basic_color
{
    T r, g, b, a;

    basic_color() : r( 0 ), g( 0 ), b( 0 ), a( 255 ) {}

    template <typename U>
    explicit basic_color( const basic_color<U>& c ) :
        r( static_cast<T>(c.r) ),
        g( static_cast<T>(c.g) ),
        b( static_cast<T>(c.b) ),
        a( static_cast<T>(c.a) )
    {}
};

using color = basic_color<std::uint8_t>;
using float_color = basic_color<float>;

__declspec(noinline)
bool change_float_color( float_color& color )
{
    color.r = 0.1f;
    return true;
}

int main()
{
    std::vector<float_color> colors = { {} };
    double sum = 0.0;
    for ( int i = 0; i < 1; ++i )
    {
        float_color fc;
        change_float_color( fc );
        color c( fc );

        std::vector<std::string> msgs;
        msgs.push_back( my_string_view( "" ).arg( c.r ) );
        msgs.push_back( my_string_view( "" ).arg( c.g ) );
        sum += fc.b - colors[i].b;
    }

    return static_cast<int>(sqrt( sum ));
}

The error in Visual Studio is this (have a look at the broken sizes of msgs and colors at the bottom):

enter image description here

My first guess was that since std::string does not have a virtual destructor, the r-values given to push_back are sliced. Thus the destructor of the derived class (my_string) is never called, some trash remains on the stack and the stack-pointer is off by some bytes. But sizeof(my_string) == sizeof(std::string) so I do not see how this can corrupt the stack.

Does anybody have an idea what could be happening here or how I can find out?

Code doesn't seem to work for larger inputs, works fine for smaller ones

While solving this question,my code doesn't seem to work for larger inputs like 100000, but seems to work fine for smaller inputs. Here's the code :

int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */ 
long long int n, h;
cin>>n;
long long int count=0;
long long int i,j;
long long int arr[n];
for(i=0;i<n;i++)
{
    cin>>arr[i];
    //cout<<arr[i]<<" ";
}
h = arr[0];
for(i=0;i<n;i++)
{
    if (arr[i]>=h)
    {
        h=arr[i];
        for(j=i;j<n;j++)
        { if (arr[j]<h)
                count++;
        }       


    }
}
cout<<(n-count);
//cout<<h;    
return 0;
}

Can anyone please help me out? Thank you.

Derived to base implicit pointer type conversion

For a generic tree structure, I'm using some code that looks like this (The following code is a MCVE):

template <typename T> class Base {
protected:
  Base() {}

public:
  T *ptr;
  void setRelated() { ptr = this; }
};

class Derived : public Base<Derived> {};

int main() {
  Derived d;
  d.setRelated();
  return 0;
}

Rationale: The reason for doing this is to save the developer using this class the effort of having to cast everything around from base to derived and back for every call and algorithm used in this class, especially that the base is abstract and can't be instantiated by itself.

This code doesn't compile. It says:

main.cpp:7: error: invalid conversion from ‘Base<Derived>*’ to ‘Derived*’ [-fpermissive]
   void setRelated() { ptr = this; }
                   ~~~~^~~~~~

The question: Is there a way to make all conversions from Base<Derived>* to Derived* implicit (assuming we shouldn't overload every method)?

Remove last char in stringstream?

For example, the stringstream contains "abc\n", I want to remove the last char '\n'.

I know it can be done by using 'str' first.

But could it be done without stringstream::str()?

Default copy constructor for a class without data members and brace syntax

Consider the following class definition:

class A { };

That is, A is a class without data members (even though it doesn't have function members either).

The following code work as expected because the compiler generates both the default constructor and the default copy constructor for the class A:

A foo;
A bar(foo); // calls A's default copy constructor

However, if the brace syntax is used instead of the parenthesis. The code doesn't compile:

A foo;
A bar{foo}; // ERROR

On GCC 4.9.3 I get the error:

too many initializers for 'A'

By doing any of the following points, the last code snippet does work:

  • Adding a data member to the A class definition.
  • Explicitly defining a copy constructor in the A class definition (not even by using = default works). Of course, the default constructor has also to be defined after doing so for the code above to work, because it is not generated by the compiler any more.

Any ideas why is this happening?

mercredi 28 juin 2017

Template function - Does the template override the normal functions

I am testing the following code with c++ templates. I have written a square function using int and float and with a function template.

#include <iostream>
using namespace std;

int square (int a){
cout << "int function" << endl;
return a*a;
};

float square (float a){
cout << "float function" << endl;
return a*a;
};

template <typename T>
T square (T x){
cout << "template function" << endl;
return x*x;
}

int main(){
cout << square<int>(5) << endl;
cout << square<float>(5.5) << endl;
cout << square(5) << endl;
cout << square(5.5) << endl;
return 0;
}

The output is

template function
25
template function
30.25
int function
25
template function
30.25

though I expected

template function
25
template function
30.25
template function
25
template function
30.25

Can someone explain the difference ?

Declaration of template

We are migrating our projects from vs2005 to VS2015 .In one of the project we are using below template declaration Hide   Copy Code template 

In 2005,it is building successfully but in vs2015 getting below error.  Hide   Copy Code 'WindowClass': illegal type for non-type template parameter 'WindowClass'

I am not sure about the use of dllexport inside a template . Anyone know why it is useful and why it is not working in vs2015?

Passing argument of object without copy constructor?

I was looking into move semantics in C++11, and got to the part where something like:

SomeClass bar = createSomeClass();     //creates some object of SomeClass
foo(bar);
foo(createSomeClass());

I know that in the first foo the compiler will call SomeClass's copy constructor and the second foo the compiler will call an overloaded move constructor since createSomeClass() returns an R-value.

What if I don't have a copy constructor declared at all? How does the compiler actually know how to copy these objects then?

overloading indirection operator fails

I have an inner class which is a custom iterator. I override the indirection operator like this:

    T& operator*() {
        return matrix->getCell(cuurent_coord);
    }

Yet, when using the iterator and applying the operator:

for (auto iter = m1.begin(); iter != m1.end(); iter++) {
    int i = *iter;
}

I get the following error: no suitable conversion function from "Foo::FooIterator to "int" exists.

It seems that the compiler ignored the overriding. Why?

Compile Error: Use constexpr to declare std::array size

I am learning constexpr and, for my understanding, constexpr tells the compiler to calculate functions during compile time instead of running time. I used the following code for testing but bumped into an error I really don't understand. Can you please explain why?

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

constexpr int foo(int i)
{
    return i + 5;
}

int main()
{
    int i = 10;
    std::array<int, foo(5)> arr; // OK
    // But...
    std::array<int, foo(i)> arr1; // Error
}

The error is: the value of 'i' is not usable in a constant expression. Why? i is declared beforehand why does it have to be a const?

Is this an acceptable way of making an iterator?

I like the range for-loop in C++, and want to use it like this:

#include <bits/stdc++.h>

int main()
{
    for (auto s : LineReader("my-very-big-textfile.txt")) {
        cout << s << endl;
    }
    return 0;
}

The purpose here is to iterate through some data (without reading all into a container first). In this case text strings which are lines in a text file. But generally it could be anything (including generated data).

Here LineReader returns an iterable "pseudo"-container. And in order for that to work, the for loop needs iterators from the LineReader object. In C++ the range is defined in terms of a begin and end iterator. But I want to use the range for-loop to iterate through data where the end might not be known at start (for example reading line for line in a (excessively big) text file without going through it first to find the end.).

So I define that like this:

Disclaimer: Example code showing the principle, so therefore I'm not "pestering" it with excessive use of std::, error handling, private/public keywords and so on...

struct ReadLineIterator {
    ifstream ifs;
    string line;

    ReadLineIterator() { }
    ReadLineIterator(string filename) : ifs(filename) { }

    bool operator!=(ReadLineIterator& other) {
        return !ifs.eof();
    }

    ReadLineIterator& operator++() {
        getline(ifs, line, '\n');
        return *this;
    }
    string operator*() {
        return line;
    }
};

struct LineReader
{
    string filename;
    LineReader(const string& filename) : filename(filename) { }

    ReadLineIterator begin()
    {
       return ReadLineIterator(filename);
    }

    ReadLineIterator end() // return a not used dummy iterator since this method must exist
    {
        return ReadLineIterator();
    }
};

When I run this, it works. But I'm skeptical if

bool operator!=(ReadLineIterator& other) {
    return !ifs.eof();
}

is a proper way to make this operator to detect the end of the sequence. This because I don't have any proper end object (the end() method just returns a dummy iterator) and comparisons aren't done against it either. Instead I check if the stream is empty.

But I don't see how I could do this in any other way? For now I'm happy with this way of doing it since it works for me, but it would be great to know if there is better ways of doing the same. Also it would be nice to know if this works with all (C++) compilers (I'm using GCC) and if so that it works with future C++ standards where iterators might be handled differently.

"Cross-cast" attempt using static_cast failing; why?

Why doesn't ths "cross-cast" work?

The following creates this object inheritance model:

     FOOD
    /    \
 CHEESE  CAKE

Here I attempt to static_cast a pointer from cheese to cake, making a cheesecake :D. I am getting the following error from Apple Clang/LLVM:

 ERROR: Static cast from 'Cheese *' to 'Cake *', which are not related by inheritance, is not allowed

But they ARE related by inheritance: they are siblings.

Why can't I cast a cheese to a cake, like I cast an int to a float? Why can't I "cross-cast" from derived objects which inherit from the same base class?

Complete, verifiable example follows, with static_cast and dynamic_cast attempts included, to highlight errors.

#include <iostream>
#include <string>

class Food {
public:
    Food(std::string brand):brand_(brand) {}
    virtual ~Food() {};
    std::string brand() { return brand_; }
    virtual void cut()const { std::cout << "Food cut." << std::endl; }
    void eat()const { std::cout << "Food eaten." << std::endl; }
private:
    std::string brand_;
};

class Cheese : public Food {
public:
    Cheese(std::string brand):Food(brand) {};
    virtual void cut()const { std::cout << "Cheese cut.\n"; }
    void eat()const { std::cout << "Cheese eaten.\n"; }
};

class Cake : public Food {
public:
    Cake(std::string brand):Food(brand) {};
    virtual void cut()const { std::cout << "Cake cut.\n"; }
    void eat()const { std::cout << "Cake eaten.\n"; }
};

int main() {
    Food f("tbd");
    Cheese c("Cheddar");
    Cake cc("Cheesecake");
    Food * food_ptr;
    Cheese *cheese_ptr, *cheeseCake_ptr;
    Cake *cake_ptr;

    food_ptr = &f;
    food_ptr->cut();  //-> "Food cut."

    food_ptr = &c;
    food_ptr->cut();  //-> "Cheese cut." Result of virtual keyword.

    cheese_ptr = dynamic_cast<Cheese*> (food_ptr);
    cheese_ptr->cut(); //-> "Cheese Cut." The downcast worked

    food_ptr = &cc;
    cake_ptr = dynamic_cast<Cake*> (food_ptr);
    cake_ptr->cut(); //-> "Cake Cut." pointer reassignment and downcast worked.


    cheeseCake_ptr = dynamic_cast<Cheese*> (food_ptr);
    cheeseCake_ptr->cut(); //-> "Cake cut." Again, Food* dynamically casted to Cheese*

    /* ~~~ NOTE: THE FOLLOWING EXAMLES INTENTIONALLY THROW ERRORS ~~~ */

    /*
     Dynamic cross-cast attempt:
     ERROR: Assigning to 'Cheese *' from incompatable type 'Cake *'
     Dynamic cast: doensn't make sense, as the relationshiop between cheese and cake is not polymorphic
    */

    cheeseCake_ptr = dynamic_cast<Cake*> (cheese_ptr);
    cheeseCake_ptr->cut();

    /*
     Static cross-cast attempt:
     ERROR: Static cast from 'Cheese *' to 'Cake *', which are not related by inheritance, is not allowed
     Static cast: why doesn't this work? We know the data types.
     */

    cheese_ptr = &c;
    cake_ptr = &cc;
    cheeseCake_ptr = static_cast<Cake*> (cheese_ptr);

    std::cout << "\n\n";
    return 0;
}

Accessing "unordered_map

Suppose we are given a dictionary in which that values are either a string or another dictionary, which is declared as:

unordered_map<string, void*> dictionary

How can we access and perform operations on this?

How to pass parameters to a variadic function, dynamically?

Consider some variadic function foo(int...args).

I want to be able to call it dynamically. That is, the parameters will be given to me through some simple data structure like an array/vector etc (doesn't really matter).

How can I pass them to call foo()?

p.s.
I'm using C++11

How to pass my own smart pointer to function?

There is smart pointer class:

template <typename T>
class UniquePtr {
public:
    UniquePtr(T* obj)
        : obj(obj)
    {
    }
    UniquePtr(const UniquePtr& ptr) = delete;
    UniquePtr(UniquePtr&& ptr)
    {
        std::cout << "!! use of move !!" << std::endl;
        obj = std::move(ptr.obj);
        ptr.obj = nullptr;
    }

    UniquePtr& operator=(const UniquePtr& ptr) = delete;
    UniquePtr& operator=(const UniquePtr&& ptr) = delete;

    ~UniquePtr()
    {
        if (obj)
            delete obj;
    }

private:
    T* obj;
};

class for test:

class Test {
public:
    Test()
    {
        std::cout << "Test is created" << std::endl;
    }
    Test(const Test& obj) = delete;
    Test(const Test&& obj) = delete;
    Test& operator=(const Test& obj) = delete;
    Test& operator=(const Test&& obj) = delete;
    virtual ~Test()
    {
        std::cout << "Test is destructed" << std::endl;
    }
};

and function:

void function(UniquePtr<Test>&& ptr)
{
    std::vector<UniquePtr<Test>> v;
    v.push_back(std::move(ptr));
}

If I pass Test class, everything is OK:

UniquePtr<Test> ptr(new Test);
function(std::move(ptr));

But if I pass derived from Test class, code isn't compiled:

class TestChild : public Test {
public:
    TestChild()
    {
        std::cout << "Test child is created" << std::endl;
    }
    TestChild(const TestChild& obj) = delete;
    TestChild(const TestChild&& obj) = delete;
    TestChild& operator=(const TestChild& obj) = delete;
    TestChild& operator=(const TestChild&& obj) = delete;
    virtual ~TestChild()
    {
        std::cout << "Test child is destructed" << std::endl;
    }
};
UniquePtr<TestChild> ptr(new TestChild);
function(std::move(ptr));

error: invalid initialization of reference of type ‘UniquePtr&&’ from
expression of type ‘std::remove_reference&>::type {aka UniquePtr}’
function(std::move(ptr)); ~~~~~~~~~^~~~~

How can I make UniquePtr<TestChild> convertible to UniquePtr<Test>&& With std::unique_ptr this code works.

std::make_shared(), std::weak_ptr and cyclic references

My question is about this claim:

If any std::weak_ptr references the control block created by std::make_shared after the lifetime of all shared owners ended, the memory occupied by T persists until all weak owners get destroyed as well, which may be undesirable if sizeof(T) is large. Source

I read here, that this object live until last weak_ptr is present. Does it free object made with make_shared, with cyclic reference to self or it will live in memory forever?

For example:

struct A
{
    std::weak_ptr<A> parent;
}

void fn()
{
    auto a=std::make_shared<A>();
    a->parent = a;
} // Will it destroy here or not?

Why is the Insertion sort giving ans in descending order when it is suppose to output in ascending order?

Insertion sort. Where you find the smallest number in the array and compare with arr[i] (arr(0) at initial), if the counter number is smaller than the initial then they swap their positions. And the for loop goes on till array finishes. The full code is below:

#include <iostream>

using namespace std;

int main()
{
    int arr[] = {11,55,2,4,5,2,48,854,5,2,4,7,8,2,41,4,8,5,2,18};
    int x = sizeof(arr) / sizeof(arr[0]);
    int small, temp;

    for(int i = 0; i != x; i++) {
        small = i;

        for(int j = 0; j != x; j++) {
            if(arr[small] > arr[j]) {
                small = j;

                if(small != i) {
                    temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
        }
    }

    for(int num: arr) {
        cout << num << " , ";
    }
    return 0;
}

The problem is on line where "arr[small] > arr[j]" means if variable at index j is smaller than initial (arr[small]) then they swap places, thus the ans should have been in ascending order but the output is opposite, it comes as descending order and vice versa.

for(int j = 0; j != x; j++) {
            if(arr[small] > arr[j]) { // the output is [854....2]
                small = j;

                if(small != i) {

I am an amateur programmer, thus, I have no other way than to seek for our help.

Thank you.

Is it possible that resizing an std::vector reduces its capacity?

I have this container: std::vector< std::tuple,std::vector > > rvec1 where each inner vector contains a number of elements. After some computations I resize the inner vectors. The problem is that when I measure the capacity of each vector it seems that it decreases. Is this normal to happen?

Here is the function where I resize the vectors:

int merge_vector_elements(std::vector< std::tuple<std::vector<int>,std::vector<float> > >& rvec1){

        long totalCapacity = 0;
        for(auto itr : rvec1){
          totalCapacity += std::get<0>(itr).capacity();
          totalCapacity += std::get<1>(itr).capacity();
        }
        std::cout<<"Total Capacity before merge / shrink: "<<totalCapacity<<std::endl;

        int nnz = 0;
        for (msize_t i=0; i<rvec1.size(); i++){
          int count = 0;
           for(msize_t j = 0; j < std::get<0>(rvec1[i]).size(); ++j, ++count){
             std::get<0>(rvec1[i])[count] = std::get<0>(rvec1[i])[j];
             std::get<1>(rvec1[i])[count] = std::get<1>(rvec1[i])[j];
             while((j+1 != std::get<0>(rvec1[i]).size()) && std::get<0>(rvec1[i])[count] == std::get<0>(rvec1[i])[j+1]){  
               std::get<1>(rvec1[i])[count] += std::get<1>(rvec1[i])[j+1];
               j++;
             } 
           }
           std::get<0>(rvec1[i]).resize(count);
           //std::get<0>(rvec1[i]).shrink_to_fit();
           std::get<1>(rvec1[i]).resize(count);
           //std::get<1>(rvec1[i]).shrink_to_fit();
           nnz += count;
        }
        totalCapacity = 0;
        for(auto itr : rvec1){
          totalCapacity += std::get<0>(itr).capacity();
          totalCapacity += std::get<1>(itr).capacity();
        }
        std::cout<<"Total Capacity after merge / shrink: "<<totalCapacity<<std::endl;

        return nnz;
      }

The results are:

Total Capacity before merge / shrink: 254396100

Total Capacity after merge / shrink: 107010297

So the capacity seems to be affected.

Also some sample code where the resize doesn't affect the capacity of the vector.

int main(){

  long bufferSize = 1000000000;

  std::vector<double> newVec(bufferSize);

  for(int i=0; i<bufferSize; i++){
      newVec[i] = i * 8.99;
  }

  std::cout<<"Capacity before resize: "<<newVec.capacity()<<std::endl;
  newVec.resize(bufferSize / 2);

  // newVec.shrink_to_fit();
  std::cout<<"Capacity after resize: "<<newVec.capacity()<<std::endl;

  return 0;
}

Compiling with gcc (Ubuntu 6.2.0-5ubuntu12) 6.2.0

std::Thread Join stuck C++

I've a problem with the std::thread join function. When i try to call for my my thread to finish, it execute until the end of my function but get stuck after that.

int C_anccap::LoopAnimation()
{


    MSG        msg;
        wglMakeCurrent(m_hDC, m_hRC);
        // Animation loop.
        //Loop until i change static variable to true
        while (!C_anccap::exit) {

    //
    //  Process all pending messages 
    // 
    while (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE) == TRUE) {
        if (GetMessage(&msg, NULL, 0, 0)) {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        else {
            return TRUE;
        }
    }
    if (anccap.CaptureVideo() != GL_FAILURE_NV)
    {
        anccap.DisplayVideo();
        rec[0].RecordShot(m_SDIin.GetTextureObjectHandle(0));
    }
}
anccap.Shutdown();
wglMakeCurrent(m_hDC, NULL);

}

//This is how i launch my thread 
    capturethread = std::thread(&C_anccap::LoopAnimation, this);

//Here is how i'm trying to join, i've try with and without mutex
case WM_CLOSE: 
        {
            std::mutex mtx;
            mtx.lock();
            C_anccap::exit = true;
                mtx.unlock();
//get stuck here
                anccap.capturethread.join();
                PostQuitMessage (0);
                DestroyWindow (hWnd); 
                break; 
            }

I've already check, i launch and call join in the main thread. Is it something like a deadlock and i'm missing something? If you have any ideas Thanks

converting .hhp files to chm using c++?

I was using hha.lib earlier provided by microsoft for compiling my project files to chm.Now how to use the HTML Help Workshop for doing the same .I am unable to find any proper documentation on the same

Binary overloaded operator=

So I'm trying to write and read from a file, using std::ostream_iterator and std::iostream_iterator. The process of writng works well without any mistakes. But as for reading I'm lost. The error, I have is:

1>c:\program files (x86)\microsoft visual studio 14.0\vc\include\xutility(2316): error C2678: binary '=': no operator found which takes a left-hand operand of type 'const WRstruct' (or there is no acceptable conversion)

and it says that:

c:\users\xxxxxxx\desktop\ttttt\ttttt\wrstruct.h(21): note: could be 'WRstruct &WRstruct::operator =(const WRstruct &)' 1> c:\program files (x86)\microsoft visual studio 14.0\vc\include\xutility(2316): note: while trying to match the argument list '(const WRstruct, WRstruct)'

What is the correct way of overloading operator=?

class:

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <iterator>
#include <istream>

class WRstruct
{
private:
    std::string name;
    std::string number;
    friend std::ostream& operator<<(std::ostream&, const WRstruct&);
    friend std::istream& operator >> ( std::istream& is, WRstruct&);

public:
    WRstruct();
    void write();
    void read();
    ~WRstruct();
};
std::ostream& operator<<(std::ostream& os, const WRstruct& p)
{
    os << "User Name: " << p.name << std::endl
        << "Name: " << p.number << std::endl
        << std::endl;
    return os;
}

std::istream& operator >> (std::istream& is, WRstruct& p)
{

    is >> p.name>>p.number;
    return is;
}

Methods:

void WRstruct::write()
{
    std::vector<WRstruct> vecP;
    std::copy(std::istream_iterator<WRstruct>(std::cin),
    std::istream_iterator<WRstruct>(), std::back_inserter(vecP));
    std::ofstream temp("temp.txt", std::ios::out);
    std::ostream_iterator<WRstruct>temp_itr(temp, "\n");
    std::copy(vecP.begin(), vecP.end(), temp_itr);


    std::ifstream readFile("temp.txt");
    std::istream_iterator<WRstruct> istr(readFile);
    std::istream_iterator<WRstruct> end_istr;
    copy(vecP.begin(), vecP.end(), istr);
    copy(istr, end_istr, back_inserter(vecP));

    std::ostream_iterator<WRstruct> osIter(std::cout, " ");
    copy(vecP.begin(), vecP.end(), osIter);

}

void WRstruct::read()
{
    std::vector<WRstruct> vec;

    std::ifstream readFile("temp.txt");
    std::istream_iterator<WRstruct> istr(readFile);
    copy(vec.begin(), vec.end(), istr);

    std::istream_iterator<WRstruct> end_istr;
    copy(istr, end_istr, back_inserter(vec));

    std::ostream_iterator<WRstruct> osIter(std::cout," ");
    copy(vec.begin(),vec.end(),osIter);

}

and main():

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

int main()
{
    WRstruct r;
    r.write();
    //r.read();

    return 0;
}

How to pass unique_ptr

I have a function in an external library, which looks like this;

bool CreateTheThing(MyThing *& pOut);

I give the function a raw pointer, and it allocates memory and assigns the pointer. It's then my responsibility to free the memory, when I'm done.

Obviously, I'd like to put this result into a unique_ptr<MyThing>.

I could create a temporary raw pointer for the API call, and pass it into the constructor for the unique_ptr, but is there a more direct method through which the API could work directly with the internal pointer of the unique_ptr?

My Project Euler code for #3 works for random numbers I test but gives 3 for 600851475143

Spoilers if you haven't done PE #3

 #include <iostream>
using namespace std;

This function tests for primes

long long isPrime(long long n)
{
    if (n % 2 == 0)
    {
        return 0;
    }
    for (int i=3; i<sqrt(n)+1; i+=2)
        if (n % i == 0)
        {
            return 0;
        }
    return 1; 
}

This one returns the biggest prime.

long long maxPrime(long long n)
{
    int max=3;
    for (int i=3; i<n+1; i+=2)
     if ((isPrime(i)==1)&&(n%i==0))
     {
         max = i;
     }
    return max;
}

This one gives the answer.

int main()
{
    int q;
    cin >> q;
    cout << maxPrime(q) << endl;



}

I have no idea why it does that. I am fairly certain my isPrime() function works and this works for smaller numbers but not 600851475143. For 600851475143, it gives 3. But for random numbers like 12321 it correctly gives 37 and the example, 13195, it correctly gives 29.

Warning: function uses 'auto' type specifier without trailing return type

The following code gives the warning below. Can someone please explain why (note the code is not useful as is as I replaced my types with int to make a complete example).

warning: 'MaxEventSize()' function uses 'auto' type specifier without trailing return type [enabled by default]

The idea is to get the maximum size of a particular structure (types go where int is).

template<typename T>
constexpr T cexMax(T a, T b)
{
    return (a < b) ? b : a;
}

constexpr auto MaxEventSize()
{
    return cexMax(sizeof(int),
           cexMax(sizeof(int),
                    sizeof(int)));
};

CMap Lookup() std::unique_ptr hits attempting to reference a deleted function

I have below code

class ObjectA
{

}

Class ADeleter
{
//used to delete ObjectA
}

using AUniquePtr = std::unique_ptr<ObjectA, ADelter>;

using myMap = CMap<CString, CString, AUniquePtr, AUniquePtr>;

myMap mapA;

mapA.insert(pairA);
mapA.insert(pairB);
mapA.insert(pairC);
mapA.insert(pairD);

AUniquePtr ptr;
CString stringA = "xxxx";
mapA.Lookup(stringA, ptr);

I hit error - attempting to reference a deleted function. I know unique_ptr can not be copied, but I do not know how to fix it. Please help.

Call fallback method if method does not exist

I want to be able to do the following in C++

  1. Try to call a function from a namespace, e.g., boost::filesystem::copy
  2. If copy is not a member of boost::filesystem, call a fallback function, e.g., boost::filesystem3::copy
  3. If fallback function does not exist (this could be either because boost does not have member filesystem3, or because boost::filesystem3 does not have member copy), the code should not compile.

After reading loads and loads of extremely long and complicated pieces of code, it is unclear to me what the simple way of doing this would be. A C++11 solution is fine. But the code sometimes requires to compile with an old boost version (1.39.0), which is precisely why this workaround is required.

Currently I do it by creating method alias after checking the BOOST_VERSION macro. But it would be good to know of a more sophisticated alternative that could be applicable for more general cases.

Get all possible topological sort of a graph

As showed bellow I am getting depth topological sort using boost library. However for my optimization problem I have to consider all topological possibilities. How to do it?

//store topological order
deque<vertex_t> topologicalSorted;

//perform topological sort
if (topologicalSort(graph, topologicalSorted)) {
    cout << "The graph is directed acyclic!" << endl;
    cout << "Topological order: ";
    for (int i = 0; i < topologicalSorted.size(); i++) {
        cout << graph[topologicalSorted.at(i)].label << " ";
    }
    cout << endl;
}

//try to perform topo sort and return true if the graph is a dag
bool topologicalSort(const graph_t &graph, deque<vertex_t> &topologicalSorted) {
    try {
        boost::topological_sort(graph, front_inserter(topologicalSorted));
    } catch (boost::not_a_dag &) {
        cout << "not a dag" << endl;
        return false;
    }
    return true;
}

Is `std::array

Consider the code below:

#include <array>

struct T
{
    T() = delete;
};

int main()
{
    std::array<T, 0> a;
    a.size();
}

We default initialize a 0-sized array. Since there's no elements, no constructor of T should be called.

However, Clang still requires T to be default constructible, while GCC accepts the code above.

Note that if we change the array initialization to:

std::array<T, 0> a{};

Clang accepts it this time.

Does non-default-constructible T prevent std::array<T, 0> from being default-constructible?

Narrowing conversion differences

With both g++ and clang it's ok to compile

std::vector<int> xs{1, 2, 3u};

but it's not ok to compile

std::vector<int> xs{1, 2, 3.0};

What is the rationale behind this apparently bizarre choice?

If we consider the type of the last value both unsigned and double cannot be converted safely to an int, and if we consider instead the specific literal values both 3u and 3.0 can instead be converted safely.

Why the distinction then?

How to sort Vector of Points based on specific two segment line

schema of point & segment line

actually I try to use tie for sorting from top left to bottom right order & it works:

std::sort(VectorCoord.begin(), VectorCoord.end(), [] (const Point2f& sr, const Point2f& sl)
                      {

                              return std::tie(sr.x, sr.y) > std::tie(sl.x, sl.y);


                      });

but if I try to insert some condition my compiler send my an error (these is not a solution for my problem, just a test to get the result) . Ex:

std::sort(VectorCoord.begin(), VectorCoord.end(), [] (const Point2f& sr, const Point2f& sl)
                      {

                              if(sr.y > 0){
                                 return std::tie(sr.x, sr.y) > std::tie(sl.x, sl.y);}
                              else{                   
                                   return std::tie(sr.x, sr.y) < std::tie(sl.x, sl.y);}


                      });

What do I do wrong? In what might be the best system to get the sort I need?

giorgio

ArraySize of const char* [] with template function

I'm trying to find the size of an array with the type const char * [] with a function :

template<typename T, std::size_t N>
constexpr std::size_t arraySize(const T* (&)[N])
noexcept
{
   return N;
}

I have the error:

template argument deduction/substitution failed:
mismatched types ‘const T* [N]’ and ‘const char* []’

failed to compile paho.mqtt,cpp under rasberry

I have compiled the C version of paho MQTT library and now I'm trying to compile the C++ version but get a compile error:

/home/pi/http://ift.tt/2tnEZXk: In member function ‘mqtt::disconnect_options& mqtt::disconnect_options::operator=(const mqtt::disconnect_options&)’:

/home/pi/http://ift.tt/2tX2wLR: error: use of deleted function ‘MQTTAsync_disconnectOptions& MQTTAsync_disconnectOptions::operator=(const MQTTAsync_disconnectOptions&)’ opts_ = opt.opts_; ^ In file included from /home/pi/http://ift.tt/2tnbkgN, from /home/pi/http://ift.tt/2tWWs5O: /home/pi/paho.mqtt.c/src/MQTTAsync.h:835:3: note: ‘MQTTAsync_disconnectOptions& MQTTAsync_disconnectOptions::operator=(const MQTTAsync_disconnectOptions&)’ is implicitly deleted because the default definition would be ill-formed: } MQTTAsync_disconnectOptions; ^ /home/pi/paho.mqtt.c/src/MQTTAsync.h:835:3: error: non-static const member ‘const char MQTTAsync_disconnectOptions::struct_id [4]’, can’t use default assignment operator /home/pi/http://ift.tt/2tnEZXk: In member function ‘mqtt::disconnect_options& mqtt::disconnect_options::operator=(mqtt::disconnect_options&&)’: /home/pi/http://ift.tt/2tnOYvz: error: use of deleted function ‘MQTTAsync_disconnectOptions& MQTTAsync_disconnectOptions::operator=(const MQTTAsync_disconnectOptions&)’ opts_ = opt.opts_; ^ src/CMakeFiles/common_obj.dir/build.make:110: recipe for target 'src/CMakeFiles/common_obj.dir/disconnect_options.cpp.o' failed make[2]: * [src/CMakeFiles/common_obj.dir/disconnect_options.cpp.o] Error 1 CMakeFiles/Makefile2:89: recipe for target 'src/CMakeFiles/common_obj.dir/all' failed make[1]: * [src/CMakeFiles/common_obj.dir/all] Error 2 Makefile:151: recipe for target 'all' failed make: *** [all] Error 2

I use for both libraries the head branch from git and compiling under raspbian with the latest version of C++

Any idea?

Difference between boost:any and std:auto

What is the difference if any between boost:any and std:auto? Is any accepted into the standard library as auto?

mardi 27 juin 2017

__VA_ARGS__ expansion fails if preceded by scope

I want to use __VA_ARGS__ in a macro to get the equivalent of writing several lines of if(a==b) return c.

When compiling "small sample", it fails with

identifier "name2" is undefined (Line 18)
C2065 'name3': undeclared identifier (Line 18)
C2065 'name2': undeclared identifier (Line 18)

if both USE_ENUM_CLASS and USE_VARIADIC_CONVERTER are defined.

A bit of rambling

I found information about previous versions of Visual Studio failing to expand __VA_ARGS__, but since the code works fine with an enum instead of an enum class I guess Visual Studio 2015 did fix at least some of the previous issues. In a real application I would use similar macros more then once, so this could save me a lot of lines and protect against forgetting to add code for enum values added later (adding to NAME_LIST would be sufficient).

Small sample

This causes the mentioned error. Comment out either line that defines USE_ENUM_CLASS or USE_VARIADIC_CONVERTER and it will compile.

#define NAME_LIST name1,name2,name3
#define USE_ENUM_CLASS
#define USE_VARIADIC_CONVERTER

#ifdef USE_ENUM_CLASS
enum class e
#else
enum e
#endif
{
    name1, name2, name3
};

e int_to_e(int const i)
{
#ifdef USE_VARIADIC_CONVERTER
#define POPULATE_INT_TO_E(...) if(i==static_cast<int>(e::__VA_ARGS__)) return e::__VA_ARGS__;
    POPULATE_INT_TO_E(NAME_LIST);
#else
#define POPULATE_INT_TO_E(x) if(i==static_cast<int>(e::x)) return e::x
    POPULATE_INT_TO_E(name1);
    POPULATE_INT_TO_E(name2);
    POPULATE_INT_TO_E(name3);
#endif
    throw - 1;
}

void main(void)
{
}

Further observations

The same error occurs when replacing the enum definition with

struct e
{
    enum
    {
        name1, name2, name3
    };
};

or

namespace e
{
    enum
    {
        name1, name2, name3
    };
}

or

namespace e
{
    int const name1 = 1;
    int const name2 = 2;
    int const name3 = 3;
};

Question

How can I rewrite/expand the macro to avoid these errors?

how to declare array with variable size in header file?

I have a struct and I want to have a array from struct but size of array (in this: size_array) calculate in cpp file! are there any way for handling this issue?

test.h
struct info_struct{
u_int16_t dl;
u_int16_t up;
};
extern info_struct array_data[size_array];

how to convert tuple to byte array in c++11

In my project, I need to write a function to convert tuple to byte array. The type of tuple may include int, long, double, std::string, char*,etc For example, std:tuple or std:tuple t2("abc", 1, 2, 1.3, 1.4) The size and type of tuple might be Arbitrary

C++11 multi producer single consumer queue

I'm calculating values on N threads at variable rates between 100-1000/sec per thread. I'd like to pass these on to a consumer that will produce stats about once a second. The idea is that the process of communicating the values out of the producer should have as little contention as possible (ideally under a microsecond or even 500 nanos).

I've looked at single producer single consumer implementations and they are fairly straightforward to implement using std::atomic's. My first attempt at this was to use a std::atomic to hold the writing position and use fetch_add(1) which seems to work nicely on the producer side. But the problem is that the fetch_add happens before the write to the circular buffer so there's a possibility that the reader thread might not get the last few values written.

I could illustrate with code if you want, but I think my description is fairly straightforward.

Another solution would be to use 1 SPSC queue per producer thread but then that would incur a bit more management for the consumer to gather everything up.

Any ideas on a good design for this problem?

What does this cоde do?

I just spotted this code:

void lechk(void){
  int a = ~255;
  if(*(char*)&a) exit(-1);
}

What is it supposed to do? It seems that condition inside if is never true (because a is constant)? What is purpose of it?

Is statement in for each loop executed each iteration? [duplicate]

This question already has an answer here:

I have a function which returns a container. Let's just call it 'Container'.

Container GenerateRandomContainer() { ... }

This function will generate a container with random elements that are different each call.

When I iterate through this container using a for each loop like this:

for(Element e : GenerateRandomContainer()) { ... }

Will it generate a new Container each iteration or will it generate only one when the for each loop is entered?

C++11 value initializer vs list initializer

It seems empirically that C++ always prefers a list initializer over a value initializer. My question is thus how can I force value initialization of a type that also supports a direct list initialization. Here is a minimal non-working example:

#include <initializer_list>

using namespace std;

struct foo {
  foo(int) {}
  foo(initializer_list<char>) {}
};

struct bar {
  foo f{256};
};

In this example, I would like f to be initialized using the constructor foo(int) rather than the foo(initializer_list<char>). However, both GCC and Clang reject the code because 256 is too big for a char, which means obviously the C++ spec requires choosing the list initializer. Obviously commenting out the second constructor of foo fixes the problem. What's the easiest way to define bar so as to use value initialization on field f? Ideally I could avoid copy initializing f, because in my real example there is no copy constructor.

compare nested iterators after boost transformed()

vector<vector<int>> input{ { { 1, 2 },{ 3, 4 } } };
auto result = input | boost::adaptors::transformed([](const auto& _) {return _; });
result.begin()->begin() == result.begin()->end();

If I run this w/ VS2015 with _ITERATOR_DEBUG_LEVEL=2, then it fires this error in _Compat(const _Myiter& _Right):

        _DEBUG_ERROR("vector iterators incompatible");

This is important because Flattening iterator uses this comparison in advance_past_empty_inner_containers().

What's going on? How do I fix it?

Why memory is new when doing std::move

In this code:

int main()
{
    std::vector<int> src{1, 2, 3};

    std::cout << "src: ";
    for (std::vector<int>::const_iterator x = src.begin(); x != src.end(); ++ x)
    {
        std::cout << *x << ' ' << &(*x) << std::endl ;
    }   

    std::vector<int> dest(std::move(src));

    std::cout << "src: ";                                                       
    for (std::vector<int>::const_iterator x = src.begin(); x != src.end(); ++ x)
    {
         std::cout << *x << ' ' << &(*x) << std::endl ;;
    }   
    std::cout << "\ndest: ";
    for (std::vector<int>::const_iterator x = dest.begin(); x != dest.end(); ++ x)
    {
        std::cout << *x << ' ' << &(*x) << std::endl ;;
    }   
    std::cout << '\n';
}

src: 1 0x43ea7d0
2 0x43ea7d4
3 0x43ea7d8
src: 
dest: 1 0x43ea7d0
2 0x43ea7d4
3 0x43ea7d8

This make sense because the memory address of dest is now what previously src was.

But when I do:

int main()
{
    std::vector<int> src{1, 2, 3};
    std::vector<int> dest(src.size());

    std::cout << "src: " << std::endl;
    for (std::vector<int>::const_iterator x = src.begin(); x != src.end(); ++ x)
    {
        std::cout << *x << ' ' << &(*x) << std::endl ;
    }   
    std::cout << "\ndest: " << std::endl;
    for (std::vector<int>::const_iterator x = dest.begin(); x != dest.end(); ++ x)
    {
        std::cout << *x << ' ' << &(*x) << std::endl ;
    }    
    std::cout << '\n';

    std::move_backward(src.begin() , src.end(), dest.end());

    std::cout << "src: " << std::endl;
    for (std::vector<int>::const_iterator x = src.begin(); x != src.end(); ++ x)
    {
        std::cout << *x << ' ' << &(*x) << std::endl ;
    }   
    std::cout << "\ndest: " << std::endl;
    for (std::vector<int>::const_iterator x = dest.begin(); x != dest.end(); ++ x)
    {
        std::cout << *x << ' ' << &(*x) << std::endl ;
    }    
    std::cout << '\n';
}

   src: 
1 0x41e0140
2 0x41e0144
3 0x41e0148

dest: 
0 0x41e0160
0 0x41e0164
0 0x41e0168

src: 
1 0x41e0140
2 0x41e0144
3 0x41e0148

dest: 
1 0x41e0160
2 0x41e0164
3 0x41e0168

Why is the second case the address being different? I thought std::move only changing the pointer, without touching the memory of the original object

overloaded += operator with multiple terms

I have a two classes, a molecule and a single_atom class with overloaded operators +=, +, and *. + works as long as the two operands are a molecule or atom. * works with an atom or molecule and an int, and can be reversed. += only works when the operand is a single molecule or atom but should be able to evauluate complex expressions. How do I incorporate += so that the following works:

single_atom a1("sulpher");
single_atom a2("mercury");
Molecule m1(a1);
m1 += 3 * a1 + a2 * 4;

or even just:

m1 += 3 * a1;

what is modifiable Rvalue?

Would someones please give an example of "modifiable rvalue"? My understanding is rvalue appeared on the right side of "=" in an expression. I tested the following example but I am not sure whether it explains the "modifiable rvalue"

int i=1
int &j = i;
j=2;  //i == 2, 

Thinking in C++(vol 1) Ch-12 Q-21

Got stuck here while going through Bruce Eckel TIC++

Create a class with an assignment operator that has a second argument, a string that has a default value that says “op= call.” Create a function that assigns an object of your class to another one and show that your assignment operator is called correctly.

Is this really possible. Does C++ allow operator=() to have multiple argument?? I tried this:

class X{
    public:
        X& operator=(const X& x,string val="op=call"){ //! error

        }
};

int main(){
    X x1;
    X x2;
    x2=x1;
}

Error given by compiler:

[Error] 'X& X::operator=(const X&, std::string)' must take exactly one argument

I think this is not a valid question or if it is then how to provide multiple argument to assignment operator??

C++11 - lambda function pass vector in capture and modify it

I have this code:

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

int main () {
  std::vector<int> kk;
  kk.push_back(2);
  std::function<int(int)> foo = std::function<int(int)>([kk](int x)
  {
      kk.push_back(1);
      return kk[0]+1;
  });

  std::cout << "foo: " << foo(100) << '\n';

  return 0;
}

Why I cannot modify vector kk, passed via capture, inside lambda function?

I got this error:

11:21: error: passing 'const std::vector' as 'this' argument of 'void std::vector<_Tp, _Alloc>::push_back(std::vector<_Tp, _Alloc>::value_type&&) [with _Tp = int; _Alloc = std::allocator; std::vector<_Tp, _Alloc>::value_type = int]' discards qualifiers [-fpermissive]

libstdc++ static linking in dynamic library

To understand question I should tell you more about program that loads dynamic library. It's Half-Life Dedicated server. It uses old libstdc++ which is located next to executable. To avoid issues, when using features from new standard library I usually link my project staticaly to libstdc++.

My friend told me that libstdc++ static linking can create problems, if 2 libraries are loaded compiled with different compilers or when I call function from server (which is internally implemented in terms of old lib).

Is it true? How can I resolve this issue?

c++ sfml 2d particle system not working, been trying for 3 days

I'm having a problem with a particle system I wrote, Everything compiles fine but it crashed whenever I try to create particles. Here's my github repository : http://ift.tt/2sWZaYP

Variable Argument List following 'const std::string&' messes up the stack

I have a function: std::string format(const std::string sformat, ...); It basically works like a fancy sprintf().

Since I call that function a lot I wanted to pass the format string as a ref: const std::string& sformat. Unfortunately va_start() seems to have problems finding the right spot on the stack to the variable argument list.

If I remove the '&' it works fine.

Two questions: A: Do I even need the reference in order to prevent a copy of sformat during the call, or is the optimizer clever enough to just do a pass-by-ref in the background? B: What can I do to prevent a pass-by-value of the format string and still don't confuse va_start() ?

My guess is: pass-by-pointer. Or is there a better solution?

Thread synchronization between data pointed by vectors of std::shared_ptr

I'm pretty new to concurrent programming and I have a specific issue to which I could not find a solution by browsing the internet..

Basically I have this situation (schematic pseudocode):

void fun1(std::vector<std::shared_ptr<SmallObj>>& v) {
  for(int i=0; i<v.size(); i++)
    .. read and write on *v[i] ..
}

void fun2(std::vector<std::shared_ptr<SmallObj>>& w) {
  for(int i=0; i<w.size(); i++)
    .. just read on *w[i] ..
}


int main() {

 std::vector<std::shared_ptr<SmallObj>> tot;

 for(int iter=0; iter<iterMax; iter++) {
   for(int nObj=0; nObj<nObjMax; nObj++)
      .. create a SmallObj in the heap and store a shared_ptr in tot ..

   std::vector<std::shared_ptr<SmallObj>> v, w;
   .. copy elements of "tot" in v and w ..

   fun1(v);
   fun2(w);
 }

 return 0;
}

What I want to do is operating concurrently spawning two threads to execute fun1 and fun2 but I need to regulate the access to the SmallObjs using some locking mechanism. How can I do it? In the literature I can only find examples of using mutexes to lock the access to a specific object or a portion of code, but not on the same pointed variables by different objects (in this case v and w)..

Thank you very much and sorry for my ignorance on the matter..

Data labels in linechart Qchart

I am trying to add data labels in LineChart using QTcharts like this Image. I am not able to figure out how I can do that. Any help will be appreciated. I am using this example http://ift.tt/2sWzHyR

change value of private variable inside class

I'm learning opengl. I got a camera class, and I change the code for the camera to contain the matrices for the projection and the view.

The projection matrix is set in the constructor. Meanwhile, the view is updated every frame. Everyframe the view matrix is calculated and stored override the previous values.

Here is the code Camera.h

class Camera : public Entity
{
public:
    Camera();
    ~Camera();

    void input(float delta);
    void update();

    const Matrix4& getView() const;
    const Matrix4& getProjection() const;

private:

    void mouseInput();

    void printMatrix(Matrix4& m);

    Matrix4 view;
    Matrix4 projection;

};

Camera.cpp

Camera::Camera()
    : projection(Maths::createProjectionMatrix())
{

}

void Camera::update()
{
    view = Maths::createViewMatrix(*this);
}

const Matrix4& Camera::getView() const
{
    return view;
}

const Matrix4 & Camera::getProjection() const
{
    return projection;
}

I removed code that it works and is not relevant. The view and projection matrices were calculated outside the class and it worked correctly. So, I decided to move inside the camera those two matrices because they belong to the camera.

Every update the view is recalculated with the camera position and rotation. If you print the matrix view at the end of the update function (where is calculated) the matrix show that is changed every frame. But if you print the matrix inside the function "getview" the matrix haven't beeing change and keeps the value from the default initialization.

How can the function "getView" return this matrix that has been updated and changed?