mardi 31 décembre 2019

Cannot change member variable via std::set iterator

I have two friend classes:

class Node {
private:
    unsigned id_;
    bool marked_;
    std::set<Node> neighbors_;

    friend class Graph;
    ......

public:
bool operator == (const Node & other) const { return id_ == other.id(); }
bool operator < (const Node & other) const { return id_ < other.id(); }
......
};

class Graph {
private:
    std::set<Node> vertices_{};
    void reach_set_helper(unsigned id, std::vector<unsigned> &reach_set);
    ......
};

I am trying to create a function that can first find a specific node in the graph vertices_, say node v. And then I want to change the marked_ property of the neighbors of v. To find v, I have to use std::find() method. However, the return iterator of this method does not allow me to change member variables of neighbors. This is what I have tried:

Node & s = v;
std::set<Node>::iterator pos = vertices_.find(s);
const std::set<Node> & neighbors = (pos->neighbors_);
for (std::set<Node>::iterator it = neighbors.begin(); it != neighbors.end(); it++) {
    if (!it->is_marked()) {
        reach_set.push_back(it->id());
        it->set_marked(true);
    }
    this->reach_set_helper(it->id(), reach_set);
}

Notice here that I have to use const std::set<Node> & neighbors because I want to change neighbors in place. But I can't change neighbors of v through const iterator it, so this method does not work. I have a way to make changes to vertices_ by erase and copy back through iterator, that's not a problem. But here it is different, I am doing operations on elements of vertices, which is another set. Any suggestions?

why compiler says couldn't deduce template parameter [duplicate]

This question already has an answer here:

#include <iostream>
#include <vector>
#include <list>
using namespace std;

template <typename T>
void print(typename list<T>::iterator first, typename list<T>::iterator end){
    for (; first != end; ++first){
        cout << *first << endl;
    }
}

int main(){
    list <int> list_1 = {0,1,2,3,4,5,6,7,8,9};
    print(list_1.begin(), list_1.end());    
    return 0;
}



void print(typename list<int>::iterator first, typename list<>::iterator end){
    for (; first != end; ++first){
        cout << *first << endl;
    }
}

but when I remove the template parameter, it works. how can I fix the problem to make the template parameter work?

How to assign a vector of atomic types?

How can I assign the members of a vector with an atomic type?

#include <iostream>
#include <thread>
#include <vector>

using namespace std;

int main()
{
    vector<atomic<bool>> myvector;
    int N=8;
    myvector.assign(N,false);
    cout<<"done!"<<endl;
}

https://wandbox.org/permlink/lchfOvqyL3YKNivk

prog.cc: In function 'int main()':
prog.cc:11:28: error: no matching function for call to 'std::vector<std::atomic<bool> >::assign(int&, bool)'
   11 |     myvector.assign(N,false);
      |                            ^

Use Current Template as a Template Parameter to one of the Template Parameters

I am trying to make a generic graph structure, but I am running into this circular dependency between vertices and edges. I define my Vertex and Edge classes like so:

template<typename EdgeType>
struct Vertex {
    std::vector<EdgeType> successors;
};

template<typename EdgeCostType, typename VertexWrapper>
struct Edge {
    EdgeCostType cost;
    VertexWrapper source;
    VertexWrapper dest;
};

I would like to instantiate it with something like Vertex<Edge<int, std::shared_ptr<decltype(v)>>> v;, but I obviously cannot. What can I do to resolve this circular dependency?

Edit:

I think what this problem boils down to is using the current template as a template parameter to one of the template parameters of the current template, e.g. how to do something like this:

template<typename VertexWrapper>
struct Vertex {
    std::vector<pair<int, VertexWrapper<Vertex>>> successors;
};

Passing a templated function parameter to a thread

I compile the following code by

g++ -std=c++11 main.cpp

and I get the error:

