vendredi 31 janvier 2020

Custom iterator range function invalid output

I want to implement range function to traverse container

template<class IterT>
struct iteratorRange {
    IterT begin_;
    IterT end_;

    IterT begin() {
        return begin_;
    }

    IterT end() {
        return end_;
    }
};

template<class T>
iteratorRange<typename vector<T>::iterator>Head(vector<T> v, size_t step) {
    return {begin(v), next(begin(v), min(step, v.size()))};
}

int main() {
   vector<int> v {1, 2, 3, 4, 5, 6, 7};
   for (int& i : Head(v, 4)) {
       cout << i  << ' '; 
   }
}

I expected

1 2 3 4

But received

1103219 1109239 3 4

What is the error?

Can't move a smart ptr into a std::function

I want to create an std::function that captures a auto_ptr/unique_ptr into but can't properly do it. I need a solution that works on c++11 but I couldn't even figure out how to do it on c++14

Following examples work with c++11 (IncByTwenty) abd c++14 (IncByThirty). However When I change those auto s to Func, it no longer compiles.

typedef std::function<int( int )> Func;
Func IncByTen = std::bind( []( const int& p, int t ) -> int
{
    return p + t;  
}, 10, std::placeholders::_1 );

std::auto_ptr< int > pTwenty(new int(20));
// should have work in c++11 i think? cant assign to Func type
auto IncByTwenty = std::bind( []( const std::auto_ptr< int >& p, int t ) -> int
{
    return ( *p ) + t;  
}, std::move( pTwenty ), std::placeholders::_1 );

std::unique_ptr< int > pThirty = std::make_unique< int >( 30 );
// c++14  cant assign to Func type
auto IncByThirty  = [p{std::move(pThirty) }]( int t ) -> int
{
    return ( *p ) + t;  
};

std::cout << IncByTen(3) << " "  << IncByTwenty(4) << " " << IncByThirty(5);

Am I doing it wrong? Otherwise I need to create something that is assignable to std::function and it needs to capture some local variables using move operator. Any suggestions?

Set columns values to NULL at run time using postgres API for C++(pqxx)

I am using C++11 and Postgres(10.4). I have a scenario where I'm creating a dynamic query using pqxx library which will be executed at run time.

The issue is that the dynamic query(an insert statement) i'm creating is having approxmiately 160 columns. I want to set some columns values to 'NULL' based on the input data. These columns are not fixed, for e.g.
"INSERT INTO players VALUES ($1, $2)";

In the above query at run time either of $1 or $2 or both can have null values.

Now with the prepared function of worker class, I'm not sure how to set column name to NULL. For e.g. "prepared("testfunction")(name)(score).exec();" In the above example either of name or score can be "NULL" based on input data.

NOTE :- I know how to set NULL value for a particular column statically as below : "prepared("testfunction")(name)().exec();" As done above, if I know that score is to be NULL, I can do it like above. But, in my issue any column can have null value.

Please advice how this can be achieved.

Thanks!

Why these code still use the lvalue function? [duplicate]

I'm currently studying C++ lvalue and rvalue these days. I got a little confuse in below code.

class Test {
public:
    Test(){}
    explicit Test(int _i): i(_i) {}

    void doSomething()& {
        cout << "L value ref" << endl;
    }

    void doSomething()&& {
        cout << "R value ref" << endl;
    }
private:
    int i;
};
void callDoSomething(Test& t) {
    t.doSomething();
}
void callDoSomething(Test&& t) {
    t.doSomething();
}

int main() {
    auto a = Test();
    callDoSomething(a);
    callDoSomething(Test());
    return 0;
}

In above code, I will get this result:

L value ref
L value ref

I have check above code via debugger and pretty sure that in this code snippet: callDoSomething(Test()); It will go to the rvalue reference one which is callDoSomething(Test&& t). But why did it still call the lvalue member function?

I also tried template and still got same result.

template <typename T>
void callDoSomething(T &&t) {
    t.doSomething();
}

I have already read this post and knows that in template version. The T &&t is actually a universal reference. But after check via debugger. The type of t is still Test&& and we can get Test&& &&t. By reference collapsing's definition, we should still get Test&& t.

Can anyone explain why this happen? Thanks a lot!

Run-time indexing of tuple

Suppose I have a variable constructors, which is a tuple of constructor functions represented in variadic generic lambdas.

// types for constructors 
using type_tuple = std::tuple<ClassA, ClassB, ClassC>;

// Get a tuple of constructors(variadic generic lambda) of types in type_tuple
auto constructors = execute_all_t<type_tuple>(get_construct());

// For definitions of execute_all_t and get_construct, see link at the bottom.

I can instantiate an object with:

// Create an object using the constructors, where 0 is index of ClassA in the tuple.
ClassA a = std::get<0>(constructors)(/*arguments for any constructor of ClassA*/);

Is it possible to index the type in runtime with a magic_get like below?

ClassA a = magic_get(constructors, 0)(/*arguments for any constructor of ClassA*/);

A minimal reproducible example: Try it online!

Is there a way to not compile unit test function body in release build without using #ifdef?

Let's say we have many unit test functions only for debug build. We don't want to compile these functions at all in release build. Is there a way other than wrapping unit test functions with #ifdef _DEBUG every time?

#ifdef _DEBUG
void testfunc_xxx() {
  ...
}
#endif

For example, we could have a macro

#ifdef _DEBUG
#define UNITTESTFUNC(name) void name()
#else
#define UNITTESTFUNC(name) template<typename T> void name()
#endif

UNITTESTFUNC(testfunc_xxx) {
  ...
}

But it depends on delayed template parsing. Is there a better way to do it? Thanks!

FindCirclesGrid c++11 does not work though detector finds all points

The Grid in the image is not found, though the simpleBlobDetector detects every blob.

I use the following code:

    vector<Point2f> pointBuf;
    Size gridSize(4, 11);

    cv::SimpleBlobDetector::Params params;
    params.maxArea = pixels / (gridSize.height * gridSize.width * 1.5);
    params.minArea = 70;
    params.minConvexity = 0.85;
    params.minThreshold = 80;
    params.maxThreshold = 230;
    params.thresholdStep = 20;
    params.minInertiaRatio = 0.05;

    auto detector = cv::SimpleBlobDetector::create(params);
    vector<KeyPoint> keypoints;
    detector->detect(image, keypoints);

    Mat debugImage = Mat::zeros(image.size(), CV_8U);
    for (auto keypoint : keypoints) {
        drawKeypoints(debugImage, keypoints, debugImage, 255);
    }
    imwrite("./debug/" + std::to_string(debugIndex) + "debugImage.png", image);
    imwrite("./debug/" + std::to_string(debugIndex) + "debugImage2.png", debugImage);

    findCirclesGrid(image, gridSize, pointBuf, cv::CALIB_CB_ASYMMETRIC_GRID, detector);

The code works for other images. So why is the code not working on this image?

Cannot output red/green/blue color value of object

vector<Text> Game_Text;

Game_Text.push_back(Text("0",Game_Font[0],50));

cout<<Game_Text[0].getFillColor().r<<endl;

Using C++11 in Code::Blocks

Nothing it outputted when run, should it not output 255? If Game_Text[0].getFillColor().r is replaced with, say, "test", it outputs test as normal. No errors, full code is working.

Is it possible to output just a single r/g/b value of an object with this method?

jeudi 30 janvier 2020

Xcode C++ code in cocoa app about serial port get operation not permitted

I build a code in Xcode console with C++ project works perfectly before:

https://i.stack.imgur.com/LNVpV.jpg

//* Open port, and connect to a device
const char devicePathStr[] = "/dev/tty.usbserial-A104RXG4";
const int baudRate = 9600;
int sfd = openAndConfigureSerialPort(devicePathStr, baudRate);
if (sfd < 0) {
    if (sfd == -1) {
        printf("Unable to connect to serial port.\n");
    }
    else { //sfd == -2
        printf("Error setting serial port attributes.\n");
    }
    return 0;
}

// * Read using readSerialData(char* bytes, size_t length)

// * Write using writeSerialData(const char* bytes, size_t length)

// * Remember to flush potentially buffered data when necessary

// * Close serial port when done
const char dataToWrite[]="abcd";
char databuffer[1024];

while(1){
    readSerialData(databuffer, 4);
    sleep(2);
    writeSerialData(databuffer, 4);
    sleep(2);

}

After this build, I tried to migrate it to my Xcode cocoa application with C++ wrappers below.

https://i.stack.imgur.com/NNOis.png

I am pretty sure my Wrapper works fine with test C++ code. That means, I can call C++ function from my ViewController.swift.

But there's one strange thing happened. I am not able to open connection with the following code.

sfd = open(portPath, (O_RDWR | O_NOCTTY | O_NDELAY));
if (sfd == -1) {
    printf("Unable to open serial port: %s at baud rate: %d\n", portPath, baudRate);
    printf("%s", std::strerror(errno));
    return sfd;
}

There error message returns :

Unable to open serial port: /dev/tty.usbserial-A104RXG4 at baud rate: 9600

Operation not permitted

I've tried change me app sandbox configuration, set up my system preference to grant access to my app, also I disable my rootless. (csrutil disable with command + R) But the problem still persists. https://i.stack.imgur.com/rfD0e.png

https://i.stack.imgur.com/hwA6r.png

I wanna ask that

  1. Why my code on Xcode C++ project works fine but fail on swift's cocoa app on Xcode?

  2. How to solve the "Operation not permitted" Issue.

My Xcode version is 11.3.1 and Mac OS is 10.14.6 Mojave.

Thread Declaration in C++

I was going through a project code in C. In there, I saw this declaration of thread :

pthread_t ui_thread = (pthread_t) 0;

I didn't understand the part starting from '=' operator. What is it and how can I code the same declaration in C++.

Use std::find with stride and only check specific member in struct

layers stores a lot of members, like each element's name:

std::vector<vk::LayerProperties> layers = vk::enumerateInstanceLayerProperties()

layerNames only stores the name of each layer:

std::vector<const char*> layerNames(layers.size());

I copy the name member from each layer element into layerNames, and then use std::find on layerNames.

Is there a way to use std::find on layers directly and use a stride to only check the name member when iterating?

Define Iterator type of template argument

In function below, how to tell the compiler that Iterator is the iterator of Cont ?

template<typename Cont, typename Pred>
Iterator<Cont> find_if(const Cont &c, Pred p)
{
    return std::find_if(std::begin(c), std::end(c), p);
}

Is this template

I'm trying to learn to implement template in C++. When I am changing my NTT (Number theoretic transform) code into one that uses template, which looks like this:

template <long long mod> struct NTT{
    int x = 0;
    NTT(){
        long long p = mod-1;
        while(!(p % 2)){
            p >>= 1;
            ++x;
        }       
    }   
    const static long long root_pw = 1 << x;
//(there is a function after this that also needs to read the value 'root_pw')
};

signed main()
{
    NTT<998244353> ntt1;
    vector<long long> a(ntt1::root_pw,0);
}

It tells me to make x static.

When I do that, it tells me to make x const, which beats the reason for x being there in the first place.

I use (GNU C++11) and my complier (Dev-C++ 5.11) set to configure (TDM-GCC 4.9.2 64-bit Release), if it helps.

I really want to make this work, but I don't know how.

This is probably stupidly easy, but just what I'm I missing?

