jeudi 30 novembre 2017

Initialilze a array of vectors with zero in C++

I want a array of vectors with 0 as a single element in all the individual vectors. Is there a much more efficient way? does this work?

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main(){

        int lastAnswer = 0;
        int n,q;
        cin >> n >> q;
        vector<int> seqArr[n];
        for(int i=0;i<n;i++)
        {
                fill(seqArr[i].begin(),seqArr[i].end(),0);
        }
return 0;
}

'stoi' was not declared in this scope after using -std=c++11

Most probably this is weird, but when I got this error that stoi wasn't declared in this scope, I smiled because I am familiar with this error and it's solution.

I checked this option have g++ follow the c++11 ISO c++ language standard [-std=c++11] in compiler settings of Code Blocks (16.01, with MinGW) and tried recompiling it, but surprisingly it didn't work and the same error persisted. I tried re-installing CodeBlocks but that didn't work.

Also, I tried with windows power shell and command prompt with gcc math_handler.cpp -std=c++11 but got the same error.enter image description here

What am I doing wrong?

Note: I tried with -std=c++0x too.

convert c style function pointer to c++11

#define CHECKED_SK_FREE_FUNC(type, p) \ void (*)(void *))> ((1 ? p : nullptr))

I am facing error when compiled with c++11 error: use of old-style cast [-Wold-style-cast]

when I tried to use c++ casting # define CHECKED_SK_FREE_FUNC(type, p) \ static_cast<(void (*)(void *))> ((1 ? p : nullptr)) error: cannot initialize a parameter of type 'void (*)(void *)' with an rvalue of type 'decltype

Creating a fractal pattern using asterisks

I need to make a fractal pattern using recursion

****
**
*
*
 *
 *
**
  **
  *
  *
   *
   *
  **
****

Here's the pattern

I'm just not sure how to make it recursive in nature. Thanks

if insertion at beginning and deletion at any place. what if best data structure to choose

Example :

I need to write two function acquire and release. acquire return smallest number, release() will return number to pool.

Let’s say at any instance pool has number {1,2,3,4,5,8,9...18,19,20,.....34.35.36.....48....52}

Acquire will return 6 Acquire will return 7

Release(1) will release 1 and if we call acquire again it will return 1.

Bug in the C++ standard library in std::poisson_distribution?

I think I have encountered an incorrect behaviour of std::poisson_distribution from C++ standard library.

Questions:

  1. Could you confirm it is indeed a bug and not my error?
  2. What exactly is wrong in the standard library code of poisson_distribution function, assuming that it is indeed a bug?

Details:

The following C++ code (file poisson_test.cc) is used to generate Poisson-distributed numbers:

#include <array>
#include <cmath>
#include <iostream>
#include <random>

int main() {
  // The problem turned out to be independent on the engine
  std::mt19937_64 engine;

  // Set fixed seed for easy reproducibility
  // The problem turned out to be independent on seed
  engine.seed(1);
  std::poisson_distribution<int> distribution(157.17);

  for (int i = 0; i < 1E8; i++) {
    const int number = distribution(engine);
    std::cout << number << std::endl;
  }
}

I compile this code as follows:

clang++ -o poisson_test -std=c++11 poisson_test.cc
./poisson_test > mypoisson.txt

The following python script was used to analyze the sequence of random numbers from file mypoisson.txt:

import numpy as np
import matplotlib.pyplot as plt

def expectation(x, m):
    " Poisson pdf " 
    # Use Ramanujan formula to get ln n!
    lnx = x * np.log(x) - x + 1./6. * np.log(x * (1 + 4*x*(1+2*x))) + 1./2. * np.log(np.pi)
    return np.exp(x*np.log(m) - m - lnx)

data = np.loadtxt('mypoisson.txt', dtype = 'int')

unique, counts = np.unique(data, return_counts = True)
hist = counts.astype(float) / counts.sum()
stat_err = np.sqrt(counts) / counts.sum()
plt.errorbar(unique, hist, yerr = stat_err, fmt = '.', \
             label = 'Poisson generated \n by std::poisson_distribution')
plt.plot(unique, expectation(unique, expected_mean), \
         label = 'expected probability \n density function')
plt.legend()
plt.show()

# Determine bins with statistical significance of deviation larger than 3 sigma
deviation_in_sigma = (hist - expectation(unique, expected_mean)) / stat_err
d = dict((k, v) for k, v in zip(unique, deviation_in_sigma) if np.abs(v) > 3.0)
print d

The script produces the following plot:

You can see the problem by bare eye. The deviation at n = 158 is statistically significant, it is in fact a 22σ deviation!

You can see the problem by bare eye. The deviation at n = 158 is statistically significant, it is in fact a 22σ deviation!

Close-up of the previous plot.

Close-up of the previous plot.

The base() function of reverse_iterator

From this old question

C++ custom collection reverse_iterator with similar behaviour to std::vector implementation

I thought that the lines (after revising his design a bit)

template <typename Iterator>
class reverse_iterator {
    Iterator _it;
public:
    reverse_iterator(const Iterator& it):_it(it) { }
    Iterator base() const {Iterator it = _it; return --it;}
    typename Iterator::value_type& operator*() const {return *base();}
//  ...
};

were correct (no one replied that they were incorrect). But it doesn't give the same output that this test with std::reverse_iterator gives:

#include <iostream>  
#include <iterator>    
#include <vector>  

int main () {
    std::vector<int> myvector = {1,2,3};
    std::vector<int>::iterator it = std::next(myvector.begin());
    std::reverse_iterator<std::vector<int>::iterator> r(it);
    std::cout << *it << '\n';  // 2
    std::cout << *r << '\n';  // 1
    std::cout << *r.base() << '\n';  // 2
}

which seems to show that the lines should instead be

template <typename Iterator>
class reverse_iterator {
    Iterator _it;
public:
    reverse_iterator(const Iterator& it):_it(it) { }
    Iterator base() const { return _it; }
    typename Iterator::value_type& operator*() const { return *--base(); }
//  ...
};

which would indeed give the same output as with std::reverse_iterator. What is correct here?

How do I kill all threads and cleanly exit my application when the process receives a signal?

I am working on a multi threaded application (probably using pthreads). The application is timing sensitive and in general needs to accomplish as much as possible as quick as possible before the allotted time runs out. The application maintains a master state data structure that retains what work is to be done, and whether or not it passed or failed if the work was attempted. Before the application exits it must print out the state structure to std out.

There is no threading contention to worry about or blocking, each thread is nicely self contained. In a normal run the threads would divvy up the work, accomplish it, synchronize (waiting for the last one to finish) and then return upwards to let the program print out its state to the console. Some threads may print to the console along the way, but generally speaking the state of the program is printed right before the application ends.

A requirement that we have to deliver is to make sure the application runs within n minutes. n is some arbitrary number of minutes supplied by configuration file, and n minutes may not be enough time for the application to complete or even attempt all of its assigned tasks, but regardless the application needs to get as much done as possible, and when the time elapses terminate the execution, printing out the state before it exits.

This application will need to trap signals, specifically alarms and then kill all threads and cleanly exit the application (printing out the state before it exits). A polling architecture is not a viable mechanism for checking if the time has elapsed, the application must respond to the alarm signal for determiniation that the applicaiton should end.

What I would like to do is that when the application is interrupted by SIGALRM, kill all the threads and then print out the accumulated state and exit the program; however from my reading using things like printf are not safe to do inside a signal handler because it can be interrupted. Im thinking of using goto's (dont tell Dijkstra...) and killing the threads, jumping to my output section and then killing the program, but Ive heard that goto's are not a good idea.

Seg Fault on unordered_map.size()

I'm having a lot of trouble with this one- I have a server app that receives a heartbeat from all the other server apps. When a heartbeat is received, the primary server (lets call it cortex) will update an unordered_map with that server.

When I have servers other than the Cortex running, the Cortex will crash almost immediately when I call unordered_map.size(). I have a mutex locking the map prior to this call too, so when it enters this function, the mutex is locked if nothing else is updating it first.

The Key for the map is a custom hash-

unordered_map<AppIdentity, AppResource> appMap; //This is in cortex's header

AppIdentity is a struct:

struct AppIdentity {
    AppType name;
    string ip;
    ushort port;
};

namespace std {
    template <>
    struct hash< AppIdentity > {
        size_t operator( )( const AppIdentity& id ) const {
            return ( hash< string >( )( toString( id.name ) ) ^ hash< string >( )( id.ip ) ) ^ hash< ushort >( )( id.port );
        }
    };
}

(toString simply converts the name to a string version)

And this is where Cortex is crashing:

try {
        lock_guard< mutex > lck( appMapMtx );
        cout << "Checking AppMap Size...\n";
        cout << "AppMap Size: " << appMap.size( ) << endl; //Crashes here
}

Any clue as to what would be causing this? I read it might be related to the hash function since I'm using an object as the key, but this app only crashes when Cortex is launched AFTER the other apps- and it doesn't happen all the time either.

Thanks in advance.

Trying to access a node's data data from inside the class but not in the node struct

I am trying to create a linked list using objects and i am not sure how to access the the data in the nodes. Right now the error that i am getting is that userId,userName, and userTime, all of the data in the nodes, are not declared in the scope. How can i fix this? thank you c++11

class labUsers
{

public:
labUsers() {head = 0;}
// mutators
void setID(int newID) {userID = newID;}
void setTS(int newTS) {userTime = newTS;}
void setName(std::string newName) {userName = newName;}
// accessors
void appendOne( int, int );
void insertOne( int, int, std::string, int, int );
// added these two (above) and the code below
// you need a display, delete, and search too

// old methods here....
int getUserID() {return userID;}
int getUserTS() {return userTime;}
std::string getName() {return userName;}
void create(labUsers*);
void logFileOn(int,int,std::string);
void logFileOff(int,int,std::string);

private:
 struct Node // node of linked lists
 {
    int userID;
    std::string userName;
    int userTime;
    struct Node * next;
 };
 Node *head; //points to the head
 ~labUsers();// destructor
 };

Can the "main" function be declared with the "noexcept" specifier?

Is the following code valid in C++?

int main() noexcept
{
}

Both clang++ 3.8.0 and g++ 7.2.0 compile it fine (with -std=c++14 -O0 -Wall -Wextra -Werror -pedantic-errors compilation flags).

Is it allowed to use complex conditions (e.g. including noexcept operator) in the noexcept specification of the main function?

And what about C++17? As I know noexcept specifier becomes the part of the function type in this revision of the standard.

clang-check does not find

I am trying to run Ale as my linter, which in turn uses clang-check to lint my code.

$ clang-check FeatureManager.h
Error while trying to load a compilation database:
Could not auto-detect compilation database for file "FeatureManager.h"
No compilation database found in /home/babbleshack/ or any parent directory
json-compilation-database: Error while opening JSON database: No such file or directory
Running without flags.
/home/babbleshack/FeatureManager.h:6:10: fatal error: 'unordered_map' file not found
#include <unordered_map>
         ^~~~~~~~~~~~~~~
1 error generated.
Error while processing /home/babbleshack/FeatureManager.h.

Whereas compiling with clang++ returns only a warning.

