dimanche 31 mai 2015

Test class destructor for pointer being allocated?

So I am having a problem with my code. I want to pass a value from my array of pointers to a function so the original object is not 'disturbed' (my code works perfectly fine if I pass the reference; I just am just trying to do it a different way as a learning exercise). After the implementation returns, I get an error:

"error for object 0x100105790: pointer being freed was not allocated *** set a breakpoint in malloc_error_break to debug".

I know this is because as the value goes out of scope upon the function's return, the destructor is called for the object but my destructor assumes a pointer that was allocated, thus the error. I was curious if there was a way to test if the genome was already allocated or not. If not I would do something else for the destructor? Is this even a problem worth bothering about since I already have it working by passing in the reference? The function is not actually destructive; I just have a desire to do some tricks. I don't like taking the easy way out.

//class destructor for int genome[]
Organism::~Organism() {
    //cout << "Deleting this: " << this << endl;
    if (this->genome != NULL) {
         delete [] this->genome;
    }
}

//function definition
Organism* reproduce(Organism, Organism);

//function call in main()
offspring.push_back(reproduce(*reproduceable[i], *reproduceable[i+1]));

//function implementation
Organism* reproduce(Organism a, Organism b) {
    int genome[4];

    //randomly decide on where to split parent genomes
    int split = rand() % 5;
    for (int i = 0; i < a.get_size(); i++) {
        if (i < split) {
            genome[i] = a.get_genome()[i];
        } else {
            genome[i] = b.get_genome()[i];
        }
    }
    //now cause random mutation in 2% of the population
    if ((rand() % 100 + 1) <= 2) {
        int rand_index = rand() % 5;
        int mutation = rand() % 6 + 1;

        genome[rand_index] = mutation;
    }

    Organism *child = new Organism(4, genome); //need to add genome
    return child;
}

How can I expand call to variadic template base classes?

I have a set of non-orthogonal policies, all of them implementing a common named method, the policies add safety checks. I want users to be able to combine the policies to allow more complex validation without creating policies for each combination case by hand. My approach is creating a new policy class to combine others.

The simplified example below shows C as the combining class, here the method id is combined. The expected result is, when calling id on C, to sequentially call the id of each base class.

#include <iostream>
using namespace std;

struct A {
    void id() { cout << "A ";}
};

struct B {
    void id() { cout << "B ";}
};

template<class A, class... As>
struct C : public A, public As... {
    void id(){
    A::id();
    As...::id(); // This line does not work, it is illustrative.
}
};

int main(){
    C<A, B> c;
    c.id();
    //expected: result A B 
}

The question is: Is it possible to expand As... somehow to do this without using a recursive approach, just using the ... operator?

Noncopyable and move constructor

I have made a member of a class non-copyable but I have given it a move constructor and assignment operator. Yet it dosn't play ball with a container like a vector.

class NonCopyable
{
public:
    NonCopyable(const NonCopyable&) = delete;
    NonCopyable& operator=(const NonCopyable&) = delete;


protected:
    NonCopyable()
    {
    }

    ~NonCopyable() _NOEXCEPT
    {
    }
};


class Member : NonCopyable
{
public:
    Member(int i) : mNum(i)
    {
    }
    ~Member()
    {
    }

    Member(Member&& other) _NOEXCEPT : mNum(other.mNum)
    {
    }

    Member& operator= (Member&& other) _NOEXCEPT
    {
        std::swap(mNum, other.mNum);
        return *this;
    }

private:
    int mNum;
};


struct Item
{
    Item(int i) : mMember(i)
    {
    }

    Member mMember;
};



int _tmain(int argc, _TCHAR* argv[])
{
    std::vector<Item> vec;
    vec.emplace_back(1);

    return 0;
}

The following compiler error:

error C2280: 'NonCopyable::NonCopyable(const NonCopyable &)' : attempting to reference a deleted function
see declaration of 'NonCopyable::NonCopyable'
This diagnostic occurred in the compiler generated function 'Member::Member(const Member &)'

Why dosn't the compiler recognize the Member can be moved? What am I missing?

EDIT: Visual studio 2013

Lock-based function runs faster than lock-free! Why?

While I was practicing lock-based vs. lock-free concurrency, I realised that my lock-based function takes less time than a function with no synchronisation:

// A simple money transfer function
void transfer(unsigned int from, unsigned int to, unsigned int amount)
{       
    lock_guard<mutex> lock(m); // removing this line makes it run slower!
    accounts[from] -= amount;
    accounts[to] += amount;
}

Here is the coliru link of the full code. What might be the reason?

Note: I am aware of the data-race issue!

C++ how to generate all the permutations of function overloads?

Lets say I have classes Date and classes Year, Month and Day.

struct Date {
  Date(Year year, Month month, Day day) : d(day), m(month), y(year) {};
  Date(Month month, Day day, Year year) : d(day), m(month), y(year) {};
  Date(Day day, Month month, Year year) : d(day), m(month), y(year) {};
  Date(Day day, Year year, Month month) : d(day), m(month), y(year) {};
  ...
  ...

  private:
    Day d;
    Month m;
    Year y;
}

This allows me not to have a specific layout of arguments for Date as I have a lot of overloadings.

Am I able to generate all the permutations/overloadings automatically?

Just to be clear:

  • Permutations are only of argument layout, nothing about them should change as I know that would not be possible to automate.
  • All the generated overloadings should have the same code as only the layout of arguments changes not the logic itself.

const constexpr char* vs. constexpr char*

I know the difference between const and constexpr. One is a compile time constant and the other is either compile time or runtime constant.

However, for array of chars/strings, I'm confused why the compiler complains about one being used over the other.

For example I have:

constexpr char* A[2] = {"....", "....."};

const constexpr char* B[2] = {"....", "....."};

With declaration "A" I get:

ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]

but with declaration "B" I get no warnings.

Why does the extra const qualifier get rid of the warning? Aren't both of them "const char*" anyway? I ask because both are declared with constexpr which should make it a const char* by default?

I'd expect A to be fine :S

Taking value from unique_ptr without generating memory leaks

I'm allocating several unique_ptr<int>s and I then pass these into an insert function that then calls an overloaded insert function and passes it the value derived from std::move(uniquePtr).

The overloaded insert does what it is supposed to do, but then I have a ton of memory leaks.

How can I eliminate these memory leaks?

typedef std::unique_ptr<int> UP;
std::vector<int> data{ 9, 10, 7, 8, 5, 6, 3, 4, 1, 2 };
custom_container<UP> s;
for (auto datum : data) {
    s.insert(UP(new int(datum)));
}

template <typename U>
void insert(std::unique_ptr<U> ptr)
{
    this->insert(std::move(ptr));
}

How to put DamageType in switch statement?

I have several DamageTypes. I want to do something special for Character depending on what DamageType have taken.

Now I use this code for solve my problem. But I don't want to use IF statements + casting!

float ABaseCharacter::TakeDamage(float Damage, struct FDamageEvent const& DamageEvent, class AController* EventInstigator, class AActor* DamageCauser)
{

    UDamageType *DamageType = Cast<UMyDamageType1>(DamageEvent.DamageTypeClass->GetDefaultObject());
    if (DamageType){
        //do something

    }

    DamageType = Cast<UMyDamageType2>(DamageEvent.DamageTypeClass->GetDefaultObject());

    if (DamageType){
        //do something

    }
// and there will be many same code (copy-paste) because 
// I need to find what DamageType I got.
    return Damage;
}

Is there more elegant solution?

C++ bind member function with variadic template

My example below uses variadic templates to register a function inside a class. Registering a single function works but what about class member functions? I tried std::bind but this expects placeholders which is not an option because I don't know the number of arguments. Is there a simple way doing this in C++11 or am I forced to implement the register function for every amount of arguments?

template<typename TReturn, typename... TArgs>
class Func {
    std::function<TReturn (TArgs...)> fn;

    template<typename TFunction, typename TObject>
    bool register(TFunction f, TObject obj){

    }

    bool register(std::function<TReturn (TArgs...)> f){
        fn = f;
        return true;
    }   
}

C++, match custom placeholders with function arguments

I am trying to write the piece of code which will do the following: let's assume we have a call of custom bind function

auto bind_obj = bind(some_func, _1)  

and after we have

auto res = bind_obj(42, "test") 

where the function some_func:

int some_func(int val, string test)

How can it possible to match placeholders with arguments provided in actual function call, i.e. bind_obj(...)??

In other words, is it possible to iterate over std::tuple (arguments and placeholders here) and variadic pack (function arguments) to:

  1. deduce the return type of function some_func;
  2. make correct std::tuple to further use it in some_func() call ?

I am trying to do this via pure C++, not boost nor std::functional. I think, my main problem is that i don't understand how to build tuple at runtime with arguments (where all the placeholders replaced correctly) and to deduce return type.

I saw _Mu template structure in STL "functional.h" but it looks too complex and overloaded.

rewrite throw after function with noexcept

I have heard that in C++11 we should replace throw with noexcept after method declaration :

In C++11, you generally should use noexcept instead. The old throw specification is deprecated.

How to do it in the following code?

template <typename Object>
class Stack
{
public:

    Stack();

    Object & peek() throw(std::runtime_error);

};

Reference link

Please avoid linking to the questions which do not work for std::runtime_error

How to use `duration_cast` for a derived class?

I'm cleaning up my timer class using std::chrono. Everything else went smooth except that I cannot seem to apply duration_cast to derived classes. Well, I made it work in a different way, but I'd still like to know what I missed.

See here for the error message.

#include <iostream>
#include <chrono>

typedef std::chrono::high_resolution_clock Clock;

class Milliseconds : public std::chrono::milliseconds
{
public:
    typedef std::chrono::milliseconds Base;
    typedef Base::rep Type;

    using Base::Base;
};

inline Milliseconds::Type millisecondsSinceEpoch()
{
    return std::chrono::duration_cast<Milliseconds::Base>(Clock::now().time_since_epoch()).count();
    //duration_cast<Milliseconds> ERROR!
}

int main() {
    using namespace std;
    cout << millisecondsSinceEpoch() << endl;
    return 0;
}

Variable initialization guidelines in C++

Which are the guidelines to initialize variables in C++? There are so many ways to initialize a variable in C++. 3 ways with which I am familiar are as following:

1) int a=3;

2) int a(3);

3) int a{3}; // valid for C++11 & later

Which is the best approach? Why 2nd way int a(3); not seen & not used in C++ programs?
Thanks.

Metaprogramming coding style

Is there any pros and cons when making a choise between two following approaches to express type trait?

#include <type_traits>

template< typename first, typename ...rest >
struct are_same;

template< typename last >
struct are_same< last >
        : std::true_type
{

};

template< typename next, typename ...rest >
struct are_same< next, next, rest... >
        : are_same< next, rest... >
{

};