main.cpp: In member function ‘void Object::que_action(double, double)’:
main.cpp:29:23: error: expected primary-expression before ‘(’ token
    th[i] = std::thread(
                       ^

What I am doing is that I am calling the function que_action which is a template function and its parameter is a method from the same class. If this function was supposed to be called directly, (this->*param_function)(x,y) would do the job. But, here I am passing it to a thread function which causes this error. How should I fix this error and make the application work?

#include <iostream>
#include <thread>
#include <cmath>

class Object
{
public:

    void aaa(double x,double y)
    {
        std::cout<<"aaa action "<<x<<","<<y<<std::endl;
    }

    void bbb(double x,double y)
    {
        std::cout<<"bbb action "<<x<<","<<y<<std::endl;
    }

    template <void (Object::*param_function)(double x,double y)>
    void que_action(double r, double theta)
    {
        double x = r * cos(theta);
        double y = r * sin(theta);

        constexpr int N = 8; 
        std::thread th[N];
        for(int i = 0; i < N; i++)
        {
            th[i] = std::thread(
                &(std::remove_reference<decltype(*this)>::type::*param_function),
                this, double x, double y);
        }

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

    void que_both_actions(double r, double theta)
    {
        que_action<&Object::aaa>(r, theta);
        que_action<&Object::bbb>(r, theta);
    }

};

int main()
{
    Object obj;
    obj.que_both_actions(5,3.14159/2.0);

    return 0;
}

Possible compiler bug in MSVC

The following code compiles with gcc and clang (and many other C++11 compilers)

#include <stdint.h>

typedef int datatype;

template <typename T>
struct to_datatype {};

template <>
struct to_datatype<int16_t> {
  static constexpr datatype value = 1;
};

template <typename T>
class data {
 public:
  data(datatype dt = to_datatype<T>::value) {}
};

int main() {
  data<char> d{to_datatype<int16_t>::value};
}

when compile with (almost) latest MSVC

> cl .\test.cpp /std:c++latest /permissive-
Microsoft (R) C/C++ Optimizing Compiler Version 19.24.28314 for x64
Copyright (C) Microsoft Corporation.  All rights reserved.

test.cpp
.\test.cpp(16): error C2039: 'value': is not a member of 'to_datatype<T>'
        with
        [
            T=char
        ]
.\test.cpp(16): note: see declaration of 'to_datatype<T>'
        with
        [
            T=char
        ]
.\test.cpp(20): note: see reference to class template instantiation 'data<char>' being compiled

Is this a bug of MSVC? If yes, which term in C++ standard best describe it?

If you replace part of the code with

template <typename T>
class data {
 public:
  data(datatype dt) {}
  data() : data(to_datatype<T>::value) {}
};

it compiles smoothly anyway.

std::async causes deadlock?

I was trying to use std::async in a heavy workload application to improve the performance but I encountered deadlock from time to time. I debugged for a very long time and I am almost certain that my code was fine and it seemed something wrong with std library.

So I wrote a simple test program to testify:

#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <future>
#include <string>
#include <mutex>
#include <unistd.h>
#include <atomic>
#include <iomanip>

std::atomic_long numbers[6];

void add(std::atomic_long& n)
{
    ++n;
}

void func2(std::atomic_long& n)
{
    for (auto i = 0L; i < 1000000000000L; ++i)
    {
        std::async(std::launch::async, [&] {add(n);});   // Small task, I want to run them simultaneously
    }
}

int main()
{
    std::vector<std::future<void>> results;
    for (int i = 0; i < 6; ++i)
    {
        auto& n = numbers[i];
        results.push_back(std::async(std::launch::async, [&n] {func2(n);}));
    }

    while (true)
    {
        sleep(1);
        for (int i = 0; i < 6; ++i)
            std::cout << std::setw(20) << numbers[i] << " ";
        std::cout << std::endl;
    }

    for (auto& r : results)
    {
        r.wait();
    }
    return 0;
}

This program will produce output like this:

              763700               779819               754005               763287               767713               748994 
              768822               785172               759678               769393               772956               754469 
              773529               789382               763524               772704               776398               757864 
              778560               794419               768580               777507               781542               762991 
              782056               795578               771704               780554               784865               766162 
              801633               812610               788111               802617               803661               784894 

After a time (minutes or hours), if there was a deadlock, the output will be like this:

             4435337              4452421              4507907              4501378              2549550              4462899 
             4441213              4457648              4514424              4506626              2549550              4468019 
             4446301              4462675              4519272              4511889              2549550              4473266 
             4453940              4470304              4526382              4519513              2549550              4480872 
             4461095              4477708              4533272              4526901              2549550              4488313 
             4470974              4488287              4543442              4537286              2549550              4498733 

The fifth column was frozen.

After one day, it became this:

            23934912             23967635             24007250             23931203              2549550           3249788689 
            23934912             23967635             24007250             23931203              2549550           3249816818 
            23934912             23967635             24007250             23931203              2549550           3249835009 
            23934912             23967635             24007250             23931203              2549550           3249860262 
            23934912             23967635             24007250             23931203              2549550           3249894331 

Almost all columns froze except last column. It look really odd.

I ran it on Linux, macOS, FreeBSD, and the result was:

  • macOS:10.15.2, Clang:11.0.0, no deadlock
  • FreeBSD:12.0, Clang:6.0.1, deadlock
  • Linux: ubuntu 5.0.0-37, g++:7.4.0, no deadlock
  • Linux: ubuntu 4.4.0-21, Clang:3.8.0, deadlock

In the gdb, the call stack was:

(gdb) thread apply all bt

Thread 10 (LWP 100467 of process 37763):
#0  0x000000080025c630 in ?? () from /lib/libthr.so.3
#1  0x0000000000000000 in ?? ()
Backtrace stopped: Cannot access memory at address 0x7fff4ad57000

Thread 9 (LWP 100464 of process 37763):
#0  0x000000080046fafa in _umtx_op () from /lib/libc.so.7
#1  0x0000000800264912 in ?? () from /lib/libthr.so.3
#2  0x000000080031f9f9 in std::__1::mutex::unlock() () from /usr/lib/libc++.so.1
#3  0x00000008002e8f55 in std::__1::__assoc_sub_state::set_value() () from /usr/lib/libc++.so.1
#4  0x00000000002053e1 in std::__1::__async_assoc_state<void, std::__1::__async_func<func2(std::__1::atomic<long>&)::$_0> >::__execute() ()
#5  0x0000000000205763 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<func2(std::__1::atomic<long>&)::$_0> >::*)(), std::__1::__async_assoc_state<void, std::__1::__async_func<func2(std::__1::atomic<long>&)::$_0> >*> >(void*) ()
#6  0x000000080025c776 in ?? () from /lib/libthr.so.3
#7  0x0000000000000000 in ?? ()
Backtrace stopped: Cannot access memory at address 0x7fff6944a000

Thread 8 (LWP 100431 of process 37763):
#0  0x000000080046fafa in _umtx_op () from /lib/libc.so.7
#1  0x0000000800264912 in ?? () from /lib/libthr.so.3
#2  0x000000080031f9f9 in std::__1::mutex::unlock() () from /usr/lib/libc++.so.1
#3  0x00000008002e8f55 in std::__1::__assoc_sub_state::set_value() () from /usr/lib/libc++.so.1
#4  0x00000000002053e1 in std::__1::__async_assoc_state<void, std::__1::__async_func<func2(std::__1::atomic<long>&)::$_0> >::__execute() ()
#5  0x0000000000205763 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<func2(std::__1::atomic<long>&)::$_0> >::*)(), std::__1::__async_assoc_state<void, std::__1::__async_func<func2(std::__1::atomic<long>&)::$_0> >*> >(void*) ()
#6  0x000000080025c776 in ?? () from /lib/libthr.so.3
#7  0x0000000000000000 in ?? ()
Backtrace stopped: Cannot access memory at address 0x7fffc371a000

Thread 7 (LWP 100657 of process 37763):
#0  0x000000080026a66c in ?? () from /lib/libthr.so.3
#1  0x000000080025e731 in ?? () from /lib/libthr.so.3
#2  0x0000000800268388 in ?? () from /lib/libthr.so.3
#3  0x000000080032de72 in std::__1::condition_variable::wait(std::__1::unique_lock<std::__1::mutex>&) () from /usr/lib/libc++.so.1
#4  0x00000008002e971b in std::__1::__assoc_sub_state::wait() () from /usr/lib/libc++.so.1
#5  0x0000000000205389 in std::__1::__async_assoc_state<void, std::__1::__async_func<func2(std::__1::atomic<long>&)::$_0> >::__on_zero_shared() ()
#6  0x000000000020346b in func2(std::__1::atomic<long>&) ()
#7  0x0000000000206f18 in main::$_1::operator()() const ()
#8  0x0000000000206eed in void std::__1::__async_func<main::$_1>::__execute<>(std::__1::__tuple_indices<>) ()
#9  0x0000000000206ea5 in std::__1::__async_func<main::$_1>::operator()() ()
#10 0x0000000000206df3 in std::__1::__async_assoc_state<void, std::__1::__async_func<main::$_1> >::__execute() ()
#11 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*) ()
#12 0x000000080025c776 in ?? () from /lib/libthr.so.3
#13 0x0000000000000000 in ?? ()
Backtrace stopped: Cannot access memory at address 0x7fffdf5f9000

Thread 6 (LWP 100656 of process 37763):
#0  0x000000080026a66c in ?? () from /lib/libthr.so.3
#1  0x000000080025e731 in ?? () from /lib/libthr.so.3
#2  0x0000000800268388 in ?? () from /lib/libthr.so.3
#3  0x000000080032de72 in std::__1::condition_variable::wait(std::__1::unique_lock<std::__1::mutex>&) () from /usr/lib/libc++.so.1
#4  0x00000008002e971b in std::__1::__assoc_sub_state::wait() () from /usr/lib/libc++.so.1
#5  0x0000000000205389 in std::__1::__async_assoc_state<void, std::__1::__async_func<func2(std::__1::atomic<long>&)::$_0> >::__on_zero_shared() ()
#6  0x0000000000207a22 in std::__1::__release_shared_count::operator()(std::__1::__shared_count*) ()
#7  0x00000000002044f4 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>&&) ()
#8  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&&) ()
#9  0x0000000000203462 in func2(std::__1::atomic<long>&) ()
#10 0x0000000000206f18 in main::$_1::operator()() const ()
#11 0x0000000000206eed in void std::__1::__async_func<main::$_1>::__execute<>(std::__1::__tuple_indices<>) ()
#12 0x0000000000206ea5 in std::__1::__async_func<main::$_1>::operator()() ()
#13 0x0000000000206df3 in std::__1::__async_assoc_state<void, std::__1::__async_func<main::$_1> >::__execute() ()
#14 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*) ()
#15 0x000000080025c776 in ?? () from /lib/libthr.so.3
#16 0x0000000000000000 in ?? ()
Backtrace stopped: Cannot access memory at address 0x7fffdf7fa000

Thread 5 (LWP 100655 of process 37763):
#0  0x000000080026a66c in ?? () from /lib/libthr.so.3
#1  0x000000080025e731 in ?? () from /lib/libthr.so.3
#2  0x0000000800268388 in ?? () from /lib/libthr.so.3
#3  0x000000080032de72 in std::__1::condition_variable::wait(std::__1::unique_lock<std::__1::mutex>&) () from /usr/lib/libc++.so.1
#4  0x00000008002e971b in std::__1::__assoc_sub_state::wait() () from /usr/lib/libc++.so.1
#5  0x0000000000205389 in std::__1::__async_assoc_state<void, std::__1::__async_func<func2(std::__1::atomic<long>&)::$_0> >::__on_zero_shared() ()
#6  0x0000000000207a22 in std::__1::__release_shared_count::operator()(std::__1::__shared_count*) ()
#7  0x00000000002044f4 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>&&) ()
#8  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&&) ()
#9  0x0000000000203462 in func2(std::__1::atomic<long>&) ()
#10 0x0000000000206f18 in main::$_1::operator()() const ()
#11 0x0000000000206eed in void std::__1::__async_func<main::$_1>::__execute<>(std::__1::__tuple_indices<>) ()
#12 0x0000000000206ea5 in std::__1::__async_func<main::$_1>::operator()() ()
#13 0x0000000000206df3 in std::__1::__async_assoc_state<void, std::__1::__async_func<main::$_1> >::__execute() ()
#14 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*) ()
#15 0x000000080025c776 in ?? () from /lib/libthr.so.3
#16 0x0000000000000000 in ?? ()
Backtrace stopped: Cannot access memory at address 0x7fffdf9fb000

Thread 4 (LWP 100654 of process 37763):
#0  0x000000080026a66c in ?? () from /lib/libthr.so.3
#1  0x000000080025e731 in ?? () from /lib/libthr.so.3
#2  0x0000000800268388 in ?? () from /lib/libthr.so.3
#3  0x000000080032de72 in std::__1::condition_variable::wait(std::__1::unique_lock<std::__1::mutex>&) () from /usr/lib/libc++.so.1
#4  0x00000008002e971b in std::__1::__assoc_sub_state::wait() () from /usr/lib/libc++.so.1
#5  0x0000000000205389 in std::__1::__async_assoc_state<void, std::__1::__async_func<func2(std::__1::atomic<long>&)::$_0> >::__on_zero_shared() ()
#6  0x0000000000207a22 in std::__1::__release_shared_count::operator()(std::__1::__shared_count*) ()
#7  0x00000000002044f4 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>&&) ()
#8  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&&) ()
#9  0x0000000000203462 in func2(std::__1::atomic<long>&) ()
#10 0x0000000000206f18 in main::$_1::operator()() const ()
#11 0x0000000000206eed in void std::__1::__async_func<main::$_1>::__execute<>(std::__1::__tuple_indices<>) ()
#12 0x0000000000206ea5 in std::__1::__async_func<main::$_1>::operator()() ()
#13 0x0000000000206df3 in std::__1::__async_assoc_state<void, std::__1::__async_func<main::$_1> >::__execute() ()
#14 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*) ()
#15 0x000000080025c776 in ?? () from /lib/libthr.so.3
#16 0x0000000000000000 in ?? ()
Backtrace stopped: Cannot access memory at address 0x7fffdfbfc000

Thread 3 (LWP 100653 of process 37763):
#0  0x000000080026a66c in ?? () from /lib/libthr.so.3
#1  0x000000080025e731 in ?? () from /lib/libthr.so.3
#2  0x0000000800268388 in ?? () from /lib/libthr.so.3
#3  0x000000080032de72 in std::__1::condition_variable::wait(std::__1::unique_lock<std::__1::mutex>&) () from /usr/lib/libc++.so.1
#4  0x00000008002e971b in std::__1::__assoc_sub_state::wait() () from /usr/lib/libc++.so.1
#5  0x0000000000205389 in std::__1::__async_assoc_state<void, std::__1::__async_func<func2(std::__1::atomic<long>&)::$_0> >::__on_zero_shared() ()
#6  0x0000000000207a22 in std::__1::__release_shared_count::operator()(std::__1::__shared_count*) ()
#7  0x00000000002044f4 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>&&) ()
#8  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&&) ()
#9  0x0000000000203462 in func2(std::__1::atomic<long>&) ()
#10 0x0000000000206f18 in main::$_1::operator()() const ()
#11 0x0000000000206eed in void std::__1::__async_func<main::$_1>::__execute<>(std::__1::__tuple_indices<>) ()
#12 0x0000000000206ea5 in std::__1::__async_func<main::$_1>::operator()() ()
#13 0x0000000000206df3 in std::__1::__async_assoc_state<void, std::__1::__async_func<main::$_1> >::__execute() ()
#14 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*) ()
#15 0x000000080025c776 in ?? () from /lib/libthr.so.3
#16 0x0000000000000000 in ?? ()
Backtrace stopped: Cannot access memory at address 0x7fffdfdfd000

Thread 2 (LWP 100652 of process 37763):
#0  0x000000080026a66c in ?? () from /lib/libthr.so.3
#1  0x000000080025e731 in ?? () from /lib/libthr.so.3
#2  0x0000000800268388 in ?? () from /lib/libthr.so.3
#3  0x000000080032de72 in std::__1::condition_variable::wait(std::__1::unique_lock<std::__1::mutex>&) () from /usr/lib/libc++.so.1
#4  0x00000008002e971b in std::__1::__assoc_sub_state::wait() () from /usr/lib/libc++.so.1
#5  0x0000000000205389 in std::__1::__async_assoc_state<void, std::__1::__async_func<func2(std::__1::atomic<long>&)::$_0> >::__on_zero_shared() ()
#6  0x0000000000207a22 in std::__1::__release_shared_count::operator()(std::__1::__shared_count*) ()
#7  0x00000000002044f4 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>&&) ()
#8  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&&) ()
#9  0x0000000000203462 in func2(std::__1::atomic<long>&) ()
#10 0x0000000000206f18 in main::$_1::operator()() const ()
#11 0x0000000000206eed in void std::__1::__async_func<main::$_1>::__execute<>(std::__1::__tuple_indices<>) ()
#12 0x0000000000206ea5 in std::__1::__async_func<main::$_1>::operator()() ()
#13 0x0000000000206df3 in std::__1::__async_assoc_state<void, std::__1::__async_func<main::$_1> >::__execute() ()
#14 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*) ()
#15 0x000000080025c776 in ?? () from /lib/libthr.so.3
#16 0x0000000000000000 in ?? ()
Backtrace stopped: Cannot access memory at address 0x7fffdfffe000

Thread 1 (LWP 100148 of process 37763):
#0  0x00000008004f984a in _nanosleep () from /lib/libc.so.7
#1  0x000000080025f17c in ?? () from /lib/libthr.so.3
#2  0x000000080045fe0b in sleep () from /lib/libc.so.7
#3  0x0000000000203b7b in main ()

It seems lots of threads got stuck on std::__1::condition_variable::wait, which is unreasonable, in the test code, there is no use of any condition at all.

Can somebody tell me, am I doing it wrong or there is a bug in the std library?

Why is min_element() returning the index of the minimum element in the following

min_element is supposed to return a pointer pointing to the minimum element in a array or vector but here why is it returning a position of the element with minimum value.

int n; cin>>n;
vector<int> arr(n);
for(int i=0;i<n;i++)
    cin>>arr[i];

int minElementIndex = min_element(arr.begin(),arr.end()) - arr.begin();
cout<<minElementIndex;

How to improve vector insert time

I have CSV file. Which contain the 1086098 lines of logs. I have written c++ code. where i search for some text and based on founding i report the issues to the respective owner.

Implementation Details

  1. Load all the file logs to std::vector.

  2. Search in the vector at run time.

Problem : push_back in the std::vector takes 1683087 ms time. How can i improve on this time. Any other suggestion is welcome.

std::vector<std::string> complete_log;

bool LoadFileToVector(const std::string& str) {
  std::string needle = str;
  std::ifstream fin(needle.c_str());
  std::string line;
  bool found = false;

  if (fin.is_open()) {
    if (!is_empty(fin)) {
      fin.exceptions(std::ifstream::badbit);

      try {
        while (getline(fin, line)) {
          complete_log.push_back(line);

        }

        for (const auto& text : start_check) {

          found = false;
          for (auto elem : complete_log) {
            if (elem.find(text) != std::string::npos) {
              basic_result[text] = true;
              found = true;
            }
          }
          if (!found)
            basic_result[text] = false;
        }

      } catch (std::ifstream::failure& FileExcep) {
        std::cout << "Caught an exception = " << FileExcep.what() << std::endl;
        fin.close();
        return false;
      } catch (...) {
        std::cout << "Unkown Exception/n";
      }
    } else {
      std::cout << "Input file "<<needle<<" is Empty" << std::endl;
      fin.close();
      return false;
    }

    fin.close();
    return true;
  } else {
    std::cout << "Cannot open file to update map" << std::endl;
    return false;
  }
  return true;
}

Not able to to do set element insertion inside constructor

I am getting compilation error while inserting values inside constructor Monitor counstructor. Could you suggest what could be approach for the same as I need to populate this vector during class instantiation. It works fine with below approach but I don't want to populate the vector separately.

   vect1.insert( make_pair(10,20) );
   vect1.insert( make_pair(30,49) );
   vect1.insert( make_pair(50,60) );
   vect1.insert( make_pair(70,80) );

below is the code snippet

  #include <iostream>
  #include <vector>
  #include<algorithm>
  #include<memory>
  #include <set>
  using namespace std;
  class Monitor
  {
  public:
  virtual ~Monitor() = default;
  explicit Monitor(
  const set< pair <double,double> > &vect1
  )
  {  

     for (auto &itr : vect1 ) 
      { 
         std::cout<<"value1 ="<<itr.first<<endl;
         std::cout<<"value2="<<itr.second<<endl;
      }       
  }

 };

int main()
{  set< pair <double,double> > vect1;
   Monitor obj (vect1.insert( make_pair(10,20) ));

 return 0;   
}

compilation error

error: no matching function for call to ‘Monitor::Monitor(std::pair >, bool>)’
    Monitor obj (vect1.insert( make_pair(10,20) ));

Auto return type matching void

Is this code legal? It compiles but I'm wondering what happens with the return value. Undefined behavior?

class Foo {
public:
    void test1() {

    }
    auto test() -> decltype(test1()) {
        return test1(); //<---return void here!
    }
};

16-bit integer in preparedstatement cppconn

I have column in MySQL table which is of type Smallint. I want to insert a row in the table in C++ using cppconn. I am using PreparedStatement. I cannot find an api like setInt16 or setShort. It is throwing error with code 1264 if I use setInt with 16-bit integer. Is there any way of doing it?

Column A -> Int auto_increment
Column B -> SmallInt


sql::PreparedStatement *insert_stmt = m_con->prepareStatement("INSERT INTO MyTable VALUES (?)");
int16_t x = 10;
insert_stmt->setInt(1, x);
insert_stmt->execute();

It is showing the following error :-

Out of range value for column 'B' at row 1 (MySQL error code: 1264, SQLState: 22003 )

lundi 30 décembre 2019

Why a enum variable is a rvalue here?

I make a sample code below:

typedef enum Color
{
    RED,
    GREEN,
    BLUE
} Color;

void func(unsigned int& num)
{
    num++;
}

int main()
{
    Color clr = RED;
    func(clr);
    return 0;
}

I get following error when I compile it:

<source>: In function 'int main()':

<source>:16:9: error: cannot bind non-const lvalue reference of type 'unsigned int&' to an rvalue of type 'unsigned int'

     func(clr);

         ^~~

I think, the variable (clr) I pass to func(unsigned int&) is a lvalue, I can get the address of clr and can assign another value to it. Why it turns into an rvalue when I try to pass it to func(unsigned int&)?

A code using pointer to function does not compile

I have used two templates in my code and a pointer to one of the template instantiate. But it doesn't compile. Can I know where is the problem?

template<typename T>
bool matcher(const T& v1, const T& v2)
{
    if (v1 == v2) return true;
    return false;
}

template<typename T1>
void compare(const T1* str1, const T1* str2, size_t size_m, bool(*)(const T1&, const T1&) func)
{
    for (size_t count{}; count < size_m; count++)
        if (func(str1[count], str2[count]))
            std::cout << "Mach at index of " << count << " is found\n";
}

int main()
{
    compare("888888", "98887", 4, &matcher<char>);
    return 0;
}

I know, I should be using std::function but I want to try this.

c++ standard library cheat sheets and resources [closed]

  1. I'm looking for new and updated c++ cheat sheets that support the latest c++ standards.
  2. Please share your methods/approaches on how you use c++ resources while coding .

Initialize a 2d array with unknown first dimension size in C++

Say I need a 2d array, first dimension size set at runtime, and second dimension size is set to 5 at compilation time.

Since we can do this to initialize a 1d array with unknown size

int* arr;
arr = new int[5];

I would like to make the following code work

int* arr[5];
arr = new int[12][5];

Notice:

I need the second dimension set to 5, not first dimension. So I need to be able to do arr[12][5] but not arr[5][12].

I know I can make arr an int** and then assign a 2d array to arr, so please avoid such answer.

I know I can use STL containers such as vector, so please avoid such answer.

How do you specialise a templated function with a templated class?

So i have a templated function:

template<typename T>
int func(const T& input){
  //do stuff
}

And I'd like to specialise it with a templated class(like std::vector) So like this:

template<typename T>
int func(const std::vector<T>& input){
  //do specialised stuff
}

But I don't know how exactly you do it. Thanks!

simple code outputting cell values gives a runtime SIGABRT error in C++

I have implemented a simple code which simulates cell life. For some cases it works fine, but for others, it gives a SIGABRT out of range error in line 72(as highlighted). The code essentially takes a vector of cell numbers as input. Then it creates two new vectors, celllife and time vectors, in which it stores the lifetime of the cell and the time elapsed to compare the cell's life. For example, if cell life vectors are

{2, 3, 4, 1, 2}

and time vector's element's are:

{0, 1, 2, 0, 1}

it means that cell 1 has a lifetime of 2 but 0 seconds have elasped for it, and so on. The program prints the total number of cells each second, and terminates when all the cells die i.e the time vector values are more than celllife values. the expected output should look something like this:

[Main] Input gene seeds: 2 10 18 26 34 66
Monitor: Total cells: 0 [0 s]
Monitor: Total cells: 6 [1 s]
Monitor: Total cells: 24 [2 s]
Monitor: Total cells: 18 [3 s]
Monitor: Total cells: 0 [4 s]

but because of the error, it only reaches till the second-last line:

[Main] Input gene seeds: 2 10 18 26 34 66
Monitor: Total cells: 0 [0 s]
Monitor: Total cells: 6 [1 s]
Monitor: Total cells: 24 [2 s]
Monitor: Total cells: 18 [3 s]

Any suggestions for fixing the error will be greatly appreciated!

// code
#include <iostream>
#include <bits/stdc++.h> 
#include <thread>
#include <string>
#include <sstream>
#include<vector>
#include <chrono>
#include <mutex>
#include <stdlib.h>
using namespace std;
vector<int> inputs;
vector<thread> threads;
vector<int>childcells;
vector<int>celllife;
vector<int>cellvalues;
vector<int> timevector;
int laststrike= 0;
int newcell_lifetime;
//int counter;
int counter= 0;
int sum;
int main()
{   
    cout<<"[Main] Please input a list of gene seeds: "<<endl;
    //we get a line as string and pass them into the vector 'inputs'
    int value;
    string line;
    getline(cin, line);
    istringstream iss(line);
    while(iss >> value){

       inputs.push_back(value);
    }

    int total=0;
    int timer= 0;
    bool happening = true;
    cout<<"[Monitor] Started [ 0 s ]"<<endl;  //intial value of total cells
    while(happening == true){//this runs until the total value reaches zero
        int j=0;

        for (int unsigned  i = 0; i < inputs.size(); i++) {
            //traverses through every element in vector
            //the following are computations for calculating variables 'lifetime' and 
 'halflife' 
            int lifetime = (0.1+(inputs.at(i)%8));
            if (timer >= lifetime ){


                inputs.erase(inputs.begin() + i);

                i--;
                continue;
            }
            j=j+1;

            int halflife= lifetime/2;
                if (timer == halflife ){
                int newcell = inputs.at(i)/ 8;
                if(newcell != 0){
                //newcells=newcells+ newcell;
                childcells.push_back(newcell);
                celllife.push_back(lifetime);
                timevector.push_back(0);

                }//if halflife equals timer, the code inserts the new cell into the childcells vector and inserts a 0 value into the time vector
            }


        }



        int count=0;
        vector<int>::iterator it;
        for(it = celllife.begin(); it != celllife.end(); it++,count++ ){

                if (celllife.at(count) == timevector.at(count)) { //this is the line with the SIGABRT error
                    timevector.erase(timevector.begin() + count);
                    celllife.erase(celllife.begin() + count);
                    childcells.erase(childcells.begin() + count);

            }

            }
        counter++;
        sum= accumulate(childcells.begin(), childcells.end(), 0); 

        total=j+sum;

        timer=timer+1;
         cout<<"[Monitor] Total cells "<<total<<" [ " <<int(timer) <<" s ]"<<endl;

        for (int unsigned  k = 0;  k< timevector.size(); k++) {
            timevector.at(k)++;

        }//after one second, all timevector values are incremented
        if(total == 0){

            happening = false;
        }

    }

    return 0;

}

How can I prevent C++ for guessing a second template argument?

I'm using a C++ library (strf) which, somewhere within it, has the following code:

namespace strf {
template <typename ForwardIt, typename CharT>
inline auto range(ForwardIt begin, ForwardIt end, const CharT* sep) { /* ... */ }

template <typename Range, typename CharT>
inline auto range(const Range& range, const CharT* sep) { /* ... */ }
}

Now, I want to use strf::range<const char*>(some_char_ptr, some_char_ptr + some_length) in my code. But if I do so, I get the following error (with CUDA 10.1's NVCC):

error: more than one instance of overloaded function "strf::range" matches the argument list:
            function template "auto strf::range(ForwardIt, ForwardIt)"
            function template "auto strf::range(const Range &, const CharT *)"
            argument types are: (util::constexpr_string::const_iterator, util::constexpr_string::const_iterator)

I realize that the library code can probably be changed to avoid this (perhaps an std::enable_if to ensure Range is not a pointer?) ; but I can't change that. Instead, I want to somehow indicate to the compiler that I really really mean to only have one template argument, not one specified and another one deduced.

Can I do so?

Would appreciate answers for C++11 and C++14; C++17 answers involving deduction guides are less relevant but if you have one, please post it (for future NVCC versions...)

How to obtain the URL of re-directed webpage in C++

I did write a c++ code which automatically parses a webpage and open and parse some of their links. The point is that in these webpage there are some addresses which were redirected to other webpages. For example, when I try to open:

https://atlas.immobilienscout24.de/property-by-address?districtId=1276001006014

I ended up opening:

https://atlas.immobilienscout24.de/orte/deutschland/baden-württemberg/böblingen-kreis/leonberg

How could I get the url of the second page in C++?

I need to change the main program, because I want input from the user how can I do it?

#include <iostream> 
using namespace std; 

const int MAX = 100; 
  \\ Fills transpose of mat[N][N] in tr[N][N] 
void transpose(int mat[][MAX], int tr[][MAX], int N) 
{ 
    for (int i = 0; i < N; i++) 
        for (int j = 0; j < N; j++) 
            tr[i][j] = mat[j][i]; 
} 

// Returns true if mat[N][N] is symmetric, else false 
bool isSymmetric(int mat[][MAX], int N) 
{ 
    int tr[N][MAX]; 
    transpose(mat, tr, N); 
    for (int i = 0; i < N; i++) 
        for (int j = 0; j < N; j++) 
            if (mat[i][j] != tr[i][j]) 
                return false; 
    return true; 
} 

// Driver code 
int main() 
{ 
    int mat[][MAX] = { { 1, 3, 5 },  // I need to replace this with a cin //command
                       { 3, 2, 4 }, 
                       { 5, 4, 1 } }; 

    if (isSymmetric(mat, 3)) 
        cout << "Yes"; 
    else
        cout << "No"; 
    return 0; 
}

The code is to find out if the matrix is symmetric or not, but I'm confused how can I read the input from user and not from the code. I've did a simple solution basically I've created the transpose of given matrix and then i checked if transpose and given matrices are same or not. 1) Create transpose of given matrix. 2) Check if transpose and given matrices are same or not

NAMESPACE ERROR '... not a namespace-name'

I started learning c++ and have namespace exercise I have some problem with namspaces

These are three files:

dane3.h

using namespace std;
namespace xddd
{
   const int QUARTERS = 4;
   struct Sales
   {
    double sales[QUARTERS];
    double average;
    double Max;
    double Min;
   };

   void setSales(Sales & s, const double ar[], int n);
   void showSales(const Sales & s);
}

dane2.cpp

using namespace std;
#include <iostream>

#include "dane3.h"
namespace xddd
{
void setSales(Sales & s, const double ar[], int n)
{
int point1 = ar[0];
int point2 = ar[0];
int point3 = 0;

for(int i=1;i < n;i++){
    if(point1 > ar[i])
        point1 = ar[1];}

for(int i=1;i < n;i++){
    if(point2 < ar[i])
        point2 = ar[1];}

for(int i=0;i < n;i++)
    point3 += ar[i];

s.average = point3;
s.Max = point2;
s.Min = point1;
}

void showSales(const Sales & s)
{
cout << s.average << "\n";
cout << s.Max << "\n";
cout << s.Min;
}
}

main.cpp

#include <iostream>
using namespace std;
#include "dane3.h"
using namespace xddd;
int main()
{
    Sales a;
    double table[4] = {10,20,30,40};
    setSales(a,table,QUARTERS);
    showSales(a);
}

I get the error:

 'xddd' is not a namespace-name

I think that error is very simple, but i dont know how to figure it BTW sorry for my english if I made some mistakes :D

Compile time text to number translation (atoi)

I want to implement atoi() function at compile time (in C++ language, by using C++11 or C++14 standard). So it should be able to parse text enclosed in double quotes as number, or repor an error. More specifically, it is a part of bigger system, which is able to parse printf-like format at compile time. And I want to split format strings on words and if some particular word can be represented by number -- output number instead of the string (behind the scene is serializer class, which can serialize numbers more effectively, than the strings, and which is more important, deserializer then not should try to parse every string as a number, because all numebers printed inside format string is always represented as numbers, but not as strings)...

As I know two there can be two approaches to solve the task:

1) by using constexpr functions;

2) by template metaprogramming.

Which way can be better? I have tried first way, and I can see there is many obstacles in this way: especially few limitations related to c++11. Looks like second might be preferable, but it requires some tricks (you need to split c-string to separate chars by using of operator"", which supported in gcc starting from c++14, and in clangs starting from c++11). Also solution based completely on TMP might be too large and too tangled.

Below is my solution, I glad to hear some suggestions about it.

http://coliru.stacked-crooked.com/a/0b8f1fae9d9b714b


#include <stdio.h>

template <typename T> struct Result
{
    T value;
    bool valid;

    constexpr Result(T v) : value(v), valid(true) {}
    constexpr Result() : value(), valid(false) {}
};

template <typename T>
constexpr Result<T> _atoi_oct(const char *s, size_t n, T val, int sign)
{
    return n == 0 ? Result<T>(sign < 0 ? -val : val)
        : *s >= '0' && *s <= '7' 
            ? _atoi_oct(s+1, n-1, val*T(010) + *s - '0', sign)
            : Result<T>();
}

template <typename T>
constexpr Result<T> _atoi_dec(const char *s, size_t n, T val, int sign)
{
    return n == 0 ? Result<T>(sign < 0 ? -val : val)
        : *s >= '0' && *s <= '9'
            ? _atoi_dec(s+1, n-1, val*T(10) + *s - '0', sign)
            : Result<T>();
}

template <typename T>
constexpr Result<T> _atoi_hex(const char *s, size_t n, T val, int sign)
{
    return n == 0 ? Result<T>(sign < 0 ? -val : val)
        : *s >= '0' && *s <= '9'
            ? _atoi_hex(s+1, n-1, val*T(0x10) + *s - '0', sign)
            : *s >= 'a' && *s <= 'f'
                ? _atoi_hex(s+1, n-1, val*T(0x10) + *s - 'a' + 10, sign)
                : *s >= 'A' && *s <= 'F'
                    ? _atoi_hex(s+1, n-1, val*T(0x10) + *s - 'A' + 10, sign)
                    : Result<T>();
}

template <typename T>
constexpr Result<T> _atoi_zero(const char *s, size_t n, int sign = 1)
{
    return n == 0 ? Result<T>()
        : *s >= '0' && *s <= '7'
            ? _atoi_oct(s+1, n-1, T(*s - '0'), sign)
            : *s == 'x' || *s == 'X'
                ? _atoi_hex(s+1, n-1, T(0), sign)
                : Result<T>();
}

template <typename T>
constexpr Result<T> _atoi_sign(const char *s, size_t n, int sign = 1)
{
    return n == 0 ? Result<T>()
        : *s == '0'
            ? _atoi_zero<T>(s+1, n-1, sign)
            : *s > '0' && *s <= '9'
                ? _atoi_dec(s+1, n-1, T(*s - '0'), sign)
                : Result<T>();
}

template <typename T>
constexpr Result<T> _atoi_space(const char *s, size_t n)
{
    return n == 0 ? Result<T>()
        : (*s == ' ' || *s == '\t' || *s == '\n' || *s == '\r' || *s == '\v')
            ? _atoi_space<T>(s+1, n-1)
            : *s == '-'
                ? _atoi_sign<T>(s+1, n-1, -1)
                : *s == '+'
                    ? _atoi_sign<T>(s+1, n-1)
                    : *s == '0'
                        ? _atoi_zero<T>(s+1, n-1)
                        : _atoi_dec(s, n, T(0), 1);
}

template <size_t N> void pstr(const char (&s)[N])
{
    printf("s '%.*s'\n", int(N-1), s);
}

template <typename Str>
__attribute__((always_inline))
void _atoi(Str s)
{
    constexpr auto result = _atoi_space<long>(s.cstr(), sizeof(s.cstr())-1);
    if (result.valid)
        printf("i %ld\n", result.value);
    else
        pstr(reinterpret_cast<const char (&)[sizeof(s.cstr())]>(s.cstr()));
}

#define atoi(STR) _atoi([]() { \
                        struct S { \
                            static constexpr const char (&cstr())[sizeof(STR)] { return STR; } \
                        }; \
                        return S();  \
                    }())