Thank you in advance.

Why does gcc gives me maybe-uninitialized warning for deque::insert with a filtered range

Why does gcc gives me maybe-uninitialized warning for deque::insert with a filtered range when compiling with -O2 and -DNDEBUG

#include <deque>
#include <vector>
#include <boost/range/adaptor/filtered.hpp>

auto foo(){
    std::deque<int> d{3,4};
    std::vector<int> v{0,2};

    const auto b = 1;

    using boost::adaptors::filtered;
    auto r = v | filtered([&b](auto i){return i>b;});

    d.insert(std::end(d),r.begin(),r.end());
    return d;
}

Compiler gcc 6.3 , flag -std=c++14 -O2 -Wall -Werror -DNDEBUG

This is the warning:

<source>: In member function 'void std::deque<_Tp, _Alloc>::_M_insert_aux(std::deque<_Tp, _Alloc>::iterator, _ForwardIterator, _ForwardIterator, std::deque<_Tp, _Alloc>::size_type) [with _ForwardIterator = boost::iterators::filter_iterator<boost::range_detail::default_constructible_unary_fn_wrapper<foo()::<lambda(auto:1)>, bool>, __gnu_cxx::__normal_iterator<int*, std::vector<int> > >; _Tp = int; _Alloc = std::allocator<int>]':
<source>:12:48: error: '*((void*)(& __mid)+16).foo()::<lambda(auto:1)>::<b capture>' may be used uninitialized in this function [-Werror=maybe-uninitialized]
     auto r = v | filtered([&b](auto i){return i>b;});
                                               ~^~
In file included from /opt/compiler-explorer/gcc-6.3.0/include/c++/6.3.0/deque:66:0,
                 from <source>:1:
/opt/compiler-explorer/gcc-6.3.0/include/c++/6.3.0/bits/deque.tcc:768:24: note: '*((void*)(& __mid)+16).foo()::<lambda(auto:1)>::<b capture>' was declared here
       _ForwardIterator __mid = __first;

If b is captured by value, then the warning is gone.

https://godbolt.org/z/gPyF6r

How to read all the numbers within same line? c++ [closed]

I do have a file which contains:-

1 2 3 4 5 6 0 10 12 13

How do I read integers in each line? Print all integers once all the contain is read within that line. And and tell me when I read end of page.

How to use dynamic_cast on vector? [duplicate]

#include <bits/stdc++.h>
using namespace std;

struct Base{

    Base() {};
    virtual ~Base() {};
};

struct Derived: Base
{
  int k;  
};

int main() {

    vector<Base> outBase;

    Derived dtemp;
    dtemp.k =10 ;

    outBase.push_back(dtemp);

    Derived& dNow = dynamic_cast<Derived&>(outBase[0]);

    return 0;
}

The above code gives execution error.

Here, at first I am storing a derived class object into a Base class vector. Then from that vector I need to get the stored data into another derived object. The main importance is to learn how to get the data that was stored in vector of type Base into a derived class object using dynamic cast !

But if Derived& dNow = dynamic_cast<Derived&>(dtemp); is done then there is no error or exception . Please note the moto is how to read the data(in the form outBase[i]) from vector of type Base into a Derived class object using dynamic cast .

Time and space complexity for boost regex_match

In boost C++,there is something called regex_match.I would like to know what is the time complexity and space comlexity of this function. On their website it is mentioned that regex_match throws an exception if the time taken to match against a string exceeds O(N^2). So should we assume that worst case time complexity is O(N^2). What about best case and average case?

How to write a lambda expression for wcin in c++

I have a code like this: wistream *source = &wcin;

wcin is an object of class wistream and so the above code seems to be ok. Is there any way to write a lambda expression for wcin instead of taking its address. Can a lambda expression of an object be written?

pass function to class as parameter C++