template< typename first, typename second, typename ...rest >
struct are_same< first, second, rest... >
        : std::false_type
{

};

static_assert(are_same< int, int, int >::value);
static_assert(!are_same< int, char, int >::value);

another approach:

template< typename first, typename ...rest >
struct are_same;

template< typename last >
struct are_same< last > 
{

    static constexpr bool value = true;

};

template< typename next, typename ...rest >
struct are_same< next, next, rest... > 
{

    static constexpr bool value = are_same< next, rest... >::value;

};

template< typename first, typename second, typename ...rest >
struct are_same< first, second, rest... >
{

    static constexpr bool value = false;

};

static_assert(are_same< int, int, int >::value);
static_assert(!are_same< int, char, int >::value);

First approach allows me to write static_assert(!are_same< int, char, int >{}); instead of verbose static_assert(!are_same< int, char, int >::value);, but is there an issue WRT compile time? Generally speaking, I mean much more complex metaprogramming statements.

Swap background image multiple times in Cocos2d-x

I am making a story-based 2D game using Cocos2d-x, and I need to switch the background sprite, which is a sprite the is taking the entire resolution of the frame, multiple times during the game. How can I do this ??

I think I should load all the background images to a texture cache of some sort at the beginning and then just swap them, but I don't really know how to do that.

I'd really appreciate some code snippets for Cocos2d-x 3.6.

ifstream attempting reference to a deleted function

I'm writing a code for a virtual tournament. The problem is that team class has an ifstream object, I understand that stream objects do not have copy constructors, therefore i converted playing8 from vector of team objects to pointer to object, So that team objects will not be copied.But now i get this error Error 16 error C2280: 'std::basic_ifstream>::basic_ifstream(const std::basic_ifstream> &)' : attempting to reference a deleted function c:\program files (x86)\microsoft visual studio 12.0\vc\include\xmemory0 592 1 Assignment3

How do i resolve this without removing ifstream object from team class? heres code for tournament.h

#include "team.h"

class Tournament
{
std::ofstream out_file;
std::ifstream in_file;
std::vector<team> teams;
std::vector<team*> playing8;
public:
void schedule();
void schedule2();
void tfinal();
void selectPlaying8();
void rankTeams();
void match(int,int);
Tournament();
~Tournament();
};

code for tournament constructor

Tournament::Tournament()
{
srand(time(NULL));
in_file.open("team_list.txt");
string input;
int noteam=0;
while (getline(in_file, input)){
    noteam++;
}
in_file.close();
for (int i = 0; i < noteam;i++){
    string x=to_string(i)+".csv";
    team temp(x);
    temp.set_teamform((6 + rand() % 5) / 10.0);
    teams.push_back(temp);
}
}

code for select playing 8;

void Tournament::selectPlaying8(){
for (int i = 0; i < 7; i++){
    playing8.push_back(&teams[i]);
    playing8[i]->set_playing();
}

attributes of team class

#include <string>
#include <vector>
#include <fstream>
#include <iostream>
#include "Player.h"

class team 
{
private:
std::ifstream in_file;
std::vector<Player> playing11;
std::string teamname;
std::vector<Player> player;
bool playing;
float matchperformance;
float teamform;
float team_rank_score;
};

Im using visual studio express 2013

Issue with Constrcutors with templates

Given below are is my cpp code.i have written both declaration and defunition in same cpp file because there are templates in this code and i got some errors when i had two seperate files for header and code.so i had to write everything in same file.Still, i have errors with constructor declaration and definition. Why is this throwing the below error, is there something which am missing.

template<class T>
class Linklist
{
public:
Linklist();
Linklist(Linklist<T> & a);
~Linklist();
}     
template<class T>
Linklist<T>::Linklist()
{
}
template<class T>
Linklist::Linklist(Linklist<T> & a) 
{
} 

Error C2244: 'Linklist::{ctor}' : unable to match function definition to an existing declaration definition 'Linklist::Linklist(Linklist &)' existing declarations 'Linklist::Linklist(Linklist &)' 'Linklist::Linklist(void)'

Need to fix my Variadic Macros

I want to use variadic macros but I get errors

#define SERVER_RE_1(ServerFunction, Type1)                          \
    {                                                               \
        Type1 arg1;                                                 \
        getData(args, arg1);                                        \
        sv. ## ServerFunction ## (ssl, arg1);                       \
    }

#define SERVER_RE_2(ServerFunction, Type1, Type2)                   \
    {                                                               \
        Type1 arg1;                                                 \
        Type2 arg2;                                                 \
        getData(args, arg1, arg2);                                  \
        sv. ## ServerFunction ## (ssl, arg1, arg2);                 \
    }

#define SERVER_RE_3(ServerFunction, Type1, Type2, Type3)            \
    {                                                               \
        Type1 arg1;                                                 \
        Type2 arg2;                                                 \
        Type3 arg3;                                                 \
        getData(args, arg1, arg2, arg3);                            \
        sv. ## ServerFunction ## (ssl, arg1, arg2, arg3);           \
    }

#define GET_MACRO(_1,_2,_3,_4,NAME,...) NAME
#define SERVER_RE(...) GET_MACRO(__VA_ARGS__, SERVER_RE_3, SERVER_RE_2, SERVER_RE_1)(__VA_ARGS__)

-

SERVER_RE(signIn, std::string, std::string);

error C2065: 'signIn' : undeclared identifier
error C2275: 'std::string' : illegal use of this type as an expression

-

But SERVER_RE_2 works good.

SERVER_RE(signIn, std::string, std::string);

samedi 30 mai 2015

Why is wstring_convert throwing a range_error?

I'm writing some code that needs to convert between byte strings and wide strings, using the system locale. When reading from a file, this is incredibly easy to do. I can use std::wifstream, imbue it with std::locale(""), and then just use std::getline.

According to cppreference's codecvt page, wifstream just uses codecvt<wchar_t, char, mbstate_t>, so I thought that I might be able to convert between std::string and std::wstring by using that as well:

// utility wrapper to adapt locale-bound facets for wstring/wbuffer
convert
template<class Facet>
struct deletable_facet : Facet
{
    template<class ...Args>
    deletable_facet(Args&& ...args) : Facet(std::forward<Args>(args)...) {}
    ~deletable_facet() {}
};

std::locale::global(std::locale(""));
std::wstring_convert<
    deletable_facet<std::codecvt<wchar_t, char, std::mbstate_t>>> wconv;
std::wstring wstr = wconv.from_bytes(data);

However, when I try to run this, I get an range_error thrown from wstring_convert. I did some googling around, and apparently this is what happens when wstring_convert fails to convert the string.

However, these strings are clearly perfectly able to be converted using wfstream, which should be using the same codecvt as I am using with wstring_convert. So why does wifstream work, but wstring_convert not?

And is there a way that can I convert between strings and wstrings using the system's locale?

A full example of my problem, adapted from the codecvt page, is here, and the output is:

sizeof(char32_t) = 4
sizeof(wchar_t)  = 4
The UTF-8 file contains the following UCS4 code points: 
U+007a
U+00df
U+6c34
U+1f34c
The UTF-8 string contains the following UCS4 code points: 
U+007a
U+00df
U+6c34
U+1f34c
terminate called after throwing an instance of 'std::range_error'
  what():  wstring_convert
Aborted (core dumped)

Can I make macro like `MACRO(x, Type1 t1, Type2 t2)`

I want to make my code smaller. I think some macros could make my code smaller.
I want to make macro which contains objects declarations.
There are switch cases

    case SIGN_UP:
    {
        std::string userName;
        std::string password
        getArgs(args, userName, password);
        sv.signUp(userName, password);
    }
    break;

    case SIGN_IN:
    {
        std::string userName;
        std::string password
        getArgs(args, userName, password);
        sv.signIn(userName, password);
    }
    break;

    case SOMETHING:
    {
        std::string s;
        int i;
        getArgs(args, s, i);
        sv.something(s, i);
    }
    break;

I want to make macro to make this code like

    case SIGN_UP:
        GET_ARGS(args, std::string userName, std::string password);
        sv.signUp(userName, password);
        break;

    case SIGN_IN:
        GET_ARGS(args, std::string userName, std::string password);
        sv.signIn(userName, password);
        break;

    case SOMETHING:
        GET_ARGS(args, std::string s, int i);
        sv.something(s, i);
        break;

Is it possible?

Is typename required or not here?

Consider the code:

#include <memory>

template <class T, class Deleter = std::default_delete<T>>
class unique_ptr_wrapper: public std::unique_ptr<T, Deleter>
{
public:
    using typename std::unique_ptr<T, Deleter>::unique_ptr;
    operator T* () const {return this->get();}
};

int main()
{
    unique_ptr_wrapper<int> upw{new int{42}};
}

g++5.1 compiles it fine, although clang++ complains

error: typename is allowed for identifiers only

I agree that we don't have an identifier here, so probably typename is not required. But is it actually forbidden? Is the compiler required to at least emit a diagnostic?

Implementing BFS using C++

I am trying to implement BFS in C++, Here is the code.

#include <iostream>
#include <list>
#include <string>
#include <limits>
#include <map>

int infinity=std::numeric_limits<int>::max();


struct Node{
        int value;
        int distance;
        std::string color;

        Node(int val):
        value(val),
        distance(infinity),
        color("white")
        {}
};

//using AdjList = std::map<Node*,std::list<Node*>>;
typedef std::map<Node*,std::list<Node*>> AdjList;
AdjList create_graph()
{
    Node* n1 = new Node(1);
    Node* n2 = new Node(2);
    Node* n3 = new Node(3);
    Node* n4 = new Node(4);
    Node* n5 = new Node(5);
    Node* n6 = new Node(6);
    Node* n7 = new Node(7);
    Node* n8 = new Node(8);

    AdjList m;
    m[n1] = {n2, n5};
    m[n2] = {n1, n6};
    m[n3] = {n4, n6, n7};
    m[n4] = {n3, n7, n8};
    m[n5] = {n1};
    m[n6] = {n2, n3, n7};
    m[n7] = {n3, n4, n6, n8};
    m[n8] = {n4, n7};
    return m;
}


void bfs(const AdjList& m, Node* n1)
{
    std::list<Node*> queue;
    queue.push_back(n1);
    unsigned count = 0;

    while (!queue.empty())
    {
        auto n = queue.front();
        std::cout << n->value << std::endl;
        queue.pop_front();
        std::cout << *(m[n].begin()) << std::endl;
        for(auto it = m[n].begin(); it != m[n].end(); ++it)
        {
            if ((*it)->color != "black")
                queue.push_back(*it);
        }

        n->color = "black";
        n->distance = count;
        ++count;
    }
}

On trying to compile with gcc, I receive the following error messages.

bfs.cpp: In function ‘void bfs(const AdjList&, Node*)’:
bfs.cpp:59:27: error: passing ‘const AdjList {aka const std::map<Node*, std::list<Node*> >}’ as ‘this’ argument of ‘std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const key_type&) [with _Key = Node*; _Tp = std::list<Node*>; _Compare = std::less<Node*>; _Alloc = std::allocator<std::pair<Node* const, std::list<Node*> > >; std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = std::list<Node*>; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = Node*]’ discards qualifiers [-fpermissive]
         std::cout << *(m[n].begin()) << std::endl;
                           ^