int main()
{
    atoi("42");
    atoi("-1");
    atoi("+1");
    atoi("010");
    atoi("-0x10");
    atoi("--1");
    atoi("x");
    atoi("3x");
    return 0;   
}

Basically I want to ask, how can I transform at compile time number (like "42") written in double quotes in the value of integral type. My solution look too cumbersome.

Best practice for will-move-from parameters

According to the core guidelines:

F.18: For “will-move-from” parameters, pass by X&& and std::move the parameter

The example is:

void sink(vector<int>&& v) {   // sink takes ownership of whatever the argument owned
    // usually there might be const accesses of v here
    store_somewhere(std::move(v));
    // usually no more use of v here; it is moved-from
}

I noticed that I tend to use smart pointers for all objects except cheaply-copied (which I almost always consider only primitives). So I almost always use the following guidelines:

void sink(std::unique_ptr<OtherThanPrimitive> p) {
    // use p ... possibly std::move(p) onward somewhere else
}   // p gets destroyed

I started to consider if I use best practice. What I can think of as advantage of the first approach is forcing caller of a function to explicitly std::move and it makes code cleaner. In the second approach move constructor will be called two times, but for smart pointer it's not a big cost. Considering above I started to think about changing my habit to use the first approach always for collections that I am sure that support moving (so most of STL collections). Second approach for custom objects (I assume that cost of considering writing custom move constructor for a class outstrips the profit of readability). Is there any best practice that covers that? What approach do you usually apply? Am I missing something in my justification?