there is error here(but when i try to send non //class function its workin); like when i try to add normal void zad1(){somethin...} its works but when i try to add function from class its not :?

 //Class that send function//
    class Lekcja1 : public ZadanieW {
    private:
        int numerZad;
    public:
        Lekcja1(int num) {
            this->numerZad = num;
        };
        ~Lekcja1() {};
        void tab();
         virtual void LekcjaChose();
    };
    /*void Zad12() {
        cout << "dupa" << endl;
    }*/
    void Lekcja1::tab() {
        cout << "dupa" << endl;
    };
     void Lekcja1::LekcjaChose() {
        wyborZadania* obj = new wyborZadania(numerZad,tab);//there is a problem
        delete obj;
    }
    //Class that takin function//
    class ZadanieW {
    public:
        virtual void LekcjaChose() = 0;
    };
    class wyborZadania{
    public:
        int _chose;
    public:
        wyborZadania(int num,void (*tab)()) {
            this->_chose = num;
            switch (_chose)
            {
            case 1:
                (*tab)();
                break;
            default:
                break;
            }
        }
        ~wyborZadania() {}
    };

array index 2 is past the end of the array

The string array d[2] should have 3 elements. But it seems that it can contain only 2 elements. The 3rd element is not being stored in the array. What is the reason? Does it have to do anyting with the memory allocation which I have done with the new operator?

#include<iostream>

class A
{
public:
    A()
    {   
        std::string d[2];
        d[0] = "Dilshdur";
        d[1] = "Dilshad";
        d[2] = "Dolon";
        for(int i=0; i<3; i++)
        {
            std::cout<<d[i]<<std::endl;
        }

    }


};


int main()
{
   A *p;
   p = new A;
   return 0;
}

mercredi 29 janvier 2020

I want to find dominant colour in an Image in Opencv C++

I am new to openCV and searching from past two weeks but all the answers are either in python or not that accurate. I am just looking to find maximum count of a colour in any image. I have tried converting to HSV plane and then by looping over image and extracting hue channel and then by increasing count of each colour which lies in the range. but this method was not accurate at all. So looking for a better solution.

How to convert a string of a time (M:SS) to float

So I'm having trouble figuring out how to convert this time: 4:27.47

into a float value of seconds.

If you need any more details, feel free to ask.

Any help would be greatly appreciated! Thank you in advance.

OpenCV - sizeof datatype at runtime [duplicate]

How can I get the byte size of a cv::Mat type with something equivalent to the sizeof function?

cv::Mat::type returns the cv type, but I need the byte size to be able to memcpy a cv::Mat buffer into another object.

cv type => byte size , how?

template deduction: Why the function pointer templates definitions are not matching when they are const and/or references?

After the question Is possible to fix the iostream cout/cerr member function pointers being printed as 1 or true? I am trying to write a C++ 98 compatible way to print any function pointer.

For this, I am using a fake C++ "variadic" template, i.e., writing all function definitions up to n parameters. However my fake variadic only works for function pointer with 0 arguments as show on the next example: https://godbolt.org/z/x4TVHS

#include<iostream>

template<typename Return>
std::ostream& operator <<(std::ostream& os, Return(*pointer)() ) {
    return os << (void*) pointer;
}

template<typename Return, typename T0>
std::ostream& operator <<(std::ostream& os, Return(*pointer)( const T0& t0 ) ) {
    return os << (void*) pointer;
}

template<typename Return, typename T0, typename T1>
std::ostream& operator <<(std::ostream& os, Return(*pointer)( const T0& t0, const T1& t1 ) ) {
    return os << (void*) pointer;
}

void fun_void_void(){};
void fun_void_double(double d){};
double fun_double_double(double d){return d;}

int main() {
    std::cout << "1. " << fun_void_void << std::endl;
    std::cout << "2. " << fun_void_double << std::endl;
    std::cout << "3. " << fun_double_double << std::endl;
}

// Prints:
//    1. funptr 0x100401080
//    2. funptr 1
//    3. funptr 1

If I write the equivalent version using C++11 real variadic templates, then everything works fine: https://godbolt.org/z/s6wdgp

#include<iostream>

template<typename Return, typename... Args>
std::ostream& operator <<(std::ostream& os, Return(*pointer)( Args... ) ) {
    return os << (void*) pointer;
}

void fun_void_void(){};
void fun_void_double(double d){};
double fun_double_double(double d){return d;}

int main() {
    std::cout << "1. " << fun_void_void << std::endl;
    std::cout << "2. " << fun_void_double << std::endl;
    std::cout << "3. " << fun_double_double << std::endl;
}

// Prints:
//    1. funptr 0x100401080
//    2. funptr 0x100401087
//    3. funptr 0x100401093

After analyzing the code, I noticed the only difference between then is that the types on the C++11 example are not const references. Then, I removed the constness and reference from the C++98 ones and it started working: https://godbolt.org/z/ZrF66b

#include<iostream>

template<typename Return>
std::ostream& operator <<(std::ostream& os, Return(*pointer)() ) {
    return os << (void*) pointer;
}

template<typename Return, typename T0>
std::ostream& operator <<(std::ostream& os, Return(*pointer)( T0 ) ) {
    return os << (void*) pointer;
}

template<typename Return, typename T0, typename T1>
std::ostream& operator <<(std::ostream& os, Return(*pointer)( T0, T1 ) ) {
    return os << (void*) pointer;
}

void fun_void_void(){};
void fun_void_double(double d){};
double fun_double_double(double d){return d;}

int main() {
    std::cout << "1. " << fun_void_void << std::endl;
    std::cout << "2. " << fun_void_double << std::endl;
    std::cout << "3. " << fun_double_double << std::endl;
}

// Prints:
//    1. funptr 0x100401080
//    2. funptr 0x100401087
//    3. funptr 0x100401093

Why the function pointer templates definitions are not matching when they are const and/or references?

Could some tell me why I'm getting this error - Template LinkedList [duplicate]

I've been trying to implement a doubly-linked list with templates in c++. I've had some problems saying that the member function for the specific type that I was calling wasn't referenced, so I've added at the end of the .cpp files an auxiliary function to tell the compiler to substitute the templates of the member functions for their implementation for each type of interest, though, I'm still getting the following error that says, in part, that the functions wasn't implemented.

The Error:

/usr/bin/ld: /tmp/ccDPJJS9.o: in function `__static_initialization_and_destruction_0(int, int)':
linkedlist.cpp:(.text+0xb1): undefined reference to `std::ios_base::Init::Init()'
/usr/bin/ld: linkedlist.cpp:(.text+0xc6): undefined reference to `std::ios_base::Init::~Init()'
/usr/bin/ld: /tmp/ccDPJJS9.o: in function `LinkedList<int>::LinkedList()':
linkedlist.cpp:(.text._ZN10LinkedListIiEC2Ev[_ZN10LinkedListIiEC5Ev]+0x19): undefined reference to `operator new(unsigned long)'
/usr/bin/ld: linkedlist.cpp:(.text._ZN10LinkedListIiEC2Ev[_ZN10LinkedListIiEC5Ev]+0x55): undefined reference to `operator delete(void*, unsigned long)'
/usr/bin/ld: /tmp/ccDPJJS9.o: in function `LinkedList<int>::~LinkedList()':
linkedlist.cpp:(.text._ZN10LinkedListIiED2Ev[_ZN10LinkedListIiED5Ev]+0x2f): undefined reference to `operator delete(void*, unsigned long)'
/usr/bin/ld: linkedlist.cpp:(.text._ZN10LinkedListIiED2Ev[_ZN10LinkedListIiED5Ev]+0x50): undefined reference to `operator delete(void*, unsigned long)'
/usr/bin/ld: /tmp/ccDPJJS9.o: in function `LinkedList<float>::LinkedList()':
linkedlist.cpp:(.text._ZN10LinkedListIfEC2Ev[_ZN10LinkedListIfEC5Ev]+0x19): undefined reference to `operator new(unsigned long)'
/usr/bin/ld: linkedlist.cpp:(.text._ZN10LinkedListIfEC2Ev[_ZN10LinkedListIfEC5Ev]+0x55): undefined reference to `operator delete(void*, unsigned long)'
/usr/bin/ld: /tmp/ccDPJJS9.o: in function `LinkedList<float>::~LinkedList()':
linkedlist.cpp:(.text._ZN10LinkedListIfED2Ev[_ZN10LinkedListIfED5Ev]+0x2f): undefined reference to `operator delete(void*, unsigned long)'
/usr/bin/ld: linkedlist.cpp:(.text._ZN10LinkedListIfED2Ev[_ZN10LinkedListIfED5Ev]+0x50): undefined reference to `operator delete(void*, unsigned long)'
/usr/bin/ld: /tmp/ccDPJJS9.o:(.data.rel.local.DW.ref.__gxx_personality_v0[DW.ref.__gxx_personality_v0]+0x0): undefined reference to `__gxx_personality_v0'
/usr/bin/ld: /tmp/cc0Da8yc.o: in function `main':
main.cpp:(.text+0x15): undefined reference to `operator new(unsigned long)'
/usr/bin/ld: main.cpp:(.text+0x25): undefined reference to `LinkedList<int>::LinkedList(int)'
/usr/bin/ld: main.cpp:(.text+0x3a): undefined reference to `LinkedList<int>::push_back(int)'
/usr/bin/ld: main.cpp:(.text+0x4b): undefined reference to `LinkedList<int>::push_back(int)'
/usr/bin/ld: main.cpp:(.text+0x5c): undefined reference to `LinkedList<int>::push_back(int)'
/usr/bin/ld: main.cpp:(.text+0x6d): undefined reference to `LinkedList<int>::push_back(int)'
/usr/bin/ld: main.cpp:(.text+0x79): undefined reference to `LinkedList<int>::traverse()'
/usr/bin/ld: main.cpp:(.text+0x94): undefined reference to `operator delete(void*, unsigned long)'
/usr/bin/ld: /tmp/cc0Da8yc.o: in function `__static_initialization_and_destruction_0(int, int)':
main.cpp:(.text+0xd5): undefined reference to `std::ios_base::Init::Init()'
/usr/bin/ld: main.cpp:(.text+0xea): undefined reference to `std::ios_base::Init::~Init()'
/usr/bin/ld: /tmp/ccN0tGib.o: in function `Node<int>::~Node()':
node.cpp:(.text._ZN4NodeIiED2Ev[_ZN4NodeIiED5Ev]+0x2f): undefined reference to `operator delete(void*, unsigned long)'
/usr/bin/ld: node.cpp:(.text._ZN4NodeIiED2Ev[_ZN4NodeIiED5Ev]+0x51): undefined reference to `operator delete(void*, unsigned long)'
/usr/bin/ld: /tmp/ccN0tGib.o: in function `Node<float>::~Node()':
node.cpp:(.text._ZN4NodeIfED2Ev[_ZN4NodeIfED5Ev]+0x2f): undefined reference to `operator delete(void*, unsigned long)'
/usr/bin/ld: node.cpp:(.text._ZN4NodeIfED2Ev[_ZN4NodeIfED5Ev]+0x51): undefined reference to `operator delete(void*, unsigned long)'
collect2: error: ld returned 1 exit status

node.h:

#ifndef _NODE_H
#define _NODE_H

template <typename T> class LinkedList;
template <typename T>
class Node
{
   friend class LinkedList<T>;

private:
   T data;
   Node<T> *previous;
   Node<T> *next;

public:
   Node();
   Node(T data);
   void operator=(const Node<T> &rhs);
   ~Node();
};

#endif //_NODE_H

node.cpp:

#include "node.h"

template <typename T>
Node<T>::Node()
   : data{}, previous{nullptr}, next{nullptr} {}

template <typename T>
Node<T>::Node(T data)
   : data(data), previous{nullptr}, next{nullptr} {}

template <typename T>
Node<T>::~Node() {
   delete previous;
   delete next;
}

template <typename T>
void Node<T>::operator=(const Node<T> &rhs) {
   // body
}

void node_classes() {
   Node<int> int_node;
   Node<float> float_node;
}

linkedlist.h:

#ifndef _LINKEDLIST_H
#define _LINKEDLIST_H
#include "node.h"

template <typename T>
class LinkedList
{
private:
   Node<T> *head;
   Node<T> *tail;
   void insert_in_place(Node<T> *current, T data);

public:
   LinkedList();
   LinkedList(T data);
   class iterator
   {
      Node<T> *current;
   public:
      iterator(Node<T> *node_ptr);
      T operator*();
      iterator &operator++();
      iterator &operator--();
      ~iterator();
   };
   void push_back(T data);
   void push_front(T data);
   void insert(int index, T data);
   void traverse();
   LinkedList<T> *begin();
   LinkedList<T> *end();
   ~LinkedList();
};

#endif // _LINKEDLIST_H

linkedlist.cpp:

#include <stdexcept>
#include <iostream>
#include "linkedlist.h"

template <typename T>
LinkedList<T>::LinkedList() {
   Node<T> *node = new Node<T>();
   head = node;
   tail = node;
}

template <typename T>
LinkedList<T>::LinkedList(T data) {
   // body
}

template <typename T>
void LinkedList<T>::push_back(T data) {
   // body
}

template <typename T>
void LinkedList<T>::push_front(T data) {
   // body
}

template <typename T>
LinkedList<T> *LinkedList<T>::begin() {
   // body
}

template <typename T>
LinkedList<T> *LinkedList<T>::end() {
   // body
}

template <typename T>
void LinkedList<T>::insert_in_place(Node<T> *current, T data) {
   // body
}

template <typename T>
void LinkedList<T>::insert(int index, T data) {
   // body
}

template <typename T>
void LinkedList<T>::traverse() {
   // body
}

template <typename T>
LinkedList<T>::~LinkedList() {
   delete tail;
   delete head;
}

// iterator subclass

template <typename T>
LinkedList<T>::iterator::iterator(Node<T> *node_ptr)
   : current(node_ptr) {}

template <typename T>
T LinkedList<T>::iterator::operator*() {
   // body
}

template <typename T>
typename LinkedList<T>::iterator &LinkedList<T>::iterator::operator++() {
   // body
}

template <typename T>
typename LinkedList<T>::iterator &LinkedList<T>::iterator::operator--() {
   // body
}

template <typename T>
LinkedList<T>::iterator::~iterator() {
   delete current;
}

void linkedlist_classes() {
   LinkedList<int> int_linked_list;
   LinkedList<float> float_linked_list;
}

main.cpp:

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

int main() {
   LinkedList<int> *list = new LinkedList<int>(0);

   list->push_back(1);
   list->push_back(2);
   list->push_back(3);
   list->push_back(4);

   list->traverse();

   return 0;
}

I thank you in advance and appreciate any help to solve and understand the problem.

C2236 : unexpected token 'struct', did you forget ';' ? C2332 : 'struct' missing a tag name

Having checked posts with similar errors. None of the solutions proposed helped overcoming this issue.

I have checked all my classes for ';' at the end of the definition.....all of them are properly defined.

I have checked the include headers file for header guards. All of them have guards

This is output of building a QT project (desktop GUI app) .

What are the typical causes of these errors aside from what's mentioned above ?

below is the output of the error :

include\ConfigServer.h(85): error C2236: unexpected token 'struct'. Did you forget a ';'?

include\ConfigServer.h(85): error C2332: 'struct': missing tag name

This 'ConfigServer.h' file include 'BlockParam.h' , 'CommsInfo.h' and 'GeoInfo.h' which I have compiled with previously on a separate console project to test their use. They work on a console program.

Any insight ?

#ifndef CONFIGSERVER_H
#define CONFIGSERVER_H

#include <iostream>
#include <iterator>

#include <QObject>
#include <QMap>
#include <QString>
#include <QVector>
#include <QFile>
#include <QXmlStreamReader>
#include <QDebug>

#include "BlockParam.h"
#include "CommsInfo.h"
#include "GeoInfo.h"




#define _delete(x) { if(x) delete x; x = nullptr;}

#define DEBUG 1
#define SHOW(X,B)  { if(DEBUG) { std::cout << X << B <<std::endl ; } }
#define DISPLAY(X) { if(DEBUG) { std::cout << X <<std::endl ; } }




enum ENUM_PLATFORM {
    NOTSET = 0,
    SILSIM = 1,  // Desktop Platform
    PILSIM = 2,  // PIL Platform
    HILSIM = 3   // HIL Platform
};

enum ENUM_CONFIG
{
    GEOINFO  = 1, // Terrain/Airport/Runway Information
    COMMS    = 2, // IP/Port data for select platforms
    MDLPARAM = 3  // Model parameters
};


typedef QMap<QString,ConfigInfo*> CfgMap;


class ConfigServer
{
public:

    ConfigServer();
    ~ConfigServer();

    bool LoadXmlFile(const QString xmlParmFileName);
    bool Validate(Xpci* xpc);

    bool IsValidated();
    bool errorsOccurred();
    QVector<QString> getErrorStrings();

    template<class T>
    ConfigInfo *GetConfigInfo(QString _inface,QString _pty,bool ebl);

    template<class T>
    void DisplayContent(T* Cfg) const;

    CfgMap *getMap()  const;
    QVector<CfgMap> *getConfigList()  const;

    ENUM_PLATFORM  PLATFORM;
    ENUM_CONFIG    CONFIGURATION;

    QVector<QString> ErrStringsVector;

private:

    void readModelXmlToMap(QXmlStreamReader* reader,CfgMap* ConfigMap_);

    template<class T>
    bool readCurrentInterfaceElement(QXmlStreamReader* reader,CfgMap* ConfigMap_);

    template<class T>
    bool readCurrentPropertyElement(QXmlStreamReader* reader,QString interface,CfgMap* ConfigMap_);

    bool readCurrentDimensionElement(QXmlStreamReader* reader,unsigned &rowDim,unsigned &colDim);

    BlockParam  nullBlockParam;
    CommsInfo   nullCommsInfo;
    GeoInfo     nullGeoInfo;

    CfgMap*  ConfigMap = nullptr;
    QVector<CfgMap>  *ConfigList = nullptr;

    unsigned requisite;
    bool validated = false;
    bool errorFlag = false;

};



template<> bool        ConfigServer::readCurrentInterfaceElement<BlockParam>(QXmlStreamReader* reader,CfgMap* ConfigMap_) ;
template<> bool        ConfigServer::readCurrentInterfaceElement<CommsInfo>(QXmlStreamReader* reader,CfgMap* ConfigMap_) ;
template<> bool        ConfigServer::readCurrentInterfaceElement<GeoInfo>(QXmlStreamReader* reader,CfgMap* ConfigMap_) ;

template<> bool        ConfigServer::readCurrentPropertyElement<BlockParam>(QXmlStreamReader *reader,QString interface,CfgMap* ConfigMap_);
template<> bool        ConfigServer::readCurrentPropertyElement<CommsInfo>(QXmlStreamReader *reader,QString interface,CfgMap* ConfigMap_);
template<> bool        ConfigServer::readCurrentPropertyElement<GeoInfo>(QXmlStreamReader *reader,QString interface,CfgMap* ConfigMap_);

template<> ConfigInfo *ConfigServer::GetConfigInfo<BlockParam>(QString _inface,QString _pty,bool ebl);
template<> ConfigInfo *ConfigServer::GetConfigInfo<CommsInfo>(QString _inface,QString _pty,bool ebl);
template<> ConfigInfo *ConfigServer::GetConfigInfo<GeoInfo>(QString _inface,QString _pty,bool ebl);

template<> void ConfigServer::DisplayContent<BlockParam>(BlockParam* Cfg) const;
template<> void ConfigServer::DisplayContent<CommsInfo>(CommsInfo* Cfg) const;
template<> void ConfigServer::DisplayContent<GeoInfo>(GeoInfo* Cfg) const;




#endif // CONFIGSERVER_H

How to cast int pointer to float pointer

I am running cppcheck (c++11) against a library that contains many casts similar to the below:

// Allocates various buffers
int*   i_buffer = (int*)   calloc (500, sizeof (int));
float* f_buffer = (float*) i_buffer;

For these casts, I see the following message:

"portability","invalidPointerCast","Casting between integer* and float* which have an incompatible binary data representation."

What is the correct way to perform the type of cast shown above ? What is the potential consequence of casting the pointer the way it is shown above ?

MWE of std::thread::join on cppreference.com and cplusplus.com produce segmentation faults

On my computer, the examples given at: https://en.cppreference.com/w/cpp/thread/thread/join and http://www.cplusplus.com/reference/thread/thread/join/ produce a segmentation fault.

The code below print "foo", then gdb report a segmentation fault at t.join(). If I replace join with detach, I get a segmentation fault at detach.

#include <thread>
void f() {std::cout << "foo" << std::endl;}

int main(int argc, char* argv[]) {
    std::thread t(f);
    t.join();
}

Similarly, in the code below, gdb report that s.get() calls std::thread::join(), which in turn produces a segmentation fault. However, replacing std::launch::async by std::launch::deferred fix it (no thread is created).

#include <future>
std::string f() {return "foo";}

int main(int argc, char* argv[]) {
    std::future<std::string> s = std::async(std::launch::async, f);
    std::cout << s.get() << std::endl;
}

The culprit might be my computer, however, it is very plain : Ubuntu 18.04, gcc 7.4. The code itself is compiled with -pthread and std=c++1y. The linker has the -lpthread flag. With such a normal configuration, if I get this problem, then most people on SO should have the same problem, but it does not seem to be the case.

What did I miss ?

tail recursion optimization

how to make tail recursion optimization enabled, when function more and vals call each other?

now, when I set n = 5, but when I set n = 50000000, it will occur error.

using Cb = std::function<void(bool, int)>;
using Read = std::function<void(bool, Cb)>;
using Sink = std::function<void(Read&)>;
using Through = std::function<Read(Read&)>;

int main() {
    int n = 5;

    Read vals = [&](bool abort, Cb cb) {
        if (n-- <= 0) {
            return;
        }
        cb(false, n); // call `more` function
    };

    Sink logInt = [&](Read &read) {
        Cb more;
        more = [&](bool abort, int val) {
            cout << val << endl;
            read(false, more); // call `vals` function
        };

        read(false, more);
    };

    logInt(vals);


    return 0;
}

whole real code example

How to determine an application is already launched or not in windows using C++?

I am launching an XYZ application by CATStartProcess(.....) the arguments are passed to it. If the application is already running I don't need to create a new instance for this.

Queue Implementation Template return type function in C++

I am trying to implement Queue Data Structure using Linked List in C++, where I've made use of classes in both the Linked List and Queue. One thing which I am not getting is that for example, I've written a method front() which will return the top element or the first element of the queue. However, I'm confused about what should I return and how should I return in the case of templated class when my queue is empty. If it would've been int type queue, I would've simply returned -1. Here I'm confused what should I return if my queue() is already empty and how should I return from a templated class.

Here's the code I've written

// Implementation of Queue Data Structure using List
#include<iostream>
using namespace std;

template<typename T>
class Node
{
public:
    T data;
    Node<T>*next;
};
template<typename S>
class Queue
{
public:
    Node<S>*q = NULL;
    void enqueue(S data){
        Node<S>* newNode = new Node<S>;
        newNode->data = data;
        newNode->next = NULL;
        if(q!=NULL){
            Node<S>* temp = q;
            while(temp->next!=NULL){    
                temp = temp->next;
            }
            temp->next = newNode;
        }
        else{
            q = newNode;
        }
    }
    void print(){ //Utility method for printing the queue with ease
        Node<S>*temp = q;
        while(temp){
            cout<<temp->data<<endl;
            temp = temp->next;
        }
    }
    auto dequeue() -> decltype(q->data){
        Node<S>*temp = q;
        q = q->next;
        S value = temp->data;
        delete temp;
        return value;
    }
    auto front() -> decltype(q->data){
        return q->data;
    }
};
int main()
{
    Queue<int>q;
    q.enqueue(1);
    q.enqueue(2);
    q.enqueue(3);

    cout<<"Front is "<<q.front()<<endl;

    cout<<"Before dequeue() printing\n";

    q.print(); 

    cout<<"Dequeue operation() "<<q.dequeue()<<endl;

    cout<<"After deueue() printing\n";

    q.print();

    return 0;
}

How to return a valid pointer in a factory method to derived class based on underlying OS

I am unable to call private methods of derived class using pointer to base class returned by Factory method.

I would like to return a unique_ptr to Cat when user is running on WIN and unique_ptr to Dog when user is running on Linux.

Base.h pure virtual class

#include <iostream>
#include <memory>

class Base
{
public:
    virtual void echo() = 0;
};

Cat.h - derived class of Base

#include "Base.h"

class Cat : public Base
{
public:
    void echo();
    void CatPrivateFunction();
};

Cat.cpp

#include "Cat.h"

void Cat::echo()
{
    std::cout << "In echo()" << std::endl;
}

void Cat::CatPrivateFunction()
{
    std::cout << "In CatPrivateFunction()" << std::endl;
}

Dog.h - derived class of Base

#include "Base.h"

class Dog
{
    void echo();
    void DogPrivateFunction();
};

Dog.cpp

#include "Dog.h"

void Dog::echo()
{
    std::cout << "In echo()" << std::endl;
}

void Dog::DogPrivateFunction()
{
    std::cout << "In DogPrivateFunction()" << std::endl;
}

BaseFactory.h

#ifdef _WIN32
#include "Cat.h"
#elif __linux__
#include "Dog.h"
#endif
#include <memory>

class BaseFactory
{
public:
    static std::unique_ptr<Base> createBase();
};

BaseFactory.cpp

#include "BaseFactory.h"

std::unique_ptr<Base> BaseFactory::createBase()
{
#ifdef __linux__
        return std::unique_ptr<Base>(new Dog{});
#elif _WIN32
        return std::unique_ptr<Base>(new Cat{});;
#endif
}

In the following script

#include "BaseFactory.h"
int main()
{
    std::unique_ptr<Base> p = BaseFactory::createBase();
    p->echo();
    p->CatPrivateFunction();
    return 0;
}

I'd expect the following output

In echo()
In CatPrivateFunction()

But p->CatPrivateFunction() is failing as Base.h doesn't have CatPrivateFunction() member function.

How can this be done?

mardi 28 janvier 2020

define function template alias by using

I define a function template alias:

template <typename T>
using Cb = typename std::add_pointer<void(bool, T)>::type;

but got this error :

error: cannot convert 'Log::operator()(Read&) [with T = int]::' to 'Cb' {aka 'void (*)(bool, int)'} in assignment

template <typename T>
class Log : public Sink<T> {
public:
    void
    operator()(Read<T> &read) {
        if (!more_) {
            // error !!!
            more_ = std::function<Cb<T>>([&](bool done, T val) {
                if (!done) {
                    cout << val << endl;
                    this->operator()(read);
                }
            });
        }
        read(false, more_);
    }

private:
    Cb<T> more_ = nullptr;
};

main function:

int main() {

    Log<int> logInt;

    return 0;
}

who to resolve this syntax error?

code example

How do I get virtual inheritance right?

In the example below I have my parent class and two child classes. Objects of either child are stored in a vector of parent. Looping over the vector I only see method invocations from the parent class. Please help me get the method definition and vtables right and how to avoid the slicing effect. Help, I have been doing python for too long where something like this would work.

#include <iostream>
#include <vector>


using namespace std;

int main()
{

    class A{
        public:

        virtual string print(){return string("A");};
    };

   class B: public A{
       virtual string print() final {return string("B");};
   };

   class C: public A{
       virtual string print() final {return string("C");};
   };

   vector<A> v;
   v.push_back(B());
   v.push_back(C());

   for(auto x : v){
       cout << x.print() << endl;
   }

}

=>

$g++ -std=c++11 -o main *.cpp
$main
A
A

Initializing member variables with braces or parentheses

When initializing member variables in a constructor you can do it in these two different ways, using braces or parentheses:

class some_class {

some_class(): foo{<value>}, bar(<value>) {}

T foo;
T bar;
};

Is there a functional difference between these two initialization methods, and if so, which one should I opt to use?

Initializing std::vector with curly braces uses initializer list

When I replace inner parens with curly braces I get a different result. Why?

Aren't they equivalent after C++11? (apart from preventing integer demotion) Why does it change construction:

from std::vector(size_type count, const T& value = T(), const Allocator& alloc = Allocator());

to std::vector(std::initializer_list<T> init, const Allocator& alloc = Allocator());

EXAMPLE

auto th_buckets = std::vector<std::vector<int>>{2, std::vector<int>(5, 0)};

0 0 0 0 0

0 0 0 0 0

auto th_buckets = std::vector<std::vector<int>>{2, std::vector<int>{5, 0}};

5 0

5 0

Need some hints for choosing win32 file APIs

As I am writing a lexer, I want to avoid as much as possible allocations, so I start by getting the file size to allocate a bunch of tokens based on a heuristic. By doing that I asking my self if the Windows kernel can get the file size with GetFileSizeEx without reading it completely, which will add a latency before I will be able to start lexing?

Does the filesystem starting to fill memory cache immediately when a file handle is open? Because GetFileSizeEx need an open file.

And after I am considering to read my file asynchronously with ReadFileScatter or ReadFileEx. But I can't figure out what is the real difference between those functions, as ReadFileEx can be used with double-buffering to be able to lex a chunk while the next one is filled in background.

ReadFileScatter seems to be a bit more complicated to use as chunks have to be pre-allocated since the beginning with memory aligned to system pages. Does someone know why it is so?

What about FileMapping functions, can it be interesting for my purpose?

PS: Files will stay open during the entire application life.

C++ shared_mutex, threads: memory dump while program is running

I'm new to threads and I have to do some multithreading. Below you'll find code so let me explain it a little bit. I have a class Writer that can write to a file and class Reader that can read from a file, of course, many readers can read from the file at the same time but only one Writer can write to file at some moment.

So, I'm using shared_mutex because it lets Readers read from the file at the same time. But when the program is running it stops and it shows me in the console that I have memory dump.

So, I have no idea what's going on. Here is my code:

#include <iostream>
#include <thread>
#include <shared_mutex>
#include <mutex>
#include <fstream>
#include <string>
#include <chrono>
#include <vector>
#include <algorithm>
#include <functional>
#include <time.h>

using namespace std;

int getSeconds() {
    return rand() % 5 + 1;;
}

class Judge {
public:
    shared_mutex decision;
    Judge(){}
};

class Reader {
public:
    string id;
    Reader(string ID) {
        id = ID;
    }
    void Action(fstream &file, shared_mutex &decision) {
        string line;

        this_thread::sleep_for(chrono::seconds(getSeconds()));
        shared_lock<shared_mutex> lock(decision);
        while (getline(file, line));
        lock.unlock();

        if(line.length() < 1) return;
        cout << id + line << endl;
    }
};

class Writer {
public:
    string id;
    Writer(string ID) {
        id = ID;
    }
    void Action(fstream &file, shared_mutex &decision) {
        int number = rand() % 1000 + 1;

        this_thread::sleep_for(chrono::seconds(getSeconds()));
        lock_guard<shared_mutex> lock(decision);
        file << id + to_string(number) << endl;
    }
};

int main()
{
    srand(time(NULL));
    int num = 5;

    vector<thread> threads;
    vector<Writer> writers;
    vector<Reader> readers;
    Judge judge = Judge();
    fstream file("dane.txt", ios::app | ios::in);

    if(file.is_open()) {
        for (int i = 0; i < num; i++)
        {
            string wID = to_string(0) + to_string(i);
            string rID = to_string(1) + to_string(i);
            writers.push_back(Writer(wID));
            readers.push_back(Reader(rID));
        }

        for (int i = 0; i < num; i++){
            threads[i] = thread(&Writer::Action, &writers[i], ref(file), ref(judge.decision));
            threads[i + num] = thread(&Reader::Action, &readers[i], ref(file), ref(judge.decision));
        }

        for(int i = 0; i < num; i++) {
            threads[i].join();
        }
        file.close();
    } else {
        cout << "Couldn't open file: dane.txt!" << endl;
    }

    return 0;
}

Returning reference to Eigen Quaternion

I have a class with an Eigen::Quaterniond as a protected member variable. I want to access it through the method attitude(). There are three ways I can think to do this right now, and none of them seem to work.

This is a minimum working example in a google test format.


#include "gtest/gtest.h"
#include <Eigen/Geometry>

class MyClass{
public:
    MyClass( double w, double x, double y, double z ) : attitude_(w,x,y,z) {}

    Eigen::Quaterniond&       attitude1()       { return attitude_; }
    const Eigen::Quaterniond& attitude1() const { return attitude_; }

    // compilation fails with " error: 'IsVectorAtCompileTime' is not a member of 'Eigen::Quaternion<double>' "
    // Eigen::Ref<Eigen::Quaterniond>             attitude2()       { return attitude_; }
    // const Eigen::Ref<const Eigen::Quaterniond> attitude2() const { return attitude_; }

    Eigen::Map<Eigen::Quaterniond>             attitude3()       { return Eigen::Map<Eigen::Quaterniond>(attitude_.coeffs().data()); }
    const Eigen::Map<const Eigen::Quaterniond> attitude3() const { return Eigen::Map<const Eigen::Quaterniond>(attitude_.coeffs().data()); }

protected:
    Eigen::Quaterniond attitude_;
};

TEST(QuaternionTest, const_reference ){

    MyClass a(0.2,0.3,0.4,0.5);
    const MyClass& b(a);

    {
        const double& pt1 = a.attitude1().w();
        const double& pt2 = b.attitude1().w();
        EXPECT_EQ(&pt1, &pt2); // FAILS
    }

    // {
    //     const double& pt1 = a.attitude2().w();
    //     const double& pt2 = b.attitude2().w();
    //     EXPECT_EQ(&pt1, &pt2);
    // }

    {
        const double& pt1 = a.attitude3().w();
        const double& pt2 = b.attitude3().w();
        EXPECT_EQ(&pt1, &pt2); // FAILS
    }
}

The commented method is the way I typically return references to internally stored Eigen objects, which enables me to then decide on the actual data storage internally without it being known past the interface (i.e stacking some Vector3 into a contiguous piece of memory).

The compile error looks like a bug to me, as we definitely do know the length of the Quaternion at compile time, it's really just a dressed up Vector4d.

Am I doing something obviously wrong?

Explanation and complexity for visible points in codefight

I came across this question on code fight/code signal Given an array of points on a plane find the maximum no of points that are visible from the origin with a viewing angle of 45 degrees.

int visiblePoints(std::vector<std::vector<int>> points) {


const double pi=M_PI,pi_45=M_PI_4,pi_360=M_PI*2.0;
const double epsilon=1e-10;
int n=points.size(),result=0;
vector<double> angles(n);
for(int i=0;i<n;i++){
    double angle=atan2(points[i][1],points[i][0]);
    angles[i]=angle;
    if(angle<pi_45-pi){
        angles.push_back(angle+pi_360);
    }
}
sort(angles.begin(),angles.end());
//std::sort(angles.begin(), angles.end());
for(auto it=angles.begin();it!=angles.begin()+n;++it){
    auto bound=upper_bound(it,angles.end(),*it+(pi_45+epsilon));
    int curr=distance(it,bound);
    if(curr>result){
        result=curr;
    }
}
return result;
/*
for (auto it = angles.begin(), e = angles.begin() + n; it != e; ++it) {
    auto bound = std::upper_bound(it, angles.end(), *it + (pi_over_4 + epsilon));
    int cur = std::distance(it, bound);
    if (cur > result)
        result = cur;
}
return result;
*/

So the code is fine,I can figure out what is happening here.I just wanted to check is the time complexity O(NlogN). The first for loop takes O(N).points is an array of several points in 2D.For example points =[[1,1],[3,1],.....] Then we have the sorting part. I am assuming that sort takes O(N*logN). Of course, quick sort in worst case takes O(N^2), but for now, I will ignore that fact. And then the last loop is again O(N) Also, will the space complexity in this scenario be O(1) or O(N)(due to the sorting) Thank you

How Friend function works

I have little problem but i don't know how to fix it. I wanted to test the friend function for the first time but I got error:

|17|error: 'minutes' was not declared in this scope|
|18|error: 'hours' was not declared in this scope|
|24|error: 'minutes' was not declared in this scope|
|24|error: 'minutes' was not declared in this scope|

That is my all code:

#include <iostream>
using namespace std;

class Time
{

    int hours;
    int minutes;
    friend Time operator+(const Time & t);
    friend void x(Time h, Time m );

};

Time operator+(const Time & t)
{
    Time sum;
    sum.minutes = minutes + t.minutes;
    sum.hours = hours + t.hours + sum.minutes / 60;
    sum.minutes %= 60;
    return sum;
}


void x(Time h, Time m) {hours = h; minutes = m;}

C++ threads error: no matching function for call to std::thread::_Invoker [duplicate]

I'm learning C++ and I have to do some multithreading. Below you'll find code so let me explain it a little bit. We have class Writer that can write to a file and class Reader that can read from a file, of course, many readers can read from the file at the same time but only one Writer can write to file at some moment. Both classes have methods that I want to give to threads. Those methods cannot be static because every object has an id needed in the method.

At this point, I'm completely lost and I have no idea what's wrong.

Here is my code:

#include <iostream>
#include <thread>
#include <shared_mutex>
#include <fstream>
#include <string>
#include <chrono>
#include <vector>
#include <algorithm>
#include <functional>
#include <time.h>

using namespace std;

int getSeconds() {
    return rand() % 5 + 1;;
}

class Judge {
public:
    shared_mutex decision;
    Judge(){}
};

class Reader {
public:
    string id;
    Reader(string ID) {
        id = ID;
    }
    void Action(fstream &file, shared_mutex &decision) {
        string line;

        shared_lock<shared_mutex> lock(decision);
        this_thread::sleep_for(chrono::seconds(getSeconds()));
        while (getline(file, line));
        lock.unlock();

        if(line.length() < 1) return;
        cout << id + line << endl;
    }
};

class Writer {
public:
    string id;
    Writer(string ID) {
        id = ID;
    }
    void Action(fstream &file, shared_mutex &decision) {
        int number = rand() % 1000 + 1;

        lock_guard<shared_mutex> lock(decision);
        this_thread::sleep_for(chrono::seconds(getSeconds()));
        file << id + to_string(number) << endl;
    }
};

int main()
{
    srand(time(NULL));
    int num = 5;

    vector<thread> threads;
    vector<Writer> writers;
    vector<Reader> readers;
    Judge judge = Judge();
    fstream file("dane.txt", ios::app | ios::in);

    if(file.is_open()) {
        for (int i = 0; i < num; i++)
        {
            string wID = to_string(0) + to_string(i);
            string rID = to_string(1) + to_string(i);
            writers.push_back(Writer(wID));
            readers.push_back(Reader(rID));
        }

        for (int i = 0; i < num; i++){
            threads[i] = thread(&Writer::Action, writers[i], &file, &judge.decision);
            threads[i + num] = thread(&Reader::Action, readers[i], &file, &judge.decision);
        }

        for(int i = 0; i < num * 2; i++) {
            threads[i].join();
        }
        file.close();
    } else {
        cout << "Couldn't open file: dane.txt!" << endl;
    }

    return 0;
}

and here is the complete error given at compilation:


    In file included from zad1.cpp:2:0:
    /usr/include/c++/7/thread: In instantiation of ‘struct std::thread::_Invoker<std::tuple<void (Writer::*)(std::basic_fstream<char, std::char_traits<char> >&, std::shared_mutex&), Writer, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*> >’:
    /usr/include/c++/7/thread:127:22:   required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (Writer::*)(std::basic_fstream<char>&, std::shared_mutex&); _Args = {Writer&, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*}]’
    zad1.cpp:83:84:   required from here
    /usr/include/c++/7/thread:240:2: error: no matching function for call to ‘std::thread::_Invoker<std::tuple<void (Writer::*)(std::basic_fstream<char, std::char_traits<char> >&, std::shared_mutex&), Writer, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*> >::_M_invoke(std::thread::_Invoker<std::tuple<void (Writer::*)(std::basic_fstream<char, std::char_traits<char> >&, std::shared_mutex&), Writer, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*> >::_Indices)’
      operator()()
      ^~~~~~~~
    /usr/include/c++/7/thread:231:4: note: candidate: template<long unsigned int ..._Ind> decltype (std::__invoke((_S_declval<_Ind>)()...)) std::thread::_Invoker<_Tuple>::_M_invoke(std::_Index_tuple<_Ind ...>) [with long unsigned int ..._Ind = {_Ind ...}; _Tuple = std::tuple<void (Writer::*)(std::basic_fstream<char, std::char_traits<char> >&, std::shared_mutex&), Writer, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*>]
        _M_invoke(_Index_tuple<_Ind...>)
        ^~~~~~~~~
    /usr/include/c++/7/thread:231:4: note:   template argument deduction/substitution failed:
    /usr/include/c++/7/thread: In substitution of ‘template<long unsigned int ..._Ind> decltype (std::__invoke(_S_declval<_Ind>()...)) std::thread::_Invoker<std::tuple<void (Writer::*)(std::basic_fstream<char, std::char_traits<char> >&, std::shared_mutex&), Writer, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*> >::_M_invoke<_Ind ...>(std::_Index_tuple<_Ind1 ...>) [with long unsigned int ..._Ind = {0, 1, 2, 3}]’:
    /usr/include/c++/7/thread:240:2:   required from ‘struct std::thread::_Invoker<std::tuple<void (Writer::*)(std::basic_fstream<char, std::char_traits<char> >&, std::shared_mutex&), Writer, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*> >’
    /usr/include/c++/7/thread:127:22:   required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (Writer::*)(std::basic_fstream<char>&, std::shared_mutex&); _Args = {Writer&, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*}]’
    zad1.cpp:83:84:   required from here
    /usr/include/c++/7/thread:233:29: error: no matching function for call to ‘__invoke(std::__tuple_element_t<0, std::tuple<void (Writer::*)(std::basic_fstream<char, std::char_traits<char> >&, std::shared_mutex&), Writer, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*> >, std::__tuple_element_t<1, std::tuple<void (Writer::*)(std::basic_fstream<char, std::char_traits<char> >&, std::shared_mutex&), Writer, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*> >, std::__tuple_element_t<2, std::tuple<void (Writer::*)(std::basic_fstream<char, std::char_traits<char> >&, std::shared_mutex&), Writer, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*> >, std::__tuple_element_t<3, std::tuple<void (Writer::*)(std::basic_fstream<char, std::char_traits<char> >&, std::shared_mutex&), Writer, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*> >)’
        -> decltype(std::__invoke(_S_declval<_Ind>()...))
                    ~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~
    In file included from /usr/include/c++/7/tuple:41:0,
                     from /usr/include/c++/7/bits/unique_ptr.h:37,
                     from /usr/include/c++/7/memory:80,
                     from /usr/include/c++/7/thread:39,
                     from zad1.cpp:2:
    /usr/include/c++/7/bits/invoke.h:89:5: note: candidate: template<class _Callable, class ... _Args> constexpr typename std::__invoke_result<_Functor, _ArgTypes>::type std::__invoke(_Callable&&, _Args&& ...)
         __invoke(_Callable&& __fn, _Args&&... __args)
         ^~~~~~~~
    /usr/include/c++/7/bits/invoke.h:89:5: note:   template argument deduction/substitution failed:
    /usr/include/c++/7/bits/invoke.h: In substitution of ‘template<class _Callable, class ... _Args> constexpr typename std::__invoke_result<_Functor, _ArgTypes>::type std::__invoke(_Callable&&, _Args&& ...) [with _Callable = void (Writer::*)(std::basic_fstream<char>&, std::shared_mutex&); _Args = {Writer, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*}]’:
    /usr/include/c++/7/thread:233:29:   required by substitution of ‘template<long unsigned int ..._Ind> decltype (std::__invoke(_S_declval<_Ind>()...)) std::thread::_Invoker<std::tuple<void (Writer::*)(std::basic_fstream<char, std::char_traits<char> >&, std::shared_mutex&), Writer, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*> >::_M_invoke<_Ind ...>(std::_Index_tuple<_Ind1 ...>) [with long unsigned int ..._Ind = {0, 1, 2, 3}]’
    /usr/include/c++/7/thread:240:2:   required from ‘struct std::thread::_Invoker<std::tuple<void (Writer::*)(std::basic_fstream<char, std::char_traits<char> >&, std::shared_mutex&), Writer, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*> >’
    /usr/include/c++/7/thread:127:22:   required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (Writer::*)(std::basic_fstream<char>&, std::shared_mutex&); _Args = {Writer&, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*}]’
    zad1.cpp:83:84:   required from here
    /usr/include/c++/7/bits/invoke.h:89:5: error: no type named ‘type’ in ‘struct std::__invoke_result<void (Writer::*)(std::basic_fstream<char>&, std::shared_mutex&), Writer, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*>’
    In file included from zad1.cpp:2:0:
    /usr/include/c++/7/thread: In instantiation of ‘struct std::thread::_Invoker<std::tuple<void (Reader::*)(std::basic_fstream<char, std::char_traits<char> >, std::shared_mutex), Reader, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*> >’:
    /usr/include/c++/7/thread:127:22:   required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (Reader::*)(std::basic_fstream<char>, std::shared_mutex); _Args = {Reader&, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*}]’
    zad1.cpp:84:90:   required from here
    /usr/include/c++/7/thread:240:2: error: no matching function for call to ‘std::thread::_Invoker<std::tuple<void (Reader::*)(std::basic_fstream<char, std::char_traits<char> >, std::shared_mutex), Reader, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*> >::_M_invoke(std::thread::_Invoker<std::tuple<void (Reader::*)(std::basic_fstream<char, std::char_traits<char> >, std::shared_mutex), Reader, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*> >::_Indices)’
      operator()()
      ^~~~~~~~
    /usr/include/c++/7/thread:231:4: note: candidate: template<long unsigned int ..._Ind> decltype (std::__invoke((_S_declval<_Ind>)()...)) std::thread::_Invoker<_Tuple>::_M_invoke(std::_Index_tuple<_Ind ...>) [with long unsigned int ..._Ind = {_Ind ...}; _Tuple = std::tuple<void (Reader::*)(std::basic_fstream<char, std::char_traits<char> >, std::shared_mutex), Reader, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*>]
        _M_invoke(_Index_tuple<_Ind...>)
        ^~~~~~~~~
    /usr/include/c++/7/thread:231:4: note:   template argument deduction/substitution failed:
    /usr/include/c++/7/thread: In substitution of ‘template<long unsigned int ..._Ind> decltype (std::__invoke(_S_declval<_Ind>()...)) std::thread::_Invoker<std::tuple<void (Reader::*)(std::basic_fstream<char, std::char_traits<char> >, std::shared_mutex), Reader, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*> >::_M_invoke<_Ind ...>(std::_Index_tuple<_Ind1 ...>) [with long unsigned int ..._Ind = {0, 1, 2, 3}]’:
    /usr/include/c++/7/thread:240:2:   required from ‘struct std::thread::_Invoker<std::tuple<void (Reader::*)(std::basic_fstream<char, std::char_traits<char> >, std::shared_mutex), Reader, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*> >’
    /usr/include/c++/7/thread:127:22:   required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (Reader::*)(std::basic_fstream<char>, std::shared_mutex); _Args = {Reader&, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*}]’
    zad1.cpp:84:90:   required from here
    /usr/include/c++/7/thread:233:29: error: no matching function for call to ‘__invoke(std::__tuple_element_t<0, std::tuple<void (Reader::*)(std::basic_fstream<char, std::char_traits<char> >, std::shared_mutex), Reader, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*> >, std::__tuple_element_t<1, std::tuple<void (Reader::*)(std::basic_fstream<char, std::char_traits<char> >, std::shared_mutex), Reader, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*> >, std::__tuple_element_t<2, std::tuple<void (Reader::*)(std::basic_fstream<char, std::char_traits<char> >, std::shared_mutex), Reader, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*> >, std::__tuple_element_t<3, std::tuple<void (Reader::*)(std::basic_fstream<char, std::char_traits<char> >, std::shared_mutex), Reader, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*> >)’
        -> decltype(std::__invoke(_S_declval<_Ind>()...))
                    ~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~
    In file included from /usr/include/c++/7/tuple:41:0,
                     from /usr/include/c++/7/bits/unique_ptr.h:37,
                     from /usr/include/c++/7/memory:80,
                     from /usr/include/c++/7/thread:39,
                     from zad1.cpp:2:
    /usr/include/c++/7/bits/invoke.h:89:5: note: candidate: template<class _Callable, class ... _Args> constexpr typename std::__invoke_result<_Functor, _ArgTypes>::type std::__invoke(_Callable&&, _Args&& ...)
         __invoke(_Callable&& __fn, _Args&&... __args)
         ^~~~~~~~
    /usr/include/c++/7/bits/invoke.h:89:5: note:   template argument deduction/substitution failed:
    /usr/include/c++/7/bits/invoke.h: In substitution of ‘template<class _Callable, class ... _Args> constexpr typename std::__invoke_result<_Functor, _ArgTypes>::type std::__invoke(_Callable&&, _Args&& ...) [with _Callable = void (Reader::*)(std::basic_fstream<char>, std::shared_mutex); _Args = {Reader, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*}]’:
    /usr/include/c++/7/thread:233:29:   required by substitution of ‘template<long unsigned int ..._Ind> decltype (std::__invoke(_S_declval<_Ind>()...)) std::thread::_Invoker<std::tuple<void (Reader::*)(std::basic_fstream<char, std::char_traits<char> >, std::shared_mutex), Reader, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*> >::_M_invoke<_Ind ...>(std::_Index_tuple<_Ind1 ...>) [with long unsigned int ..._Ind = {0, 1, 2, 3}]’
    /usr/include/c++/7/thread:240:2:   required from ‘struct std::thread::_Invoker<std::tuple<void (Reader::*)(std::basic_fstream<char, std::char_traits<char> >, std::shared_mutex), Reader, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*> >’
    /usr/include/c++/7/thread:127:22:   required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (Reader::*)(std::basic_fstream<char>, std::shared_mutex); _Args = {Reader&, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*}]’
    zad1.cpp:84:90:   required from here
    /usr/include/c++/7/bits/invoke.h:89:5: error: no type named ‘type’ in ‘struct std::__invoke_result<void (Reader::*)(std::basic_fstream<char>, std::shared_mutex), Reader, std::basic_fstream<char, std::char_traits<char> >*, std::shared_mutex*>’