bfs.cpp:60:20: error: passing ‘const AdjList {aka const std::map<Node*, std::list<Node*> >}’ as ‘this’ argument of ‘std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const key_type&) [with _Key = Node*; _Tp = std::list<Node*>; _Compare = std::less<Node*>; _Alloc = std::allocator<std::pair<Node* const, std::list<Node*> > >; std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = std::list<Node*>; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = Node*]’ discards qualifiers [-fpermissive]
   for(auto it = m[n].begin(); it != m[n].end(); ++it)
                    ^
bfs.cpp:60:40: error: passing ‘const AdjList {aka const std::map<Node*, std::list<Node*> >}’ as ‘this’ argument of ‘std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const key_type&) [with _Key = Node*; _Tp = std::list<Node*>; _Compare = std::less<Node*>; _Alloc = std::allocator<std::pair<Node* const, std::list<Node*> > >; std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = std::list<Node*>; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = Node*]’ discards qualifiers [-fpermissive]
   for(auto it = m[n].begin(); it != m[n].end(); ++it)

I am not sure what is wrong. Please point out the mistake.

Union. User-Defined Constructor or non-trivial default constructor

Current Error: vec4 has a user-defined constructor or non-trivial default constructor.

Hello,

I looked up a few things on this bug, by going into what a non-trivial default constructor is and got no where. The code is currently this

union 
{
    float elements[4 * 4];
    vec4 columns[4];
};

To my current knowledge as long as i was to flag the constructor as default i would be fine which i did here.

    vec4() = default;
    vec4(const float& x, const float& y, const float& z, const float& w);

If anyone has any knowledge on what is going on here, or can help can help me reach a conclusion that would be great!

Thanks

Weird memory leak in Visual Studio C++ project

I use unique_ptr. For creating this poiters, I use this code snippet:

template<typename T, typename ...Args>
std::unique_ptr<T> make_unique(Args&& ...args)
{
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); //line 44
}

I test my project for memory leaks with help built-in memory leak checker.

I get the following result:

Detected memory leaks!
Dumping objects ->
my_header.h(44) : {228} normal block at 0x008AD568, 8 bytes long.
 Data: <        > A0 CB 8A 00 01 00 00 00 
my_header.h(44) : {226} normal block at 0x008AD5B8, 8 bytes long.
 Data: <        > 00 D6 8A 00 00 00 00 00 
/////////////////this error repeats many times

Also, I use deleaker. This tool says, that there is no memory leaks.

GetLastError() returns ERROR_INVALID_HANDLE / 6 after calling SwapBuffers(HDC)

Whenever I attempt to call SwapBuffers(), GetLastError() returns 6 / ERROR_INVALID_HANDLE. For a while I have attempted to fix this by rewriting this code in different ways, attempting to find different origins of errors and generally looking at what I could be doing wrong. But, I haven't come to a single conclusion on what is inducing this or what I can do to resolve this.

I have also recognized when I call OpenGL functions such as glUseProgram() and glVertexAttribPointer(), glGetError() returns 1282 / GL_INVALID_OPERATION.

I'm thankful for any replies.

Window::Window(string title, int xPos, int yPos, int width, int height, string icon_path)
        {
            this->title = title;
            this->width = width;
            this->height = height;

            if (this->height == 0)
                this->height = 1;

            if (!Create(xPos, yPos))
            {
                cout << "Window Creation Failure!" << endl;
                exit(EXIT_FAILURE);
            }

            HANDLE hIcon = LoadImage(0, icon_path.c_str(), IMAGE_ICON, 0, 0, LR_DEFAULTSIZE | LR_LOADFROMFILE);

            SendMessage(hWnd, WM_SETICON, ICON_BIG, (LPARAM) hIcon);

            glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        }

        Window::~Window()
        {
            wglMakeCurrent(hDC, 0);
            wglDeleteContext(hRC);

            ReleaseDC(hWnd, hDC);
        }

        bool Window::Create(int xPos, int yPos)
        {
            WNDCLASS WndClass;
            DWORD dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
            DWORD dwStyle = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX;

            this->hInstance = GetModuleHandle(nullptr);

            if (!this->hInstance)
                return false;

            WndClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
            WndClass.lpfnWndProc = (WNDPROC) WndProc;
            WndClass.cbClsExtra = 0;
            WndClass.cbWndExtra = 0;
            WndClass.hInstance = this->hInstance;
            WndClass.hIcon = LoadIcon(nullptr, IDI_WINLOGO);
            WndClass.hCursor = LoadCursor(nullptr, IDC_ARROW);
            WndClass.hbrBackground = nullptr;
            WndClass.lpszMenuName = nullptr;
            WndClass.lpszClassName = this->title.c_str();

            if (!RegisterClass(&WndClass))
                return false;

            this->hWnd = CreateWindowEx(dwExStyle, this->title.c_str(), this->title.c_str(), dwStyle,
                xPos, yPos, this->width, this->height, nullptr, nullptr, this->hInstance, nullptr);

            if (!this->hWnd)
                return false;

            if (!this->CreateContext())
                return false;

            ShowWindow(this->hWnd, SW_SHOW);
            UpdateWindow(this->hWnd);

            return true;
        }

        bool Window::CreateContext()
        {
            this->hDC = GetDC(hWnd);

            if (!this->hDC)
                return false;

            PIXELFORMATDESCRIPTOR pfd;
            memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR));
            pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
            pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;
            pfd.iPixelType = PFD_TYPE_RGBA; 
            pfd.cColorBits = 32;
            pfd.cDepthBits = 32;
            pfd.iLayerType = PFD_MAIN_PLANE;

            int nPixelFormat = ChoosePixelFormat(this->hDC, &pfd);

            if (!nPixelFormat) 
                return false;

            bool bResult = SetPixelFormat(this->hDC, nPixelFormat, &pfd);

            if (!bResult)
                return false;

            HGLRC tempOpenGLContext = wglCreateContext(this->hDC);
            wglMakeCurrent(this->hDC, tempOpenGLContext);

            GLenum err = glewInit();

            if (GLEW_OK != err)
                return false;

            int attributes[] = 
            {
                WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
                WGL_CONTEXT_MINOR_VERSION_ARB, 2,
                WGL_CONTEXT_FLAGS_ARB,                          WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
                0
            };

            if (wglewIsSupported("WGL_ARB_create_context") == true)
            {
                this->hRC = wglCreateContextAttribsARB(this->hDC, NULL, attributes);
                wglMakeCurrent(nullptr, nullptr);
                wglDeleteContext(tempOpenGLContext);
                wglMakeCurrent(this->hDC, this->hRC);

                if (!this->hRC)
                    return false;
            }
            else 
            {
                this->hRC = tempOpenGLContext;
            }

            int glVersion[2] = {-1, -1};
            glGetIntegerv(GL_MAJOR_VERSION, &glVersion[0]);
            glGetIntegerv(GL_MINOR_VERSION, &glVersion[1]);

            cout << "Opengl is running on context version : " << glVersion[0] << ", " << glVersion[1]  << endl;

            return true;
        }

        int Window::GameLoop(Core *core)
        {
            MSG msg;

            while (core->IsRunning())
            {
                if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
                {
                    if (msg.message == WM_QUIT)
                    {
                        core->SetRunning(false);
                    }
                    else
                    {
                        TranslateMessage(&msg);
                        DispatchMessage(&msg);
                    }
                }
                else
                {
                    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

                    core->Run();

                    SwapBuffers(this->hDC);
                }
            }

            Core::Destroy();

            return (int)(msg.wParam);
        }

Calling parent methods and accessing it's protected fields

Me and my friends are trying to write some kind of a game as a study project in university. We use Eclipse and write program on C++11. And we met very strange (as for me) problem.

We have special class PlayingObject:

    class PlayingObject{
    protected:
        Action* currAction;
        std::queue<Action*> ActionQueue;
        .....
    public:
        virtual Action* GetAction();
        virtual void NextAction();
        virtual void AddAction(Action* action, bool replace);
        virtual Stop();
        .....
    }

This class has two children, Unit and Building. They both override methods, mentioned before, but not all. Unit:

   class Unit: public PlayingObject{
   public:
       .....
       virtual Action* GetAction();
       virtual void NextAction();
       virtual void AddAction(Action* action, bool replace);
       virtual Stop();
       .....
   }

and the same thing in Building:

   class Building: public PlayingObject{
   public:
       .....
       virtual Action* GetAction();
       virtual void NextAction();
       virtual void AddAction(Action* action, bool replace);
       virtual Stop();
       .....
       void Produce();
   }

Unit::AddAction() works OK. We can even use such a code:

   Unit* unit=new Unit(...);
   unit->Stop();

Stop() is not overriden in Unit, but it works. Unit has access to currAction and ActionQueue.

But problem occures when we make same things in Building. We cannot call parent methods in Building;

   Building* building=new Building(...);
   building->Stop(); //crashes program
   building->NextAction(); //crashes program
   unsigned int temp=building->ActionQueue.size(); //suddenly returns very large number, when it should not
   Action* act=ActionQueue.front(); //crashes program

The idea is that project builds well. It works (I mean, we control units, they move and can be picked) until we call building->NextAction() or building->AddAction(action, true). Project closes without any log.

It happens exactly when we write realisation of Building::Produce():

   void Building::Produce(){
       .....
       this->AddAction(action, true); //here it crashes
       //AddAction(action, true); //also would crash
       PlayingObject::AddAction(actioon, true); //no crash, but works incorrectly; ActionQueue.size() inside PlayingObject::AddAction() returns 18446744073709551552 and it doesn't look real;
       this->ActionQueue.size(); //also returns this number
       Action* act;
       act=ActionQueue.front(); //crashes project. again.
   }

We almost sure we don't push something bad into ActionQueue, we checked it many times. And when we try to override this methods like this:

   void Building::AddAction(Action* action, bool replace){
       PlayingObject::AddAction(action, replace);
   }

and then call building->AddAction(...) in Building::Produce(), it also crashes, like before.

We cannot understand, what happens here. There is, in fact, no difference between Building and Unit. Building is even simplier. But why we cannot call Building::AddAction() from other Building methods even if it's overriden?!

Please, help me to understand, what it is and why one child can override parant's methods and has access to it's protected members, and another can do nothing of this correctly.