Static specialized template members in C++17 - why there is difference between GCC and MSVC?

My question is about template static members not not about template static functions.

Prior to C++17, when building with GCC and having includes in several CPP files, to avoid "multiple definitions" linker errors of static specialized template members similarly to static functions, they have to be either defined as inline or defined in CPP files (see this).

I have reasons not to define static template members in CPP files so I have to use inline. But to do this I have to switch in both GCC and VS2017 to C++17 because static template inline functions are allowed after C++11 but static template inline members are allowed only after C++17.

But this whole problem does not exist at all in MSVC. This is demonstrated below:


ClassT.h:

template <typename T>
class ClassT
{
public:
    static const T  CC;     
};

template<> const char ClassT<char>::CC = '\\';


Main.cpp:

#include "ClassT.h"

int main()
{
    return 0;
}


Test.cpp:

#include "ClassT.h"

This will compile and links without warnings in MSVC but will not compile with GCC giving linker error: "multiple definition of `ClassT::CC'.

MSVC linker figures out that there is more than one definition and takes only one of them while GCC obviously fails to do this. To solve it for GCC one have to add inline:

template <typename T>
class ClassT
{
public:
    inline static const T  CC;     
};

template<> inline const char ClassT<char>::CC = '\\';

Which however forces to switch to C++17 otherwise will not compile with MSVC.