I have no idea what's wrong, I don't understand these errors.

function template with Segmentation fault

I write pull function to link (read -> through ... -> sink)

template<typename T>
auto pull(T &&stream) {
    return std::forward<T>(stream);
}

// return void/read
// read -> sink
// read -> through
template<typename R, typename S>
auto pull(R &&read, S &sink) {
    return sink(std::forward<R>(read));
}

// return read
// read -> through -> ...
template<typename R, typename T, typename... Ts>
auto pull(R &&read, T &through, Ts &&... args) {
    return pull(through(std::forward<R>(read)), std::forward<Ts>(args)...);
}

read function, like this, provide a vector:

template<typename T>
auto values(T &begin, T &end) {
    return [&](bool abort, auto cb) {

        if (end != begin) {
            cb(false, *begin++);
        } else {
            cb(true, *begin);
        }
    };
}

through function, like this:

template<typename T, typename M>
auto Map(M &&mapper) {

    return [&](auto &&read) {
        return [&](bool abort, auto cb) {
            read(abort, [&](bool end, T val) {
                if (end)
                    cb(true, val);
                else
                    cb(false, mapper(val));
            });
        };
    };
}

sink function like this:

template<typename T, typename R>
auto log(R &&read) {

    std::function<void(bool, T)> more = [&](bool done, T val) {
        if (!done) {
            cout << val << endl;
            read(false, more);
        }
    };

    read(false, more);
}