$ clang++ -std=c++11 -Wall FeatureManager.cxx FeatureManager.h
clang-5.0: warning: treating 'c-header' input as 'c++-header' when in C++ mode, this behavior is deprecated [-Wdeprecated]

There are no flags to clang-check allowing me to set compilation flags.

Extract the substring for a given byte-span from a string in c++

I have a std::string and a byte-span (start_byte, end_byte) From this, how do I extract a substring corresponding to this span? I checked std::string::substr(), but it works only with a character position and length.

error C2679: binary '[': no operator found which takes a right-hand operand

I am trying to run this code for my class project but I keep getting the C2679 error on line 20 of the Hex.cpp file. The full error is binary '[': no operator found which takes a right-hand operand of type 'std::_Vector_iterator>>' (or there is no acceptable conversion). I do get another error on line 154 but I'd like to solve the first error beforehand. If anybody could help me solve this I'd appreciate it.

#include "Hex.h"
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <vector>

using namespace std;

void Hex::HexToBin(string hex) {
    {
        //vector<char> binnum;
        char hexdec[100];
        string h = hex;
        strcpy_s(hexdec, h.c_str());
        vector<char> word(hexdec, hexdec + sizeof hexdec / sizeof hexdec[0]);
        vector<char>::iterator i;
        i = word.begin();
        while (i != word.end())
        {
            switch (word[i]) //error here
            {
            case '0': cout << "0000";
                binum.push_back((0));
                binum.push_back(0);
                binum.push_back(0);
                binum.push_back(0);
                break;
            case '1': cout << "0001";
                binum.push_back(0);
                binum.push_back(0);
                binum.push_back(0);
                binum.push_back(1);
                break;
            case '2': cout << "0010";
                binum.push_back(0);
                binum.push_back(0);
                binum.push_back(1);
                binum.push_back(0);
                break;
            case '3': cout << "0011";
                binum.push_back(0);
                binum.push_back(0);
                binum.push_back(1);
                binum.push_back(1);
                break;
            case '4': cout << "0100";
                binum.push_back(0);
                binum.push_back(1);
                binum.push_back(0);
                binum.push_back(0);
                break;
            case '5': cout << "0101";
                binum.push_back(0);
                binum.push_back(1);
                binum.push_back(0);
                binum.push_back(1);
                break;
            case '6': cout << "0110";
                binum.push_back(0);
                binum.push_back(1);
                binum.push_back(1);
                binum.push_back(0);
                break;
            case '7': cout << "0111";
                binum.push_back(0);
                binum.push_back(1);
                binum.push_back(1);
                binum.push_back(1);
                break;
            case '8': cout << "1000";
                binum.push_back(1);
                binum.push_back(0);
                binum.push_back(0);
                binum.push_back(0);
                break;
            case '9': cout << "1001";
                binum.push_back(1);
                binum.push_back(0);
                binum.push_back(0);
                binum.push_back(1);
                break;
            case 'A': cout << "1010";
                binum.push_back(1);
                binum.push_back(0);
                binum.push_back(1);
                binum.push_back(0);
                break;
            case 'B': cout << "1011";
                binum.push_back(1);
                binum.push_back(0);
                binum.push_back(1);
                binum.push_back(1);
                break;
            case 'C': cout << "1100";
                binum.push_back(1);
                binum.push_back(1);
                binum.push_back(0);
                binum.push_back(0);
                break;
            case 'D': cout << "1101";
                binum.push_back(1);
                binum.push_back(1);
                binum.push_back(0);
                binum.push_back(1);
                break;
            case 'E': cout << "1110";
                binum.push_back(1);
                binum.push_back(1);
                binum.push_back(1);
                binum.push_back(0);
                break;
            case 'F': cout << "1111";
                binum.push_back(1);
                binum.push_back(1);
                binum.push_back(1);
                binum.push_back(1);
                break;
            case 'a': cout << "1010";
                binum.push_back(1);
                binum.push_back(0);
                binum.push_back(1);
                binum.push_back(0);
                break;
            case 'b': cout << "1011";
                binum.push_back(1);
                binum.push_back(0);
                binum.push_back(1);
                binum.push_back(1);
                break;
            case 'c': cout << "1100";
                binum.push_back(1);
                binum.push_back(1);
                binum.push_back(0);
                binum.push_back(0);
                break;
            case 'd': cout << "1101";
                binum.push_back(1);
                binum.push_back(1);
                binum.push_back(0);
                binum.push_back(1);
                break;
            case 'e': cout << "1110";
                binum.push_back(1);
                binum.push_back(1);
                binum.push_back(1);
                binum.push_back(0);
                break;
            case 'f': cout << "1111";
                binum.push_back(1);
                binum.push_back(1);
                binum.push_back(1);
                binum.push_back(1);
                break;
            default: cout << "\nInvalid hexadecimal digit " << hexdec[i]; //error here
            }
            i++;
        }
    }
}

#include <iostream>
#include <string>
#include <vector>
//takes a string and stores, accept a string, convert to binary
/***************************************************************
Class Hex
This class will take a hexidecimal and convert it to a binary
number which will then be stored to be used in other class files.
***************************************************************/
using namespace std;

class Hex {

public:
    void HexToBin(string s);
private:
    vector<char> binum;
    vector<char> word;
    vector<int>::const_iterator i;
};
#include <iostream>
#include "Hex.h"
using namespace std;

int main()
{
    // VARIABLE DECLARATIONS
    Hex hex;
    hex.HexToBin("A24B");
        return 0;
}

What is returned from std::vector::data() when the vector is empty?

Given this example:

// "C" function prototype:
void foo(const int*);

// code:
std::vector<int> v;
foo(v.data());

Is it guaranteed by the standard that v.data() on an empty vector will produce a null pointer? I don't understand this wording:

"The pointer is such that range [data(); data() + size()) is always a
valid range, even if the container is empty (data() is not
dereferenceable in that case)."

I see that on VS2015 it does indeed produce a null pointer, but I was worried some implementations might return a pointer to some internal scratch buffer within vector.

How to implement overloading of assignment operators in C++?

I am trying to use assignment operator overloading to perform deep copy but not able to figure out the right way to do it. I have a Class Computer and need to use it to copy its object to that of class Laptop.

Use of unique_ptr in classes with protected destructors

I am studying policy based design from Modern C++ Design, and I have got stuck in a simple example below, where I was trying to use a std::vector of std::unique_ptrs in my templated policy class:

#include <memory>
#include <vector>

template <class T> struct MyPolicy {
  MyPolicy() = default;
  MyPolicy(std::size_t N) : myvec{std::vector<std::unique_ptr<T>>(N)} {
    for (std::size_t i = 0; i < N; i++)
      myvec[i].reset(new T(i));
  }

  // protected: // or, even, public:
  //   /*virtual*/ ~MyPolicy() = default;

private:
  std::vector<std::unique_ptr<T>> myvec;
};

template <class T, template <class> class Policy>
struct Shell : public Policy<T> {
  Shell() = default;
  Shell(std::size_t N) : Policy<T>(N) {}
};

int main(int argc, char *argv[]) {
  Shell<double, MyPolicy> s;
  s = Shell<double, MyPolicy>(7);

  Shell<double, MyPolicy> s2{6};
  s = std::move(s2);
  return 0;
}

Everything works well above. However, the catch is that since MyPolicy is supposed to be inherited from, its destructor needs to be either virtual and public, or non-virtual and protected (at least, quoting from the book).

In the above example, whenever I uncomment the lines to make them either

public:
virtual ~MyPolicy() = default;

or

protected:
~MyPolicy() = default;

the code does not compile. I cannot understand what the problem related to std::unique_ptr is in this example, since the type T is not incomplete or something that has a protected/private destructor.

I would appreciate your help. Thanks.

Can long-running std::asyncs starve other std::asyncs?

As I understand it, usual implementations of std::async schedule these jobs on threads from a pre-allocated thread pool.

So lets say I first create and schedule enough long-running std::asyncs to keep all threads from that thread pool occupied. Directly afterwards (before long they finished executing) I also create and schedule some short-running std::asyncs. Could it happen that the short-running ones aren't executed at all until at least one of the long-running ones has finished? Or is there some guarantee in the standard (specifically C++11) that prevents this kind of situation (like spawning more threads so that the OS can schedule them in a round-robin fasion)?

Extract day and time from Howard Hinnant's date library

I am using Howard Hinnant's free, open-source, cross-platform, C++11/14 timezone library:

#include "date/tz.h"
#include <iostream>

int
main()
{
    std::cout << date::make_zoned("Europe/Rome", std::chrono::system_clock::now()) << '\n';
}

And I am getting an output like this:

2017-11-29 16:24:32.710766 CET

Is it possible from zoned_time to extract the day (for example: Monday) and the HH:MM in diffent strings? Can the zoned_time be converted to struct tm?

redhawk install in raspberry

I create the core framework above the raspberry pie follow the tutorial http://ift.tt/2BA3MIC. I downloaded the latest img file from Raspberry Pi official for website 2017-09-07-raspbian-stretch.zip, according to the documentation I successfully come to the installation of the core framework step, but when I make the " make -j 2", the following error occurs, Access to a lot of information and can not get rid of it, could you please tell me how to solve this problem?


error: no match for ‘operator<<’ (operand types are ‘std::basic_ostream’ and ‘const std::basic_ifstream’) return ((std::basic_ostream&) os) << val;

error: cannot bind ‘std::basic_ostream’ lvalue to ‘std::basic_ostream&&’

return ((std::basic_ostream&) os) << val;

thank you very much

Initialize with nullptr

When initializing with a pointer a nullptr can be ambiguous if there are multiple constructors accepting a pointer argument.
You can solve this by casting C cast or static_cast, example:

#include <iostream>
#include <cstddef>

using namespace std;

struct A{
    A(int*){ cout << "int constructor" << endl;}
    A(double*) { cout << "double constructor" << endl;}
};

struct B{
    B(std::nullptr_t) { cout << "nullptr constructor" << endl;}
    B(int*){ cout << "int constructor" << endl;}
    B(double*) { cout << "double constructor" << endl;}
};

int main(){
    //A a(nullptr); constructor is ambiguous 
    A a1((int*)nullptr);// int constructor
    A a2(static_cast<double*>(nullptr));// double constructor

    B b(nullptr);// nullptr constructor
    return 0;
}

I included B to illustrate that a constructor with std::nullptr_t exist and is possible but for this question let's focus on A.

From "Why use static_cast(x) instead of (int)x?" I understand the most dangerous thing about C cast being you don't know which will be used:

The main reason is that classic C casts make no distinction between what we call static_cast<>(), reinterpret_cast<>(), const_cast<>(), and dynamic_cast<>(). These four things are completely different.

Are any of these casts unsafe for a nullptr or can you safely use the C-style cast?

How to declare a variable which can be set into a param of type std::chrono::milliseconds

I have the following method which intakes std::chrono::milliseconds

void SomeMethod(std::chrono::milliseconds some_value) {

  // some logic
}

I am able to call it in the following way:

using namespace std::chrono_literals;
SomeMethod(1000ms);

Works.
But, I want to call it in the following way by passing a member variable or some globally declared variable. Something like this,

using namespace std::chrono_literals;
std::chrono::system_clock::duration timeout = 3000ms;