Why does this hashtable function shows a compilation error?

#include <iostream>
#include <string>
#include <unordered_map>

using namespace std;

int main (void)
{
    unordered_map<string,string> myhash;
    int i,n,m,len1,len2;
    cin>>n>>m;
    string arr2[3010];
    string s1,s2;
    for ( i = 0; i < m; i++ )
    {
        cin>>s1>>s2;
        myhash.emplace(s1,s2);
    }
    for ( i = 0; i < n; i++ )
    {
        cin>>arr2[i];
    }
    for ( i = 0; i < n; i++ )
    {
        len1 = arr2[i].length();
        len2 = myhash[arr2[i]].length();
        if ( len1 > len2 )
            cout<<myhash[arr2[i]]<<"\t";
        else
            cout<<arr2[i][0]<<"\t";
    }
    cout<<"\n";
    return 0;
}

On compilation, it shows an error.

error: no member named 'emplace' in
      'std::__1::unordered_map<std::__1::basic_string<char>, std::__1::basic_string<char>,
      std::__1::hash<std::__1::basic_string<char> >,
      std::__1::equal_to<std::__1::basic_string<char> >, std::__1::allocator<std::__1::pair<const
      std::__1::basic_string<char>, std::__1::basic_string<char> > > >'
                myhash.emplace(s1,s2);

I made the above code in which I am taking input a number of strings and adding them to the hashtable named myhash. Why do I see this error? Is it because my compiler doesn't support emplace function?

How init() works internally when used in C++

Init() is the initial or we can say a daemon process being called up on Bootup runs till shutdown if we won't kill it. So, this a Linux based definition. I have doubt whether the same definition is applicable in C++ environment. Help Appreciated.

why cant i initialize 3 default parameters at a time in c++

class Complex 
{
private:

float rp, ip;
//const int a=10;
//static int b;
//static const int c = 50;
public:
Complex();
//Complex(float );
/*Complex(float,float);*/
Complex(float , float = 20, float = 30);
} 

The above code works fine but when i try to have 3 default parameters

class Complex
{
private:
float rp, ip;
//const int a=10;//static int b;//static const int c = 50;
public:
Complex();
//Complex(float );
/*Complex(float,float);*/
Complex(float =10  , float = 20, float = 30);
} 

i get the below error main.cpp(12): error C2668: 'Complex::Complex' : ambiguous call to overloaded function complex.h(15): could be 'Complex::Complex(float,float,float)' complex.h(12): or 'Complex::Complex(void)'

I have created a unordered set, when I am trying to get the constant iterator the compiler is giving error

template Node* LinkedList::findCommonNode_hash(LinkedList* list_2)

{

     unordered_set<Node<T>*>* set = new unordered_set<Node<T>*>();
     Node<T>* curr_list_1 = head->next;
     Node<T>* curr_list_2 = list_2->head->next;
     unordered_set<Node<T>*>::const_iterator itr = set->find(curr_list_1);
     if(itr == set->end())
     {
         set->insert(curr_list_1);
     }
     else
        return curr_list_1;
     unordered_set<Node<T>*>::const_iterator itr1 = set->find(curr_list_2);
     if((itr1 == set->end()))
     {
         set->insert(curr_list_2);
     }
     else
        return curr_list_2;
     return nullptr;

}

IDE: codeblock C++11 . I am getting the below error when trying to get the const_iterator to find the element exist in the set or not.

C:\Education\DataStructure_Algorithms\List\List.cpp|252|error: need 'typename' before 'std::unordered_set*>::const_iterator' because 'std::unordered_set*>' is a dependent scope|

Delegate to another object's arrow operator

Writing at alias template that will deduce the return type of some type T's operator->, so far I have this

template <typename T>
using arrow = decltype(std::declval<T&>().operator->());

which works for all class types, but doesn't work for pointers. A similar problem exists trying to actually call the ->

template <typename T>
struct D {
    T t;
    arrow<T> f() { 
        // not valid to call .operator->() on pointers
        return t.operator->();
    }
};

How can I make this function get the correct return type declared, and delegate correctly for both class types and pointers?

Static Class Template member initialization

I have an issue when trying to initialize static members of a static class template.

Basically, what I thought this approach would be useful for: I have a lot of objects, which are of course all of the same Base type but they have differing object types. I just want to manipulate these objects, that's why I decided to use a static template as there are quite a number of different types these object can consist of.

However, for logging and options passing I wanted to add the corresponding members to the template whithout having to write initializers for every derived static class.

Please note that the following code is not actually working, because there is some SDK involved. I'm just aksing for the right approach, not right code.

Thanks in advance. :)

template.h:

#ifndef _TEMPLATE_H
#define _TEMPLATE_H

#include "stats.h"

template<class T>
class TemplateObj
{
public:
    static void SetParameters(const Options& options)
    {
        T::_options = options;  // Is this even possible?
        T::Init();
        T::DoStuff(_options);
    }

protected:
    static void Message() { stats.Print("Message from Template static method"); }
    static Stats& TemplateObj<T>::stats = Stats::GetInstance(); // This will not work as this is a non-trivial initializer, how to do it correctly? Stats::GetInstance() retrieves a singleton instance
    static Options& TemplateObj<T>::_options;   // Possible?
};

#endif

derived.h:

#ifndef _DERIVED_H
#define _DERIVED_H
#include "template.h"

class Derived :TemplateObj < Derived >
{
public:
    static void Init();
    static void DoStuff(Options& options)
};

#endif

derived.cpp:

#include "derived.h"

void Derived::Init()
{
    // Init stuff here
    TemplateObj::Message(); // Call static method from template directly
}

void Derived::DoStuff(Options& options)
{
    // Do something with options 
    stats.Print("Message from derived static method."); // Access to "stats" here. "stats" should be declared and initialized inside the template.
    options.Load(); // Example
}

main.h

#include "derived.h"

main()
{
    TemplateObj<Derived>::SetParameters(new Options);
}

error in compilation in codeforces

can anyone help me in this

#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
#define ll long long int
struct points{
ll a;
ll b;
};
int cos(points x , points y)
{
    return x.b<y.b;
}
int main()
{
   ll n,r,avg,i,j,k;
   points pt[100005];
   cin>>n>>r>>avg;
   for(i=0;i<n;i++)
   {
       cin>>pt[i].a>>pt[i].b;
   }
   sort(pt,pt+n,cos);
   ll sum=avg*n;
   for(i=0;i<n;i++)sum-=pt[i].a;
   if(sum<=0)cout<<"0\n";
   else
   {

   ll ans=0;
   for(i=0;i<n;i++)
   {
       if(sum==0)break;
       else
       {
           if(sum>r-pt[i].a)
           {
               ans=ans+pt[i].b*(r-pt[i].a);
               sum=sum-(r-pt[i].a);
           }
           else
           {
               ans=ans+sum*pt[i].b;
               sum-=sum;
           }
       }
   }
   cout<<ans<<endl;
   }
    return 0;
}

when im compiling in my system its working fine and getting the correct output but when i'm submitting in codeforces under GNUC++ 11 im getting compllation error? can u help me

How to use typename instead of typedef?

I have the following code snipper:

template <class T>
int foo(T (*f)()) {
    typedef T (*func)();
    typedef funct<T, func> F; //this line 
    auto result = F(f);
    auto result2 = bar<F>();

    return 0;
}

As you can see, we use typedef a function pointer on line 4. I want to remove first typedef. For example, I want to rewrite my code snippet, as:

template <class T>
int foo(T (*f)()) {
    typedef funct<T, typename f> F; //this line 
    auto result = F(f);
    auto result2 = bar<F>();

    return 0;
}

But, of course, there is a error.

Main purpose of this action is to simplify my code.

How to assign a unique_ptr with a custom deleter

I am trying to pass a pointer to a function that then sets a unique_ptr inside a struct to the pointer passed in. However, I get the following compile error on the last line of the function.

error C2280: 'std::unique_ptr< ALLEGRO_BITMAP,std::default_delete< ALLEGRO_BITMAP>>::unique_ptr(const std::unique_ptr< ALLEGRO_BITMAP,std::default_delete< ALLEGRO_BITMAP>> &)' : attempting to reference a deleted function

c:\program files (x86)\microsoft visual studio 12.0\vc\include\memory(1486) : see declaration of 'std::unique_ptr< ALLEGRO_BITMAP,std::default_delete< ALLEGRO_BITMAP>>::unique_ptr'

This diagnostic occurred in the compiler generated function 'Skin::Skin(const Skin &)'

Judging from the errors I believe it has something to do with me adding the delete template for ALLEGRO_BITMAP to namespace std, but I don't know why or how to fix it.

using namespace std;

namespace std {
template<>
class default_delete < ALLEGRO_BITMAP > {
public:
    void operator()(ALLEGRO_BITMAP* ptr) {
        al_destroy_bitmap(ptr);
    }
};
}

typedef struct {
    unique_ptr<ALLEGRO_BITMAP> img;
} Skin;

typedef struct {
    Skin skins[MAX_ENTITY_COUNT];
} World;

unsigned int createBlock(World world, ALLEGRO_BITMAP* img) {
    unsigned int entity = newEntityIndex(world);
    world.skins[entity].img = make_unique<ALLEGRO_BITMAP>(img);
    return entity;
} // error on this line

Any help is appreciated. Thanks.

Brace-or-equal initializer causing C2098 and C2059 in Visual Studio 2015 RC

The following, seemingly correct looking, code does not compile in Visual Studio 2015 RC, with errors like this:

test.cpp(6): error C2098: unexpected token after data member 'T'
  test.cpp(11): note: see reference to class template instantiation 'Foo<int>' being compiled
test.cpp(6): error C2059: syntax error: '>'

The code:

template <typename, typename> struct X {};

template <typename T>
struct Foo
{
    X<int, T> * p = new X<int, T>;
};

int main()
{
   Foo<int> f;
}

Why is this and how can I overcome this problem?

non-static data member initialization with new expression

Consider the following code:

#include <map>

template <typename T>
struct X {
    std::map<int, T>* storage = new std::map<int, T>();
};

int main() {
    X<int> x;
}

This compiles on clang 3.6.0, but fails to compile on gcc 5.1. It would compile, however, if the type of storage were instead std::vector<T>* (or just T*). I'm fairly certain this is a compiler bug on gcc's part, but thought I'd ask to make sure: is there any reason the above example shouldn't compile?

gcc compile error:

main.cpp:5:51: error: expected ';' at end of member declaration    
     std::map<int, T>* storage = new std::map<int, T>();    
                                                   ^    

main.cpp:5:51: error: declaration of 'std::map<int, T> X<T>::T'    
main.cpp:3:11: error:  shadows template parm 'class T'    
 template <typename T>    
           ^

main.cpp:5:52: error: expected unqualified-id before '>' token    
     std::map<int, T>* storage = new std::map<int, T>();    
                                                    ^    