then in the main function:

int main() {
    vector<int> vec;
    for (int i = 1; i < 4; i++) {
        vec.push_back(i);
    }
    auto begin = vec.begin();
    auto end = vec.end();

    auto vals = values(begin, end);
    auto mapper = [&](int val) { return val * 2; };
    auto timesTwo = Map<int>(mapper);
    auto newVals1 = pull(vals, timesTwo, timesTwo);
    auto newVals2 = pull(vals, timesTwo);
    auto logInt = [&](auto read) { log<int>(read); };

    //pull(newVals1, logInt); // Segmentation fault, how to correct `pull` function to make this run right
    pull(newVals2, logInt); // ok

    return 0;
}

pull(newVals2, logInt); work right,

but pull(newVals1, logInt); throw Segmentation fault;

I want to make pull(newVals1, logInt); work right.

I think, may be some bug in pull function, but i do not know where, who can help me?

code example

set_intersection with a custom set comparator

When I use the std::set_intersection function with a set that has custom comparator I don't get the expected result. The follow code outputs that {5,9,7} intersect {9} is empty set. However if I just use the normal comparator I get {9}.

#include <iostream>
#include <cstdlib>
#include <set>

using namespace std;
auto cmp = [](int* a, int* b) { return a < b; };
using stupid_set = set<int*, decltype(cmp)>;
int main() {
    int* n5 = new int(5);
    int* n9 = new int(9);
    int* n7 = new int(7);
    stupid_set s0 {n5, n9, n7};
    stupid_set s1 {n9};
    stupid_set i;
    for (auto s:s0) {
        cout << "s0:" << *s << endl;
    }
    for (auto s:s1) {
        cout << "s1:" << *s << endl;
    }
    set_intersection(s0.begin(), s0.end(), s1.begin(), s1.end(), std::inserter(i, i.begin()));
    for (auto x : i) {
        cout << "Int=" << *x << endl;
    }
}