I wonder which one is correct and according to specification in this case GCC or MSVC linker and how exactly the latter resolves such static members without the inline definition?

The argument of the nan() function

Sometimes there is a need to get NaN value (for example, to return it from a function as an error value). С++11 provides the double nan(const char* tagp); function to get NaN see doc. This function gets C-string argument tagp which:

can be used by library implementations to distinguish different NaN values in a implementation-specific manner. If this is an empty string (""), the function returns a generic NaN value

I want to understand this function more deeply. Could someone explain in more detail

  1. What tagp values can be used besides empty string ""? Where can I find a list of possible values?
  2. What happens if the passed tagp argument is not supported by the compiler?
  3. Is it safe to use this implementation-specific function in cross-platform code?

How to split a string based on a char

I can get a substring from the following line

 string filename = C:\Shaders\Test\Model\source\scene.fbx"
 filename.substr( 0 , filename.find_last_of('\') );

this would be the result

  C:\Shaders\Test\Model\source

Now if i want to get the sub string from the last "\" to the end of the string that would be

   scene.fbx 

i am trying this line.

 filename.substr(filename.find_last_of('\'), filename.size() )

but i get a crash.

Problem in choosing best available GPU using openCL programatically

I'm using the advice given here for choosing an optimal GPU for my algorithm. https://stackoverflow.com/a/33488953/5371117

I query the devices on my MacBook Pro using boost::compute::system::devices(); which returns me following list of devices.

Intel(R) Core(TM) i7-8850H CPU @ 2.60GHz
Intel(R) UHD Graphics 630
AMD Radeon Pro 560X Compute Engine

I want to use AMD Radeon Pro 560X Compute Engine for my purpose but when I iterate to find the device with maximum rating = CL_DEVICE_MAX_CLOCK_FREQUENCY * CL_DEVICE_MAX_COMPUTE_UNITS. I get the following results:

Intel(R) Core(TM) i7-8850H CPU @ 2.60GHz, 
freq: 2600, compute units: 12, rating:31200

Intel(R) UHD Graphics 630, 
freq: 1150, units: 24, rating:27600

AMD Radeon Pro 560X Compute Engine, 
freq: 300, units: 16, rating:4800

AMD GPU has the lowest rating. Also I looked into the specs and it seems to me that CL_DEVICE_MAX_CLOCK_FREQUENCY isn't returning correct value.

According to AMD Chip specs https://www.amd.com/en/products/graphics/radeon-rx-560x, my AMD GPU has base frequency of 1175 MHz, not 300MHz.

According to Intel Chip specs https://en.wikichip.org/wiki/intel/uhd_graphics/630, my Intel GPU has base frequency of 300 MHz, not 1150MHz, but it does have a boost frequency of 1150MHz

std::vector<boost::compute::device> devices = boost::compute::system::devices();

std::pair<boost::compute::device, ai::int64> suitableDevice{};

for(auto& device: devices)
{
    auto rating = device.clock_frequency() * device.compute_units();
    std::cout << device.name() << ", freq: " << device.clock_frequency() << ", units: " << device.compute_units() << ", rating:" << rating << std::endl;
    if(suitableDevice.second < benchmark)
    {
        suitableDevice.first = device;
        suitableDevice.second = benchmark; 
     }
}      

Am I doing anything wrong?

Assign RepeatedPtrField to repeated field in a protobuf message

I have a RepeatedPtrField<M::Table> and a protobuf message M as:

message M {
  message Table {
    optional string guid = 1;
    optional int64 schema_version = 2;
    optional int64 data_version = 3;
    repeated Column column = 4;
  }
  repeated Table table = 1;
}

How to I create a instance of M having the contents of RepeatedPtrField. I can write a for loop to copy data explicitly, but I am currently looking for something more concise, preferably using std::move() like optimization.

dimanche 29 décembre 2019

Can anyone explain the shared_ptr implementation with all functionalities

I know the basics of shared_ptr and how does it works.But trying to implement the functionalities but facing the difficulty.

Can anyone explain the implementation or suggest any links that would be great helpful.

Thanks in advance.

Finding maximum and minimum numbers in a vector entered by user [closed]

I'm a beginner programmer...I'm trying to write a piece of code which does these actions in order:

  1. Asks the user how many numbers he/she wants to enter
  2. gets the numbers from input and store them in the vector using the .push_back method
  3. finding the max and min element using *max_element(vector.begin(), vector.end() and *min_element(vector.begin(), vector.end())

I've tried these methods and this is the error I get:

error: no match for 'operator<<' (operand types are 'std::vector<int>::iterator' {aka '__gnu_cxx::__normal_iterator<int*, std::vector<int> >'} and '<unresolved overloaded function type>')

And this is the piece of code I've written:

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

int main()
{
    int times{};
    int input{};
    cout << "How many numbers do you want to enter? ";
    cin >> times;
    vector <int> Data(times);
    cout << "Enter the numbers: ";
    for(int i{1}; i<=times; i++){
        cin >> input;
        Data.push_back(input);
    }
    cout << "Max = " << *max_element(Data.begin(), Data.end() << endl;
    cout << "Min = " << *min_element(Data.begin(), Data.end()) << endl;

    return 0;
}

I don't know what I've done wrong here...If anyone can help I would highly appreciate it...

How do I get CMake Tools to compile programs in Visual Studio Code with C++11 (or higher) features?

I'm new to CMake in general so hopefully there is something simple I'm doing wrong but I'm pulling my hair out trying to find the solution. I can't get CMake tools to compile even a trivial program with c++11 (or higher features). Ideally I'd like to enable c++17.

For example, if my entire main() function is

int main(int, char**) 
{
    auto number{9};

    return 0;
}

I get the following 2 errors and 1 warning when attempting a build:

error: declaration of variable 'number' with deduced type 'auto' requires an initializer

error: expected ';' at end of declaration

warning: 'auto' type specifier is a C++11 extension [-Wc++11-extensions]

My VSCode C++ settings are set to the C++17 standard, and I don't get any Intellisense errors or warnings when writing the code, just when I try to build using the CMake Tools extension.

I've also tried adding the following to my CMakeLists.txt file:

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

What am I missing? Thanks very much!

Platform and Versions

Operating System: macOS High Sierra 10.13.6

CMake Version: 3.16.2

VSCode Version: 1.41.1

CMake Tools Extension Version: 1.2.3

Compiler/Toolchain: Clang 10.0.0

Good implementation (JAVA or C++) of chan's Algorithm to find 2D convex hull (finite points)?

I'm not able to find any tutorial about the implementation of chan's algorithm in java Or C++. Please help me guys if you have any link or pdf.

Using swap vs assignment for out string parameter of a function

If we have a function which is supposed to populate the string value to its out parameter based on some calculation, then which one should we prefer to use and why?

void function(string& x)
{
    // In actual code, this value is calculated based on certain conditions
    string temp = "Stack Overflow";

    x.swap(temp);
}

Vs

void function(string& x)
{
    // In actual code, this value is calculated based on certain conditions
    string temp = "Stack Overflow";

    x = t;
}

How to print array which I use in a map?

Here is my code:

typedef array<int,6> Array;
Array dayHours{0,0,0,0,0,0};

I am using this data in here:

void Schedule::studentSchedule()
{
    string c, s;
    int courseNum;
    list<string>::iterator studentLoc;
    map<pair<string, int>, pair<string, Array> >::iterator location;

    cout << "Enter the student name" << endl;
    cin >> s;
    cout << "Enter how many course you want?" << endl;
    cin >> courseNum;
wrongCourse:
    cout << "Enter the course names you want" << endl;
    for (int i = 0; i < courseNum; ++i)
    {
        cin >> c;
        auto predicate = [&](auto& course) { return compareName(course, c); };
        studentLoc = find(getStudentList().begin(), getStudentList().end(), s);
        location = find_if(getMatchMap().begin(), getMatchMap().end(), predicate);
        map<pair<string, int>, pair<string, Array> >::iterator it;
        cout << "Student:\t\t" << "Course:\t\t" << "Course Day:\t\t" << "Course Hours:" << endl;
        if (studentLoc != getStudentList().end() && location != getMatchMap().end())
        {
            getCourseScList().insert({ make_pair(s,c),make_pair(getDay1()[i],getDayHours()) });
        }
        else
        {
            cout << "The course you're writing isn't available.Please enter existed courses!" << endl;
            goto wrongCourse;
        }
    }
}

I am sending the array to the map here:

if (studentLoc != getStudentList().end() && location != getMatchMap().end())
{
    getCourseScList().insert({ make_pair(s,c),make_pair(getDay1()[i],getDayHours())});
}

The question is how can I reach the array element:

map< pair<string, string>, pair<string, Array> >::iterator last;
for (last = getCourseScList().begin(); last != getCourseScList().end(); ++last)
{
    cout << (last->first).first << "\t\t\t\t"
         << (last->first).second
         << "\t\t" << (last->second).first
         << (last->second).second << endl;
}

The (last->second).second is representing my array but I can not print this to screen. What can I do?

samedi 28 décembre 2019

How to create a 2D array in C++?

OK, this question seems to be silly but bear with me. When I trying to create a 2D array in C++, it gave me a warning (len is an integer):

double a[len][len];
// warning: variable length arrays are a C99 feature
// warning: variable length array used

So I tried another:

double **a = new double[len][len];
// error: only the first dimension of an allocated array may have dynamic size
// read of non-const variable 'len' is not allowed in a constant expression

How can I do it correctly?

Is there any way to change function prototypes at compile time in C++?

suppose you have to write code that should compile under C++,C++11,C++17,etc.

A function like this for example.

bool Ispalindrome(const std::string &str) 
{ 
   // Code 
}

That compiles under all C++ implementations. But if you want to use the old and the new the C++17 string_view feature you have deal with something similar to

#ifdef LEGACYCPP
   bool Ispalindrome(const std::string &str) 
  { 
     // Code 
  }
#elseif CPP17
  bool Ispalindrome(std::string_view str) 
  { 
     // OMG Repeated Code 
  }
#endif

Using conditional compiling is right, but have to repeat code.

Is there any way to choose a function prototype at compile time ? Or other way to circumvent double coding ? (in situations where it can be applied)

Thanks

C++ My code doesn't work I don't know the reason

I need help with this code. I don't know why my program doesn't work as it should and only the first sentence "Please enter ten integers for fill the Array" was printed repetitively.This is what I get.

Please enter ten integers for fill the Array: 12345678910 Please enter ten integers for fill the Array: Please enter ten integers for fill the Array: Please enter ten integers for fill the Array:

I've changed the code and the brackets and the program does not work for me. I don't have much experience programming and I don't find the problem with my code. Here is the code.

//This program transpose an array and create a vector with even elements of the array.
//This program define a function called fillArray to fill a one-dimensional array with ten integers entered by user.
//A function called printArray to print an array and a function called transpose to transpose the array entered by user.
//Even elements of transpose array should are copied in a vector.


#include <iostream>
#include <vector>

using namespace std;

int main()

{

    void fillArray(); // Function to fill the array with integers entered by user.

    {
        int Array[10];
        int i;

        for (i = 0; i < 10; i++) // loop for the numbers entered by the user.

        {
            cout << "Please enter ten integers for fill the Array: " << endl; //This ask the user for the numbers of the array
            cin >> Array[i];
        }
        cout << endl;

    }

}

void printArray(int Array[]) // Function that prints the array.

{
    int i;
    {

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

        {
            cout << " Original Array: ";

            cout << Array[i] << " ";
            cout << endl;
        }
    }

    void transpose(int Array[]); //Function to transpose array.

    {
        {

            int i; //For the numbers entered by user.
            int j = 9; //
            int ArrayJ;// For transpose Array with integers entered by user.

            for (i = 0; i < 5; i++)

            {
                ArrayJ = Array[i];
                Array[i] = Array[j];
                Array[j] = ArrayJ;
                ArrayJ--;
            }
        }

        vector<int> vector(Array, Array + 10); // Vector for even elements of the Array.

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

        {
            if (Array[i] % 2 == 0) //Condition for even numbers.
            {
                vector.push_back(Array[i]);
            }

            //Prints even numbers

            cout << "Even Vector:";
            for (i = 0; i < 5; i++)

            {
                cout << Array[i] << " ";
            }
            cout << "/n";
        }

    }

}

I can't assign a value to a 2d array

So this is my first attempt to write a program using classes in c++. As an exercise, I'm trying to create a 2d-array class that can do certain things. This is a part of the code in the main.cpp that my class has to be able to run.

int main()
{
    array2d<double> ar(2,2);

    ar(1,1) = 1; 
    ar(0,0) = 2;
    ar(0,1) = 3;
    ar(1,0) = 4;

    auto X{ar};

    array2d<double> c(2,2);
    c = ar;
    c.diagonal(1) = 5; //c(1,1) = 5 
}

And this is my code. I'm getting an error in the diagonal function "error: lvalue required as left operand of assignment". I can't figure out what I should do. The purpose of this function is to assign values in the diagonal elements of the array.

template<typename T>
class array2d
{
private:
    int n,m;
    vector<T> vec;

public:
    array2d(int M, int N)
    : n{N}, m{M}
    {
        vector<T> vec1(n*m);
        vec = vec1;
    }

    array2d(array2d<T> &arr)
    : n{arr.N()} , m{arr.M()}
    {
        vec = arr.V();
    }

    array2d &operator=(array2d<T>  & arr){
        vec = arr.V();
        return *this;
    }

    T &operator()(int i,int j)
    {
        auto it = vec.begin();
        it += i*n+j;
        return *it;
    }  

    T diagonal(int a)
    {
        auto x= *this;
        return x(a,a);
    }

    int M (){return m;}
    int N (){return n;}
    vector<T> V(){return vec;}
};

Why defining copy constructor gives me error: cannot bind non-const lvalue reference of type 'obj&' to an rvalue of type 'obj'?

#include <iostream>
#include <vector>
#include <array>
#define Nbodies 3

class Assembly {
public:
    // initializing constructor
    Assembly(double _dataA)
        : data(_dataA), AssA(nullptr), AssB(nullptr) { }

    // double argument copy constructor
    Assembly(Assembly &A, Assembly&B)
        : AssA(&A), AssB(&B) {
        data = A.data * B.data;
    }

    // single argument copy constructor - generates errors once uncommented
/*
    Assembly(Assembly &A)
        : data(A.data), AssA(&A), AssB(&A) {
        // initialize other members of this class here
    }
*/
    double data;
private:
    // these are const pointers to non-const objects of a type Assembly
    Assembly *const AssA, *const AssB;
};

int main() {
    std::array<double, Nbodies> datas = {1.0, 2.0, 3.0};

    // Initilize first branch of the binary tree
    std::vector<Assembly> base_assembly;
    for (int i = 0; i < Nbodies; i++) {
        base_assembly.emplace_back(datas[i]);
    }

    // Binary tree assembly - MWE (for general case, I'm using nested for loop)
    Assembly AssemblyAB = Assembly(base_assembly[0], base_assembly[1]);
    Assembly AssemblyC = Assembly(base_assembly[2]);
    Assembly AssemblyS = Assembly(AssemblyAB, AssemblyC);

    std::cout << AssemblyS.data << std::endl;

    return 0;
}

I'm working on a program that generates a binary try recursively. When I have a branch with an odd number of elements, I need to "rewrite" an element to a lower branch. For this, I use a copy constructor since I need to initialize additional members of the class (I'm using the Eigen library, and some operations can not be done as a one-liner in the initialization list).

My problem arose when I defined a singe argument copy constructor. I get the following error:

.../mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_construct.h:75:7: error:

cannot bind non-const lvalue reference of type 'Assembly&' to an rvalue of type 'Assembly'

Why defining a single argument copy constructor generates such an error? Note that in the case of a two-argument copy constructor the are no errors at all.

How to Pass Vector Elements Into a Class

the following is the code for iterating over a vector object called cells. I am trying to pass each integer in this vector as an object into a class called Cell. Then the vector element should be passed to another vector threads as a parameter for the function function. I'm not sure what I'm doing wrong and would love any suggestions regarding this!

  for (int unsigned ii = 0; ii < cells.size(); ii ++) {
        cells.push_back(Cell(cells.at(ii)));
        threads.push_back(std::thread(function, cells[ii]));
    }

codeblocks keeps bringing out blank output for this code,what is wrong with it?

int main() 
{  
    vector temps;                                   
    for (double temp; cin>>temp; )   
        temps.push_back(temp);
    double sum = 0;
    double high_temp = 0;
    double low_temp = 0;
    for (int x : temps)  
    {          
        if(x > high_temp) 
            high_temp = x;       
        if(x < low_temp) 
            low_temp = x;           
        sum+=x;     
    }

    cout << "High temperature: " << high_temp<< '\n';           
    cout << "Low temperature: " << low_temp << '\n'; 
    cout << "Average temperature: " << sum/temps.size() << '\n'; 
}

Calling recording script command of linux terminal from C++ program

Consider the following scenario: I have a Python program which executes a C++ program by using the command call(["./record"]). "record" is a C++ executable which contains the following lines:

int main(void) {
    system("script --force --flush -q output.txt");
    return 0;
}

This just turns on console recording. Then the Python script should print stuff which I would want to appear in output.txt. But as I see, after calling this C++ program the Python prints does not appear and the console is ready. Only once I type exit my Python program continues. How can I handle this?

Why following callable function gives compilation error while calling with C++11 thread object?

I got following error on VS2017:

Error   C2672   'std::invoke': no matching overloaded function found
Error   C2893   Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...) noexcept(<expr>)'

When I execute following code:

thread t2(do_customized_work, 5);

Follwoing is callable function:

void do_customized_work(int count)
{
    for (int i = 0; i < count; i++)
    {
        cout << i << endl;
        this_thread::sleep_for(0.1s);
    }
}

What are the benefits of SQL in a C++ application instead of a class object containing binary file?

I'm making a C++ and QML application with Qt. It's basically about collecting, manipulating, and querying the data of individuals with a fancy UI. Qt has it's own SQL implementation, but I don't see the reason to use it for my needs over a simple binary file with class instances containing all the data I need to store. I can easily create functions to manipulate this data from the file and encrypt it after each use for security. Using SQL, I think, would only require me to learn all of the commands and the Qt SQL implementation. Still, I'm ready to do it if there are any real advantages. Any wise words? Thank you!

why we use typename keyword in template in c++

Why we use typename keyword inside the template in c++ please explain in a simpler way with example. why it is necessary to write this keyword. xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Back-porting chrono string literal operators

I want to allow the use of string literal operators introduced with c++14 with c++11. I wrote something like that:

namespace MYNAMESPACE {
#if __cplusplus < 201402L
constexpr std::chrono::seconds operator""s(unsigned long long int v) {
return std::chrono::seconds(v);
}
#else
using namespace std::literals::chrono_literals;
#endif
}

Is it possible? If I well understood the ADL rules, this code shouldn't work because the basic types should belong to the global namespace, so the lookup should be performed in the global namespace instead of using my own namespace.

Descending order sorting on basis of first element in vector of pair is not giving desired results

In below shared code link ,Sorting the vector elements on the basis of first element of pairs in descending order is performed but it looks like sorting is not happening and expected output is not received.Here first iterative value needs to be printed in descending order and for the same below code is written in iterateVector() function.

sort(vect.begin(),vect.end(),[] (const pair<double,double> &a,
const pair<double,double> &b){return (a.first > b.first);});  

http://coliru.stacked-crooked.com/a/d868271155375b17

Actual output:

first iterative value =30 second iterative value=300
first iterative value =45.3 second iterative value=300
first iterative value =23 second iterative value=301
first iterative value =175 second iterative value=303

Expected output:

first iterative value =175 second iterative value=303
first iterative value =45.3 second iterative value=300
first iterative value =30 second iterative value=300
first iterative value =23 second iterative value=301

How to insert elements into shared pointer of std::map?

I can insert with map like this:

std::map<int, int> testMap;
testMap.insert(std::make_pair(0, 1));

But if I surround the map with shared pointer like this:

std::shared_ptr<std::map<int, int>> testSharedMap;
testSharedMap->insert(std::make_pair(0, 1));

It doesn't work. I get a runtime error.

Exception thrown: read access violation.
_Scary was nullptr. occurred

How can I use the std::map when it was surrounded by std::shared_ptr?

vendredi 27 décembre 2019

What is the lifetime of C++ member variables when running in a std::thread?

#include <iostream>
#include <string>
#include <thread>

using namespace std;

struct safe_thread : public thread
{
    using thread::thread;

    safe_thread& operator=(safe_thread&&) = default;

    ~safe_thread()
    {
        if (joinable())
        {
            join();
        }
    }
};

struct s
{
    safe_thread t;
    std::string text = "for whatever reason, this text will get corrupted";

    s() noexcept
    {
        std::cout << text << '\n'; // it works in constructor as expected
        t = safe_thread{ [this]
                         { long_task(); }};
    }

    s(s&&) noexcept = default;

    void long_task()
    {
        for (int i = 0; i < 500; ++i)
        {
            std::cout << text << '\n'; // the text gets corrupted in here
        }
    }
};

int main()
{
    s s;
}

In the code above, the text variable would print correctly in the constructor. However, in the long_task() function running in a separate thread, the text gets corrupted (it outright crashes on another machine). How is that so? If the destructor of safe_thread would be run in the destructor of struct s, shouldn't the lifetime of thread and text last equally long? I.e they would both go out of scope when s goes out of scope at main()?

C++ Boost ASIO Disable BOOST_ASIO_WINDOWS or not to include winsock and other windows file

We have an embedded product and make use of Visual Studio to develop code. We also build our code base using gcc and an embedded tool chain.

We also make use of Boost library and one in concern in boost/asio/ip/address.hpp. We also have TCP/IP library which has its own socket.h header file

Now we need the functionality of Boost address but all declarations of socket data should refer from socket.h

When I compile my CPP code include boost address.hpp & socket.h I get multiple macro re-definition issue from winsocket header files.

How can I avoid this issue?

Is an initializer list static enough to allow instantiating templates?

I apologize for the badly formed question. I wasn't sure how to ask it.

#include <iostream>

template <int V>
void output() {
  std::cout << V << "\n";
}

int main() {

  output<1>(); // this works
  output<2>();

  for (int v : {1,2,3} ) {
    output<v>(); // this not
  }
  return 0;
}

I thought having a finite number of iterations would be enough to make that templated function instantiated, but no.

Is there a way to get this to work?

C++ Hold all socket definitions in a container

We are trying to write a Socket APIs wrapper for both IPV4 and IPV6 such that the application is detached from socket library.

The issue I am facing is that constants and #defines that socket.h has for IPv4 and IPV6 like:

IN6ADDR_LOOPBACK_INIT 
in6addr_loopback
IN6ADDR_ANY_INIT
INADDR_ANY
INADDR_LOOPBACK
etc and others

All my attempts to store them in a user defined container / variable are failing - objective is that user can specify request to create IPv4 or IPV6 socket by providing a IP, PORT and PROTOCOL - so it can provide the above defined one.

Since my objective is to hide all the declarations, I need to write a wrapper that hides all definitions and create / map new dataset to it?

Any idea how the same can be achievable?

C++ Object Creation through Inputs

I would like to create objects of a class with the name of an input

class Rectangle {
public:
 int width;
 int height;
 ...
 //assume a constructor that assigns (width, height)
}

how would i generate an object of a new name using an input. (not me typing Rectangle myRectangle(1,1); )

assume that there is anywhere from 1 to infinite objects created by the user

(i am not looking for help with the human input, or checking if they still want an input, solely how to use an input to create a uniquely named object)

this is my first stack overflow post so please inform me if i did something wrong.

Cheers,

Coal lad

What is the time complexity of inserting elements of an array into a map?

If inserting an element takes log(N) time in a map, where N is the size of the map. Then inserting elements of the array one by one means log(1)+log(2)+....+log(N) = log(N!) complexity. But the normal best complexity for getting the elements sorted is Nlog(N), Where am I going wrong?

C++ member function callback and object lifetime

I have a zeromq subscriper class which handles events from any of my connectes publisher services. This works well but now I want class member function callbacks. The specific class which contains all the member functions has the subscriber class as member but how to manage object lifetime when registering member functions in the subscriber class.

I do not know exactly how to name this problem but imagine the following situation:

1) The subscriber class has a data structure which holds all callbacks. This is quite easy to implement using lambdas and std::function for binding to class members.

2) The class containing the subscriber class is destructed and goes into the destructor. After the destructor all members (including the subscriber) are destroyed. This is the situation which is critical because the server is still abre to send some data and the subscriber is still alive after the desructor has been called but calling a member function after the destructor might be dangerous.

How would you handle this situation?

V shape figure using nested for loop C++

I want to make a V shape diagram using nested for loop in C++. My code is below:

#include<iostream>
using namespace std;
int main()
{
    for(int i=0; i<5; i++)
    {
        for(int k=-i+5; k>5;k++)
        {
            cout<<' ';
        }
        cout<<'@';
        for(int j=i+2; j<7;j++)
        {
            cout<<' ';
        }
        cout<<'@'<<endl;
    }
}

Shared pointer lifetime

If I dereference a shared_ptr and invoke a method on the contained object, is the shared_ptr lifetime guaranteed?

Let's say:

stream.linkInfoPtr->addTxRxBytes( txBytes, rxBytes );

Where linkInfoPtr is shared_ptr and stored in the stream object. Does it mean if linkInfoPtr would be destroyed from another thread during addTxRxBytes invocation I would face a segfault?

How to manipulate an array of structure containing 2D array

Using C++, I am implementing an array of structure HiddenLayer defined as

    struct HiddenLayer
    {
        int prev;     ///Number of Rows in node
        int next;     ///Number of Columns in node

        float **node; ///2D array pointer
    };

The array of structure is initialized in the main routine and node is the pointer to the 2D array inside the structure. I am initializing this array as

    int main()
    {
        struct HiddenLayer HLayer[1]; 

        HLayer[0].prev = 1;  //Num of rows
        HLayer[0].next = 3;  //num of col

        HLayer[0].node = (float *) malloc((HLayer[0].prev) * sizeof(float *));  

        for(int i=0;i<HLayer[0].prev;i++)
            HLayer[0].node[i] = malloc(HLayer[0].next * sizeof(float));


        return 0;
    }

But I get this error:

In function ‘int main()’:
main.cpp:22:73: error: cannot convert ‘float*’ to ‘float**’ in assignment
     HLayer[0].node = (float *) malloc((HLayer[0].prev) * sizeof(float *));  
                                                                         ^

>main.cpp:25:35: error: invalid conversion from ‘void*’ to ‘float*’ [-fpermissive]
         HLayer[0].node[i] = malloc(HLayer[0].next * sizeof(float));

I followed the answers given Here and Here

What wrong am I doing?

Declare variable in namespace, define it in main, make it visible to all other files

Using C++14, I'm trying to define a variable in a namespace where commonly used variables are stored (App::Common). The main function should be the one that sets it, since it gets set to argv[0]. Meanwhile I need the variable to be visible by all other classes/files. But I get the linker error shown below. Also, ideally I would like the variable to be const where only the main function would set it once.

common.hpp

#pragma once
#include <string>
namespace App{
    namespace Common{
        extern std::string appPath;
    }
}

main.cpp

#include "common.hpp"
#include "client.hpp"
#include <string>
int main() {
    App::Common::appPath = argv[0];
}

client.hpp

#include "common.hpp"
class Client {
    public:
    void printAppPath();
};

client.cpp

#include <iostream>
#include <string>
#include "common.hpp"
#include "client.hpp"
void Client::printAppPath() {
    std::cout << App::Common::appPath << std::endl;
}

I get the following error by the linker:

ld: main.o: in function `main':
main.cpp:(.text.startup.main+0x25): undefined reference to `App::Common::appPath[abi:cxx11]'
ld: Client.o: in function `Client::printAppPath()':
Client.cpp:(.text...): undefined reference to `App::Common::appPath[abi:cxx11]'

How to iterate and find from map

This is my map:

map<pair<string, int>, pair<string, Array> > matchMap;

This is the function:

void Schedule::studentSchedule() 
{
    string s, c;
    cout << "Enter the student and course name to create schedule" << endl;
    cin >> s >> c;

    list<string>::iterator studentLoc;
    map<pair<string, int>, pair<string, Array> >::iterator courseL;

    studentLoc = find(getStudentList().begin(), getStudentList().end(), s);
    courseL = find(getMatchMap().begin(), getMatchMap().end(), c);

    if (studentLoc != getStudentList().end() && courseL != getMatchMap().end())
    {}
}

I can not find the string here because I am getting an error:

courseL = find(getMatchMap().begin(),getMatchMap().end(),c);

How can I find the element which I want ? This is the error:

In file included from C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algobase.h:71,
                 from C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/algorithm:61,
                 from C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:4:
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h: In instantiation of 'bool __gnu_cxx::__ops::_Iter_equals_val<_Value>::operator()(_Iterator) [with _Iterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Value = const std::__cxx11::basic_string<char>]':
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:104:42:   required from '_InputIterator std::__find_if(_InputIterator, _InputIterator, _Predicate, std::input_iterator_tag) [with _InputIterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = __gnu_cxx::__ops::_Iter_equals_val<const std::__cxx11::basic_string<char> >]'
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:161:23:   required from '_Iterator std::__find_if(_Iterator, _Iterator, _Predicate) [with _Iterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = __gnu_cxx::__ops::_Iter_equals_val<const std::__cxx11::basic_string<char> >]'
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:3905:28:   required from '_IIter std::find(_IIter, _IIter, const _Tp&) [with _IIter = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Tp = std::__cxx11::basic_string<char>]'
C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:24:63:   required from here
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h:241:17: error: no match for 'operator==' (operand types are 'std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > >' and 'const std::__cxx11::basic_string<char>')
  { return *__it == _M_value; }
           ~~~~~~^~~~~~~~~~~
In file included from C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algobase.h:67,
                 from C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/algorithm:61,
                 from C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:4:
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_iterator.h:860:5: note: candidate: 'template<class _IteratorL, class _IteratorR, class _Container> bool __gnu_cxx::operator==(const __gnu_cxx::__normal_iterator<_IteratorL, _Container>&, const __gnu_cxx::__normal_iterator<_IteratorR, _Container>&)'
     operator==(const __normal_iterator<_IteratorL, _Container>& __lhs,

MOCK_METHOD() - mocking a function that listens to a HTTP post

I have the following test MyClassTestTest.when_fileDownloadedFromServer_then_checksumIsCorrect. The function downloadFile(), does a http GET command to a specific URL, downloads the file and calculates the md5sum of the file.

TEST_F(MyClassTestTest, when_fileDownloadedFromServer_then_checksumIsCorrect) {
    EXPECT_EQ(m_Test->getLinuxAdapterValues()->downloadSuccess, false);
    m_Test->downloadFile();
    EXPECT_EQ(m_Test->getLinuxAdapterValues()->downloadSuccess, true);
    EXPECT_EQ(m_Test->getLinuxAdapterValues()->md5sum, "dbfa46c88e9ce5b3f33e4b6a5502c9a2");
}

Instead of having a python Flask API, running http server, I want to mock function that will wait for a http GET. Can I do that? Is it possible using google mock.

How to hash a word using Hashing technique in python using list / dictionary(as c++ )?

I want to hash a word in python to count each letter occurence.

c++ code:

     int *arr = new int[256]();
    for(int i=0;i<s.size();i++){
         arr[s[i]]++;
        }

I want to implement the same in python using dictionary or list.

jeudi 26 décembre 2019

c++ error: no matching constructor for initialization [closed]

I am calling a default constructor of a class with initializer list and getting error 'no matching constructor for initialization'

classA.h

explicit classA();

classA.cpp

//mMember local member which is initialized.

classA::classA() : mMember(getInstance()) {
    pObj = nullptr;
}

classB.cpp

  classAobj = classA(); // getting error: no matching constructor for initialization

Can somebody help with what I am missing here.

Capture arguments are copied from rvalue lambda? [duplicate]

This question already has an answer here:

Are captured arguments copied during the conversion of lambdas to std::function?
I need to convert a lambda that captures a non-copyable type to std::function.
So I passed a lambda to std::function as an rvalue, but an error occurred.

// Foo is non-copyable.
auto a = [f = Foo()]{ };
std::function<void()> b = std::move(a) // error, calls deleted Foo::Foo(const Foo&);

When should we use std::unique_ptr vs std::shared_ptr for class memeber variables?

I know the general philosophy behind std::unique_ptr<T> and std::shared_ptr<T>. A unique pointer should be used in cases where no other pointer variable will ask for access to the object / primitive data pointed to by the unique pointer. A shared pointer, however, exists for shared/concurrent access to a single resource such as a file.

This all remains true for class data members of pointer types as well of course. However, in particular regards at the implementation level, does this general rule cover all cases?

  • Assume that you have a class with 3 member variables, all of pointer type. If none of your member functions return a pointer to one of these variables (such as a getter function) then you should declare the member variable to be of type std::unique_ptr<T>. If however, you return one these member variables then you could potentially have a situation where another pointer tries to bind to the same resource. In which case, you should declare that particular member to be of type std::shared_ptr<T>.

This seems to be a logical rule to follow. I guess, what I'm trying to figure out is how to deal with smart pointers when declared as member variables because the decision is more difficult.

Reverse variadic template arguments in hierarchy

I currently have this class which uses typelist:

template<class AbstractF, template<class, class > class Creator, class TList>
class A: public B<typename Reverse<TList>::Result, Creator, AbstractF> {
};

I'm trying to make the code more c++11 friendly replacing the typelist with variadic template arguments.

template<class AbstractF, template<class, class > class Creator, class TList...>
class A: public B<Creator, AbstractF, TList...> { //<---how to revert here?
};

The problem is: how to reverse a variadic list? Looking at other questions I saw the use of std::tuple, but in this case I'm not able to understand how to "unpack" it since the variadic arguments are not part of simple templated function but they are used as arguments in a class hierarchy.

Iterator for loop in map

I tried the following code but i am not able to find the error. The error is in the loop section but I can not figure out that how to correctly use the iterator in order to avoid the errors. Please help and please clarify my concepts. The problem statement is https://codeforces.com/contest/268/problem/A. I have solved it via vector

    int main()
    {
        std::ios::sync_with_stdio(false);
        int n,x,y,count=0; cin>>n;
        std::vector<pair<int,int>> v;
        for (int i = 0; i < n; ++i)
        {
            cin>>x>>y;
            v.push_back(make_pair(x,y));
        }

        for (int i = 0; i < n; ++i)
        {
            for (int j=i+1; j < n; ++j)
            {
                if(v[i].f==v[j].s){
                    count++;
                }
                if(v[i].s==v[j].f){
                    count++;
                }
            }
        }
        cout<<count;


        return 0;
    }

but having problem via map. It gives SIGTSTP error when using map.

#include <iostream>
#include <map>

using std::cin;
using std::cout;
using std::make_pair;

int main() {
  std::ios::sync_with_stdio(false);
  int n, x, y, count = 0;
  cin >> n;
  std::map<int, int> m;
  for (int i = 0; i < n; ++i) {
    cin >> x >> y;
    m.insert(make_pair(x, y));
  }

  for (auto i = m.begin(); i != m.end(); ++i) {
    for (auto j = ++i; j != m.end(); ++j) {
      if (i->first == j->second) {
        count++;
      }
      if (i->second == j->first) {
        count++;
      }
    }
  }
  cout << count;
  return 0;
}