main.cpp:5:46: error: wrong number of template arguments (1, should be at least 2)    
     std::map<int, T>* storage = new std::map<int, T>();    
                                              ^

In file included from /usr/local/include/c++/5.1.0/map:61:0,    
                 from main.cpp:1:    
/usr/local/include/c++/5.1.0/bits/stl_map.h:96:11: note: provided for 'template<class _Key, class _Tp, class _Compare, class _Alloc> class std::map'    
     class map    
           ^

C++11 alternative to the Java anonymous callback class

I realise that the solution I have here is far from ideal with C++, so I'm asking what a proper C++ programmer would do in this situation. (C++11)

I have a DialogBox class, which stores a collection of buttons. At the moment I have a pure abstract inner class DialogBox::Button with the pure virtual function virtual void callback() const.

From Java I'm used to using this strategy to create and instantiate an anonymous class deriving from Button in-place which implements the callback function. Something like this:

db.add_button(new Button( "Button text", BUTTONTYPE ) {
    public void callback() {
        // Callback code
}});

which is what prompted this C++ solution.

My C++ solution therefore looks like

dialogbox.h

class DialogBox {
public:
    // Abstract class for buttons with callback functions
    class Button;

private:
    /* ...
      stuff 
     */

public:
    /* ...
      stuff 
     */
    const std::vector< unique_ptr<DialogBox::Button> >& get_buttons() const;
    void add_button( unique_ptr<DialogBox::Button>& new_button );
};


class DialogBox::Button {

private:
    /* ...
      stuff
     */

public:
    // Constructor
    Button( const string& button_text, const DialogButtonType button_type = DialogButtonType::NORMAL );

    /* ...
      stuff
     */

    // Virtual callback function
    virtual void callback() const = 0;

};

Usage:

// Instantiate
DialogBox db{ /* ... args ... */ };
// Test adding buttons
class Button1 : public DialogBox::Button {
    using DialogBox::Button::Button;
    public: void callback() const {
        // Callback code
    }
};
std::unique_ptr<DialogBox::Button> button1{ new Button1{ "Button1", DialogButtonType::ENTER } };
db.add_button( button1 );

This works, but it's clearly not as clean as the Java version and certainly feels like I'm shoehorning in something that C++ is not designed to do.

So, how would a C++ programmer do this? It seems conceptually right to have Button as a class (since it has internal data and its own behaviour). At the moment I'm thinking of using a lambda expression to pass in the callback function to Button's constructor, but I thought I'd get some expert opinion on the subject.

How to compare thread's result with other variable

The thing is I have one function that calculates and gets result of these operations. After getting result I want to compare and get the best result using criteria. The problem is that I do not know if it is good idea to compare variable with result got by threads. Is it going to mess up things for example if two threads are comparing with this variable at the same time or it has some sort of defense?

#include <iostream>
#include <thread>

double RESULT;

void call_from_thread(int i)
{
    //some calculation
    double result;
    if(result>RESULT)
    {
        RESULT=result;
    }
}

int main(int argc, char *argv[])
{
    std::thread t[64];
    for(int i=0;i<64;i++)
    {
        t[i]=std::thread(call_from_thread,i);
    }

    for(int i=0;i<64;i++)
    {
        t[i].join();
    }


    return 0;
}

Is it going to mess RESULT?

What is the logic behind these destructor calls

I ran the following code

#include <iostream>
using namespace std;

class Count
{
    private:

        int count;      

    public:

        //Constructor
        Count():count(0) { cout << "Constructor called" << endl; }

        //Destructor
        ~Count() { cout << "Destructor called" << endl; }

        //Display the value.
         Count display() 
         { 
               cout << "The value of count is " << count << endl; 
               return *this;
         }

};

int main()
{
    Count C;
    C.display();
}

Result :-

Constructor called
The value of count is 0
Destructor called
Destructor called

In the above case, the destructor is called twice, one for destruction of the "this" object and one for return from main.

Is my observation correct ??

Can anyone explain me also the temporary object created in this process like why it is created, if created??

Thread was not delcared in this scope error

I am learning concurrent programing with c++ and I have a problem. I get en error: "thread was not declared in this scope error"

with this code:

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

void function1(){
    cout << "Beauty is only skin deep" << endl;
}

int main(){
    thread t1(function1);
    return 0;
}

I am using CodeBlock and I have enabled this option in compiler settings: "Have g++ follow the C++11 ISO C++ language standard [-std=c++11]"

I am using C++11 a lot and this is only thing that doesn't work. How to fix that ?

My operatins system is WIndows XP and compiler is GNU GCC

EDIT:

my PATH: "D:\Aplikacje\NVIDIA Corporation\PhysX\Common;C:\Documents and Settings\All Users\Dane aplikacji\Oracle\Java\javapath;D:\Aplikacje\Borland\CBUILD~1\Bin;D:\Aplikacje\Borland\CBUILD~1\Projects\Bpl;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\system32\wbem;C:\PROGRAM FILES\QUICKTIME\QTSYSTEM;%PROGRAMFILES%\Internet Explorer;C:\Program Files\QuickTime\QTSystem\;C:\xampp\mysql\lib;D:\aplikacje\Java\jdk1.8.0_45\bin;D:\Aplikacje\MATLAB\R2011a\runtime\win32;D:\Aplikacje\MATLAB\R2011a\bin"

EDIT2: Full compiler output:

"||=== ewghm, Debug ===| C:\Documents and Settings\KM\Pulpit\PROGRAMY\ewghm\main.cpp||In function 'int main()':|

C:\Documents and Settings\KM\Pulpit\PROGRAMY\ewghm\main.cpp|10|error: 'thread' was not declared in this scope|

C:\Documents and Settings\KM\Pulpit\PROGRAMY\ewghm\main.cpp|10|error: expected ';' before 't1'|

||=== Build finished: 2 errors, 0 warnings (0 minutes, 0 seconds) ===| "

Searching vectors in C++

I need to find whether a vector<unsigned> searchvec; is present in a vector<vector<unsigned> > containerVec;. One way to do the same is to iterate over vector<vector<unsigned> > containerVec; and see whether searchVec is present in containerVec. Is there any build in c++ function which can help me do the same.

Also my searchVec is of size 1 million vector

For example if my searchVec is (9,28,4,2) and my containerVec is ((1,3,678,27),(9,28,4,2), (595,85,52)). Then searchVec (9,28,4,2) is present in ((1,3,678,27),(9,28,4,2), (595,85,52)). However if my searchVec is (23,84,25,11) then it is not present in containerVec.

vendredi 29 mai 2015

How to make function or macros for any count of arguments with any types?

There are client and server. I send and receive data using boost::serialization. Often several arguments with different types send. Are there ways to make function or macros for this?

For example send(argType1, argType2, argType3);

I think i will not send more then 5 arguments for one time.

Is there a memory leak in the following c++ code?

I am writing my program for my DataMining project. I get segmentation error on my code. I tried to debug using the gdb and created core dump using ulimit in ubuntu.

Below is the error I was able to backtrace in gdb.

Python Exception Cannot access memory at address 0x7fff48c47738: #0 0x000000000040cdb0 in TokenReader::getToken ( this=, this@entry=, buf=, buf@entry=) at src/tokread.c++:26 Cannot access memory at address 0x7fff48c47738

My code:



    /*********************************************************
     * Project: 2
     * File: tokread.h
     * Anil Pediredla, KUID 28056
     *********************************************************/

    #ifndef _TOKREAD_H_
    #define _TOKREAD_H_

    #include 
    using namespace std;

    const short NEW_LINE = 0;
    const short SPACE    = 1;
    const short TOKEN    = 2;
    const short COMMENT  = 3;

    class TokenReader {
      public:

        TokenReader(istream &in);

        char* getToken(char* buf);

      private:
        istream &in;
        short state;
    };



    #endif //_TOKREAD_H_

    /*********************************************************
     * Project: 2
     * File: tokread.h
     * Anil Pediredla, KUID 28056
     *********************************************************/

    #include 
    #include 

    using namespace std;

    #include "tokread.h"


    /*********************************************************
     * Class: TokenReader
     *********************************************************/
    TokenReader::TokenReader(istream &in):
      in(in), state(NEW_LINE) {
    }


    char* TokenReader::getToken(char* buf) {
      bool done = false;
      int tokLen = 0;
      while (!done && !in.eof()) {
        char ch = in.get();
        switch (state) {
          case NEW_LINE:
            if (ch == '!') state = COMMENT;
            else {
              in.unget();
              state = SPACE;
            }
          break;
          case SPACE: 
            if ((ch == 13) && (in.peek() == '\n')) in.get();
            if (ch == '\n') {
              state = NEW_LINE;
              break;
            }
            if ((ch != ' ') && (ch != '\t')) {
              in.unget();
              state = TOKEN;
            }
          break;
          case TOKEN:
            if ((ch == 13) && (in.peek() == '\n')) in.get();
            if (ch == '\n') {
              state = NEW_LINE;
              done = true;
              break;
            }
            if ((ch == ' ') || (ch == '\t')) {
              in.unget();
              state = SPACE;
              done = true;
              break;
            }
            buf[tokLen++] = ch;
          break;
          case COMMENT:
           if (ch == '\n'){
               state = NEW_LINE;
           }
          break;
        }
      }
      buf[tokLen] = '\0';
      return buf;
    }


freeglut Refresh the display and wait before refreshing again

So I'm using freeglut on a C++ program for displaying nodes on a network (it might not be the best option but it's what I have to work with). Currently, I have a 'for' cycle, which goes from 1 to a certain given value, and on every iteration it has the possibility of changing a node's state (their states are represented by the colours of the points on the display). I want to be able to see those changes, before it moves on to the next iteration (so kinda like refresh the display and then make a pause for about 5 seconds) so I was wondering if you guys could help me achieve that... If you need me to elaborate on something, just let me know. And thanks in advance!

Dijsktra algorithm in C++

I have a number of source vertices and need to find paths using Dijkstra from these source vertices. For doing so I wrote the following program. As path from each source vertex is computed independently of the other, therefore I parallelized the code using openmp. However, the program seems to be running in an infinite loop, can someone please tell me as to where am I going wrong. Is there any other way by which I may parallelize the execution of Dijsktra algorithm for finding paths from a number of source vertices.

#include <iostream>
#include <set>
#include <vector>
#include <map>
using namespace std;

typedef vector<int> vi;
typedef pair<int,int> ii;
typedef vector<ii> vii;
typedef vector<vii> vvii;

const int MAX = 1001;
const int MAXINT = 1000000000;

int n;
vvii G(MAX);