wrapper to make anonymous enums proper types

I have some typedef'd enums that are included from c-code, i,e. they are available in the form
typedef enum {FOO=3, BAR=5} my_enum; and I would like use it in C++ code in a typesafe manner while leaving the enum names (FOO and BAR) and values (3 and 5) and their association unmodified.

Are there any best practices or patterns like template wrappers, that can be recommended to accomplish that, say in C++11 or higher?

Error C2677: binary '*': no global operator found (C++)

Sorry for asking a similar question that has been asked before, but I wasn't able to understand the answers.

Header file

    float Dot(const Point& other) const;

CPP

Point Point::operator*(float operand) const
{
    return Point(mX * operand, mY * operand);
}

and I am getting Error C2677: binary '*': no global operator found

what is the problem??

is unordered_set thread safe if data race is irrelevant?

I would like to have threads add unique floats to a list, and first thought about approaching it by inserting into an unordered_map<float,int> where the values does not matter (which essentially is an unordered_set<float>). The threads could override each other with values 1 in the same key, ie. it doesn't matter if Thread 1 wrote value 1 first, or Thread 2, because in the end, it will just end up as 1. As such, data races should be irrelevant.

#include <iostream>
#include <string>
#include <unordered_set>
#include <thread>
#include <set>

std::unordered_set<float> mySet;