But I get the following error:

error: no viable conversion from 'duration<[...], ratio<[...], 1000000>>' to 'duration<[...], ratio<[...], 1000>>'
SomeMethod(some_value);
                                                                             ^~~~~~~

Is there any reason except forgetfulness/"no time" that the old algorithms in

For example, std::shuffle does accept its random number generator by universal reference.

It would seem like a good idea and non-breaking to change the prototypes of any algorithm accepting a predicate to accept its functor by universal reference, or am I missing something.

I also can't seem to find a proposal suggesting this, nor a defect report about it being forgotten for ... C++11. Does anyone know more about this?

As a small/tiny example that shows a case where using forwarding references over functor by value: http://ift.tt/2BnBVdH.

Smart pointers in C++ unique_ptr and shared_ptr

Why smart pointers(unique_ptr and shared_ptr) work only with user defined objects and not for example Direct3D objects... or any OpenGL objects. Am i doing something wrong or they are designed that way only.

Is it possible to remove dispatch_once in Objective-C++?

Since C++11, local static variables are known to be initialized in a thread safe manner (unless the -fno-threadsafe-statics is given), as specified in this question. Does that mean that the following well-known pattern:

+ (NSObject *)onlyOnce {
  static NSObject *object;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    object = [[NSObject alloc] init];
  });
  return object;
}

Can be replaced with the much shorter:

+ (NSObject *)onlyOnce {
  static NSObject *object = [[NSObject alloc] init];
  return object;
}

When compiling the code as Objective-C++ with C++ language dialect of C++11 and higher?

Using template specializing for hierarchical class construction

Suppose we have a class named DTOBase which contains some declarations, some times i need DTOBase with extra declarations based on given template like this :

class DTOBase {
   /* DTOBase Declarations */
}

template<typename EntityType>
class DTOBase {
     /* DTO Base Declarations */
     /* Extra declarations for EntityType */
}

Now using classes:

DTOBase dto;
/* using with DTOBase members */


DTOBase<SomeEntity> dto;
/* using with DTOBase members and extra templated members */

I create a private base class and then created two version of DTOBase (non templated and templated one), but i think its possible to do it better way, eg. using C++11 template specialization or something like this.

Is it possible to declare a templated class, which inherits members from its non templated version?

mercredi 29 novembre 2017

GMOCK method is throwing compilation error

When I try to implementation GMOCK method like below I get compilation error but the code and the MOCK class works fine when I remove it:

MOCK_METHOD2(myfunc, void (std::shared_ptr<route>, std::unique_ptr<message, std::default_delete<message> >));

I get the below compilation error:

error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = message; _Dp = std::default_delete<message>]'
             MOCK_METHOD2(ship, void (std::shared_ptr<route>, std::unique_ptr<message, std::default_delete<message> >));
             ^
        In file included from C:/tools/mingw64/x86_64-w64-mingw32/include/c++/memory:81:0,
        ......................................................................................
        C:/tools/mingw64/x86_64-w64-mingw32/include/c++/bits/unique_ptr.h:356:7: note: declared here
               unique_ptr(const unique_ptr&) = delete;
    error:   initializing argument 2 of 'R testing::internal::FunctionMocker<R(A1, A2)>::Invoke(A1, A2) [with R = void; A1 = std::shared_ptr<route>; A2 = std::unique_ptr<message>]'
       R Invoke(A1 a1, A2 a2) {
         ^
    In file included from ...

    C:/tools/mingw64/x86_64-w64-mingw32/include/c++/tuple: In instantiation of 'constexpr std::_Head_base<_Idx, _Head, false>::_Head_base(const _Head&) [with long long unsigned int _Idx = 1ull; _Head = std::unique_ptr<message>]':
    C:/tools/mingw64/x86_64-w64-mingw32/include/c++/tuple:255:44:   recursively required from 'constexpr std::_Tuple_impl<_Idx, _Head, _Tail ...>::_Tuple_impl(const _Head&, const _Tail& ...) [with long long unsigned int _Idx = 1ull; _Head = std::unique_ptr<message>; _Tail = {}]'
    C:/tools/mingw64/x86_64-w64-mingw32/include/c++/tuple:255:44:   required from 'constexpr std::_Tuple_impl<_Idx, _Head, _Tail ...>::_Tuple_impl(const _Head&, const _Tail& ...) [with long long unsigned int _Idx = 0ull; _Head = std::shared_ptr<cmb::mim::MimChannel>; _Tail = {std::unique_ptr<message, std::default_delete<message> >}]'
    C:/tools/mingw64/x86_64-w64-mingw32/include/c++/tuple:531:30:   required from 'constexpr std::tuple<_T1, _T2>::tuple(const _T1&, const _T2&) [with _T1 = std::shared_ptr<cmb::mim::MimChannel>; _T2 = std::unique_ptr<message>]'
    C:/work/googletest/googlemock/include/gmock/gmock-generated-function-mockers.h:122:50:   required from 'R testing::internal::FunctionMocker<R(A1, A2)>::Invoke(A1, A2) [with R = void; A1 = std::shared_ptr<cmb::mim::MimChannel>; A2 = std::unique_ptr<message>]'
    C:/work/Mock.hpp:39:5:   required from here
    C:/tools/mingw64/x86_64-w64-mingw32/include/c++/tuple:134:25: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = message; _Dp = std::default_delete<message>]'
           : _M_head_impl(__h) { }

I am not sure what the error is and how to fix it - commenting or removing the MOCK method declaration the compilation goes fine?

Can you parse information in the middle of a std::string using getline()?

Assume that I run this function below:

const std::string Utilities::nextToken(const std::string& record, size_t& 
startposition, bool& more)
{
  std::string token; 
  std::istringstream ss(record);
  std::getline(ss, token, delimiter);

  if (!token.empty())
  {
      startposition += token.size();
      more = true;
  }
  return token;
}

What I'm trying to achieve here is by sending a record "Hithere|yo|man" to this function and then read everything up until it hits a delimiter. In this case, it's a "|", but at the same time, it will keep track of the cursor location. The reason why I'd like to keep track of the cursor location is because when the function gets called again, it'll remember the cursor location and start from then. In this case, it'll read "Hithere" and increase the startposition by 7 as there are 7 characters. The next time this function runs, i'd like it to start from the next delimiter and obtain the next token, which would be "yo" and increase the startposition by another 2.

Can you parse information in the middle of a std::string using getline() and if not, could i have some suggestions on how to tackle this problem?

How to make CMAKE find specific version of lib curl on OSX?

Question is: How do I get CMAKE to set/make the CURL_INCLUDE_DIR be "/usr/local/Cellar/curl/7.75.0/include/"?

No matter what I do, CMAKE only finds the Xcode lib version/location.

My CMAKE file contains:

set(CURL_ROOT_DIR /usr/local/Cellar/curl/7.75.0/include/)
find_package(curl REQUIRED)
message(STATUS ">>> CURL Dir Found: " ${CURL_INCLUDE_DIR})

No matter what I've tried, the above CMAKE code will result in a "CURL_INCLUDE_DIR" of

"/Applications/http://ift.tt/2ngH4C2

Note, utilizing "include(findcurl)" instead of "find_package(curl REQUIRED)" gives same result.

I've resorted to adding

set(CMAKE_CXX_FLAGS "-I/usr/local/Cellar/curl/7.57.0/include -L/usr/local/Cellar/curl/7.57.0/lib")

to get CMAKE to actually utilize the lib version/location that I want. Is there a better way that I'm failing to figure out?

SHOpenFolderAndSelectItems() with arrays

I can successfully use SHOpenFolderandSelectItems() in trivial cases. Code looks similar to this:

ITEMIDLIST *idl = ILCreateFromPath(L"C:\\testing\\example.txt");
SHOpenFolderAndSelectItems(idl, 0, 0, 0);
ILFree(idl);

Now what I'd like to do is open up a folder and select multiple files within it. But I'm confused as to what SHOpenFolderAndSelectItems() is expecting. Simplified, this is what I'm trying:

ITEMIDLIST *folder = ILCreateFromPath(L"C:\\testing\\");
std::vector<ITEMIDLLIST*> v;
v.push_back( ILCreateFromPath(L"C:\\testing\\test1.txt");
v.push_back( ILCreateFromPath(L"C:\\testing\\test2.txt");
v.push_back( ILCreateFromPath(L"C:\\testing\\test3.txt");

SHOpenFolderAndSelectItems(folder, v.size(), v.data(), 0);

for (auto idl : v)
{
    ILFree(idl);
}
ILFree(folder);

This results in:

error C2664: 'HRESULT SHOpenFolderAndSelectItems(LPCITEMIDLIST,UINT,LPCITEMIDLIST *,DWORD)': cannot convert argument 3 from '_ITEMIDLIST **' to 'LPCITEMIDLIST *'

What is a decent way to create the array of items?

Does std::is_constructible work with arguments that are convertible to parameters?

Does std::is_constructible<T, Arg1> work if Arg1 is a type that is convertible to a valid one-parameter constructor for T? It appears to work when the type has a non-templated conversion operator, but does not work (under some compilers) if the conversion operator is templated.

In the below example, the final static_assert fails under GCC 7.2 and clang 5.0, but passes under MSVC 19. Is there undefined behavior in here, or is one of the compilers misbehaving?

#include <type_traits>

struct foo
{
    foo(int) {}
    foo(int, int) {}
};

struct converts
{
    template <class T>
    operator T(){}
};

int main()
{
    // These compile
    foo f1(converts());
    foo f2(converts(), converts());
    static_assert(std::is_constructible<foo, converts, converts>::value, "foo(converts(), converts())");
    // This line doesn't
    static_assert(std::is_constructible<foo, converts>::value, "foo(converts())");
}

Live example: http://ift.tt/2AISDrp

How to store a variable from each time a loop is completed

Mr. Ya Rajaie has N books and wants to put them in bookshelves, each bookshelf can have at most 5 books. Find the minimum number of bookshelves needed to store the N books.

Input The first line of input contains a single integer T, the number of test cases.

Each test case contains a single integer N (1 ≤ N ≤ 10^9), the number of Ya’s books.

Output For each test case, print on a single line the minimum number of bookshelves needed to store the books.

In this problem I need to store a variable each time a loop is completed but I don't know how. her's the input and output examples Input: 2 7 15 output: 2 3

How to cast `std::chrono::milliseconds` to `boost::posix_time::milliseconds`

I am using a boost::asio::deadline_timer like so to set some timeout before an async_read operation on a tcp socket. I am using boost 1.61.

long time_out_millis = 2000;
boost::asio::deadline_timer theTimer(theSocket.get_io_service(), boost::posix_time::milliseconds(time_out_millis));

Problem:
Other parts of my code use std::chrono::milliseconds. I want use std::chrono instead of the "long time_out_millis" & if possible use std::chrono::milliseconds instead of boost::posix_time::milliseconds. How can I do that?

Question:
So, how can I use std::chrono::milliseconds here ? Is there a way I cast from std::chrono::milliseconds to boost::posix_time::milliseconds ?

Using specialization to test the existence of a value within a class

Lets say I have the following class:

struct Color
{
   enum {
      blue,
      red,
      unknown
   };
};

I would like to test in compile time if the class Color has the unknown value.

I thought the following could work but it is currently returning an incorrect result.

#include <iostream>

template <typename T, typename U = T>
struct test
{
  static constexpr bool value = false;
};

template <typename T>
struct test<T, decltype(T::unknown)>
{
  static constexpr bool value = true;
};

int main()
{
  std::cout << test<Color>::value << std::endl; //prints 0
}

Could you provide some insight on how I can accomplish the check? Or what is wrong with my example?

Thanks

Deciding between random_device and seed_seq to generate seeds for multiple random number sequences

When writing code that requires multiple independent random number distributions/sequences (example below with two), it seems that there are two typical ways to implement (pseudo-)random number generation. One is simply using a random_device object to generate two random seeds for the two independent engines:

std::random_device rd;
std::default_random_engine en(rd());
std::default_random_engine en2(rd());
std::uniform_real_distribution<> ureald{min,max};
std::uniform_int_distribution<> uintd{min,max};

The other involves using the random_device object to create a seed_seq object using multiple "sources" of randomness:

std::random_device rd;
std::seed_seq seedseq{rd(), rd(), rd()}; // is there an optimal number of rd() to use?
std::vector<uint32_t> seeds(5);
seedseq.generate(seeds.begin(), seeds.end());
std::default_random_engine en3(seeds[0]);
std::default_random_engine en4(seeds[1]);
std::uniform_real_distribution<> ureald{min,max};
std::uniform_int_distribution<> uintd{min,max};

Out of these two, is there a preferred method? Why? If it is the latter, is there an optimal number of random_device "sources" to use in generating the seed_seq object?

Are there better approaches to random number generation than either of these two implementations I've outlined above?

Thank you!

Operations over list of ints with template metaprogramming [C++11]

I have implementation of list of ints with template:

template<int ... Int>
struct IntList;

template<int H, int ... T>
struct IntList<H, T...>{
    static const int Head = H;
    using Tail = IntList<T...>;
};
template<>
struct IntList<>{};

I want to define metafunctions to work with IntList: IntCons that allows to increase list by one element, and Generate that allows to generate a list of length N with ints from 0 to N-1 (Example of usage: using L = Generate<5>::type; // IntList<0,1,2,3,4>). I define IntCons this way:

template<int H, typename IL>
struct IntCons;

template<int H, int... Tail>
struct IntCons<H, IntList<Tail...>>{
    using type = IntList<H, Tail...>;
};

And i can't define metafunction Generate in such way that use function IntCons inside. Here's hint, according to i need use default parameter in Generate.

template<int N /*, typename IL =  default parameter?*/ >
struct Generate;

template<int N /*, typename IL =  default parameter?*/ >
struct Generate<N>{
    using type = ......;
};

What are the ways to define the meta-function Generate, how can i implement it?

Create distinct type for class with specific member variable value

Given a class that have some enum that defines a type of the class, like in following example:

class Fruit {
 public:

   enum class FruitType {
      AppleType = 0,
      OrangeType = 1,
      BananaType = 2,
   };
   Fruit(FruitType type) : type_(type) {}
   FruitType fruit_type() const { return type_; }

 private:
   FruitType type_;
};

Would it be possible to somehow define a distinct type for Fruit with each of the specific enum values:

class Apple   // Fruit with FruitType = AppleType
class Orange  // Fruit with FruitType = OrangeType
class Banana  // Fruit with FruitType = BananaType

so that 3 classes Apple, Orange and Banana are distinct types.

My question is somewhat similar to How to define different types for the same class in C++, except that I want to explicitly store information about class type as enum member variable in the class, and to have a common base class for all distinct types.

What would be the most efficient way to do that?

Where does the memory allocation happens for an underlying object of a static shared_ptr?

I have come across a class called Runtime in GENIVI/capicxx-core-runtime. Part of the code specified below.

class Runtime {
 public:
     COMMONAPI_EXPORT static std::shared_ptr<Runtime> get();
     COMMONAPI_EXPORT Runtime();
     COMMONAPI_EXPORT virtual ~Runtime()

 private:
     static std::shared_ptr<Runtime> theRuntime__;
};

std::shared_ptr<Runtime> Runtime::theRuntime__ = std::make_shared<Runtime>();

std::shared_ptr<Runtime> Runtime::get() {
   return theRuntime__;
}

My doubt is with the theRuntime__ variable. Since shared_ptr does heap allocation, will the underlying object of theRuntime__ variable is allocated on heap in this scenario or is it allocated on BSS/DATA segment?

C++11: Store pointer to templated class member function

I am trying to implement a generic templated observer pattern in C++11. The target is to provide a mechanism for any class member function to be registered as a callback to the observer. The observer template is as following:

template <typename... Args>
class tsubject {
public:

   /// @brief Register a member function of any class as callback to the subject.
   template <typename AnyObserver>
   void register( AnyObserver* observer, void(AnyObserver::*func)(Args... ) ) {
       register( [=]( Args... args ) {
           ( observer->*func )( args... );
       });
   }

   /// @brief Register an std::function as callback to the subject.
   void register( std::function<void(Args...)> const & func ) {
       mCallbacks.push_back( func );
   }

   /// @brief Notify all registered observers
   void update( Args... p ) {
       for( auto it : mCallbacks ) {
           it( p... );
       }
   }

private:
    std::vector<std::function<void(Args...)> mCallbacks;
};

Usage:

class MyObserverClass {
public:
    void callback( std::string arg1, int arg2 ) {
       std::count << "callback:" << arg1 << ":" << arg2 << std::endl;
    }
}

int main( ) {
    tsubject<std::string, int> subject;

    MyObserverClass observer;
    subject.register( &observer, &MyObserverClass::callback );

    subject.update( "test", 1 );
}

Output:

callback: test:1

Issue:

int main( ) {
    tsubject<std::string, int> subject;

    MyObserverClass observer;
    subject.register( &observer, &MyObserverClass::callback );
    subject.register( &observer, &MyObserverClass::callback );

    subject.update( "test", 1 );
}

Output:

callback: test:1
callback: test:1

The issue with this implementation is that if the same observer method is registered multiple times, the callback is triggered multiple times. Since C++11 pointer to member functions are not normal pointers, they cannot be type-casted to void* for later comparison and since this is a variadic template functions, an std::map cannot be used for mCallback since the type cannot be specified. Is there any mechanism possible to avoid multiple registration elagantly?

how to find files faster in linux in a big project which contains thousands of directories and files

how to find files faster in linux in a big project which contains thousands of directories and files? Is there any utility or tool or program to find that?

check whether a string is palindrome - trying to do it in a specific method - C++

Can help me to write palindrome-checking program which should cut a string in half, and check whether the first half is equal to the last half(reversed of course) ? I have tried it out, and so far it works only for code with even number of letters.

#include <iostream>
#include <string> 

using namespace std;

int main()
{

string line;

getline(cin,line);
int i = 0;
string firstHalf;
cout << line.length() << endl;
while(i < (line.length()/2)){
    firstHalf += line[i];
    i++;
}
i = line.length();
string secondHalf;
while(i < (line.length()/2)){
    secondHalf[i];
    i--;
}

cout << firstHalf << endl; cout << secondHalf;

    return 0;
}

Singleton class with smart pointers and destructor being called

I want to create a singleton class such that when all pointers to the class go away the destructor is called.

#include <memory>
#include <iostream>

class MyClass {
public:
    uint8_t str[50]; //some random data
    MyClass() {LOG("constructor Called"); }
    ~MyClass() {LOG("destructor Called");}
    static std::shared_ptr<MyClass> &Get();

private:
     static std::shared_ptr<MyClass> instance;

};

std::shared_ptr<MyClass> MyClass::instance=NULL;


std::shared_ptr<MyClass> &MyClass::Get()
{
    if (instance == NULL)
    {
        instance= std::shared_ptr<MyClass>(new MyClass());
        return instance;
     }
     return instance;
}

int main()
{

    std::shared_ptr<MyClass> &p1 =MyClass::Get();

     printf("We have %" PRIu32, p1.use_count());
     if (1)
     {
        std::shared_ptr<MyClass> &p2 =MyClass::Get();//this should not  
                                                 //  create a new class
        printf("We have %" PRIu32, p1.use_count());  //this should be two...
        printf("We have %" PRIu32, p2.use_count());  //this should be two...
        //when p1 goes out of scope here it should not call destructor
      }
      printf("We have %" PRIu32, p1.use_count());

     //now destructor should be called
      return 0;
}

The above code does not work and I was wondering if anyone had a suggestion?

C++ insert a value in a set of values from a class in a Map

I have a map in my class Cjt_Trets that contains a string called rasgo and a class called Trets. In Trets I have a set<int> id; that will contain the id's of the people containing that rasgo. My problem comes when I try to insert the id that the function receives, into that set. How am I supposed to do it?

Here I leave part of the code that can help you understand better my situation:

Private of the class Cjt_Trets

private:
  map<string, Trets> mtrets;  
};

Private of Trets

private:
  set<int> id;
  string gen;  
};

Actual part of the code I don't know how to do:

void Cjt_Trets::afegir_tret(int id, string rasgo){    
  mtrets.insert( make_pair<string, Trets> (rasgo, Trets.id.insert(id)) );
}

Thanks a lot

when using =std=C++98 to complie, #include

when I use -std=c++98 to compile, the error occur

In file included from c:\mingw\lib\gcc\mingw32\5.3.0\include\c++\bits\locale_facets.h:39:0,
                 from c:\mingw\lib\gcc\mingw32\5.3.0\include\c++\bits\basic_ios.h:37,
                 from c:\mingw\lib\gcc\mingw32\5.3.0\include\c++\ios:44,
                 from c:\mingw\lib\gcc\mingw32\5.3.0\include\c++\ostream:38,
                 from c:\mingw\lib\gcc\mingw32\5.3.0\include\c++\iostream:39,
                 from 2299.cpp:4:
c:\mingw\lib\gcc\mingw32\5.3.0\include\c++\cwctype:89:11: error: '::iswblank' has not been declared
   using ::iswblank;

my g++ version is g++(GCC) 5.3.0. I want to know why......

May a destructor be final?

Does the C++ standard allow a destructor to be declared as final? Like this:

 class Derived: public Base
 {
      ...
      virtual ~Derived() final;
 }

And if so, does that prevent the declaration of a derived class:

 class FurtherDerived: public Derived {// allowed?
 }

If it is allowed, is a compiler likely to issue a warning? Is declaring a destructor to be final a workable idiom for indicating that a class is not intended to be used as a base class?

Declaring a structure pointer as a return type for a function

The following code gives an error-"DECLARATION SYNTAX ERROR" Here node is a structure(for a linked list) [Forgive me if this is a stupid question ,as I am new to programming] [click here to view image->]1

Converting from wstring to Multibyte for Japanese string

I was trying to use wcstombs_s to convert my Japanese wstring into multibyte char but am getting empty string . Here's what i was doing my first approach using wcstombs_s -

wstring str = "ス";
char * outputString;
size_t outputSize = str.length() + 1; // +1 for null terminator
outputString = new char[outputSize];
size_t charsConverted = 0;
const wchar_t * inputW = str.c_str();
wcstombs_s(&charsConverted, outputString, outputSize, inputW, str.length());

i receive empty string in inputW,

I also tried using builtin api WideCharToMultiByte here also am not getting the expected output. Here's what i am doing could anyone tell me where am doing the mistake -

char *nstringw = new char[256]; 
size_t status = WideCharToMultiByte( 932U, 0, str.c_str(), static_cast<int>(str.length() + 1), nstringw, 256, nullptr, nullptr);

i receive the same number of characters in nstringw but junk value. I am just reading the text field value and want to convert it.

SAL Annotations: _Ret_maybenull_ for std::shared_ptr

Is it possible to annotate my smart pointer-returning function with SAL?

_Ret_maybenull_ std::shared_ptr<MyClass> getMyObject();

Gives me the warning

warning C6504: Invalid annotation: 'Null' property may only be used on values of pointer, pointer-to-member, array, or reference type: Function 'getMyObject' return. Actual type 'class std::shared_ptr'.

and not a single warning when writing this:

auto a = getMyObject();
a->foo();

Custom iterator function for c++

I have a collection of object of type "T" that i want to iterate through. An object of type "T" has two important properties:

int r; // row number int c; // column number

I would like to define an iterator that allows me to iterate through all elements of the collection.

This can be done using:

std::vector v;

for(std::vector::iterator it = v.begin(); it != v.end(); ++it) { .... }

However, I would like the iterator to have one more property. I would like to be able to call

it.nextrow()

calling this function should return the element "e" of v where e.r + 1 = ec.r and e.c = ec.c, where ec is the current element pointed by the iterator. I.e. calling it.nextrow() should give me a pointer to the element where column is the same, but row is incremented by one. Hope it makes sense.

I am not sure what I need to do in order for this to work, as I am fairly new advanced c++ concepts. Can anybody help me?

Thread in C++11 not in class member

I'm recently using C++11 threads and I have a question about something (strange for me) happened. I created a method inside a class, able to start thread. The starting thread method and the callback function of the thread are class methods. To clarify, in my Person.cpp file I have:

void Person::callbackForThread(){
    ...
}


void Person::startThread(){
    this call threads. Something like:
    thread(callbackForThread);
}

The problem is that C++11 doesn't allow me to declare these two function as class methods. This means that if I declare them as normal function, i.e:

 void callbackForThread(){
    ...
}


void startThread(){
    this call threads. Something like:
    thread(callbackForThread);
}

Everythings works. I would know how could I declare thread and callback inside a class in C++, if it is possible. For the farther, I have omitted the inclusion of the libraries and the name of the real class. The class shown in this question is fictitious.

g++ compile options with -std=c++14 compile error showing Werror=c++11-compat

my environment Arch Linux, gcc 7.2

I'm learning C++ and I'm using keyword constexpr to define a constant, while compile, it give me an error message error: identifier ‘constexpr’ is a keyword in C++11 [-Werror=c++11-compat]

I can compile my program with default g++, but cannot compile with -std=c++14 and -Werror

I believe the -Werror option caused the issue. but what is the issue? can someone tell me please?

#include<iostream>

int main(){
    constexpr double yen_dollar = 0.107;
    std::cout<<yen_dollar<<std::endl;
    return 0;
}


test.cpp:4:5: error: identifier ‘constexpr’ is a keyword in C++11 [-Werror=c++11-compat]
     constexpr double yen_dollar = 0.107;
     ^~~~~~~~~
4.4.1trythis.cpp: In function ‘int main()’:
4.4.1trythis.cpp:4:5: error: ‘constexpr’ was not declared in this scope
4.4.1trythis.cpp:5:16: error: ‘yen_dollar’ was not declared in this scope
     std::cout<<yen_dollar<<std::endl;

Use boost or std to get the current local time in a specific timezone

Is it possible to use Boost libraries or std to get the current time in a specific timezone without knowing the offset but only the TZ?

For example: What is the current local time in "Europe/Rome"?

mardi 28 novembre 2017

Internal compiler error at runtime CLion

I am getting a weird error when running my program inside CLion. I checked my code and couldn't find any open braces or semicolon missing or hanging. I have 1 class (.cpp and .h) and a main.cpp. It's a really small program but I can't figure out what's wrong. The error I get is as follow

internal compiler error: in finish_expr_stmt, at cp/semantics.c:677 xword::xword(map words) {

This application has requested the Runtime to terminate it in an unusual way.

Please contact the application's support team for more information. C:\Users\marti\CLionProjects\crossword\xword.cpp:8:37: internal compiler error: Aborted

This application has requested the Runtime to terminate it in an unusual way.

Please contact the application's support team for more information. g++.exe: internal compiler error: Aborted (program cc1plus)

Please submit a full bug report, with preprocessed source if appropriate.

xword.cpp

#include <iostream>
#include <sstream>
#include "xword.h"
//Constructor que acepta las palabras con su orientacion en un mapa como parametro y basicamente
//crea e inicializa la matriz
//ademas llena los espacios vacios con letras al azar

xword::xword(map<string, char> words) {
    //Inicializamos la matr9z
    grid = new char*[SIZE];
    for(int x = 0;x < SIZE;x++){
        grid[x] = new char[SIZE];
    }

    //Se valida las palabras y su orientacion
    //en caso sean validas se añaden a la lista
    //sino son descartadas
    for(pair<string, char> w : words){
        if(validate_word(w.first, w.second)){
            add_word(w.first, w.second);
        }
    }

    srand(NULL);

}
bool xword::validate_word(string word, char pos) {
    //Validacion de longitud
    if(word.length() > 10)
        return false;
    //Validacion de que no este repetida
    for(const auto iter : words_i){
        if(iter.first.compare(word) == 0)
            return false;
    }

    //Validacion de espacion para la orientacion deseada
    for(int x = 0;x < SIZE;x++){
        for(int y = 0;y < SIZE;y++){
            char tmp  = grid[x][y];
            if(tmp != 0){
                break;
            }
            if(!has_space(word.size(), pos, x, y))
                return false;
        }
    }

    //TODO verificar caracteres validos


    return true;
}
//Imprime la matriz
void xword::prnt_grid() {
    for(int x = 0;x < SIZE;x++){
        for(int y = 0;y < SIZE;y++){
            cout << grid[x][y] << " ";
        }
        cout << endl;
    }
}
//Añadir una palabra al mapa miembro
bool xword::add_word(string word, char pos){
    if(validate_word(word, pos)){
        words_i[word] = pos;
        int x1, y1, x2, y2;
        get_espacio_libre(word.size(), pos, x1, y1, x2, y2);

        for(int x = x1, count = 0;x <= x2;x++){
            for(int y = y1;y < y2;y++){
                grid[x][y] = word[count];
                count++;
            }
        }
        return true;
    }
    return false;
}

//Verifica si ya se han acabado las palabras para encontrar
bool xword::ganado(){
    vector<string> keys;
    for(pair<string, char>& par : words_i){
        keys.push_back(par.first);
    }
    return keys.size() == p_encontradas.size();
}

//Añade una palabra a la lista de encontradas
void xword::encontrar_palabra(string palabra) {
    p_encontradas.push_back(palabra);

}
//Itera sobre todas las palabras encontradas y retorna true si la encuentra
bool xword::is_p_encontrada(string palabra) {
    for (string p : p_encontradas){
        if(p == palabra)
            return true;
    }
    return false;
}

//Busca letras entre las coordenadas propuestas y retorna en forma de palabra
string xword::palabra_at(int x1, int y1, int x2, int y2){
    stringstream ss;
    for(;x1 < x2;x1++){
        for(;y1 < y2;y1++){
            ss << grid[x1][y1];
        }
    }
    return ss.str();
}

//Verificacion de que la matriz tenga espacio en la orientacion
//dadas las posiciones x e y
bool xword::has_space(char word_size, char orientation, char xpos, char ypos) {
    if(orientation == 'V')
    {
        for(int x = xpos;x < word_size;x++){
            char tmp = grid[x][ypos];
            if(tmp != 0)
                return false;
        }
    }
    else if(orientation == 'H')
    {
        for(int y = ypos;y < word_size;y++){
            char tmp = grid[xpos][y];
            if(tmp != 0)
                return false;
        }
    }
    return true;
}

//Consigue el primer espacion libre para una palabra de len word_size y orientacion definida
void xword::get_espacio_libre(char word_size, char orientation, int& x1, int& y1, int& x2, int& y2){
    for(char x = 0;x < SIZE;x++){
        for(char y = 0;y < SIZE;y++){
            if(grid[x][y] == 0 && has_space(word_size, orientation, x, y))
            {
                if(orientation == 'V'){
                    x1 = x;
                    y1 = y;
                    x2 * x+word_size;
                    y2 = y;
                    return;
                }
                else{
                    x1 = x;
                    y1 = y;

                    x2 = x;
                    y2 = y+word_size;
                    return;
                }
            }
        }
    }
}

xword.h

#include <string>
#include <vector>
#include <map>

//Tamaña predefinido de matriz eg. 10x10
#define SIZE 10

#ifndef CROSSWORD_XWORD_H
#define CROSSWORD_XWORD_H


using namespace std;

class xword {
private:

    //Mapa de las palabras y orientaciones
    map<string, char> words_i;

    //Palabras encontradas
    vector<string> p_encontradas;

    //Matriz
    char** grid = nullptr;

    //Caracteres permitidos
    char ls[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    //Validar palabra y orienta
    bool validate_word(string word, char pos);

    //Validar espacion en matriz
    bool has_space(char word_size, char orientation, char xpos, char ypos);

    //Retornar coordenadas de espacio libre en los numeros que se le pasan
    void get_espacio_libre(char word_size, char orientation,  int& x1, int& y1, int& x2, int& y2);

public:
    //Retorna true si ya se gano el juego
    bool ganado();
    //Añade a palabras encontradas
    void encontrar_palabra(string palabra);
    //Retorna true si la palabra ya se ha encontrado
    bool is_p_encontrada(string palabra);
    //Retorna la palabra entre 2 coordenadas
    string palabra_at(int x1, int x2, int y1, int y2);
    //Imprime matriz
    void prnt_grid();
    //Añade palabra al mapa
    bool add_word(string word, char pos);
    //Constructor que deberia ser usado
    xword(map<string, char> words);

};


#endif //CROSSWORD_XWORD_H

main.cpp

#include <iostream>
#include <assert.h>
#include "xword.h"

#define VERTICAL 'V'
#define HORIZONTAL 'H'

using namespace std;

xword* xw;
map<string, char> lista_palabras =
        {
                make_pair("cuadro", VERTICAL),
                make_pair("mesa", HORIZONTAL),
                make_pair("palabra", VERTICAL),
                make_pair("raton", HORIZONTAL),
                make_pair("poste", VERTICAL),
                make_pair("comida", HORIZONTAL),
                make_pair("letrero", VERTICAL),
                make_pair("usar", HORIZONTAL),
                make_pair("dos", VERTICAL),
                make_pair("quince", HORIZONTAL)
        };

void ingresar_palabras(){
    map<string, char> words;
    string inpt;
    cout << "Ingresa la palabra seguida de un espacio y una letra indicando la orientacion deseada " << endl;
    cout << "o un 0(cero) para que sea al azar eg( palabra (V, vertical, v, VERTICAL) )" << endl;
    //Mientras se siga alimentando palabras y orientaciones el programa sigue corriendo
    while(getline(cin, inpt)){
        if(inpt.empty())
            break;
        string name;
        char orient;

        string tmp = inpt.substr(inpt.find(" "));
        name = inpt.substr(0, inpt.find(" "));
        //Asignamos la orientacion basado en lo que se encuentra despues de la palabra inicial al macro VERTICAL o HORIZONTAL
        orient = (tmp.compare("v") || tmp.compare("V") || tmp.compare("vertical") || tmp.compare("VERTICAL")) ? VERTICAL :
                 (tmp.compare("h") || tmp.compare("H") || tmp.compare("horizontal") || tmp.compare("HORIZONTAL")) ? HORIZONTAL :
                 HORIZONTAL;

        words[name] = orient;
    }
    lista_palabras = words;
}
bool in_lista(string palabra){
    for(pair<string, char> pal : lista_palabras){
        if(pal.first == palabra) {
            return true;
        }
    }
    return false;
}
bool main_loop(){
    bool inicia = true;
    while(inicia){
        xw->prnt_grid();
        int x1, y1, x2, y2;
        cout << "Elige una posicion x y";
        cin >> x1, y1;
        cout << "Elige otra posicion x y";
        cin >> x2, y2;
        string palabra = xw->palabra_at(x1, y1, x2, y2);
        if(in_lista(palabra) ){
            cout << "Encontraste una palabra!";
            xw->encontrar_palabra(palabra);
            if(xw->ganado()) {
                cout << "Ganaste el juego!";
                break;
            }
            continue;
        }
        cout << "Esa palabra no es valida, sigue intentando";

    }
}

int main() {
    //Eliges usar la lista que ua hay de palabras o ingresar una nueva lista
    int opt;
    cout << "Desea ingresar palabras (0) o usar la lista predetermina de palabras (1): ";
    cin >> opt;

    //Se asegura de que sea opcion 1 o 2 sino muestra un error
    assert(opt == 1 | opt == 0);

    if (opt == 0) {
        ingresar_palabras();
    }

    xw = new xword(lista_palabras);
    main_loop();

    return 0;
}

C++ SFINAE and numeric conversions (coercion)

I try to learn SFINAE right now, but it seems I have a problem with coercion, how can I do to make hasRead<Y> and hasRead<Z> fail since the method argument doesn't correspond to an uint_16 ?

I joined my code to see what can be done to make it work like I want !

Thanks in advance :)

#include <cstdint>
#include <iostream>
#include <utility>

template<typename Class>
struct hasRead {
private:
    template<typename T>
    static constexpr auto check(T *) -> typename std::is_same<
        decltype(std::declval<T().read(std::declval<uint16_t>())), uint8_t>::type;


    template<typename>
    static constexpr std::false_type check(...);

    typedef decltype(check<Class>(0)) type;

public:
    static constexpr bool value = type::value;
};

struct X {
    uint8_t read(uint16_t x) { return 3; }
};

struct Y {
    uint8_t read(uint8_t x) { return 3; }
};

struct Z {
    uint8_t read(int64_t x) { return 3; }
};

static_assert(hasRead<X>, "");
static_assert(hasRead<Y>, "");
static_assert(hasRead<Z>, "");

User-defined literal string: compile-time length check

I have a user-defined literal operator that only makes sense for strings of a specific length, like this:

constexpr uint16_t operator "" _int(const char* s, std::size_t len)
{
    return len == 2 ? s[0] | (s[1] << 8) : throw;
}

This works:

"AB"_int // equals 16961

But this also compiles, and I don't want it to:

"ABC"_int // throws at runtime

I tried static_assert(len == 2), but it isn't allowed in a constexpr function.

How can I make "ABC"_int cause an error at compile time?

syntax error at the end of input (classes)

#include <iomanip>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <string>
using namespace std;

struct FIELDS
{
    string name;
    string value;
};

const int cnt =3;

void parse(string, FIELDS []);
string param(string, FIELDS[], int);

class WebApps {
public:
void parse (string qs, FIELDS f_name_value_pairs[])
{
    cout << "debug in parse<br>\n" << endl;
    string name, value;
    int start_pos = 0, pos;
    for (int counter=0; counter < cnt; counter++) {
            pos = qs.find("=", start_pos);
            name = qs.substr(start_pos, pos - start_pos);
            cout << "name: " << name << "<br>" << endl;
            start_pos = pos + 1;
            pos = qs.find("&", start_pos);
            if (pos == string::npos) {
                    pos = qs.length();
            }
            value = qs.substr(start_pos, pos - start_pos);
            cout << "value: " << value << "<br>" << endl;
            start_pos = pos + 1;
            f_name_value_pairs[counter].name=name;
            f_name_value_pairs[counter].value=value;
    }

    }

string param(string lookUp, FIELDS f_name_value_pairs[], int f_cnt)
{
 string found="";
for(int i=0;i<f_cnt;i++)
{
if(lookUp==f_name_value_pairs[i].name)
{
found=f_name_value_pairs[i].value;
return found;

}
}
};
int main()
{
WebApps wo;
FIELDS name_value_pairs[cnt];

string qs(getenv("QUERY_STRING")); 
            //string qs("first=fred&last=flint&color=red");
    cout << "Content-type:text/html\n\n";
    cout << "debug with qs: " << qs << "<p>" << endl;
 wo.parse(qs, name_value_pairs);
 // debug to show content of name_value_pairs
    cout << "debug to show content of name_value_pairs array: " << endl 
  << "<br>";
    for (int index = 0; index<cnt; index++) {
    cout << "name: " << name_value_pairs[index].name << endl << "<br>";
    cout << "value: " << name_value_pairs[index].value << endl << "<br>";
}


    // Three fields data are retrieved from the param function
    string firstname = wo.param("firstname", name_value_pairs, cnt);
    string lastname = wo.param("lastname", name_value_pairs, cnt);
    string season = wo.param("season", name_value_pairs, cnt);

    // code an HTML page, which includes the three fields
    // received.

    cout << "<html><head><title>Four Seasons</title></head>";
    cout << "<body><center>";
    cout<<"Hey, "<<firstname<<" your favourite season is ";
    cout<<season<<"<br>";

    if(season=="winter"){
    cout << "<img src=\"http://ift.tt/2AGT8CA\">";
    cout <<" <br> You are as cute as Olaf from Frozen! :]";
    else if(season=="spring"){
    cout << "<img src=\"http://ift.tt/2Ag6hl7?\">";
    cout <<" <br> You are a very very sweet person! Everybody blooms around your presence :]";
      }
    else if(season == "summer"){
    cout << "<img src=\"http://ift.tt/2AGxUEM\">";
    cout <<" <br> You have a hot personality that everybody loves :]";
     }
      else{
    cout << "<img src=\"http://ift.tt/2AcOM58\">";
    cout << "<br> Great things are coming for you! Just sitback and relax :]";
     }
    cout << "</center></body>";
    cout << "</html>";

return 0;
}

Above is my code for an class assignments. It is to turn the parse() and param() functions into classes. I cant find any mistakes in my code but it seems to say "syntax error at the end of the input" on the last line of code

Duplicate retrieve_form.cpp as retrieve_form_OOP.cpp, along with it counterpart html file as web_form_OOP.html.

1.Create a class named WebApps

2.This class will contain (under public:) two functions (methods), parse and param. Use the existing function - no change necessary.

3.Leave the class definition above 'main', as demonstrated in the first video.

4.Create an object from the WebApps class and name it 'wo' (for web object).

help :]

Covering legacy C style functions using C++ template

I have the following two functions in C.

float floatAdd(float a, float b)
{
    return a+b;
}

double doubleAdd(double a, double b)
{
    return a+b;
}

Now, I would like to combine both functions and write a tempalte function in C++ as follows.

template<class T>
T add(T a, T b)
{
    // if T=float, return floatAdd(a,b)
    // if T=double, return doubleAdd(a,b)

}

Since the return types are different, I am unable to find a solution!

Install OpenCV Ubuntu 16.04 c++11

I try to install OpenCV 3.3.0 on Ubuntu 16.04. So I write:

cmake -DCMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D INSTALL_PYTHON_EXAMPLES=ON \
-D INSTALL_C_EXAMPLES=OFF \
-D ENABLE_CXX11=ON \
-D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib-3.3.0/modules \
-D PYTHON_EXECUTABLE=~/.virtualenvs/cv/bin/python \
-D BUILD_EXAMPLES=ON ..

But Configuring incomplete, errors occurred! My CMakeError.log:

Compilation failed:
    source file: '/home/natalya/opencv-3.3.0/cmake/checks/cxx11.cpp'
    check option: ''
===== BUILD LOG =====
Change Dir: /home/natalya/opencv-3.3.0/build/CMakeFiles/CMakeTmp

Run Build Command:"/usr/bin/make" "cmTC_038ae/fast"
/usr/bin/make -f CMakeFiles/cmTC_038ae.dir/build.make CMakeFiles/cmTC_038ae.dir/build
make[1]: Entering directory '/home/natalya/opencv-3.3.0/build/CMakeFiles/CMakeTmp'
Building CXX object CMakeFiles/cmTC_038ae.dir/cxx11.cpp.o
/usr/bin/c++      -o CMakeFiles/cmTC_038ae.dir/cxx11.cpp.o -c /home/natalya/opencv-3.3.0/cmake/checks/cxx11.cpp
/home/natalya/opencv-3.3.0/cmake/checks/cxx11.cpp:4:2: error: #error "C++11 is not supported"
 #error "C++11 is not supported"
  ^
/home/natalya/opencv-3.3.0/cmake/checks/cxx11.cpp: In function ‘int main()’:
/home/natalya/opencv-3.3.0/cmake/checks/cxx11.cpp:11:10: error: ‘res’ does not name a type
     auto res = test();
          ^
/home/natalya/opencv-3.3.0/cmake/checks/cxx11.cpp:12:12: error: ‘res’ was not declared in this scope
     return res;
            ^
CMakeFiles/cmTC_038ae.dir/build.make:65: recipe for target 'CMakeFiles/cmTC_038ae.dir/cxx11.cpp.o' failed
make[1]: *** [CMakeFiles/cmTC_038ae.dir/cxx11.cpp.o] Error 1
make[1]: Leaving directory '/home/natalya/opencv-3.3.0/build/CMakeFiles/CMakeTmp'
Makefile:126: recipe for target 'cmTC_038ae/fast' failed
make: *** [cmTC_038ae/fast] Error 2

===== END =====

I read many adviсes, but it isn't helps me.
Help me please.

Sort a vector of vectors in parallel using a conditional variable?

I am trying to sort a NxN vector of vectors in parallel by dispatching N threads for each vector. I want to display the vector of vectors every time each vector within the vector of vectors has been sorted. Please see example below.

Initially

2,1,3,4
1,3,2,4
3,4,1,2
3,2,1,4

Sorting . . Display

1,2,3,4
1,2,3,4
1,4,3,2
2,3,1,4

. . Sorting . .

1,2,3,4
1,2,3,4
1,3,4,2
2,1,3,4

... and so on..

I have some executable code to do this sequentuially and I have tried to do this using a conditional variable but I can't get it to work with the conditional variable at all.

Below is the sequential code which is working in terms of sorting the vector of vectors but it can't produce the display that I desire.

#include<iostream>
#include<vector>
#include <ctime> 
#include <random>


std::vector<int> row;
std::vector<std::vector<int>> block;
int cols = 10;
auto rng = std::default_random_engine{};


void init()
{

        srand((unsigned)time(0));
        for (int i = 0; i < 10; i++)
        {
            int j;
            j = (rand() % 100) + 1;
            row.push_back(j);
    }

            for (int i = 0; i < 10; i++)
            {

                std::vector<int> y;
                std::shuffle(std::begin(row), std::end(row), rng);
                y = row;
                block.push_back(y);
            }

    for (int i = 0; i < cols; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            std::cout << block[i][j] << ", "; 

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

void Sort(std::vector<int> &Row)
{

        for (int i = 0; i < cols; i++)
        {
            for (int j = 0; j < i; j++)
            {
                if (Row[i] < Row[j])
                {
                    int temp = Row[i];
                    Row[i] = Row[j];
                    Row[j ] = temp;
                }
            }
        }

}

void display()
{
    for (int i = 0; i < cols; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            std::cout << block[i][j] << ", ";

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


int main() {

    std::cout << "test\n";
    init();
    std::cout << "\n";
    std::cout << "Sorting";
    std::cout << "\n";
    for(int i =0; i < cols; i++)    
        Sort(block[i]);
    std::cout << "\n";
    display();
    std::cout << "Sorted";
    getchar();
}

The output for the above code is as follows

98, 15, 13, 10, 44, 63, 85, 93, 39, 43,
93, 10, 15, 13, 43, 44, 39, 63, 85, 98,
93, 13, 63, 15, 43, 85, 98, 39, 44, 10,
44, 98, 39, 85, 13, 10, 63, 43, 93, 15,
10, 98, 63, 93, 85, 44, 39, 15, 13, 43,
63, 39, 44, 98, 93, 15, 43, 85, 13, 10,
43, 63, 93, 44, 15, 39, 10, 85, 98, 13,
39, 85, 13, 63, 44, 98, 93, 43, 10, 15,
39, 44, 85, 63, 43, 93, 98, 10, 15, 13,
15, 43, 44, 93, 85, 39, 63, 10, 98, 13,

Sorting

10, 13, 15, 39, 43, 44, 63, 85, 93, 98,
10, 13, 15, 39, 43, 44, 63, 85, 93, 98,
10, 13, 15, 39, 43, 44, 63, 85, 93, 98,
10, 13, 15, 39, 43, 44, 63, 85, 93, 98,
10, 13, 15, 39, 43, 44, 63, 85, 93, 98,
10, 13, 15, 39, 43, 44, 63, 85, 93, 98,
10, 13, 15, 39, 43, 44, 63, 85, 93, 98,
10, 13, 15, 39, 43, 44, 63, 85, 93, 98,
10, 13, 15, 39, 43, 44, 63, 85, 93, 98,
10, 13, 15, 39, 43, 44, 63, 85, 93, 98,
Sorted

The multi-threaded approach that I have taken below is not working as expected. I have tried a number of things but to no success.

#include<iostream>
#include <thread>
#include<vector>
#include <ctime> 
#include <mutex>
#include<chrono>
#include <algorithm>
#include <random>
#include <deque>

std::deque<int> q;
std::mutex mu;
std::condition_variable cond;
int count = 4;
std::vector<int> x{ 5,2,1,3,4 };
std::vector<std::vector<int>> xx;
void init() {
    for (int i = 0; i < 5; i++)
    {
        xx.push_back(x);
    }
}

void display()
{
    for (int i = 0; i < xx.size(); i++)
    {
        for (int j = 0; j < xx[i].size(); j++)
        {
            std::cout << xx[i][j] << " ,";
        }
        std::cout << "\n";
    }

}

bool isSorted(int z)
{
    for (int i = 0; i < 5; i++)
    {
        if (xx[z][i] > xx[z][i + 1])
            return false;
    }
    return true;
}

void function_1(int &row)
{

    while (!isSorted(row))
    {
        std::unique_lock<std::mutex> locker(mu);
        for (int i = 0; i < 4; i++)
        {
            if (xx[row][i] > xx[row][i + 1])
            {
                int temp = xx[row][i];
                xx[row][i] = xx[row][i + 1];
                xx[row][i + 1] = temp;
            }
        }
        count--;
        locker.unlock();
        cond.notify_one();
        std::this_thread::sleep_for(std::chrono::seconds(2));

    }
}

void function_2() {
    int data = 0;
    while (data != 1)
    {
        std::unique_lock<std::mutex> locker(mu);
        cond.wait(locker, []() {return (count == 0); });
        q.clear();
        display();
        count = 4;
        locker.unlock();

    }
}

int main()
{
    init();
    for (int i = 0; i < 4; i++) {
        std::thread *t1 = new std::thread(function_1, std::ref(i));
    }
    std::thread t2(function_2);
    //  t2.join();
    std::cout << " all threads done";
    getchar();
}

Recursive function in program causing a stack overflow

My recursive function seems to be causing a stack overflow in my program. I do not know exactly where the error is because everything seems to be fine and initialized. I do not know where in my program I am going wrong. My question is that where is this error coming from and how do I fix it? Please if someone could help me out.

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

template <typename TK, typename TD>
class Node      // done
{
public:
Node()
{
    ptrLeft = nullptr;
    ptrRight = nullptr;
}

~Node()
{
    if (ptrLeft != nullptr) { delete ptrLeft; }
    if (ptrRight != nullptr) { delete ptrRight; }
}

Node<TK, TD>* ptrLeft;

Node<TK, TD>* ptrRight;

//! The data stored by the node
TD data;

//! The key of this node
TK key;
};

template <typename TK, typename TD>
class BinarySearchTree
{
public:
BinarySearchTree()  // done
{
    m_ptrRoot = nullptr;
    m_nodeCount = 0;
}

~BinarySearchTree()     // done
{
    if (m_ptrRoot != nullptr) { delete m_ptrRoot; }
}

void Insert(const TK& newKey, const TD& newData)
{
    if (m_ptrRoot == nullptr)
    {
        m_ptrRoot = new Node<TK, TD>;
        m_ptrRoot->key = newKey;
        m_ptrRoot->data = newData;
        m_nodeCount++;
    }
    else
    {
        RecursiveInsert(newKey, newData, m_ptrRoot);
    }

}

string GetInOrder()     // done
{
    stringstream stream;
    GetInOrder(m_ptrRoot, stream);
    return stream.str();
}

string GetPreOrder()     // done
{
    stringstream stream;
    GetPreOrder(m_ptrRoot, stream);
    return stream.str();
}

string GetPostOrder()     // done
{
    stringstream stream;
    GetPostOrder(m_ptrRoot, stream);
    return stream.str();
}

private:

void RecursiveInsert(const TK& newKey, const TD& newData, Node<TK, TD>* ptrCurrent)
{
    if (ptrCurrent == nullptr)
    {
        ptrCurrent = new Node<TK, TD>;
        ptrCurrent->key = newKey;
        ptrCurrent->data = newData;
        m_nodeCount++;
    }
    if (newKey < ptrCurrent->key)
    {
        if (ptrCurrent->ptrLeft == nullptr)
        {
            ptrCurrent->ptrLeft = new Node<TK, TD>;
            ptrCurrent->ptrLeft->key = newKey;
            ptrCurrent->ptrLeft->data = newData;
            m_nodeCount++;
        }
        else
        {
            RecursiveInsert(newKey, newData, ptrCurrent->ptrLeft);
        }
    }
    else if (newKey > ptrCurrent->key)
    {
        if (ptrCurrent->ptrRight == nullptr)
        {
            ptrCurrent->ptrRight = new Node<TK, TD>;
            ptrCurrent->ptrRight->key = newKey;
            ptrCurrent->ptrRight->data = newData;
            m_nodeCount++;
        }
        else
        {
            RecursiveInsert(newKey, newData, ptrCurrent->ptrRight);
        }
    }
}


void GetInOrder(Node<TK, TD>* ptrCurrent, stringstream& stream)
{
    if (ptrCurrent != nullptr)
    {
        GetInOrder(ptrCurrent->ptrLeft, stream);
        stream << ptrCurrent->key << " ";
        GetInOrder(ptrCurrent->ptrRight, stream);
    }
}

void GetPreOrder(Node<TK, TD>* ptrCurrent, stringstream& stream)
{
    if (ptrCurrent != nullptr)
    {
        stream << ptrCurrent->key << " ";
        GetPreOrder(ptrCurrent->ptrLeft, stream);
        GetPreOrder(ptrCurrent->ptrRight, stream);
    }
}

void GetPostOrder(Node<TK, TD>* ptrCurrent, stringstream& stream)
{
    if (ptrCurrent != nullptr)
    {
        GetPostOrder(ptrCurrent->ptrLeft, stream);
        GetPostOrder(ptrCurrent->ptrRight, stream);
        stream << ptrCurrent->key << " ";
    }
}


private:
Node<TK, TD>* m_ptrRoot;

int m_nodeCount;

friend class Tester;
};

#endif

Trailing return type for reference

Consider the following code.

#include <iostream>

class A
{

public:
using T = float;
     A(const T& x)
    {
        m_value = x;
    }

    T& value();

private:
    T m_value;

};

// A::T& A::value() 
//  {
//      return m_value;
//  } 

    auto& A::value()->T &
    {
        return m_value;
    }


int main()
{
    A a(10.0);
    std::cout<<a.value()<<std::endl;


    return 0;
}

When compile using C++11, I get the following error.

error: ‘value’ function with trailing return type has ‘auto&’ as its type rather than plain ‘auto’
   auto& A::value()->T &
                       ^

The equivalent code (the commented function) is working fine. But I would like to use trailing return type.

C++ Advantage of Proxy Classes

Scott Meyers says in "Effective Modern C++" that the expression

Matrix sum = m1 + m2 + m3 + m4

(where all objects have type 'Matrix') "can be computed much more efficiently if operator+ for Matrix objects returns a proxy for the result instead of the result itself. That is, operator+ for two Matrix objects would return an object of a proxy class such as Sum instead of a Matrix object.".

Now, I understand that proxy classes emulate behaviour of some other classes and do implicit converisons, but how and why is proxy approach in this case more efficient?

Best regards

Explicit constructors and nested initializer lists

The following code successfully compiles with most modern C++11 compatible compilers (GCC >= 5.x, Clang, ICC, MSVC).

#include <string>

struct A
{
        explicit A(const char *) {}
        A(std::string) {}
};

struct B
{
        B(A) {}
        B(B &) = delete;
};

int main( void )
{
        B b1(});
}

But why does it compile in the first place, and how are the listed compilers interpreting that code?

Why is MSVC able to compile this without B(B &) = delete;, but the other 3 compilers all need it?

And why does it fail in all compilers except MSVC when I delete a different signature of the copy constructor, e.g. B(const B &) = delete;?

Are the compilers even all choosing the same constructors?

Why does Clang emit the following warning?

17 : <source>:17:16: warning: braces around scalar initializer [-Wbraced-scalar-init]
        B b1(});

Compare std::function created with std::bind

Here is a toy example

#include <iostream>
#include <functional>

struct Obj
{
  int x;

  int foo()
  {
    return 42;
  }
};

int main()
{
  Obj a, b;
  std::function<int()> f1 = std::bind(&Obj::foo, &a);
  std::function<int()> f2 = std::bind(&Obj::foo, &b);
  std::function<int()> f3 = std::bind(&Obj::foo, &a);
  std::function<int()> f4 = std::bind(&Obj::foo, &b);
}

How can I verify that f1 == f3 and f2 == f4, where the == comparator, here, means that both std::function objects correspond to the same method of the same object?

Pugi XML: How to set the precision for float numbers

I use pugi::XML parser and i want to set the precision for the floating point numbers. I have already used the rounding function on the float variable, but while printing with pugi::xml, it is printed with 6 decimal digits.

I use below statement to print value in C++11 :

subNode.append_child(pugi::node_pcdata).set_value(to_string(doubleVal).c_str());

Example:

<value>97.802000</value>

must be printed as

<value>97.802</value>

How can i do that ?

rsyslog writing to synchronous file does not block

I am on ubuntu 16.04 with rsyslog version 7.4.4. I am writing some tests for an C++ syslog wrapper. In the wrapper I just call syslog(3).

There is only one rule in the config file.

user.*    /var/log/user.log

I turned filter duplicate messages off and I can see all the messages in the log files.

During the test I noticed that the syslog call is not blocking.

TEST(BlockingTest, block)
{
  ifstream file;
  long oriPos=0;
  long newPos=0;

  int offset = strlen("Nov 28 13:07:01 4dac2c62ebe7 logTest: blockinglogger: blocking call")+1;

  file.open("/var/log/user.log");
  if(file.is_open())
  {
    file.seekg(0,ios::end);
    oriPos = file.tellg();
  }
  file.close();

  Syslogging::Logger logger("blockinglogger",Syslogging::Level::DEBUG);
  logger.debug("blocking call");

  // This needs to be here else undefined behavior.
  this_thread::sleep_for(chrono::milliseconds(2));

  file.open("/var/log/user.log");
  if(file.is_open())
  {
    file.seekg(0,ios::end);
    newPos = file.tellg();
  }
  file.close();

  EXPECT_EQ(newPos, oriPos+offset);
}

I thought that using the above config it would block for each syslog call till it was written to the file. But I need a small timeout or I get undefined behavior (sometimes it passes, sometimes it fails).

Do I need another setting or anybody that can explain this behavior more clearly pls?

usage of this pointer in std::bind

I was trying to read and understand std::bind when I stumbled on below answer:

Usage of std::bind

I see one statement like below:

auto callback = std::bind(&MyClass::afterCompleteCallback, this, std::placeholders::_1);

I am unable to understand what is the usage of 'this' pointer and when one should make use of it? 'this' pointer means the current object address itself so it would something mean that 'use this object' - if so how can I use the same statement outside the class still having the same meaning?

Vector creating which contains type*

Class has a definitions in private area

private:
    vector <int *> moves;
    int counter = 0;

and some function in class

void ConnectFourPlusUndo::backupMoves(int i,int j)
{
    cout << "getcounter" << getCounter() << endl;

    moves[getCounter()] = new int[2];
    /*Error occurs here*/

    int tempArr[2]; 

    setCounter(getCounter()+1);

    tempArr[0] = i;
    tempArr[1] = j;

    moves.push_back(tempArr);

    return;
}   

Guys how can i solve this error? Any idea?

SFML Vertical Sync is not supported

I trying to implement a wator simulation were sharks eat fishes, I want to randomly spawn sharks, the program compiles but i get "Setting Vertical Sync not supported" .

working on Ubuntu 16.04. Before i was working on something else and i got the same error but the window was displayed this is not. Any help?

#include <SFML/Graphics.hpp>

int n;
int x;
int y;
int main()
{

 sf::RenderWindow window(sf::VideoMode(800, 800), "SFML works!");

    window.setFramerateLimit(30);

    srand(time(0));

    sf::Texture shark;
    shark.loadFromFile("image.png");
    std::vector<sf::Sprite> Fishes(n,sf::Sprite(shark));
    for (int i = 0; i < Fishes.size(); i++){
        Fishes[n].setOrigin(15, 15);
        Fishes[n].getPosition();
        Fishes[n].setPosition(x = rand() % 790 + 10, y = rand() % -10 - 50);
    }

    // run the program as long as the window is open
    while (window.isOpen())
    {
        // check all the window's events that were triggered since the last iteration of the loop
      sf::Event event;
        while (window.pollEvent(event))
        {
            // "close requested" event: we close the window
      if (event.type == sf::Event::Closed){
                window.close();
            }

        Fishes[n].setPosition(x, y+=1);
            Fishes[n].rotate(1);

            // clear the window with black color
            window.clear(sf::Color::Black);

            // draw everything here...
            // window.draw(...);
            window.draw(Fishes[n]);

            // end the current frame
            window.display();
        }

        return 0;
    }
}

lundi 27 novembre 2017

Poly output error - linked list

My current output is giving me an error and I do not understand why. If someone could guide me as to why it does it would be greatly appreciated. I am able to add two polynomials together but when I get the output I get a segmentation fault after removing a space from the output operator. I do not know why this is. I am also using codeblocks if that helps.

main.cpp

#include <iostream>
#include "poly.h"
using namespace std;
int main ()
{

int x1[] = {1 , 0 , 3 , 4 , 5};
int x2[] = {3 , 2};

polynomial p1(x1 , 4);
polynomial p2(x2 , 1);
polynomial p3(5);
polynomial p4;
polynomial result;

result = 6;


cout << " p1 = " << p1 << endl ;
cout << " p2 = " << p2 << endl ;
cout << " p3 = " << p3 << endl ;
cout << " p4 = " << p4 << endl ;
cout << " result = " << result << endl << endl ;

result = p1 + p2 ;
cout << " p1 + p2 = " << result << endl ;

poly.h

#include <iostream>
using namespace std;

class polynomial
{

    struct node
    {
        int coefficient ;
        node * link ;
    };

public:
polynomial();
polynomial(const polynomial&);
polynomial(int* ,int);
polynomial(int);
~polynomial();


polynomial operator+(const polynomial&) const;
polynomial operator+(int) const;
const polynomial& operator=(const polynomial &);
const polynomial& operator=(int);

friend ostream& operator<<(ostream& outfile , const polynomial&);
friend polynomial operator+(int ,const polynomial&);

private:
node* head;
int degree;
};

poly.cpp

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

polynomial::polynomial()
{
    head = new node;
    head->coefficient = 0;
    head->link = NULL;
    degree = -1;
};

polynomial::polynomial(const polynomial& copy)
{
    if(this != &copy)
    {
        delete[] head;
        head = copy.head;
    }
};

polynomial::polynomial(int * p, int degree)
{
    this->degree = degree;
    head = new node;
    head->coefficient = p[0];
    head->link = NULL;

    for(int x=1;x<degree;x++)
    {
        node* temp;
        temp = new node;
        temp->coefficient = p[x];
        temp->link = head;
        head = temp;
    }

    node* temp;
    temp = new node;
    temp->coefficient = p[degree];
    temp->link = head;
    head = temp;
};

polynomial::polynomial(int s)
{
    degree = 0;
    head = new node;
    head->coefficient = s;
    head->link = NULL;
};

polynomial::~polynomial()
{
    node* temp = head;
    node* current = head;
    while(current != NULL)
    {
        current = current->link;
        delete temp;
        temp = current;
        if (current == NULL || current == NULL)
            break;
    }
};

polynomial polynomial::operator+(const polynomial& rhs) const
{
    polynomial hold;
    polynomial tempLhs;
    polynomial tempRhs = rhs;

    tempLhs.degree = degree;
    tempRhs.degree = rhs.degree;
    hold.degree;
    int tempDegree;

    tempLhs.head = new node;
    tempRhs.head = new node;
    hold.head = new node;

    for(int x=0;x<tempDegree+1;x++)
    {
        node* temp;
        temp = new node;
        temp->coefficient = 0;
        temp->link = hold.head;
        hold.head = temp;
    }

    tempLhs.head = head;
    tempRhs.head = rhs.head;

    if(tempLhs.degree < tempRhs.degree)
    {
        tempDegree = tempLhs.degree;
        hold.degree = tempDegree;
        for(int x = (tempDegree-tempLhs.degree-1);x<tempDegree+1;x++)
        {
            node* temp;
            temp = new node;
            temp->coefficient = 0;
            temp->link = tempLhs.head;
            tempLhs.head = temp;
        }

    }
    else if(tempLhs.degree > tempRhs.degree)
    {
        tempDegree = tempLhs.degree;
        hold.degree = tempDegree;
        for(int x = (tempDegree-tempRhs.degree-1);x<tempDegree+1;x++)
        {
            node* temp;
            temp = new node;
            temp->coefficient = 0;
            temp->link = tempRhs.head;
            tempRhs.head = temp;
        }
    }
    else
    {
        tempDegree = tempRhs.degree = tempLhs.degree;
        hold.degree = tempDegree;
    }


    node* lhsCurrent = tempLhs.head;
    node* rhsCurrent = tempRhs.head;
    int tempArr[tempDegree];

    while(lhsCurrent != NULL && rhsCurrent != NULL)
    {
        for(int x=tempDegree;x>-1;x--)
        {
            tempArr[x]= lhsCurrent->coefficient + rhsCurrent->coefficient;
            lhsCurrent = lhsCurrent->link;
            rhsCurrent = rhsCurrent->link;
        }
    }

    polynomial use(tempArr, tempDegree);
    return use;
};

polynomial polynomial::operator+(int rhs) const
{
    polynomial temp = *this;

    return rhs+temp;
};

const polynomial& polynomial::operator=(const polynomial& rhs)
{
    cout << "doing = operator" << endl;
    degree = rhs.degree;

    if(this != &rhs)
    {
        delete[] head;
        head = rhs.head;
    }

    return *this;
};

const polynomial& polynomial::operator=(int rhs)
{
    degree = 0;
    head = new node;
    head->coefficient = rhs;
    head->link = NULL;
};

ostream& operator<<(ostream& out, const polynomial& rhs)
{
    out << "operator ";

    polynomial::node* temp = new polynomial::node;
    temp = rhs.head;

    while(temp != NULL)
    {
        out << temp->coefficient << " ";
        temp = temp->link;
        if(temp == NULL)
            break;
    }
    out << " ";
};

The output should be this

p1 = 5 x ^4 + x ^2 + 5 x + 4
p2 = 3 x + 2
p3 = 5
p4 = 0
result = 6
p1 + p2 = 5 x ^4 + x ^2 + 8 x + 6

I am getting this result but I just have to format it so that the degrees are represented correctly but my addition it coming out correctly I just need to adjust the output operator which is not the issue.

Whenever I run the program without

out << " ";

which is the second to last line of poly.cpp I get an error.

It says I have segmentation fault after line 215 which happens to be the last line of poly.cpp when the out<< is deleted from the code.