void Dijkstra(int s,vi& D)
{
    set<ii> Q;
    D[s] = 0;
    Q.insert(ii(0,s));

    while(!Q.empty())
    {
        ii top = *Q.begin();
        Q.erase(Q.begin());
        int v = top.second;
        int d = top.first;
        for (vii::const_iterator it = G[v].begin(); it != G[v].end(); it++)
        {
            int v2 = it->first;
            int cost = it->second;
            if (D[v2] > D[v] + cost)
            {
                if (D[v2] != 1000000000)
                {
                    Q.erase(Q.find(ii(D[v2], v2)));
                }
                D[v2] = D[v] + cost;
                Q.insert(ii(D[v2], v2));
            }
        }
    }
}        
int main()
{
    vector<unsigned> sourceNodes; //intializing source nodes from a separate file
    map<unsigned,vector<int> > mapSourceDistance;
    #pragma omp parallel for    
    for(unsigned i=0;i<sourceNodes.size();i++)
    //for(auto it : rankingNodes)
    {       
        vi D(MAX, MAXINT);
        Dijkstra(sourceNodes[i],D);
        #pragma omp critical
        mapSourceDistance[sourceNodes[i]]=D;
    }    
}

gcc which I am using is gcc-4.8

OpenGL error "function call missing arguments list"

Have anyone any idea how I can solve this problem from my code?

'Sphere::handleKeypress': function call missing argument list; use '&Sphere::handleKeypress' to create a pointer to member

here is my code

Sphere class:

#include "glos.h"
#include <glut.h>
#include <math.h>  
class Sphere{

private:
    float x2, y2, z2, r2;
public:
    float x, y, z, r,speed = 0.10;
    Sphere(float x, float y, float z, float r){
        this->x = x;
        this->y = y;
        this->z = z;
        this->r = r;
    }
    bool colision(Sphere sfera){
        x2 = sfera.x;
        y2 = sfera.y;
        z2 = sfera.z;
        r2 = sfera.r;
        float d = sqrt(pow(x - x2, 2) + pow(y - y2, 2) + pow(z - z2, 2));
        if (d <= r + r2){
            return true;
        }
        else{
            return false;
        }
    }
    void draw(){
        glPushMatrix();
        glTranslatef(x, y, z);
        glutSolidSphere(r, 100, 100);
        glPopMatrix();
    }
    void handleKeypress(unsigned char key, int x, int y){
        Sphere sfera(x2, y2, z2, r2);
        if (key == 'a'){
            if (!colision(sfera)){
                x -= speed;
            }
            else{
                if (x  <  x2){
                    x -= speed;
                }
            }
        }
        if (key == 'd'){
            if (!colision(sfera)){
                x += speed;
            }
            else{
                if (x  >  x2){
                    x += speed;
                }
            }
        }
        if (key == 's'){
            if (!colision(sfera)){
                y -= speed;
            }
            else{
                if (y  <  y2){
                    y -= speed;
                }
            }
        }
        if (key == 'w'){
            if (!colision(sfera)){
                y += speed;
            }
            else{
                if (y  >  y2){
                    y += speed;
                }
            }
        }
        if (key == 'e'){
            if (!colision(sfera)){
                z += speed;
            }
            else{
                if (z  >  z2){
                    y += speed;
                }
            }
        }
        if (key == 'q'){
            if (!colision(sfera)){
                z -= speed;
            }
            else{
                if (z  <  z2){
                    z -= speed;
                }
            }
        }
        glutPostRedisplay();
    }
};

Main class:

#include "glos.h"
#include <gl.h>
#include <glu.h>
#include <glut.h>
#include <glaux.h>
#include <math.h>  
#include "Sphere.cpp"
using namespace std;

Sphere sfera1(0, 0, 0, 1);
Sphere sfera2(5, 0, 0, 1);

void myinit(void);

void myinit(void)
{
    glEnable(GL_LIGHTING); // activare iluminare
    glEnable(GL_LIGHT0);    // activare sursa 0

    glDepthFunc(GL_LESS);
    glEnable(GL_DEPTH_TEST);
}

void  display(void)
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    sfera1.draw();
    sfera2.draw();
    glFlush();
}

void  myReshape(GLsizei w, GLsizei h)
{
    if (!h) return;
    glViewport(0, 0, w, h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(65.0, (GLfloat)w / (GLfloat)h, 1.0, 20.0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glRotated(25, 0.0, 1.0, 1.0);
    glTranslatef(0.0, -1.0, -6.0);
}

int main(int argc, char** argv)
{
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);
    glutInitWindowSize(640, 640);
    glutInitWindowPosition(10, 10);
    glutCreateWindow("Programming Techniques - 3D Spheres");
    myinit();
    glutReshapeFunc(myReshape);
    glutDisplayFunc(display);
    while (!sfera1.colision(sfera2)){
        glutKeyboardFunc(sfera1.handleKeypress);
    }
    glutMainLoop();
    return(0);

}

Thx for help

Iterator for a subset of a vector

Is it possible to get a const iterator from a vector that can only iterate a certain range of the vector before being invalidated?

For example if I have a vector of 10 elements, I want to return an iterator of elements 4 to 7.

pseudo-code:

int main()
{
    std::vector<int> vector = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    auto iterator = GetRangedIterator(vector, 4, 7)
    for (const int& num : iterator)
        print num;      // 4, 5, 6, 7
}

'array' in namespace 'std' does not name a template type

I receive the following error:

'array' in namespace 'std' does not name a template type.

I changed my compiler to g++ 4.9. Still having issues. I think that I may have an old version of the std library but am not sure on how to proceed to fix that.

#ifndef DBINTERFACE_H_
#define DBINTERFACE_H_

#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include "mysql_driver.h"
#include <array>

class DBInterface {
private:
    double Found_Buffer[100][59];
    int Found_Count;
    double New_Buffer[100][59];
    std::array<double, 5> BLAH;

    int New_Count;
    double M[59];
    double B[59];
    sql::mysql::MySQL_Driver *driver;
    sql::Connection *con;

public:
    DBInterface();
    virtual ~DBInterface();
    void Update();
    void Search();
    void Add2DB();
    void Add2Buffer(double Found_Objects[][59], double New_Objects[][59]);
    void Build();

    /*
     * To be added:
     * void CollapseBuffer();
     * void DetDynamic();
     *
     */
};

#endif /* DBINTERFACE_H_ */

Finding vectors in C++

I have two vectors of vector<unsigned> namely: vector<vector<unsigned> > sbp, vector<vector<unsigned> > sp. I want to print all those vectors in sbp which are also in sp. Both vectors sbp and sp are stored (i) first by size; (ii) and when the size are equal, then the vectors are sorted lexicographically. I wrote the following code for doing the same. The code appears to be giving segmentation fault. I debugged the code (by printing out values), but I am not able to find the source of the error.

Can someone please help me find what could be the source of segmentation fault. Also if there is some algorithm which is faster than this, then that will be really great

#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
    vector<vector<unsigned> > sbp;
    vector<vector<unsigned> > sp;
    vector<vector<unsigned> >::iterator itSP=sp.begin();   
    for(vector<vector<unsigned> >::iterator itSbp=sbp.begin(),lSbp=sbp.end();itSbp!=lSbp;)
    {
        if(std::lexicographical_compare(((*itSbp)).begin(), ((*itSbp)).end(), (*itSP).begin(), (*itSP).end()))
        {
            itSbp++;
        }else{
            if((*itSbp)==(*itSP)) 
            {
                cout<<(*itSbp)<<"\n";
                itSbp++;
            }else{
                itSP++;                
            }            
        }
    }
}

I am using C++11(gcc 4.8)

Can std::this_thread::sleep_for() have spurious wakeups?

Note, this is not a question about std::condition_variable::sleep_for(). I know that can wake spuriously.

My program’s behavior suggests the answer to this question is Yes, but the STL documentation is quite clear for the condition_variable case. At least at cppreference.com, the correct answer for this_thread appears to be No.

Compiler is gcc 4.8.1, in case this is a defect.

Sorting vectors in c++

I need to sort the data structure vector<pair<unsigned, pair<vector<unsigned>, vector<unsigned> > > > sbp first by sbp.second.second vector and for equal values of sbp.second.second by sbp.second.first -- both the vectors are compared by (i) size of vectors; (ii) if size of vectors are equal, then vectors are lexicographically sorted. For doing so, I wrote the following code. But I dont know why but this code is getting stuck in an infinite loop. Can someone please help me with as to where am I going wrong.

#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
typedef std::pair<std::vector<unsigned>, std::vector<unsigned> > vec_pair;

bool sortingFunc(const pair<unsigned,vec_pair>& a, const pair<unsigned,vec_pair>& b)
{
    if((a.second).second.size() == (b.second).second.size()) {
        if(std::lexicographical_compare((a.second).second.begin(), (a.second).second.end(), (b.second).second.begin(), (b.second).second.end()))//a<b
        {
            return true;
        }else{
            if((a.second).first.size() == (b.second).first.size()) {
                return std::lexicographical_compare((a.second).first.begin(), (a.second).first.end(), (b.second).first.begin(), (b.second).first.end());
            } else {
                // Sort by size.
                return (a.second).first.size() < (b.second).first.size();
            }            
        }
    } else {
        // Sort by size.
        return (a.second).second.size() < (b.second).second.size();
    }
}

int main()
{
    vector<pair<unsigned, pair<vector<unsigned>, vector<unsigned> > > > sbp;
    std::sort(sbp.begin(), sbp.end(), sortingFunc);
}

I am using C++11 (gcc 4.8.2)

Valgrind detect this as Possible Memory Leak

Below is the extract of Code, in which i am getting some Possible memory loss in Valgrind Report.