void someTask(int i) {
    mySet.insert(i % 3);
}

int main()
{
    std::thread threads[8];
    for (int i = 0; i < 8; i++) {  
     threads[i] = std::thread(someTask, i);
    }
    for (int i = 0; i < 8; i++) {  
     threads[i].join();
    }    

    for (auto const& mySetVal : mySet) {
     std::cout << mySetVal << std::endl;    // Oddly, mySet might have duplicates
    }    

    std::set<float> mySet_( mySet.begin(), mySet.end() ); // Make a new ordered set, and removing duplicates along the way

    for (auto const& mySetVal : mySet_) {
     std::cout << mySetVal << std::endl;   // Would this always produce the expected result of 0,1,2?
    }
}

However mySet despite being an unordered_set has duplicates, and I'm guessing this is due to a race condition while reading for the key, and ended up inserting twice? But when I replace mySet with a unordered_map<float,int>, there are still duplicates- I would've thought even if there is a race condition, and although we can't guarantee which thread will execute first, in the end, the threads can override one another without any harm.

So why are there duplicates?

And by removing the duplicates at the end, is this thread-safe, or would it produce the expected results of 0,1,2 consistently/reliably? If not, a thread-safe solution for the code above would be awesome!

How do I get the previous element of a list using the same iterator in C++?

I am making a sudoku solver and I cannot manage to get backtracking working by refering to the last element of my list (which holds the positions of the blank spaces).

The code below shows my naive initial approach to this issue

{
    position CurrentPos;

    list<position>::iterator j;
    for (j = blankSpaces.begin();  j != blankSpaces.end();  j++)
    {
        CurrentPos.row = j->row;
        CurrentPos.col = j->col;

        for (int i = arr[CurrentPos.row][CurrentPos.col] + 1; i < 10; i++)
        {
            if (valid(arr, CurrentPos, i))
            {
                arr[CurrentPos.row][CurrentPos.col] = i;
                visitedStack.emplace_front(CurrentPos);
            }
            if (!(valid(arr, CurrentPos, i)) && (i == 9))
            {
                j--;
            }
        }
    }

}

Thanks in advanced

lundi 27 janvier 2020

Why first COUT is printing whole input? which is incorrect

Why first "cout" is printing incorrect char array that is if i enter char more than array size it is returning the same as input, whereas second cout is printing fine , that is it is able to detect the error!

#include <bits/stdc++.h>

using namespace std;

int main()
{
    char name[4];

    cin >> name;

    cout << name << endl;
    int  i;
    for(i = 0 ;name[i] != '\0' ; i++)
    {

    }

    cout << name <<endl;

    cout << "Number of chars are: " << i ;

}

if i enter name as: NishantVarshney , output is : NishantVarshney Nish? Number of chars are: 5

c++ error: incomplete type is not allowed

I want to rebuild the RplidarCpp.dll file and add some functions to it. I created the project in visual studio 2010. But there are some errors that I can't fix. Please help me to solving them.

thank you very much

#include "stdafx.h"
#include "rplidar.h"
#include <iostream>

#define _DLLEXPORT __declspec(dllexport)

using namespace rp::standalone::rplidar;

class LidarMgr
{
public:
    LidarMgr() ;
    ~LidarMgr();

    const LidarMgr& operator=(const LidarMgr&) = delete;
    const LidarMgr(const LidarMgr &) = delete;

public:
    static RPlidarDriver * lidar_drv;
    bool m_isConnected;
    rplidar_response_device_info_t devinfo;

the errors occur in below lines:

const LidarMgr& operator=(const LidarMgr&) = delete;
const LidarMgr(const LidarMgr &) = delete;

Top code is not complete.

How to interpret the template function signature of backtrace in GDB?

The output of backtrace of GDB is pretty messy, especially for template.

For instance:

Thread 2 (LWP 100146 of process 1245):
#0  thr_new () at thr_new.S:3
#1  0x000000080025c3da in _pthread_create (thread=0x7fffdfffd880, attr=<optimized out>, start_routine=0x205500 <void* std::__1::__thread_proxy<std::__1::tuple<std::__1::unique_ptr<std::__1::__thread_struct, std::__1::default_delete<std::__1::__thread_struct> >, void (std::__1::__async_assoc_state<void, std::__1::__async_func<func2(std::__1::atomic<long>&)::$_0> >::*)(), std::__1::__async_assoc_state<void, std::__1::__async_func<func2(std::__1::atomic<long>&)::$_0> >*> >(void*)>, arg=0x8007fa8e0) at /usr/src/lib/libthr/thread/thr_create.c:188
#2  0x0000000000204e40 in std::__1::thread::thread<void (std::__1::__async_assoc_state<void, std::__1::__async_func<func2(std::__1::atomic<long>&)::$_0> >::*)(), std::__1::__async_assoc_state<void, std::__1::__async_func<func2(std::__1::atomic<long>&)::$_0> >*, void>(void (std::__1::__async_assoc_state<void, std::__1::__async_func<func2(std::__1::atomic<long>&)::$_0> >::*&&)(), std::__1::__async_assoc_state<void, std::__1::__async_func<func2(std::__1::atomic<long>&)::$_0> >*&&) ()
#3  0x0000000000204309 in std::__1::future<void> std::__1::__make_async_assoc_state<void, std::__1::__async_func<func2(std::__1::atomic<long>&)::$_0> >(std::__1::__async_func<func2(std::__1::atomic<long>&)::$_0>&&) ()
#4  0x00000000002035ea in std::__1::future<std::__1::__invoke_of<std::__1::decay<func2(std::__1::atomic<long>&)::$_0>::type>::type> std::__1::async<func2(std::__1::atomic<long>&)::$_0>(std::__1::launch, func2(std::__1::atomic<long>&)::$_0&&) ()
#5  0x0000000000203462 in func2(std::__1::atomic<long>&) ()
#6  0x0000000000206f18 in main::$_1::operator()() const ()
#7  0x0000000000206eed in void std::__1::__async_func<main::$_1>::__execute<>(std::__1::__tuple_indices<>) ()
#8  0x0000000000206ea5 in std::__1::__async_func<main::$_1>::operator()() ()
#9  0x0000000000206df3 in std::__1::__async_assoc_state<void, std::__1::__async_func<main::$_1> >::__execute() ()
#10 0x0000000000207183 in void* std::__1::__thread_proxy<std::__1::tuple<std::__1::unique_ptr<std::__1::__thread_struct, std::__1::default_delete<std::__1::__thread_struct> >, void (std::__1::__async_assoc_state<void, std::__1::__async_func<main::$_1> >::*)(), std::__1::__async_assoc_state<void, std::__1::__async_func<main::$_1> >*> >(void*) ()
#11 0x000000080025c776 in thread_start (curthread=0x8007de500) at /usr/src/lib/libthr/thread/thr_create.c:292
#12 0x0000000000000000 in ?? ()
Backtrace stopped: Cannot access memory at address 0x7fffdfffe000

In frame #8, there are three pairs of parentheses, std::__1::__async_func<main::$_1>::operator()() () what do they mean exactly?

Ambiguous != operator for reverse_iterator

When I reverse iterate a map in the following code:

    std::map<Version, VersionBatch>::reverse_iterator versionBatch = self->versionBatches.rbegin();
    for (; versionBatch != self->versionBatches.rend(); versionBatch++) {
        self->batch[batchIndex] = Reference<MasterBatchData>(new MasterBatchData());
        self->batchStatus[batchIndex] = Reference<MasterBatchStatus>(new MasterBatchStatus());
        fBatches.push_back(distributeWorkloadPerVersionBatch(self, batchIndex, cx, request, versionBatch->second));
        batchIndex--;
    }

I got the error from CMake. It seems the reverse_iterator can be interpreted by both utility and iterator, which causes the compiler to confuse. Is there a way to dis-ambiguous this?

Users/ciuser/jenkins/foundationdb-ci.foundationdb.org/workspace/jobs/prb-cmake-macos/fdbserver/RestoreMaster.actor.cpp:276:22: error: use of overloaded operator '!=' is ambiguous (with operand types 'std::map<Version, VersionBatch>::reverse_iterator' (aka 'reverse_iterator<__map_iterator<__tree_iterator<std::__1::__value_type<long long, VersionBatch>, std::__1::__tree_node<std::__1::__value_type<long long, VersionBatch>, void *> *, long> > >') and 'std::__1::map<long long, VersionBatch, std::__1::less<long long>, std::__1::allocator<std::__1::pair<const long long, VersionBatch> > >::reverse_iterator' (aka 'reverse_iterator<__map_iterator<__tree_iterator<std::__1::__value_type<long long, VersionBatch>, std::__1::__tree_node<std::__1::__value_type<long long, VersionBatch>, void *> *, long> > >'))
                        for(;versionBatch != self->versionBatches.rend();versionBatch++) {
                             ~~~~~~~~~~~~ ^  ~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Library/Developer/CommandLineTools/usr/include/c++/v1/utility:218:1: note: candidate function [with _Tp = std::__1::reverse_iterator<std::__1::__map_iterator<std::__1::__tree_iterator<std::__1::__value_type<long long, VersionBatch>, std::__1::__tree_node<std::__1::__value_type<long long, VersionBatch>, void *> *, long> > >]
operator!=(const _Tp& __x, const _Tp& __y)
^
/Library/Developer/CommandLineTools/usr/include/c++/v1/iterator:710:1: note: candidate function [with _Iter1 = std::__1::__map_iterator<std::__1::__tree_iterator<std::__1::__value_type<long long, VersionBatch>, std::__1::__tree_node<std::__1::__value_type<long long, VersionBatch>, void *> *, long> >, _Iter2 = std::__1::__map_iterator<std::__1::__tree_iterator<std::__1::__value_type<long long, VersionBatch>, std::__1::__tree_node<std::__1::__value_type<long long, VersionBatch>, void *> *, long> >]
operator!=(const reverse_iterator<_Iter1>& __x, const reverse_iterator<_Iter2>& __y)
^
1 error generated.

Thank you very much!

Initialize a constant vector of pointers

I have the following classes in a header file designed to create runtime polymorphism for a set of instructions that describe system states in an embedded environment:

class foo
{
public:
  virtual void bar(void) = 0;
  virtual ~foo() {}
};

class derived1 : public foo
{
private:
  int data1;
public:
  void bar(void)
  {
    //implementation 1
  };
  derived1(int d) : data1(d) {}
  ~derived1() {}
};

class derived2 : public foo
{
private:
  int data2;
public:
  void bar(void)
  {
    //implementation 2
  }
  derived2(int d) : data2(d) {}
  ~derived2() {}
};

What is the best way to initialize a vector of type const vector<foo*>? I am currently doing the following:

const std::vector<foo*> v =
{   
  new derived1(a),
  new derived1(b),
  new derived2(c),
  new derived2(d)
};

Given the const qualifier, is this memory still dynamically allocated? It is stored in an anonymous namespace for use by several state classes. Because many state classes share the same elements I wanted to define the vector for all of them to chose from to save code space. Is a vector best suited for this behavior?

Ps, I do not need to worry about calling delete on any of the pointers since the application requires this information for all runtime.

Type deduction of parameter and parameter pack

I have the following code for generically wrapping Petsc objects in a unique_ptr, but it doesn't quite work the way I'd expect from cppreference's documentation on template type deduction: https://en.cppreference.com/w/cpp/language/class_template_argument_deduction.

template <typename obj_type, typename... constructor_args>
using petsc_cons = PetscErrorCode (*)(constructor_args..., obj_type *);

template <typename obj_type> using petsc_destr = PetscErrorCode (*)(obj_type *);

template <typename obj_type, typename... constructor_args>
auto petsc_make_unique(petsc_cons<obj_type, constructor_args...> construct,
                       petsc_destr<obj_type> destroy, constructor_args... args) {
  // allocation code...
}

class NLOptimizer {
public:
  NLOptimizer(const size_t num_vars)
      : tao_ctx(petsc_make_unique<Tao>(TaoCreate, TaoDestroy,
                                       PETSC_COMM_SELF)) {}

This fails on g++:

autodiff_tao.hpp: In constructor ‘auto_diff::optimize_tao::NLOptimizer<expr_t>::NLOptimizer(expr_t, size_t)’:
autodiff_tao.hpp:45:62: error: no matching function for call to ‘petsc_make_unique<Tao>(PetscErrorCode (&)(MPI_Comm, _p_Tao**), PetscErrorCode (&)(_p_Tao**), MPI_Comm)’
   45 |                                               PETSC_COMM_SELF)) // ,
      |                                                              ^
autodiff_tao.hpp:24:6: note: candidate: ‘template<class obj_type, class ... constructor_args> auto auto_diff::optimize_tao::petsc_make_unique(auto_diff::optimize_tao::petsc_cons<obj_type, constructor_args ...>, auto_diff::optimize_tao::petsc_destr<obj_type>, constructor_args ...)’
   24 | auto petsc_make_unique(petsc_cons<obj_type, constructor_args...> construct,
      |      ^~~~~~~~~~~~~~~~~
autodiff_tao.hpp:24:6: note:   template argument deduction/substitution failed:
autodiff_tao.hpp:45:62: note:   mismatched types ‘_p_Tao*’ and ‘ompi_communicator_t’
   45 |                                               PETSC_COMM_SELF)) // ,

Clang is able to deduce the parameter pack types and compiles the code above. Is this a bug in g++, clang, or am I relying on undefined behaviour here?

I've attempted this compilation on multiple minor versions of clang 9 and g++ 9, and several less successful variations of the code above.

Comparing 2 vectors and removing elements from 2nd vector that are not found in the 1st - c++

I have 2 string vectors:

vector < string > animals = {"cat", "dog", "pig", "tiger", "monkey", "lion"}
vector < string > someAnimals = {"dog", "mouse", "snake", "monkey", "cat"}

How can I compare these 2 vectors and remove elements in someAnimals vector("mouse" and "snake") that aren't found in the animals Vector?

C++ Compiler Error: P1LinkedList.cpp:145: error: call of overloaded ‘to_string(int&)’ is ambiguous

I'm implementing a linked list. I'm getting the error:

P1LinkedList.cpp:145: error: call of overloaded ‘to_string(int&)’ is ambiguous
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/basic_string.h:2604: note: candidates are: std::string std::to_string(long long int)
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/basic_string.h:2610: note:                 std::string std::to_string(long long unsigned int)
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/basic_string.h:2616: note:                 std::string std::to_string(long double)

(I'm compiling my code with g++ -std=c++0x

The method throwing this exception:

std::string P1LinkedList::print(){

    std::string print = "";
    iterator itr = begin();

    for(int i = 0; i < theSize; i++){
        print += std::to_string(itr.current->data) + " ";
        itr++;
    }

    return print; 
}

current is the current Node being pointed to by the iterator. data is an int that is within the Node class.

Node.h:

#ifndef Node_h
#define Node_h

struct Node{

        int data; 
        Node* next; 
        Node* prev; 

        Node(const int & d = 0, Node *p = 0, Node *n = 0); 
};

#endif

Part of my const_iterator.h file where current is declared (my iterator class extends from the '''const_iterator''' class:

    protected:  
        Node *current; 
        int& retrieve() const; 
        const_iterator(Node*p); 
        friend class P1LinkedList; 
};

I'm trying to pass data through to_string as a regular int value, which I thought itr.current->data was doing, but could I possibly be getting this error because it's not passing the int value of data, but a pointer to it instead?

In C++11, can a global object be instantiated by a function call?

There are two files ObjectCreator.h and ObjectCreator.cpp that declare and define the following function.

In ObjectCreator.h

#include "Object.h"

Object* Create_Object();

In ObjectCreator.cpp

#include "ObjectCreator.h"

Object* Create_Object()
{
   return new Object();
}

The question is, can I create a global instance of Object in the following way in a main.cpp file?

In main.cpp

#include "ObjectCreator.h"

static Object* object = Create_Object();

int main()
{
   // Nothing here
}

The best way I could ask this question was an example and I have verified this is possible. I am just not sure if it is possible in C++11 or what the technical term for this is. I am aware objects can be instantiated globally, I am just not sure if they can be done in this specific way in C++11.

"Missing type specifier - int assumed" cannot be solved by adding "return 0" to the main function

I am trying to figure out how the C++ key word "this" works. I followed the codes below, but it does not pass and show the error of

#include <iostream>
#include <string>

void PrintEntity(const Entity& e);

class Entity
{
public:
    int x, y;

    Entity(int x, int y)
    {
        this->x = x;
        this->y = y;

        PrintEntity(*this);
    }
};

void PrintEntity(const Entity& e)
{
    std::cout << "Entity" << std::endl;
}

int main()
{
    return 0;
}

I reviewed other similar questions, the solutions include adding "return 0" to the Main function or circular dependency. But I don't think these solutions apply for me. Please help me solve it, thanks!

WebRTC crash at line webrtc::PeerConnectionInterface::RTCConfiguration config; for Native Linux application

I'm writing a Native WebRTC application for Linux (Ubuntu), code is crashing at webrtc::PeerConnectionInterface::RTCConfiguration config;

I have below two speculations

  1. I might be messing up with rtc threads, since the same line runs fine in the sample application.
  2. Is there any mistake in the handling of C++ strings. Not sure how it can impact during the declaration of the variable.

Below is the trace:

0 0x00007fbd841e6fdf in std::__cxx1998::vector, std::allocator >, std::allocator, std::allocator > > >::~vector() () at /usr/include/c++/8/bits/stl_vector.h:567 1 0x00007fbd841e696e in std::__debug::vector, std::allocator >, std::allocator, std::allocator > > >::~vector() () at /usr/include/c++/8/debug/vector:210 warning: Could not find DWO CU obj/api/libjingle_peerconnection_api/peer_connection_interface.dwo(0x88209d7623c67b6c) referenced by CU at offset 0xe2f950 [in module /opt/Citrix/ICAClient/libwebrpc.so]

2 0x00007fbd8464272c in webrtc::PeerConnectionInterface::IceServer::~IceServer() () at ../../../api/peer_connection_interface.h:208 warning: Could not find DWO CU obj/pc/peerconnection/peer_connection_factory.dwo(0xc714b8e7fa522831) referenced by CU at offset 0xe2f03c [in module /opt/Citrix/ICAClient/libwebrpc.so]

3 0x00007fbd84438068 in void std::_Destroy(webrtc::PeerConnectionInterface::IceServer*) () at /usr/include/c++/8/bits/stl_construct.h:98

4 0x00007fbd844370b3 in void std::_Destroy_aux::__destroy(webrtc::PeerConnectionInterface::IceServer*, webrtc::PeerConnectionInterface::IceServer*) () at /usr/include/c++/8/bits/stl_construct.h:108

5 0x00007fbd84435a85 in void std::_Destroy(webrtc::PeerConnectionInterface::IceServer*, webrtc::PeerConnectionInterface::IceServer*) () at /usr/include/c++/8/bits/stl_construct.h:137

6 0x00007fbd84433f1b in void std::_Destroy(webrtc::PeerConnectionInterface::IceServer*, webrtc::PeerConnectionInterface::IceServer*, std::allocator&) () at /usr/include/c++/8/bits/stl_construct.h:206

7 0x00007fbd8464454f in std::__cxx1998::vector >::~vector() () at /usr/include/c++/8/bits/stl_vector.h:567

8 0x00007fbd84644192 in std::__debug::vector >::~vector() () at /usr/include/c++/8/debug/vector:210

9 0x00007fbd84643132 in webrtc::PeerConnectionInterface::RTCConfiguration::~RTCConfiguration() () at ../../../api/peer_connection_interface.h:292