681 int pbsc::PBSCAppMain( int argc, char **argv )
682 {
683     char pbscPath[255];
684     std::string configDir = "/../config/";
685     std::string pbscBinPath = getcwd(pbscPath,255);
686     std::string pbscConfigPath = pbscBinPath + configDir;
687
688
689
690     std::string localConfigFile = pbsc::GetFileNameFromDir(pbscConfigPath, PBSC_LOCAL_CONFIG_FILE);
691     if(false == localConfigFile.empty())
692     {
693         std::string localConfigFileWithPath = pbscConfigPath + localConfigFile;
694         ReadLocalConfiguration(localConfigFileWithPath);
695     }
696
697     std::string loggerConfigFile = pbsc::GetFileNameFromDir(pbscConfigPath, PBSC_LOGGER_CONFIG_FILE);
698     if(false == loggerConfigFile.empty())
699     {
700         std::string loggerConfigFileWithPath = pbscConfigPath + loggerConfigFile;
701         log4cxx::PropertyConfigurator::configureAndWatch(loggerConfigFileWithPath, 20000);
702     }
703

Below is the error what i am getting from Valgrind

==4594== 
==4594== 67 bytes in 1 blocks are possibly lost in loss record 754 of 1,141
==4594==    at 0x4A075BC: operator new(unsigned long) (vg_replace_malloc.c:298)
==4594==    by 0x5812CA8: std::string::_Rep::_S_create(unsigned long, unsigned long, std::allocator<char> const&) (new_allocator.h:104)
==4594==    by 0x581387A: std::string::_Rep::_M_clone(std::allocator<char> const&, unsigned long) (basic_string.tcc:629)
==4594==    by 0x5813913: std::string::reserve(unsigned long) (basic_string.tcc:510)
==4594==    by 0x58139B7: std::string::append(std::string const&) (basic_string.tcc:332)
==4594==    by 0x455446: std::basic_string<char, std::char_traits<char>, std::allocator<char> > std::operator+<char, std::char_traits<char>, std::allocator<char> >(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) (basic_string.h:2369)
==4594==    by 0x45ED5F: pbsc::PBSCAppMain(int, char**) (PBSCApp.cpp:686)
==4594==    by 0x45EC9B: main (PBSCApp.cpp:677)
==4594== 

My Question is when control leave this function why still memory is associated to this function? I am calling this function number of times that's why my program size keeps on growing.

Please suggest where exactly i am doing mistake.

Thanks.

Map a range of values to a single value

I need to map values ranging between lowerBound and upperBound to a certain value.

Illustrative Example:

For example, imagine I have GPS system which has users subscribed to it. This system is able to provide me the distance of the user from a certain point. Based on the distance of the user I want to assign them an ID.

Thus users in distance from

  • 1 to 100 get ID: 8.4
  • 101 to 200 get ID: 7.2
  • 201 to 300 get ID: 3.6
  • 401 to 600 get ID: 4.1

and so on...

My approach:

So what I did, I created an std::map by initializing it as follows:

   std::map<int, double> distanceToIdMap; 

   distanceToIdMap =
    {
            {100, 8.4},
            {200, 7.2},
            {300, 3.6},
    };

Then I use this code to get the ID for the given distance:

double roundUpToHundred = std::ceil(realDistance / 100.0) * 100;
double powerForDistance = distanceToIdMap.at(roundUpToHundred);

However my approach breaks down for the 401 to 600 distance, because by ceiling to the nearest hundred for a distance of 400+ I get the value 500 for which I don't have an entry in the map. Of course the trivial solution would be to add an entry for 500 to the distanceToIdMap but that is not how I want to handle this problem.

I would like to have a map with {(lowerbound, upperbound) , correspondingID} structure so I can address cases where an ID covers distance spanning more than 100m. And a given can check if the lowerBound < realDistance < upperBound and then provide the ID.

Multiple destructor calls

I ran the following code..

#include <iostream>
using namespace std;

class Base
{
protected:
    int count=0;
public:
    Base() { cout << "Constructor called" << endl; }
    ~Base() { cout << "Destructor called" << endl; }
    int getCount() {cout << "The count value is " << count << endl;}
    Base operator ++ (int) {count++;  cout << "Postfix increment called" << endl;}
    Base operator ++ () {count++;  cout << "Prefix increment called" << endl;}
};

class Derived : public Base
{
public:
    Base operator --(int)  {count--;  cout << "Postfix decrement called" << endl;}
};

int main()
{
    Derived A;
    A++;
    ++A;
    A--;
    return 0;
}

The result I get is

Constructor called Postfix increment called Destructor called Prefix increment called Destructor called Postfix decrement called Destructor called Destructor called

My question is why the destructor called so many times.

unable to determine the template type even it is passed in

I have the following code:

template <typename T>
struct Data {
   struct Embed
   { 
      T t;
   };
};

struct Functor {
  template <typename T>
  void foo( typename Data<T>::Embed & e) {}
};
template <typename T, typename F>
struct Caller
{
  F f;
  template <typename T>
  void invoke() {
    typename Data<T>::Embed e;
    f.foo<T>(e); //compiler error pointed this line
   }
 };

Then I specialized the template as:

 Caller<int, Functor> c;
 c.invoke();

compiler error is : error: expected primary-expression before '>' in f.foo<T>(e); line. It seems compiler suddenly doesn't know what T is even it is specified in the template declaration on the function.

Take out the explicit specified T in foo.invoke(e) line will result could not deduce template parameter 'T'

How do I fix this? (I still want to keep the functionality that Caller can have generic functor and functor's function can be templated).

Brace-enclosed initializer list must be initialized by constructor

I would like to create a type of MoleculeTypes as follow:

const std::string Molecule::REVENZ = "REVENZ"; //!< Reversible Enzyme
const std::string Molecule::IRRENZ = "IRRENZ"; //!< Irreversible Enzyme
const std::string Molecule::INTMET = "INTMET"; //!< Internal Metabolite
const std::string Molecule::EXTMET = "EXTMET"; //!< External Metabolite
const std::string Molecule::METABOLITE = "METABOLITE"; //!< Metabolite
const std::string Molecule::REACTION = "REACTION"; //!< Reaction
const std::string Molecule::REACTANT = "REACTANT"; //!< Reactant
const std::string Molecule::PRODUCT = "PRODUCT"; //!< Product

std::map<std::string, const int> MoleculeTypes =
{
    {Molecule::REVENZ,1},
    {Molecule::IRRENZ,2},
    {Molecule::INTMET,3},
    {Molecule::EXTMET,4},
    {Molecule::METABOLITE,5},
    {Molecule::REACTION,6},
    {Molecule::PRODUCT,7},
    {Molecule::REACTANT,8}
};

If I compile the program by using Makefile, it works well. But it throws the following error when I build it in Qt Creator. C++11 is enabled too.

  • bio.cpp:26: error: in C++98 'MoleculeTypes' must be initialized by constructor, not by '{...}'
  • bio.cpp:26: error: could not convert '{{Molecule::REVENZ, 1}, {Molecule::IRRENZ, 2}, {Molecule::INTMET, 3}, {Molecule::EXTMET, 4}, {Molecule::METABOLITE, 5}, {Molecule::REACTION, 6}, {Molecule::PRODUCT, 7}, {Molecule::REACTANT, 8}}' from '' to 'std::map, const int>' };

Is std::async guaranteed to be called for functions returning void?

I've wrote the following code to test std::async() on functions returning void with GCC 4.8.2 on Ubuntu.

#include <future>
#include <iostream>

void functionTBC()
{
    std::cerr << "Print here\n";
}

int main(void)
{
#ifdef USE_ASYNC
    auto i = std::async(std::launch::async, functionTBC);
#else
    auto i = std::async(std::launch::deferred, functionTBC);
#endif
    //i.get();
    return 0;
}

If i.get(); is uncommented, the message "Print here" always exists; however, if i.get(); is commented out, "Print here" exists if and only if USE_ASYNC is defined (that is, std::launch::async always leads to message printed out while std::launch::deferred never).

Is this guaranteed behavior? What's the correct way to ensure the asynchronous call returning void to be executed?

This is a continuation of this question c++ function ptr in unorderer_map, compile time error

I was trying to use std::function instead function pointer, and I can insert function only if the functions are static. otherwise I will get following error

main.cpp:15:11: error: no matching member function for call to 'insert'

  map.insert(std::make_pair("one",&Example::procesString));

#include<string>
#include <unordered_map>
#include<functional>

namespace Test
{
 namespace Test
{
  class Example
  {
  public:
    Example()
    {

      map.insert(std::make_pair("one",&Example::procesString));
    }
    static void procesString(std::string & aString)
    //void procesString(std::string & aString) -> compiler error 
    {

    }
    static  void processStringTwo(std::string & aString)
    {

    }

    std::unordered_map<std::string,std::function<void(std::string&)>> map;
  };
}
}

int main()
{
  return 0;
}

Using an element of a constexpr array vs a const array to instantiate a template

While answering a question, I ran into an issue that I couldn't explain.

It seems there is large enough difference between

constexpr size_t IntArray[2] = {1, 2};

and

const size_t IntArray[2] = {1, 2};

that the elements of the first can be used to instantiate a template but not the elements of the second.

Sample program that demonstrates the difference.

#include <cstddef>

template <size_t N> struct Foo {};

// Works fine
void test1()
{
   constexpr size_t IntArray[2] = {1, 2};
   const size_t i = IntArray[0];
   Foo<i> f;
   (void)f; // Remove unused f warning.
}

// Does not work
void test2()
{
   const size_t IntArray[2] = {1, 2};
   const size_t i = IntArray[0];
   Foo<i> f;
   (void)f; // Remove unused f warning.
}

int main()
{
   return 0;
}

I get the following compiler error using g++ 4.9.2.

g++ -std=c++11 -Wall    socc.cc   -o socc

socc.cc: In function ‘void test2()’:
socc.cc:17:8: error: the value of ‘i’ is not usable in a constant expression
    Foo<i> f;
        ^
socc.cc:16:17: note: ‘i’ was not initialized with a constant expression
    const size_t i = IntArray[0];
                 ^
socc.cc:17:9: error: the value of ‘i’ is not usable in a constant expression
    Foo<i> f;
         ^
socc.cc:16:17: note: ‘i’ was not initialized with a constant expression
    const size_t i = IntArray[0];
                 ^
socc.cc:17:9: note: in template argument for type ‘long unsigned int’
    Foo<i> f;
         ^
socc.cc:17:12: error: invalid type in declaration before ‘;’ token
    Foo<i> f;

My question is why does the constexpr array work but not the const array?

C++ map vector of one type to another using lambda

I have a bit of code that looks like

B Convert(const A& a) { 
  B b;
  // implementation omitted.
  return b;
}

vector<B> Convert(const vector<A>& to_convert) {
  vector<B> ret;
  for (const A& a : to_convert) {
    ret.push_back(Convert(a));
  }
  retun ret;
}

I was trying to rewrite this using lambdas but the code does not look more concise or more clear at all:

vector<B> Convert(const vector<A>& to_convert) {
  vector<B> ret;
  std::transform(to_convert.begin(), 
                 to_convert.end(),
                 ret.begin(),
                 [](const A& a) -> B { return Convert(a); });
  retun ret;
}

What I would really like to do is something like:

vector<B> Convert(const vector<A>& to_convert) {
  return map(to_convert, [](const A& a) -> B { return Convert(a); });
}

Where map is a functional style map function that could be implemented as:

template<typename T1, typename T2>
vector<T2> map(const vector<T1>& to_convert, 
               std::function<T2(const T1&)> converter) {
  vector<T2> ret;
  std::transform(to_convert.begin(), 
                 to_convert.end(),
                 ret.begin(),
                 converter);
  retun ret;
}

Obviously the above is limited because it only works with vector, ideally one would want similar functions for all container types. At the end of the day, the above is still not better than my original code.

Why isn't there something like this (that I could find) in the stl?

How do I copy numbers in string separated by space to an array in C [on hold]

If the string is "5 12 99 120 150 119". How can I copy these numbers in an array

Dynamically construct tuple from vector [duplicate]

This question already has an answer here:

I've got an interesting problem where I need to dynamically create a tuple from a vector where the number of type parameters of tuple equals the length of the vector.

vector<int> v1 = {1,2,3};
tuple<int, int, int> t1 = create_tuple(v1);
vector<int> v2 = {1,2};
tuple<int, int> t2 = create_tuple(v2);
vector<int> v3 = {1};
tuple<int> t3 = create_tuple(v3);

I'm guessing this can only be done, if possible, at compile time?

Add unique_ptr as instance field of a class instead of explicitly removing copy / assignment ctors

There are some macros for preventing classes from being copied, eg: Macros to disallow class copy and assignment. Google -vs- Qt

Would I get identical results just by having a unique_ptr in my class? If so, is there a reason not to do this? eg

class Foo {
  private:
    std::unique_ptr<int> DISABLE_COPY;
};

Forbide linking against a c++ method

I try to forbide the use of a method, to have a compile error if some piece of code use it.

This is a proprietary legacy module, that I know that some methods are problematic. We have headers files, and dlls.

I can't figure out all the use of this method in the huge project I use (lot of defines, some implicit cast...)

Can the compiler stop (or just warn) if it detect the use of this method?

vector erase-remove idiom compile error

I have the following removeOneParam(Parameter* param) code which is from this answer:

class A
    {
        private:
          std::vector<Parameter*> params;
        public:
          void removeOneParam(Parameter* param)
          {
            params.erase(std::remove(params.begin(), params.end(), param), params.end());
          }
}

But I get the following compile error:

error: cannot convert ‘std::vector<Parameter*>::iterator {aka __gnu_cxx::__normal_iterator<Parameter**, std::vector<Parameter*> >}’ to ‘const char*’ for argument ‘1’ to ‘int remove(const char*)

How can I use that answer to my case?

Ambigous overload for template ostream << operator C++

This question follows my previous question : Generic operator<< ostream C++ for stringifiable class where I would like to implement a generic <<ostream operator which would work for any class which owns a to_str() method.

I have succeeded checking whether a class implements a to_str() method and use std::cout << stringify(a) thanks to this answer. However, I have difficulties writing template ostream<< operators to make std::cout << a works.

The following test code :

#include <iostream>
#include <sstream>
#include <string>

template<class ...> using void_t = void;

template<typename T, typename = void>
struct has_to_string
: std::false_type { };

template<typename T>
struct has_to_string<T, 
    void_t<decltype(std::declval<T>().to_str())>
    >
: std::true_type { };

template<typename T> std::enable_if_t<has_to_string<T>::value, std::string> 
stringify(T t) { 
    return t.to_str(); 
} 

template<typename T> std::enable_if_t<!has_to_string<T>::value, std::string> 
stringify(T t) { 
    return static_cast<std::ostringstream&>(std::ostringstream() << t).str(); 
} 

// The following does not work
/*
template<typename T> std::enable_if_t<has_to_string<T>::value, std::ostream&> 
operator<<(std::ostream& os, const T& t) {
    os << t.to_str();
    return os;
}

template<typename T> std::enable_if_t<!has_to_string<T>::value, std::ostream&> 
operator<<(std::ostream& os, const T& t) {
    os << t;
    return os;
}
*/

struct A {
    int a;
    std::string to_str() const { return std::to_string(a); }
};

struct B {
    std::string b;
    std::string to_str() const { return b; }
};

int main() {
    A a{3};
    B b{"hello"};
    std::cout << stringify(a) << stringify(b) << std::endl;    // This works but I don't want to use stringify
    // std::cout << a << b << std::endl;               // I want this but it does not work
}

gives the same error as in the original question. What am I doing wrong ?

QtCreator, C++11 and 'unable to find string literal operator'

I am compiling a QTGUI Application with my own makefile. Everything worked nice when I used the C++03 standard.

Now I need the C++11 standard and get the error:

unable to find string literal operator 'operator"" __ FILE__' "

at the following lines in my window.cpp

connect(ui->myGLWidget, SIGNAL(xRotationChanged(int)), ui->rotXSlider, SLOT(setValue(int)));
connect(ui->myGLWidget, SIGNAL(yRotationChanged(int)), ui->rotYSlider, SLOT(setValue(int)));
connect(ui->myGLWidget, SIGNAL(zRotationChanged(int)), ui->rotZSlider, SLOT(setValue(int)));

I tried to compile my .ui file with the UIC version 4 and 5 and nothing changed. The result of the UIC, ui_window.h has the same errors whenever Qbject::connect(.....) is used.

I can't go back to the old C++ standard and both UIC compilers produces the same ui_window.h file.

How can I get rid of it?

Use decltype( *this ) not inside a member

I tried to do:

struct Something {
    decltype( *this ) *something;
};

Which got me 'this' may only be used inside a nonstatic member function, and is nonsense.

I tried more:

auto something -> decltype( *this );
auto something -> this;
typedef decltype( this ) t;
t something;

And failed multiple times. Is there a way to achieve this?

I am forced to do something similar to this: (A lot more of those bad macros)

#define Head() this_type *x; this_type *Get( ) { ... }; void Set( this_type *_x ) { ... };

The sad part is that I mustn't give the Head() the current type as a parameter. It's as if they are trying to make new language out of C++.

Unpack ts... to t0.a(), t0.b(), t1.a(), t1.b(),

I want to call one variadic function from another variadic function in the following manner:

template <typename ...Ts>
void f(Ts const & ...) { /* ... */ }

template <typename ...Args>
void g(Args const & ...args)
{
  // shall call f(arg0.a(), arg0.b(), arg1.a(), arg1.b(), ...)
}

I have done it the following way:

struct sentinel_t { };

template <typename Arg, typename ...Args>
void g_impl(Arg const & arg, Args const & ...args)
{
  g_impl(args..., arg.a(), arg.b());
}

template <typename ...Ts>
void g_impl(sentinel_t , Ts const & ...ts)
{
  f(ts...);
}

template <typename ...Args>
void g(Args const & ...args)
{
  g_impl(args..., sentinel_t{});
}

Is there another/better way to implement this pattern?

how to pass both function pointers and lambda's using one interface

I am trying to use function pointers and lambda's together using one interface. I decided to use std::function, but i quickly found out std::function cannot deal with overloaded functions by itself.

Example:

void foobar(double i_double ){std::cout << "double argument" << i_double << std::endl;}
void foobar(){std::cout << "no argument" << std::endl;}
void foobar(int){std::cout << "int argument" << std::endl;}

std::function<void(double)> func = static_cast<void(*)(double)>(&foobar);

Only by using a static_cast this code compiles.. Since at our company we have quite a lot of overloaded functions this is too much of a hassle. For now i decided to implement two interfaces.. one for std::function objects and another one for function pointers, although i would really like to just wrap the function pointers in a std::function object as well (without additional code on the calling side).

Any "nice" solution to this problem?

Run Time Error in a C++ code

I am getting Run-Time-Error in a C++ code. I am giving my source code. Need Help! Thanks in advance.

Source code:

#include <map>
#include <cstdio>
using namespace std;

class Pair{
    public:
    int x;
    int y;
};

map < Pair , int > mapper;

int main(){
    Pair a;
    a.x = 8;
    a.y = 9;
    mapper[a] = 1; // Here i get Run-Time-Error
    return 0;
}

Using Type Traits from Base Class

I am trying to understand the concept of type traits.

Say i have some templatized Class Hierachy like this and a client function:

template<typename T>
class Base
{
public:
//...
    virtual bool inline isSymmetric() const = 0;
};


template<typename T>
class ChildrenOperation:public Base<T>
{
public:
//...
    virtual bool inline isSymmetric() const override
    {
        return true;
    }
};

void clientFunction(const Base& operation)
{
  //do symmetry independent stuff...
  if(operation.isSymmetric())
  { //use operation the one way 
  } else { //use operation the other way
  }
}

Obviously, clientFunction is polymorphic and different children can have different implementations of isSymmetric. However, since isSymmetric seems to be constant and really more of a type information, i've read about type traits and i was wondering whether it is possible to rewrite the client function to not depend on isSymmetric on runtime, but rather compile time.

I've tried adding a trait like this. But i am not sure how to specialize it and use it in a polymorphic context.

template <typename T>
struct is_symmetric {
  static const bool value = false;
};

How efficient smart pointers are?

I know, that std::shared_ptr uses reference counting, so it has copy&move semantics, on the other hand std::unique_ptr (hence the name unique) only has move semantics, so trying to copy it is a compile error.

However, its not quite clear for me how big of a deal is that. Can I simply use std::shared_ptr over std::unique_ptr in most cases, or should I use std::unique_ptr whenever possible, as it's far more efficient because it doesn't have to take care of reference counting?

Also, I know that smart pointers are useful when dealing with, for example exception safety, but are they a mean to generally replace traditional T* pointers? Is it a good programming practice to use smart pointers over traditional T* pointers whenever possible?

Static array of lambda functions (C++)

I'd like to do something like this (inside a class):

static constexpr MyStruct ops[6] = {
    {'+', [&] (double a, double b) { return a+b; } },
    {'-', [&] (double a, double b) { return a-b; } },
    ...
};

Being MyStruct like:

typedef double (*binOp)(double, double);
struct MyStruct {
    char c;
    binOp fn;
};

I also tried:

std::function <double(double,double)> fn;

for the definition of fn, but no luck.

The error I get for the first case is "error: field initializer is not constant" which I don't really get. If I try with std::function it's worse since it says "cannot be initialized by a non-constant expression when being declared".

Why is the lambda function non-constant? Am I missing something?

Thanks!

shared pointer behavior when container object passed as (void*)

I have shared_ptr variable in my class object (ObjA). There is a requirement where this object is to be stored as (void*) entity of another Class' object (ObjB).

My doubt is, what will be the behavior of shared_ptr (will associated heap memory be freed?, what will happen to its reference count?)-

  1. when ObjA is converted to void*

  2. when void* entity of ObjB is cast back to (ClassA *)

Simplified Code:

Class AA{

    shared_ptr<int> aptr;

    public:
        AA(){
            aptr = make_shared<int>(100);
        }
        shared_ptr<int> get_aptr(){
            return aptr;
        }
};


Class BB{

    void *smpl;

    public:

        void setter(void* p){
            smpl = p;
        }

        void* getter(){
            return smpl;
        }
};

int main(){

    AA *objA = new AA();
    BB *objB = new BB();

    objB->setter(objA);
    //status of allocated int in class AA here?

    //some code later
    AA *objA_2 = (AA*)objB->getter();
    //status of allocated int in class AA here?

    shared_ptr<int> p2 = objA_2->get_aptr();
    //is this allowed

}