mercredi 31 juillet 2019

Prevent space after pre-processor macro replacement

I am curious if it is possible to eliminate the space that pre-processor inserts/retains (?) after replacing macro token

//Code

#define s std::

void PrintMatches2(std::string str, s regex reg)



//Output

void PrintMatches2(std::string str, std:: regex reg)

/*---------------------------------------^----------Want to eliminate space here*/

TIA

Reading and writing to files in C++

I have an assignment. I have to read in a text file. The file can contain alpha characters, numbers or any other non alphanumeric, including whitespace etc. Once I've read the file, I have to make the 1st alpha character uppercase and make the remaining contents correct for uppercase and lowercase. Then I have to write the corrected contents to a different file.

I've nearly finished it, but am stuck on the last part. If the last character on the read file is a period then the program doesn't finish and is stuck writing endless periods to the write file. If the last character of the input file is not a period, then the program finishes but replicates that last character twice in the write file.

I feel I need to do something with !inFile.eof() but nothing I've tried on that so far has worked. Appreciate any guidance.

#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;


int main() {

    ifstream inFile;
    ofstream outFile;
    char ch;
    string inputFileName;
    string outputFileName;

    cout << "Please enter the name and extension of the file you want read from: " << endl;
    cin >> inputFileName;

    cout << "Please enter the name and extension of the file you want to write to: " << endl;
    cin >> outputFileName;

    inFile.open(inputFileName, ios::in);
    outFile.open(outputFileName, ios::out);
    if (!outFile) {
        cerr << "Unable to open: " << outputFileName << endl;
        exit(1);
    }

    if (inFile) {
        // The following if statements take care of uppercasing the first alpha character. Do this before the main while loop starts
        if (!inFile.eof()) {
            inFile.get(ch); //get the 1st character
            if ((!islower(ch)) && (!isupper(ch))) { //if it's not an alpha enter into a "not alpha" while loop
                while ((!islower(ch)) && (!isupper(ch))) {
                    outFile.put(ch); //just write non alpha characters to output file as-is
                    inFile.get(ch); //get the next character and keep looping until it's an alpha
                }
                if (isupper(ch)) {
                    outFile.put(ch); //if the first alpha character is uppercase, write to outFile as is
                }
                else {
                    outFile.put(toupper(ch)); //if the 1st alpha is lowercase, write to outFile as uppercase
                }
            }
        }

        while (inFile)  //move on to the rest of the document
        {
            if (!inFile.eof()) {
                inFile.get(ch);
                if (ch == '.') { //if ch is a period, take action to get the next alpha to uppercase
                    outFile.put(ch); // write the period to the outFile
                    inFile.get(ch); //get the next char
                    if ((!islower(ch)) && (!isupper(ch))) { // if the char after period is not an alpha
                        while ((!islower(ch)) && (!isupper(ch))) { //loop while it is not an alpha
                            outFile.put(ch); //just write it to the outfile
                            inFile.get(ch); //get the next char
                        }
                            if (isupper(ch)) {
                                outFile.put(ch); // write the uppercase back to the output file
                            }
                            else if (islower(ch)) {
                                outFile.put(toupper(ch)); //write the lowercase back as an uppercase
                            }
                            else {
                                outFile.put(ch);
                            }
                    }
                    else if (islower(ch)) {
                        outFile.put(toupper(ch)); // write the uppercase back to the output file
                    }
                    else {
                        outFile.put(ch);
                    }
                }
                else if (isupper(ch)) { // change non sentence starting uppercases to lowercase 
                    outFile.put(tolower(ch));
                }
                else {
                    outFile.put(ch);
                }
            }
        }
    }
    else {
        cerr << "Unable to open file: " << inputFileName << endl;
        exit(1);
    }
    return 0;
}

weak_ptr vs unique_ptr reference - passing interface impl to other object

Here is an example code:

class Interface
{
public:
    virtual ~Interface(){}
    virtual void fun() = 0;
};

class InterfaceImpl: public Interface
{
public:
    void fun() override
    {}
};

class B
{
public:
    B(const std::shared_ptr<Interface>& impl /*std::unique_ptr<Interface>& impl* ?*/): impl_(impl){}
private:
    std::weak_ptr<Interface> impl_;
    //std::unique_ptr<Interface>& impl_; ?
};

class A
{
public:
    A(): impl_(std::make_shared<InterfaceImpl>()), b(impl_){}
private:
    std::shared_ptr<Interface> impl_;
    //std::unique_ptr<Interface> impl_ ?
    B b;
};

Class A contains an interface implementation and other object of type B. That object also need to use an interface implementation. I wonder which types of smart pointers should be used to create interface impl in class A and pass that impl to class B. Should I use shared_ptr in class A and weak_ptr in class B or unique_ptr in class A and a reference to unique ptr in class B ?

OpenCL 1.2 no member Error in namespace cl

I am trying to write an openCL 1.2 program based off examples I have found online and I'm encountering an error. Has the library changed to use std::exception now similar to std::vector?

With the snippet below:

 // Build the kernel
    cl::Program program(context, sources);
    try{
        program.build({device});
    } catch(cl::Error& e){
        std::cerr << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device) << std::endl;
        throw e;
    }

Maximum number of threads in C++

Trivia

Usually, when I want to write multi-threaded program in C++, I inquiry the hardware regarding the number of supported concurrent thread as shown in what follows:

unsigned int numThreads = std::thread::hardware_concurrency();

This returns the total number of supported concurrency. Hence, if we have 2 CPUs each of which can support 12 threads, numThreads will be equal to 24.

Problem

Recently I used numactl to enforce a program to run on ONE CPU ONLY.

numactl -N 1 ./a.out

The problem is that std::thread::hardware_concurrency() returns 24 even when I run it with numactl -N 1. However, under such settings the output of nproc is 12.

numactl -N 1 nproc --> output = 12

Question

Perhaps std::thread::hardware_concurrency() is not designed to support such a scenario. That's not my concern. My question is, what is the best practice to get the supported number of threads when I want to run my program with numactl.

Further information

In case you haven't dealt with numactl, it can be used to run a process using a NUMA policy. For example, you can use it to enforce your program to be ran on one CPU only. The usage for such a case is shown above.

Thank you.

template argument deduction/substitution failed erro, when iterating two maps simultaneously

I am trying to iterate two unordered maps simultaneously using a pair of two iterators. This method works fine if we iterate over two vectors;

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

int main() 
{ 
    std::unordered_map<std::string,double> mypantry = flour;
    std::unordered_map<std::string, int> dubVec = key;
    std::unordered_map<std::string, std::string> intVec = {"key", "name"};
    double result = 0;

    typedef std::unordered_map<std::string, std::string>::iterator intIter;
    typedef std::unordered_map<std::string, bool>::iterator dubIter;

    for (std::pair<intIter, dubIter> i(intVec.begin(), dubVec.begin());
     i.first != intVec.end() && i.second != dubVec.end();
     ++i.first, ++i.second)
    {
        cout << i.first.first << "\n" << i.first.second << "\n" << i.second.second;
    }
    return 0; 
}

prog.cpp: In function 'int main()': prog.cpp:18:70: error: no matching function for call to 'std::pair, std::__cxx11::basic_string >, false, true>, std::__detail::_Node_iterator, bool>, false, true>

::pair(std::unordered_map, std::__cxx11::basic_string >::iterator, std::unordered_map, int>::iterator)' for (std::pair i(intVec.begin(), dubVec.begin()); ^ In file included from /usr/include/c++/5/bits/stl_algobase.h:64:0, from /usr/include/c++/5/bits/char_traits.h:39, from /usr/include/c++/5/ios:40, from /usr/include/c++/5/ostream:38, from /usr/include/c++/5/iostream:39, from prog.cpp:3: /usr/include/c++/5/bits/stl_pair.h:206:9: note: candidate: template std::pair<_T1, _T2>::pair(std::tuple<_Args1 ...>&, std::tuple<_Args2 ...>&, std::_Index_tuple<_Indexes1 ...>, std::_Index_tuple<_Indexes2 ...>) pair(tuple<_Args1...>&, tuple<_Args2...>&, ^ /usr/include/c++/5/bits/stl_pair.h:206:9: note: template argument deduction/substitution failed: prog.cpp:18:70: note:
'std::unordered_map, std::__cxx11::basic_string >::iterator {aka std::__detail::_Node_iterator, std::__cxx11::ba

How does the ostream class object behaves on single parameter string input?

I was exploring ostream class in C++. I am stuck on strange output of cout object on string and integer datatype.

While passing an integer or a floating value, the output is exactly what i pass. for eg cout.operator<<(10); prints "10". But while using string as argument it is printing some hexadecimal values.

#include <iostream>
#include <string>

using namespace std;

int main() {
        const char* str = "aia";
        cout.operator<<(str);
        return 0;
}

output when string is passed: 0x4007e0 and the output is same for various strings i tried to pass.

What Is a Proper and Elegant Way to Overload Constructors in C++

I touched C++ a few years ago and am having to go back to it for a project I'm working on. I learned most of the basics but never really nailed down on how C++ wants you to implement its idea of classes.

I have experience in other languages like Java, Python, and C#.

One of the troubles I'm having is understanding how to overload constructors in C++ and how to properly do inheritance.

For example, say I have a class called Rect and a class called Square that inherits from Rect.

In Java...

public class Rect {
   protected double m_length, m_width;

   public Rect(double length, double width) {
      this.m_length = length;
      this.m_width = width;
   }

   public double Area()
   {
      return (this.m_length * this.m_width);
   }

}

public class Square extends Rect {
   private String m_label, m_owner;
   public Square(double side) {
      super(side, side);
      this.m_owner = "me";
      this.m_label = "square";
   }

   //Make the default a unit square
   public Square() {
      this(1.0);
      this.m_label = "unit square";
   }
}

However the same process in C++ just feels convoluted.

Headers:

class Rect
{
public:
   Rect(double length, double width) : _length(length), _width(width) { } 
   double Area();

protected:
   double _length, _width;
}

class Square : public Rect 
{
public:
   Square(double side) : 
   Rect(side, side), _owner("me"), _label("square") { }

   Square() : Rect(1.0, 1.0), _owner("me"), _label("unit square");

private:
   std::string _owner, _label;
}

I feel like I shouldn't have to write out Rect again. It just seems like an awful lot of rewriting, especially since in my project I'm working with matrices a lot and I want to have constructors to be able to extend each other like in Java to avoid rewriting lots of code.

I'm sure there's a way to do this properly, but I haven't see anyone really talk about this problem.

Qt Connections: Using Lambda Expression Resets Passed int Variable (Weird)

Consider the following code:

int counter = 0;

QTimer* timer = new QTimer(this);

connect(timer, &QTimer::timeout, [this, &counter]() mutable {
    counter++;
    qDebug() << counter;
});

timer->start();

Expected:

1
2
3
4
...

Output:

32766 (a random number)
...

Is there some undefined stuff going on here? I can't find anything about this effect.

Can a constexpr linked list of arbitrary types be created?

I'm trying to implement a trait-based policy subsystem and I have an issue which I don't really know how to tackle (if it's even possible). I have a traits that looks like this:

template <typename ValueT, typename TagT = void, typename EnableT = void>
struct TPolicyTraits
{
    static void Apply(ValueT& value) { }
};

And this trait can be specialized as such:

struct MyPolicy {};

template <typename ValueT>
struct TPolicyTraits<ValueT, MyPolicy>
{
    static void Apply(ValueT& value) { /* Implementation */ }
};

I would like to register policy at compile time in a sort of linked list. The policy system would be used like this:

namespace PolicyTraits
{
    template <typename ValueT, typename TagT>
    using TPolicyTraitsOf = TPolicyTraits<std::decay_t<ValueT>, TagT>;

    template <typename ValueT>
    void Apply(ValueT& value) 
    {
        // todo iterate through constexpr tag list and apply policies
    }

    template <typename TagT>
    constexpr void Enable()
    {
        // todo add tag to constexpr list
    }
}

int main()
{
    PolicyTraits::Enable<MyPolicy>();
    PolicyTraits::Apply(std::string());
}

Is there any way to achieve this?

Call Before Main using a Static Object Constructor = Warning Unused Static

I know that there are a few questions similar to this one, but I believe that this one is diferent in the details.

I'm trying to "register" some cases, that should call a Class::instance("some string") and for that I created

class register { 
      register::register(const char *a) {
           Class::instance()->register(a);
      }
}

that I use as follows:

namespace {
     auto a = register("abc");
     auto b = register("cbd");
}

This first gave me the warning "non pod static variable", but it worked. Then I tried to use a second approach:

namespace { 
    int silence_warning = (Class::instance()->register("abc"), 0);
}

also works, but a new warning: "warning, not used static variable"

There's anything I can do to get rid of both warnings and still be able to call this before main?

Why is there set data structure implemented in C++ when the same thing can be done using map?

Why is there an implementation of set data structure in C++ when the same thing can be done using map, although map will take 2*n space rather than n but it should not affect anything. I have read about set and map and only significant difference is key and value, which is not convincing.

Avoiding Implicit Conversion in Constructor. Explicit keyword doesn't help here

I am able to avoid the implicit conversion of constructor using explicit keyword. So now, conversions like A a1 = 10; can be avoided.

But still I can initialize A a1 = A(20.2);. How can I disable the object creation such that only object can be created if we pass integer as a parameter e.g. A a1 = A(10)?

#include <iostream>

class A
{
public :
    explicit A(int a)
    {
     num = a;
    }

    int num;
};

int main()
{
    A a1=A(10.0);
    std::cout << a1.num;
    return 0;
}

Gmock - strict mock and unique ptr - how to pass mock to impl

Here is an example code:

class Interface
{
public:
    virtual ~Interface(){}
    virtual void Start() = 0;
};

class MockInterface: public Interface
{
public:
    MOCK_METHOD0(Start, void());
};

class T
{
public:
    T(std::unique_ptr<Interface>& impl): impl_(impl){}
private:
    std::unique_ptr<Interface>& impl_;
};

I would like to create a strict mock but I'm not sure how to construct it as unique ptr and then pass to T constructor.

Call common function in destructor before destroying derived members

Assuming we have the classical Base class and derived class like this

class B {
public:
    virtual ~B() {
        // calling it here is too late, see explanations
        //common_pre_cleanup_function();
    }

    void common_pre_cleanup_function() { }
};

class D : public B {
public:
    virtual ~D() {
        // What if we forget to do this call in another derived class?
        common_pre_cleanup_function();
    }
};

How would you make sure a function like common_pre_cleanup_function() is called in all derived Ds destructors before the members of D are destroyed but without having to explicitly call this function in every destructor-implementation of a new D?

Background

In my current project we have a base class that implements certain parallelism and threading features and will eventually start a new thread that does the actual work. In the destructor of this base class we wanted to make sure, that the thread is always stopped and joined so that it gets cleaned up properly.

However derived classes may create members that are used by this thread in the base class. So if we destroy objects of the derived class, these members are also destroyed. But at this time the thread that is managed by the base class can still be running and now wrongfully access destroyed members.

I'm aware that this isn't the smartest approach to solve the issue and probably splitting up the threading/parallelisation parts and the "actual work" parts into separate classes might be the much smarter idea. However I'm interested if there are any approaches that don't involve an entire rewrite of the existing code base.

This code here is closer to our situation

class BackgroundTask {
public:
    virtual ~BackgroundTask() {
        // if we forget to call stop() in the derived classes, we will
        // at this point have already destroyed any derived members
        // while the thread might still run and access them; so how/where
        // can we put this call?
        //stop();
    }

    void stop() {
        cancelFlag_.set();
        thread_.join();
    }

    // more functions helping with Background tasks

private:
    Thread thread_;
    Condition cancelFlag_;
};

class MyTask : public BackgroundTask {
public:
    virtual ~MyTask() {
        // with the current case, we have to remember to call
        // this function in all destructors in classes derived
        // from BackgroundTask; that's what I want to avoid
        stop();
    }

private:
    std::unique_ptr<MyClass> member;
};

Getting multiple string input after integer?

I came through this programming question where I need to input multiple strings after inputing a integer. The string also include spaces.

//Program

#include <iostream>
#include<string.h>
using namespace std;

int main() {
int t;
cin>>t;
while(t--){
    string s;
    getline(cin,s,'\n');  //also used cin>>s;
    cout<<"$"<<s<<"$";
}
return 0;
}

Input

2
Hello World
Hello StackOverFlow

Expected Output

Hello World
Hello StackOverFlow

Program's Output

$$$Hello World$

Why is a variable not an lvalue in C++?

#include <type_traits>

int main()
{    
    int n;
    n = 0;

    // failure!
    static_assert(std::is_lvalue_reference_v<decltype(n)>); 
}

n can be put on the left side, so it should be obviously an lvalue.

Why does the static_assert fail?

mardi 30 juillet 2019

How to interpret the report of perf

I'm learning how to use the tool perf to profile my c++ project. Here is my code:

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


std::mutex mtx;
long long_val = 0;

void do_something(long &val)
{
    std::unique_lock<std::mutex> lck(mtx);
    for(int j=0; j<1000; ++j)
        val++;
}


void thread_func()
{
    for(int i=0; i<1000000L; ++i)
    {
        do_something(long_val);
    }
}


int main(int argc, char* argv[])
{
    std::vector<std::unique_ptr<std::thread>> threads;
    for(int i=0; i<100; ++i)
    {
        threads.push_back(std::move(std::unique_ptr<std::thread>(new std::thread(thread_func))));
    }
    for(int i=0; i<100; ++i)
    {
        threads[i]->join();
    }
    threads.clear();
    std::cout << long_val << std::endl;
    return 0;
}

To compile it, I run g++ -std=c++11 main.cpp -lpthread -g and then I get the executable file named a.out.

Then I run perf record --call-graph dwarf -- ./a.out and wait for 10 seconds, then I press Ctrl+c to interrupt the ./a.out because it needs too much time to execute.

Lastly, I run perf report -g graph --no-children and here is the output:

enter image description here

My goal is to find which part of the code is the heaviest. So it seems that this output could tell me do_something is the heaviest part(46.25%). But when I enter into do_something, I can not understand what it is: std::_Bind_simple, std::thread::_Impl etc.

So how to get more useful information from the output of perf report? Or we can't get more except the fact that do_something is the heaviest?

How to copy characters into string vector

Attempting to copy from a character vector to a string vector has been unsuccessful across multiple attempts at a solution

allocating memory to the vector prior to copying allows std::copy to work properly when placed at "OutputIterator result" (based on function template). I attempted:

std::copy(char1.begin(), char1.end(), std::back_inserter(v1));

however, this was unsuccessful as well. using back_inserter returns error c2679 "binary '=': no operator found which takes a right-hand operand of type'char' (or there is no acceptable conversion).

input file is located here: https://adventofcode.com/2018/day/2

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstring>
#include <algorithm>
#include <iterator>
#include <cstdio>



    int main() {

        std::string field1;
        std::string field2;
        char characters;

        std::vector<char>::iterator ptr;
        std::vector<char>::iterator ptr2;

        std::vector<char> char1;
        std::vector<char> char2;

        int size = 0;

        std::ifstream inFile;

        inFile.open("C:\\Users\\Administrator\\Desktop\\c++ files\\input2.txt");

        if (!inFile) {

            std::cout << "abort";

            return 1;

        }

        while (inFile >> characters) {          //read variables from input stream

            char1.push_back(characters);

        }

        std::vector<std::string> v1(6500);

        std::copy(char1.begin(), char1.end(), std::back_inserter(v1)); 

        inFile.close();

        return 0;

    }

    //26

expect vector v1 to hold values in vector char1. I am assuming the problem stems from the data type of v1 vs. char1, however, I have not been able to find a concrete solution. I do not want to read directly into a string vector; hence my current problem.

Qabstractitemmodel, show a string list into child index

I have a class A with some data (primitive) and a string list. I collect some A objects into a list. I want to show this collection into a qtableview based on a custom qabstractitemmodel that represents my list. I want to show the A objects one for row: Every column has one of the primitive types of an A. Next I want to show the string list of an A under it's row like files' name under folders in the file system viewer. I don't want to create, like qt example, a treeitem class: first because I have strings not objects and second because I don't need a recursive objects to hold data

How to find given IPv6 address falls in the CIDR range

If I have an ipv6 address 2001:4860:4860:0000:0000:0000:012D:8888 and want to find whether this falls in the given CIDR range 2001:4860:4860:0000:0000:0000:0000:8888/32. How do I do this in C or C++?

I tried similarly as we do for ipv4. (ip & netmask) == (range & netmask)

unsigned int ipv6 = (ip[0]<<112) + (ip[1]<<96) + (ip[2]<<80) + (ip[3]<<64)+ (ip[4]<<48) + (ip[5]<<32) + (ip[6]<<16) + ip[7];

unsigned int range = (cidr_ip[0]<<112) + (cidr_ip[1]<<96) + (cidr_ip[2]<<80) + (cidr_ip[3]<<64)+ (cidr_ip[4]<<48) + (cidr_ip[5]<<32) + (cidr_ip[6]<<16) + cidr_ip[7];
unsigned int mask = (~0u) << (128-netmask);

if((ipv6 & mask) == (range & mask)){
    printf("matched\n");
}
else
{
    printf("no match\n");
}


This didn't work for me as expected. The above ipv6 falls in the range. But the program says "no match".

How to send parameter to function only if statement is matched?

I have a map, that I only want to send to a function if it has elements in it. The function takes a parameter pack so I can send how many or how few elements I want.

Is there a way to make the size-check of the map in the call itself? There are a lot of maps that will be sent in the same call meaning that it would be very tedious to do the check outside of the call itself.

pseudo-code of what I want:

std::map<int, int> a;
std::map<int, int> b;
std::map<int, int> c;
std::map<int, int> d;
fun( (if (a.size() > 0), (if (b.size() > 0), (if (c.size() > 0), (if (d.size() > 0));

I know this code is very wrong, but it is just to give you an idea of what I am after.

Easy way to create object with members of various datatypes

In C++, I often need to use an extremely simple, primative object containing a variety of datatypes simply so that I can pass it around easily between functions. In Python, I achieve this by using dictionaries. For example:

easy = {"keyframe_range":[], "value":0.25, "interpolation":"bezier"}

However, in C++, if I wanted to create something similar, I would need to:

struct obj
{
  vector<int> keyframe_range;
  float value;
  string interpolation;

  obj(vector<int> vv, float ff, string ss) : keyframe_range(vv), value(ff), interpolation(ss) {}

};

obj easy(vector<int>(), 0.25, "bezier");

When I need to create who-knows what kind of object on a whim, It's extremely inefficient and a huge waste of time to manually write a parameterized constructor for every object I need. In Python, I can essentially avoid this with dictionaries; however, unordered_maps in C++ must map to the same datatype, so they aren't really what I'm looking for.

Essentially, I'm just wanting an easy way to create a simple object which acts as a collection of items of various datatypes and nothing more. Can this be done in C++ 11, and if so, how?

Why send a ndarray from Python to C++ get a strange result?

I'm trying to use the boost-python to bind C++ code. And I get a strange result when I receive a ndarray object from Python to C++. There are two problems make me confuse:

Problem 1: I using the member function get_data() to return the char*. And print by std::string type. The question is why doesn't get any output on my terminal?

Problem 2: When I convert to std::vector it looks like instead space to zero?! If so, what the best strategy to solve this kind of problem?

I will be very thankful if anyone can help me =)

The following code is my test. I also call the other two function "greet()" and "printNDArray()" in this test and work in my expectations.

In C++ side - hello.cpp:


    #include <boost/python.hpp>
    #include <boost/numpy.hpp>

    char const* greet()
    {
       return "hello, world";
    }

    #include <iostream>
    #include <string>
    boost::numpy::ndarray showArray(const boost::numpy::ndarray& in) {
            int input_size = in.shape(0);
            const char* cc = in.get_data();
            std::string str(cc); // Why doesn't get anything?? Why?
            std::cout << " === " << str << std::endl;
            auto input_ptr = reinterpret_cast<int*>(in.get_data());
            std::vector<int> v(input_size);
            for (int i = 0; i < input_size; ++i)
                v[i] = *(input_ptr + i);

            for (auto itr : v) std::cout << itr << std::endl;

            int v_size = v.size();
            boost::python::tuple shape = boost::python::make_tuple(v_size);
            boost::python::tuple stride = boost::python::make_tuple(sizeof(int));
            boost::numpy::dtype dt = boost::numpy::dtype::get_builtin<int>();
            boost::numpy::ndarray output = boost::numpy::from_data(&v[0], dt, shape, stride, boost::python::object());
            boost::numpy::ndarray output_array = output.copy();
            return output_array;
    }

    boost::numpy::ndarray printNDArray() {
            boost::python::tuple shape = boost::python::make_tuple(3,3,3);
            boost::numpy::dtype dtype = boost::numpy::dtype::get_builtin<float>();
            boost::numpy::ndarray result = boost::numpy::zeros(shape,dtype);

            return result;
    }

    BOOST_PYTHON_MODULE(hello)
    {
        using namespace boost::python;
        Py_Initialize();
        boost::numpy::initialize();

        def("greet", greet);

        def("showArray", showArray);

        def("printndarray", printNDArray);
    }


In Python side - hello.py:


    #!/usr/bin/env python

    import numpy as np
    import hello

    a = np.arange(5,10)

    print(a)

    print (hello.showArray(a))

    print (hello.greet())

    print (hello.printndarray())


The following is my terminal output:


    $ python hello.py
    [5 6 7 8 9]
     === 
    5
    0
    6
    0
    7
    [5 0 6 0 7]
    hello, world
    [[[ 0.  0.  0.]
      [ 0.  0.  0.]
      [ 0.  0.  0.]]

     [[ 0.  0.  0.]
      [ 0.  0.  0.]
      [ 0.  0.  0.]]

     [[ 0.  0.  0.]
      [ 0.  0.  0.]
      [ 0.  0.  0.]]]


Pointer variable is not being assigned

I'm trying to write a program to reverse a linked-list using recursion.The recursive function is working properly except in terminal condition the pointer variable(*start) that is being assigned a value is not reflecting in it after the function completes.

I put some print statements and found that in function the value is being assigned to pointer correctly.

 void revList(node *hd,node *start){
     if(hd->next==NULL){
         cout<<start<<endl; 
         start=hd;
         cout<<start<<endl; //this show it is being modified
         return;
     }
     node *first=hd;
     node *rest=hd->next;
     first->next=NULL;
     revList(rest,start);
     cout<<first<<" "<<rest<<endl;
     rest->next=first;
 }

int main(){ 
    node *head=new node;
    head->val=9;
    head->next=NULL;
    addnode(head,6);
    addnode(head,7);
    addnode(head,8);
    node *s;
    revList(head,s);
    cout<<s<<endl; //but it's not reflecting here.

    while(s!=NULL){
        cout<<s->val<<"->";
        s=s->next;
    }
return 0;
}

//output:
0x7ffd5c1422c0                                                                                                           
0x1e45c80                                                                                                                
0x1e45c60 0x1e45c80                                                                                                      
0x1e45c40 0x1e45c60                                                                                                      
0x1e45c20 0x1e45c40                                                                                                      
0x7ffd5c1422c0                                                                                                           
Segmentation fault (core dumped)//I'm not worried about this.

How to declare and use global variables in C++ Windows Forms?

I am trying to use global variables in the default Form.h file in C++ windows form. I have two functions in Form.h file:

private: System::Void Button1_Click(System::Object^ sender, System::EventArgs^ e) {

//Some Code

}

and

private: System::Void Button2_Click(System::Object^ sender, System::EventArgs^ e) {

//Some Code

}

I want to declare globals variables in such a way that both of those above functions can access and modify the variables.

I have already tried making a separate Globals.h file where I have the following code:

namespace Globals { extern bool globalVariable1 = false;

}

In my Form.h file, I have an "#include "Globals.h" declaration. And then I am accessing the global variables in Globals.h and modifying as

Globals::globalVariable1 = true;

This doesn't seem to work.

Size limits on stringstream for embedded

Keen to use stringstream on an STM32 for handling data that gets sent over various UART connections to radio modules (wifi, BLE, Zigbee, etc). I am running FreeRTOS, if that matters. Very concerned about the dynamic memory allocation in the STL lib causing unhandled overflows (I have to have "-fno-exceptions"). I can handle buffer overruns myself in a simple writer method, so that isn't an issue, but I want to be certain that the stringstream never tries to increase it's memory beyond a pre-set limit.

Currently I just use char* buffers, but, I want to find a better solution.

I want to be able to do something like this.

#include <sstream>      // std::stringstream

class Wifi
{
public:
    std::stringstream* ss;

    Wifi()
    {
        ss.set_max_size(1024); // 1kB
    }
};

TIA

how can I understand my valgrind error message?

I am getting the follow error message from valgrind:

==1808== 0 bytes in 1 blocks are still reachable in loss record 1 of 1,734
==1808==    at 0x4A05E7D: malloc (vg_replace_malloc.c:309)
==1808==    by 0x4CC2BA9: hwloc_build_level_from_list (topology.c:1603)
==1808==    by 0x4CC2BA9: hwloc_connect_levels (topology.c:1774)
==1808==    by 0x4CC2F25: hwloc_discover (topology.c:2091)
==1808==    by 0x4CC2F25: opal_hwloc132_hwloc_topology_load (topology.c:2596)
==1808==    by 0x4C60957: orte_odls_base_open (odls_base_open.c:205)
==1808==    by 0x632FDB3: ???
==1808==    by 0x4C3B6B9: orte_init (orte_init.c:127)
==1808==    by 0x403E0E: orterun (orterun.c:693)
==1808==    by 0x4035E3: main (main.c:13)
==1808==
==1808== 0 bytes in 1 blocks are still reachable in loss record 2 of 1,734
==1808==    at 0x4A05E7D: malloc (vg_replace_malloc.c:309)
==1808==    by 0x4CC2BD5: hwloc_build_level_from_list (topology.c:1603)
==1808==    by 0x4CC2BD5: hwloc_connect_levels (topology.c:1775)
==1808==    by 0x4CC2F25: hwloc_discover (topology.c:2091)
==1808==    by 0x4CC2F25: opal_hwloc132_hwloc_topology_load (topology.c:2596)
==1808==    by 0x4C60957: orte_odls_base_open (odls_base_open.c:205)
==1808==    by 0x632FDB3: ???
==1808==    by 0x4C3B6B9: orte_init (orte_init.c:127)
==1808==    by 0x403E0E: orterun (orterun.c:693)
==1808==    by 0x4035E3: main (main.c:13)

I am not able to understand which kind of problem valgrind is reporting. Is there anybody willing to explain?

I have checked all new instances. All of them are properly deleted.

I am getting valgrind error messagges and a further error form mpi when the code ends:

---------------------------------------------------------------------
mpirun noticed that process rank 0 with PID 1811 on node laki.pi.ingv.it exited on signal 11 (Segmentation fault).
----------------------------------------------------------------------

What other control can i use to replace 'Ctrl + Z'?

So I make a program where you can custom write a text file. These is a program meaning that there are functions. I have 3 different functions where the user will have to choose one when starting the program. The first function is to add new text into tect file. The second fucntion is to display the text file. The third fucntion is to create a new text file in the directory. However my first function seem to have a problem, when writing a new text file it require you to press ctrl+z to add and exit at the same time. Since my file is in a loop this cause infinite loop and in order to continues is to close the program and re-run it. Is there anyone who know how to help me fix this? Thank you

I've tried break, return, ctrl+c, ctrl +d but nothing work.

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

    void welcome();
    void addFile();
    void displayFile();
    void createFile();

    int main() {
        char choice;
        welcome();  
        cin >> choice;
        switch (choice) {
            case 'a': 
                cout << "You has choose to add to files. \n";
                addFile();
                break;
            case 'b': 
                cout << "You has choose to display the schedule. \n";
                displayFile();
                break;
            case 'c':
                cout << "You has chose to create a new file. \n";
                createFile();
                break;
            default:
                cout << "Please enter a valid choice.";
                break;
        }
        main();
    }

    void welcome() {
        cout << "Welcome to your Personal Schedule \n";
        cout << "Choose 'a' to add to schedule. \n" << "Choose 'b' to                 display the schedule \n" << "Choose 'c' to create a new file \n"; 
    }

    void createFile() {
        ofstream scFile("schedule.txt");
        scFile << "It has 4 doors! \n";
        scFile.close(); 
    }

    void addFile() {
        ofstream scFile("schedule.txt");

        cout << "Enter date, month and task" << endl;
        cout << "Press Control + Z to confirm and quit" << endl;

        int date, month;
        string task;

        while(cin >> date >> month >> task) {
            scFile << date << ' ' << month << ' ' << task << endl;
        }
    }

    void displayFile() {
        ifstream scFile("schedule.txt");

        int date, month;
        string task;

        while(scFile >> date >> month >> task) {
            cout << date << ", " << month << ", " << task << endl;
        }
    }

terminate called after throwing an instance of 'std::logicerror

I am creating a shoping list program using array,and when I compile the code and run it it throws me this error:

terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_M_construct null not valid

searched for some solution online but none helped the problem.

code:

#include<iostream>
using namespace std;

int main(){
  string inputnumber = 0;
  int allocationSize = 5;
  int elementsused = 0;
  int maximumAllocation = allocationSize;

  string *pArrayoflist = new string[allocationSize];

  cout << "enter list item :" ;
  cin >> inputnumber;

  while(inputnumber != "exit"){
    pArrayoflist[elementsused++] = inputnumber;

    if (elementsused == maximumAllocation){
      string *plargerArray = new string[maximumAllocation + allocationSize];

    for(int i = 0;i < allocationSize;i++){
      plargerArray[i] = pArrayoflist[i];
    }

    delete [] pArrayoflist;
    pArrayoflist = plargerArray;
    maximumAllocation += allocationSize;
    }

    cout << "enter list item :" ;
    cin >> inputnumber;


  }
  string response;
  cout << "press Y to show list : ";
  cin >> response;

  if (response == "y" || response == "Y" ){
    for (int i = 0 ; i < elementsused ; i++){
      cout << pArrayoflist[i] << endl;
    }
  }
    else{
      return 1;
    }
   return 0;
}

Order of tasks (handlers) putting to taskqueue via post and dispatch

The output is:

Handler A
Handler B
Handler D
Handler E
Handler C

Given,

  • post() puts the handler into the taskqueue and returns immediately

  • dispatch() can run the task immediately if the main thread already calls run() (which is the case)

then,

  • why "Handler E" wasn't run before B and D ? It was dispatch(), and main thread already runs the io_context after all.

  • why "Handler C" was run last ? It kinds of make sense as it was post within post. But still the order of the tasks being put to the taskqueue isn't very self-explained.

int main()
{
    boost::asio::io_service io_service;

    io_service.dispatch( [](){ cout << "Handler A\n"; } );

    io_service.post(
        [&io_service]() {
            cout << "Handler B\n";
            io_service.post(
                [](){
                    cout << "Handler C\n";
                }
            );
        }
    );

    io_service.post( []() {
            cout << "Handler D\n";
        }
    );

    io_service.dispatch( [](){ cout << "Handler E\n"; } );

    cout << "Running io_service\n";
    io_service.run();

    return 0;
}

Is it possible to return a printed value into a variable?

I am currently doing a project involving the conversion of decimal numbers into IEEE 754 Floating Point representation. I am making use of a code provided by GeeksforGeeks for the conversion process and edited it to suit my project.

I am unsure as to how to modify the code so that it returns the appropriate Floating Point representation into the variables as the variables currently stores the decimal values instead.

I ran into the issue where the function being used to convert said decimal values is just simply printing the Floating Point representation. I would need to be able to return the printed Floating Point representation value into a variable. Is that possible? Else, is there an alternative method?

// C program to convert a real value
// to IEEE 754 floating point representaion

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

int modifyBit(int n, int p, int b)
{
    int mask = 1 << p;
    return (n & ~mask) | ((b << p) & mask);
}


void printBinary(int n, int i)
{

    // Prints the binary representation
    // of a number n up to i-bits.
    int k;
    for (k = i - 1; k >= 0; k--) {

        if ((n >> k) & 1)
            printf("1");
        else
            printf("0");
    }
}

typedef union {

    float f;
    struct
    {

        // Order is important.
        // Here the members of the union data structure
        // use the same memory (32 bits).
        // The ordering is taken
        // from the LSB to the MSB.
        unsigned int mantissa : 23;
        unsigned int exponent : 8;
        unsigned int sign : 1;

    } raw;
} myfloat;

// Function to convert real value
// to IEEE foating point representation
void printIEEE(myfloat var)
{

    // Prints the IEEE 754 representation
    // of a float value (32 bits)

    printf("%d | ", var.raw.sign);
    printBinary(var.raw.exponent, 8);
    printf(" | ");
    printBinary(var.raw.mantissa, 23);
    printf("\n");
}

// Driver Code
int main()
{

    // Instantiate the union
    myfloat var, var2;
    int sub, sub2, mant, pos, finalMant;


    // Get the real value
    var.f = 1.25;
    var2.f = 23.5;


    // Get the IEEE floating point representation
    printf("IEEE 754 representation of %f is : \n",
           var.f);
    printIEEE(var);
    printf("No 2: %f : \n", var2.f);
    printIEEE(var2);
    printf("\n");

    //Get the exponent value for the respective variable
    //Need to compare which exponent is bigger
    printBinary(var2.raw.exponent, 8);
    printf("\n");
    printf("Exponent of Var in Decimal: %d: \n", var.raw.exponent);
    printf("Exponent of Var2 in Decimal: %d: \n", var2.raw.exponent);

    if (var.raw.exponent > var2.raw.exponent)
    {
        printf("1st is bigger than 2 \n");

        //Difference in exponent
        sub = var.raw.exponent - var2.raw.exponent;
        printf("Difference in exponent: %d \n", sub);

        //New mantissa with the new right shift
        mant = var2.raw.mantissa>>sub;

        //Modifying the hidden bit to be included into the mantissa
        pos = 23 - sub;
        finalMant = modifyBit(mant, pos, 1);

        //Print the final mantissa
        printf("New Binary : \n");
        printBinary(finalMant, 23);
    }
    else
    {
        printf("2nd bigger than 1 \n");

        //Difference in exponent
        sub = var2.raw.exponent - var.raw.exponent;
        printf("Difference in exponent: %d \n", sub);

        //New mantissa with the new right shift
        mant = var.raw.mantissa>>sub;

        //Modifying the hidden bit to be included into the mantissa
        pos = 23 - sub;
        finalMant = modifyBit(mant, pos, 1);

        //Print the final mantissa
        printf("New Binary : \n");
        printBinary(finalMant, 23);
    }
    return 0;
}

This code correctly converts the decimal value into the intended Floating Point representation. However, if I were to print the variable as it is using printf(finalMant) instead of printBinary, it would display as a decimal value instead of a Floating Point representation. This might be due to the lack of any return values.

lundi 29 juillet 2019

Specialized template accepting constructor parameter when only default constructor defined

So, I have this template class and its specialization.

    #include <iostream>

    using namespace std;

    template<bool> struct CompileTimeChecker{

       CompileTimeChecker(...) \\constructor, can accept any number of parameters;

    };

    template<> struct CompileTimeChecker<false> {};

Case 1:

In the main function I am defining a local class called ErrorA. When I create a temporary of CompileTimeChecker<false> with temporary object of ErrorA fed as an initializer, the compiler is not detecting any error.

int main()
{


    class ErrorA {};

    CompileTimeChecker<false>(ErrorA()); //Case 1;

    CompileTimeChecker<false>(int());    //Case 2;

    return 0;

}

Case 2:

Next I feed it with temporary object of type int, and suddenly the compiler recognizes the issue (there is no constructor that takes args in the specialized template CompileTimeChecker<false>)

main.cpp:30:36: error: no matching function for call to ‘CompileTimeChecker::CompileTimeChecker(int)’ CompileTimeChecker<false>(int());

Why does it not recognize the issue in case 1?

compile liblog4cplus.a library with std=c++11

I am using a Visual Studio GDB project and I have a problem including the liblog4cplus. a static library in the linker inputs.

This are the errors received:

....\Dependencies\log4cplus-1.2.1.libs\liblog4cplus.a(liblog4cplus_la-appender.o): In function void std::__cxx11::basic_string, std::allocator >::_M_construct(char*, char*, std::forward_iterator_tag)': 2>\usr\include\c++\5\bits\basic_string.tcc(223): error : undefined reference tostd::cxx11::basic_string, std::allocator >::_M_create(unsigned long&, unsigned long)' 2>......\Dependencies\log4cplus-1.2.1.libs\liblog4cplus.a(liblog4cplus_la-appender.o): In function std::__cxx11::basic_string, std::allocator >::operator=(std::__cxx11::basic_string, std::allocator >&&)': 2>\usr\include\c++\5\bits\basic_string.h(589): error : undefined reference tostd::cxx11::basic_string, std::allocator >::swap(std::__cxx11::basic_string, std::allocator >&)'

It seems that the library is not recognised as being compiled with -std=c++11

In order compile the library with c++11 I added the command -std=c++11 in the configure file(CXXFLAGS = "-std=c++11")

The command used to compile the library is: sudo ./configure --enable-static

The compilation worked well.

This is some part of the configure file if test "$GXX" = yes; then CXXFLAGS="-O2 -std=c++11"

I think the error from visual studio is related to c++11 compilation and after the compilation the error should not be anymore, but still have the same error.

Could you please tell me if the compilation procedure is ok?

If not, please tell which is the right procedure to compile the library for c++11?

Does the errors mean something else?

Dynamic attributes type

I'm writing a program that reads a text file and then instantiate a few objects. The problem is, it needs to decide what kind of attributes those objects will get based upon what has been parsed from the text file.

To simplify the problem, let's suppose in the text file you should write only "int" or "double" and the object needs to be instantiated with a member variable of type respectively int or double.

The solution I've come up with is, at its core, the following:

  1. Implement an abstract class, NumericalType, with no attribute.
  2. Write one child class for every admitted type. In this case, int and double, so intType and doubleType, with a member variable of the proper type and proper implementations to deal with it.
  3. Give every instatiated object a NumericalType * const (const because once read from the text file, it stays the same) and assign to it the proper type.

However I don't like it that much. There's a lot indirection; for example, variables can be accessed only through getters or a dynamic_cast (which seems a bit too much for what should be a simple architecture).

Can this be done in a more simple and elegant way?

Should the deleted default constructor be in Public or Private?

I had to delete the default constructor to ensure that the parameterized constuctor is used always. That's when I wanted to know if my deleted default constructor should be under public or private access specifier.

I just wrote a sample code to test this. I tried to access the deleted default constructor.

class A
{
public:
    A(const int val)
    {
        assign = val;
    }
private:
    A() = delete;
    int assign;
};

int main()
{
    A obj1(5);
    A obj2;
}

main.cpp: In function ‘int main()’:

main.cpp:35:7: error: ‘A::A()’ is private within this context

A obj2;

main.cpp:28:5: note: declared private here

A() = delete;

main.cpp:35:7: error: use of deleted function ‘A::A()’

A obj2;

main.cpp:28:5: note: declared here

A() = delete;

Condition variable should be used or not to reduce missed wakeups

I have two threads, one is the producer and other is consumer. My consumer is always late (due to some costly function call, simulated in below code using sleeps) so I have used ring buffer as I can afford to loose some events.

Questions: I am wondering if it would be better to use condition variable instead of what I currently have : continuous monitoring of the ring buffer size to see if the events got generated. I know that the current while loop of checking the ring buffer size is expensive, so I can probably add some yield calls to reduce the tight loop.

Can I get rid of pointers? In my current code I am passing pointers to my ring buffer from main function to the threads. Wondering if there is any fancy or better way to do the same?

#include <iostream>
#include <thread>
#include <chrono>
#include <vector>
#include <atomic>
#include <boost/circular_buffer.hpp>
#include <condition_variable>
#include <functional>

std::atomic<bool> mRunning;
std::mutex m_mutex;
std::condition_variable m_condVar;
long int data = 0;

class Detacher {
    public:
    template<typename Function, typename ... Args>
    void createTask(Function &&func, Args&& ... args) {
        m_threads.emplace_back(std::forward<Function>(func), std::forward<Args>(args)...);
    }

    Detacher() = default;
    Detacher(const Detacher&) = delete;
    Detacher & operator=(const Detacher&) = delete;
    Detacher(Detacher&&) = default;
    Detacher& operator=(Detacher&&) = default;

    ~Detacher() {
        for (auto& thread : m_threads) {
            thread.join();
        }
    }

    private:
    std::vector<std::thread> m_threads;
};

void foo_1(boost::circular_buffer<int> *cb)
{
    while (mRunning) {
        std::unique_lock<std::mutex> mlock(m_mutex);
        if (!cb->size())
            continue;
        int data = cb[0][0];
        cb->pop_front();
        mlock.unlock();
        if (!mRunning) {
            break;  
        }
        //simulate time consuming function call
        std::this_thread::sleep_for(std::chrono::milliseconds(16));
    }
}

void foo_2(boost::circular_buffer<int> *cb)
{
    while (mRunning) {
        std::unique_lock<std::mutex> mlock(m_mutex);
        cb->push_back(data);
        data++;
        mlock.unlock();
        //simulate time consuming function call
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }
}

int main()
{
    mRunning = true;
    boost::circular_buffer<int> cb(100);
    Detacher thread_1;
    thread_1.createTask(foo_1, &cb);
    Detacher thread_2;
    thread_2.createTask(foo_2, &cb);
    std::this_thread::sleep_for(std::chrono::milliseconds(20000));
    mRunning = false;
}

Cannot dereference generic iterator type

I was just trying to build something that involved a generic iterator type, specifically something that chains iterators, but I cannot dereference the iterator. MVE:

#include <iterator>

#include <iterator>
#include <vector>

int main() {
    std::vector<int> a = {1};
    std::iterator<std::random_access_iterator_tag, int> my_iterator = a.begin();
    int my_int = *my_iterator;
    return 0;
}

Error:

iterator.cxx:6:57: error: no viable conversion from 'std::__1::vector<int, std::__1::allocator<int> >::iterator'
      (aka '__wrap_iter<int *>') to 'std::iterator<std::random_access_iterator_tag, int>'
    std::iterator<std::random_access_iterator_tag, int> my_iterator = a.begin();
                                                        ^             ~~~~~~~~~
/Applications/Xcode-9.4.1.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/iterator:531:29: note: 
      candidate constructor (the implicit copy constructor) not viable: no known conversion from
      'std::__1::vector<int, std::__1::allocator<int> >::iterator' (aka '__wrap_iter<int *>') to 'const
      std::__1::iterator<std::__1::random_access_iterator_tag, int, long, int *, int &> &' for 1st argument
struct _LIBCPP_TEMPLATE_VIS iterator
                            ^
/Applications/Xcode-9.4.1.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/iterator:531:29: note: 
      candidate constructor (the implicit move constructor) not viable: no known conversion from
      'std::__1::vector<int, std::__1::allocator<int> >::iterator' (aka '__wrap_iter<int *>') to
      'std::__1::iterator<std::__1::random_access_iterator_tag, int, long, int *, int &> &&' for 1st argument
1 error generated.

Is there some other generic iterator class I'm unaware of that has this functionality?

Access IP camera (rtsp) using OpenCV (C++) in Docker?

I am trying to build a docker image to get the video streams from the IP camera and take each frame for further processing using:

Ubuntu 18.04 OpenCV 4.1 C++ 11 Docker

I have tried to use the webcam on the laptop using the following docker command and it works:

docker run -i -t --device /dev/video0 <docker image> /bin/bash

C++ code:

    VideoCapture cap;  

    if(videoStreamUrl=="0")
    {
        std::cout <<"default camera applied"<< std::endl;
        cap.open(0);
    }
    else
    {
        std::cout <<"Video stream address: "<< videoStreamUrl << std::endl;
        cap.open(videoStreamUrl);
    }

    if (!cap.isOpened())
    {  
        std::cout << "Couldn't open camera : " << endl;  
        return -1;  
    }

but when I am trying to use the rtsp url of the IP camera in docker, it is not working:

to start the docker :

docker run -i -t <docker image> /bin/bash

in the cpp code shown above

let videoStreamUrl = rtsp://name:pwd@ and cap.isOpened() is always false in docker image (but works in my local linux system).

may I check is there anything missing ?

Thanks a lot !

inputMask fills QLineEdit with spaces

When i set inputMask to "99999" , run programm, and mouse clicking to QLineEdit, it filled with 5 spaces, so i have to delete the spaces first, and only then put the value i need.

I've tried to set cursor position to 0 ,but it doesn't work. Also tried to set text to empty string, same result.

ui->engineCapacity_lineEdit->setInputMask("99999");
ui->engineCapacity_lineEdit->setCursorPosition(0);
ui->engineCapacity_lineEdit->setText("");

It suppose to put cursor to the begining of lineEdit, instead it's on 5th character of the line

dimanche 28 juillet 2019

Why would you use a hash table over an AVL Tree for determining if a value was seen before? Is a hash table a better choice?

Is there ever a case where an AVL Tree would be a better choice?

How to fix error Undefined symbols for architecture x86_64

I am trying to code a very simple class in C++11 but I am getting the compiler error 'Undefined symbols for architecture x86_64'. What does it mean? How do I deal with it?

I am using Visual Studio Code for MacOS and the compiler Clang-8 (updated 2 days ago).

Here are the 3 files I have written so far:

*------------------------------------------------------------------*/
class Point
{
    // Type declaration statements for data members
    private:
    double xCoord, yCoord; // Class atributes

    public:
    // Declaration statements for class methods
    // Constructors for Point class
    Point(); // Default constructor
    Point(double x, double y); // Parameterized constructor
};
/*------------------------------------------------------------------*/

/*------------------------------------------------------------------*/
#include "Point.h" // Required
#include<iostream> // Required for cout

using namespace std;

// Default constructor
Point::Point()
{
    cout << "Constructing point object, default: \n";
    cout << "Initializing to zero" << endl;
    xCoord = 0.0;
    yCoord = 0.0;
}

// Parameterized constructor
Point::Point(double x, double y)
{
    // Input paraneters x and y
    cout << "Constructing point object, parameterized: \n";
    cout << "Input parameters: " << x << "," << y << endl;
    xCoord = x;
    yCoord = y;
}
/*------------------------------------------------------------------*/

/*------------------------------------------------------------------*/
#include<iostream> 
#include "Point.h"

using namespace std;

int main()
{
    // Declare and initialize objects
    cout << "In main, declare p1... " << endl;
    Point p1;
    cout << "\nIn main, declare p2... " << endl;
    Point p2{1.5, -4.7};
    return 0;
}
/*------------------------------------------------------------------*/

The full error message is:

Undefined symbols for architecture x86_64: "Point::Point(double, double)", referenced from: _main in cpp14test-15cf25.o "Point::Point()", referenced from: _main in cpp14test-15cf25.o ld: symbol(s) not found for architecture x86_64 clang-8: error: linker command failed with exit code 1 (use -v to see invocation) The terminal process terminated with exit code: 1

Return type agnostic template class member function

I have a class like:

tempate<class TReturn>
struct MyClass {
 template<class T>
 TReturn doSomething(const T &t) {
  // Do something
  return someValue;
 }
};

Now TReturn can be anything even void but in case it is void I want no return statement at the end and some minor different code in the function. What I want is a different function body depending on the return type. I'm using C++11 so if constexpr is not possible for me. Is there any way to to this in plain C++11?

parameter-pack-like usages acted wired

I want to have a function with a variadic parameter number, there are two ways to achieve this - parameter pack from C++11 - va_list from C lang I think. The C way is not good, because it has no type information provided

official parameter pack is something used in template classes/functions, but it is compilable when being outside of a template, which acted wired, what's the right way to achieve this?

#include<iostream>

class A {
 public:
  int a;
  int P(A* args ...) {
    for(A *m: { args  }) {
      std::cout << m->a << " ";
    }
  }
};


int main() {
  A AA[10];
  for(int i = 0; i < 10; i++) {
    AA[i].a = i+1;
  }
  AA[0].P(AA+1, AA+2, AA+3, AA+4);
}


This c++11 code printf 2, which is far away from what I expected to be 2 3 4 5, why?

need your help for C++ homework

ı wanna write find function for my basic string class

but I could not do it look my code and give me idea how to create this function with loops and strcmp strcat etc.. ?

private: enum{SIZE=50}; char data[SIZE];

public:

MyPatient()
{
    data[0] = '\0';
}


//1 arg structor
MyPatient( char const k[])
{
    strcpy_s(data, k);
}

//destructor 
~MyPatient()    {};

     int find( const MyPatient  k)  ???
{

    return (strcmp(k.dizi, dizi));


}

explain by giving a code example

Do we need to set move constructor = default? For legacy classes with user declared destructor buildet with C++98/03 in the past?

So the question is, lets consider a big legacy project in c++ in the past always build for C++98/03 standard.

And the project followed the rule of three, so therefore there are a lot of user defined destructors in the project.

If now the project is build for standard C++11/14/17, is it a good idea to set the move constructor = default manually?

Because due to the slide shown by Howard Hinnant at Accu_2014 these classes are not automatically provided with an move constructor. ACCU2014 Howard Hinnant, Special Members

So the question is could the project benefit in performance by setting the move constructor = default for every class?

And to be more precise, lets say after setting the move constructor = default the application runs exactly as before and all unit test work as before.

Do you think there will be a performance benefit by defining the move constructor = default?

Thanx

Unpack C++ array to arguments on a function call

I'm implementing a library capable of understanding Godot's RPC requests.

From the RPC request, I have made an array of arguments of arbitrary size. The arguments are all of the same type, Variant. Each Variant contains a type enum and casting overloading to return the proper type, be it an int or a const char*, etc.

Now, I'd like to have the library accept registrations of function points, or std::function instances, etc. The library should be able to unpack this array Variant* to arguments on the registered function.

i.e.

std::function<void(int, float, const char*)> foo;


Variant* args = ...;
size_t numArgs = ...;

/**
 * For example,
 * if (args[0].type == VAR_INT) {
 *     int arg_int = (int)args[0];
 * }
 * would be valid.
 */

foo(args...);

Is there a way to make this possible?

Thanks,

How to inplace construct std::map

I was learning about the in-place construction of std::map and I found a solution using emplace and std::piecewise_construct, std::forward_as_tuple.

std::map emplace without copying value

I tried it with an example class in which I deleted the copy constructor and allowed only move. The map looks like std::map<int, std::array<Class, 2>> myMap;.

#include <iostream>
#include <string>
#include <map>
#include <tuple>
#include <array>

class Class
{
    int m_var;
    std::string m_str;
public:
    Class(int var, const std::string& str) : m_var(var), m_str(str)
    {
        std::cout << "Cont'r called...\n";
    }
    Class(const Class&) = delete;
    Class& operator=(const Class&) = delete;
    Class(Class&& other) :m_var(std::move(other.m_var)), m_str(std::move(other.m_str))
    {
        std::cout << "Move called...\n";
    }
    Class& operator=(Class&& other)
    {
        this->m_var = std::move(other.m_var);
        this->m_str = std::move(other.m_str);
        std::cout << "Move= called...\n";
        return *this;
    }
};

using Value = std::array<Class, 2>;
int main()
{
    std::map<int, Value> myMap;
    // create in place the objects
    myMap.emplace(
        std::piecewise_construct,
        std::forward_as_tuple(1),
        std::forward_as_tuple(
            Class{ 10, std::string("ten") },   // here is the problem
            Class{ 20, std::string("twenty") }
        )
    );

    return 0;
}

But it gave me a lot of error, which I couldn't understand. Could you please tell me what I did wrong here? I'm using C++11.

Thanks in advance!

In file included from /opt/wandbox/gcc-6.3.0/include/c++/6.3.0/bits/stl_map.h:63:0,
                 from /opt/wandbox/gcc-6.3.0/include/c++/6.3.0/map:61,
                 from prog.cc:3:
/opt/wandbox/gcc-6.3.0/include/c++/6.3.0/tuple: In instantiation of 'std::pair<_T1, _T2>::pair(std::tuple<_Args1 ...>&, std::tuple<_Args2 ...>&, std::_Index_tuple<_Indexes1 ...>, std::_Index_tuple<_Indexes2 ...>) [with _Args1 = {int&&}; long unsigned int ..._Indexes1 = {0ul}; _Args2 = {Class&&, Class&&}; long unsigned int ..._Indexes2 = {0ul, 1ul}; _T1 = const int; _T2 = std::array<Class, 2ul>]':
/opt/wandbox/gcc-6.3.0/include/c++/6.3.0/tuple:1575:63:   required from 'std::pair<_T1, _T2>::pair(std::piecewise_construct_t, std::tuple<_Args1 ...>, std::tuple<_Args2 ...>) [with _Args1 = {int&&}; _Args2 = {Class&&, Class&&}; _T1 = const int; _T2 = std::array<Class, 2ul>]'
/opt/wandbox/gcc-6.3.0/include/c++/6.3.0/ext/new_allocator.h:120:4:   required from 'void __gnu_cxx::new_allocator<_Tp>::construct(_Up*, _Args&& ...) [with _Up = std::pair<const int, std::array<Class, 2ul> >; _Args = {const std::piecewise_construct_t&, std::tuple<int&&>, std::tuple<Class&&, Class&&>}; _Tp = std::_Rb_tree_node<std::pair<const int, std::array<Class, 2ul> > >]'
/opt/wandbox/gcc-6.3.0/include/c++/6.3.0/bits/alloc_traits.h:455:4:   required from 'static void std::allocator_traits<std::allocator<_CharT> >::construct(std::allocator_traits<std::allocator<_CharT> >::allocator_type&, _Up*, _Args&& ...) [with _Up = std::pair<const int, std::array<Class, 2ul> >; _Args = {const std::piecewise_construct_t&, std::tuple<int&&>, std::tuple<Class&&, Class&&>}; _Tp = std::_Rb_tree_node<std::pair<const int, std::array<Class, 2ul> > >; std::allocator_traits<std::allocator<_CharT> >::allocator_type = std::allocator<std::_Rb_tree_node<std::pair<const int, std::array<Class, 2ul> > > >]'
/opt/wandbox/gcc-6.3.0/include/c++/6.3.0/bits/stl_tree.h:543:32:   required from 'void std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_construct_node(std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Link_type, _Args&& ...) [with _Args = {const std::piecewise_construct_t&, std::tuple<int&&>, std::tuple<Class&&, Class&&>}; _Key = int; _Val = std::pair<const int, std::array<Class, 2ul> >; _KeyOfValue = std::_Select1st<std::pair<const int, std::array<Class, 2ul> > >; _Compare = std::less<int>; _Alloc = std::allocator<std::pair<const int, std::array<Class, 2ul> > >; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Link_type = std::_Rb_tree_node<std::pair<const int, std::array<Class, 2ul> > >*]'
/opt/wandbox/gcc-6.3.0/include/c++/6.3.0/bits/stl_tree.h:560:4:   required from 'std::_Rb_tree_node<_Val>* std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_create_node(_Args&& ...) [with _Args = {const std::piecewise_construct_t&, std::tuple<int&&>, std::tuple<Class&&, Class&&>}; _Key = int; _Val = std::pair<const int, std::array<Class, 2ul> >; _KeyOfValue = std::_Select1st<std::pair<const int, std::array<Class, 2ul> > >; _Compare = std::less<int>; _Alloc = std::allocator<std::pair<const int, std::array<Class, 2ul> > >; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Link_type = std::_Rb_tree_node<std::pair<const int, std::array<Class, 2ul> > >*]'
/opt/wandbox/gcc-6.3.0/include/c++/6.3.0/bits/stl_tree.h:2149:64:   required from 'std::pair<std::_Rb_tree_iterator<_Val>, bool> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_emplace_unique(_Args&& ...) [with _Args = {const std::piecewise_construct_t&, std::tuple<int&&>, std::tuple<Class&&, Class&&>}; _Key = int; _Val = std::pair<const int, std::array<Class, 2ul> >; _KeyOfValue = std::_Select1st<std::pair<const int, std::array<Class, 2ul> > >; _Compare = std::less<int>; _Alloc = std::allocator<std::pair<const int, std::array<Class, 2ul> > >]'
/opt/wandbox/gcc-6.3.0/include/c++/6.3.0/bits/stl_map.h:559:64:   required from 'std::pair<typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, typename __gnu_cxx::__alloc_traits<_Alloc>::rebind<std::pair<const _Key, _Tp> >::other>::iterator, bool> std::map<_Key, _Tp, _Compare, _Alloc>::emplace(_Args&& ...) [with _Args = {const std::piecewise_construct_t&, std::tuple<int&&>, std::tuple<Class&&, Class&&>}; _Key = int; _Tp = std::array<Class, 2ul>; _Compare = std::less<int>; _Alloc = std::allocator<std::pair<const int, std::array<Class, 2ul> > >; typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, typename __gnu_cxx::__alloc_traits<_Alloc>::rebind<std::pair<const _Key, _Tp> >::other>::iterator = std::_Rb_tree_iterator<std::pair<const int, std::array<Class, 2ul> > >]'
prog.cc:43:2:   required from here
/opt/wandbox/gcc-6.3.0/include/c++/6.3.0/tuple:1586:70: error: no matching function for call to 'std::array<Class, 2ul>::array(Class, Class)'
         second(std::forward<_Args2>(std::get<_Indexes2>(__tuple2))...)
                                                                      ^
In file included from /opt/wandbox/gcc-6.3.0/include/c++/6.3.0/tuple:39:0,
                 from /opt/wandbox/gcc-6.3.0/include/c++/6.3.0/bits/stl_map.h:63,
                 from /opt/wandbox/gcc-6.3.0/include/c++/6.3.0/map:61,
                 from prog.cc:3:
/opt/wandbox/gcc-6.3.0/include/c++/6.3.0/array:90:12: note: candidate: std::array<Class, 2ul>::array(std::array<Class, 2ul>&&)
     struct array
            ^~~~~
/opt/wandbox/gcc-6.3.0/include/c++/6.3.0/array:90:12: note:   candidate expects 1 argument, 2 provided

samedi 27 juillet 2019

Can i use Base Function in derived class

I have a base class

Class Base

int a; // Private member of Base

Function Test( int t) // public member of base class
  a = t;

Which is derived by another class

Class Derived : Public Base  // derived class of base

Can i call a base class function from a derived class Object

Derived d;
d.Test( 5 );

Two threads running the same io_service

https://youtu.be/rwOv_tw2eA4?t=1030

This example has one io_service and two threads running on it.

  • the io_service has two tasks attached to it: timer1 and timer2

  • two threads are created to run the io_service

void timer_expired( std:: string id )
{
    std::cout << timestamp() << ": " << id << ": begin\n";
    std::this_thread::sleep_for( std::chrono::seconds(3) );
    std::cout << timestamp() << ": " << id << ": end\n";
}

int main()
{
    boost::asio::io_service io_service;

    boost::asio::deadline_timer timer1( io_service, boost::posix_time::seconds(5) );
    boost::asio::deadline_timer timer2( io_service, boost::posix_time::seconds(5) );

    timer1.async_wait( []( auto ... ){ timer_expired("timer1"); });
    timer2.async_wait( []( auto ... ){ timer_expired("timer2"); });


    std::cout << timestamp() << ": calling io_service run\n";

    std::thread thread1( [&](){ io_service.run(); } );
    std::thread thread2( [&](){ io_service.run(); } );

    thread1.join();
    thread2.join();

    std::cout << timestamp() << ": done\n";

    return 0;
}

Every time I run this sample the output looks ok, in that:

  • the two timers started at the same time

  • the two timers expired at the same time (after 5s, they were async)

  • the callbacks were invoked at the same time (after 3s)

The author stated that this code has race in there andshould not work (garage output).

What's not very clear is that we have two threads, each can serve one completion handler (here the timer callback). So why race? And the fact that I ran this code several times and unable to produce any garbage output as what the author presented.

The output looks as expected, here's a sample:

2019-07-28 11:27:44: calling io_service run
2019-07-28 11:27:49: timer1: begin
2019-07-28 11:27:49: timer2: begin
2019-07-28 11:27:52: timer1: end
2019-07-28 11:27:52: timer2: end
2019-07-28 11:27:52: done

Avoiding spurious construction and destruction in RAII timer object

I have a Timer object which should time the region of code from its construction to its destruction. These Timer objects are created by and associated with a long-lived TimerMananger object. In fact, the Timer objects are just thin wrappers around a pointer to TimerManager which does the heavy lifting.

I'd like the user the Timer objects like this:

TimerManager manager; // maybe a global, thread local, whatever

...
{
  Timer timer = manager.newTimer();
  // code under test

} // timer object destroyed and timer stops here

The Timer object can be as simple as:

class Timer {
  TimerManger* manager_;
public:
  Timer(TimerManger* manager) : manager_(manager) {
    manager_->start();
  }

  ~Timer() {
    manager_->stop();
  }
};

Here all the heavy lifting of starting and stopping the timer is delegated to the manager.

However, if I implement TimerManager::newTimer() like so:

TimerManager::newTimer() {
  Timer t(this);
  // ...
  return t;
}

Then depending on whether RVO kicks in, I may get a spurious construction and destruction of Timer object t, different from the real region I want to time in the calling code.

I could instead use the following code to initialize Timer objects:

{
  Timer timer(&manager);
  // code under test

} // timer object destroyed and timer stops here

This ensures extra Timer objects are not created or destroyed, but I prefer the assignment syntax, especially since it lets me have various newTimer() type methods with different behavior. Is there any way to get something like this w/o having the extra side effects of Timer creation and destruction.

Performance matters here.

I am not using C++17 so I cannot avail myself of guaranteed return value optimization.

Using cin and cout in different threads. Why is the cin buffer removing the first char?

I am trying to make a socket program that lets two people chat. I have one thread for sending a message and another for receiving a message. When I use cin, it cuts off the first char that I input.

I've been looking at different threads here about cin and cout being tied and not being very thread safe, but nothing has worked.

Here is my send and receive threads: RECV

char buffer[32];
  while(true)
  {
    memset(&buffer, 0, sizeof(buffer));
    unsigned long bytes_recv;

    bytes_recv = recv(socketfd, &buffer, sizeof(buffer), 0);

    if(bytes_recv == 0)
    {
      break;
    }

    for(unsigned long i = 0; i < bytes_recv; i++)
    {
      buffer[i] = buffer[i] ^ key;
    }

    printf("Message Received: %s\n", buffer);
  }

and Send

char buffer[32];
  int conn = 1;
  while(true)
  {
    memset(buffer, 0, sizeof(buffer));

    std::cout << "Send a message to host: ";
    std::cin.clear();

    std::cin.getline(buffer, sizeof(buffer));

    std::cout << "StrLen: " << strlen(buffer) << std::endl;

    for(unsigned long i = 0; i < strlen(buffer); i++)
    {
      std::cout << "Char: " << buffer[i] << std::endl;
      buffer[i] = key ^ buffer[i];
    }
    conn = send(socketfd, &buffer, strlen(buffer), 0);
    if(conn == -1)
    {
      break;
    }
  }

If I type "Hello", the buffer only reads "ello" even from the cin thread.

Custom Functions in C++ Template

If I am using a C++ class with a template parameter of an int like:

template<int width> class ap_uint { ... }

then I understand that I can create specific definitions from this type of certain widths like:

typedef ap_uint<72> data_t;

However, if I wanted to say define a constant and pass that in, what are my options (other than define)? Say something like this:

#define WIDTH 72
typedef ap_uint<WIDTH> data_t;
typedef ap_uint<WIDTH / 8> mask_t; // Does this even work?

Further would it be possible to define a function or use an existing one in the template parameter selection? Something like this:

#define SIZE 1024
typedef ap_uint<ceil(log(SIZE, 2))> addr_t;

I am fine having to write the functions myself, if that is even possible.

Why Knight Tour Problem is taking so much time in this code?

I wrote down the code for knight tour problem, I couldn't figure out what is the actual issue with the solution, it's running fine upto n=6, but after that, it is taking a long time to run. It's showing correct output but taking a really long time as I put n=7 or n=8 or higher. Here's my code :

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

bool isSafe(vector<vector<int>> sol, int x, int y){
    int n=sol.size();
    return (x>=0 && x<n && y>=0 && y<n && sol[x][y]==-1);
}

bool findSolUtil(vector<vector<int>> &sol, vector<int> xMoves, vector<int> yMoves, int x, int y, int count){
    int n=sol.size(), i, next_x, next_y;
    if(count==n*n){
        return true;
    }
    for(i=0; i<8; i++){
        next_x = x+xMoves[i];
        next_y = y+yMoves[i];
        if(isSafe(sol, next_x, next_y)){
            sol[next_x][next_y] = count;
            if(findSolUtil(sol, xMoves, yMoves, next_x, next_y, count+1)){
                return true;
            }
            sol[next_x][next_y] = -1;
        }
    }
    return false;
}

void findSol(int n){
    vector<vector<int>> sol(n, vector<int>(n, -1));
    vector<int> xMoves = {2, 1, -1, -2, -2, -1, 1, 2};
    vector<int> yMoves = {1, 2, 2, 1, -1, -2, -2, -1};
    sol[0][0] = 0;
    cout << findSolUtil(sol, xMoves, yMoves, 0, 0, 1);
}

int main(){
    int n;
    cout << "Size of the board is nXn, enter n : ";
    cin >> n;
    findSol(n);
    return 0;
}

What's the difference between' bool operator()' and 'bool operator <'?

I was trying to make objects of a set and when I searched in StackOverflow I found a suggestion which worked: bool operator<(.....). what does this mean? and how it's different from bool operator () ?

i tried replacing < with () but it threw an error

bool operator<(const hello &p1) const{}

(hello is a struct)

Accessing outer class from inner class without explicitly passing an instance

The following code produces the output

outer::inner::inner, o=00000000
outer
outer::inner::val, o=00000000
outer::print

Can anyone explain how I can access the outer class method print through o without explicitly assigning o's value at construction?

#include <iostream>

class outer {
public:
    outer() { 
        std::cout << __func__ << std::endl; 
    }

    class inner {
        outer *o = nullptr;
    public:
        inner() { 
            std::cout << __FUNCTION__ << ", o=" << o << std::endl;
        }
        void val() { 
            std::cout << __FUNCTION__ << ", o=" << o << std::endl;
            o->print(); // **call outer class method**
        }
    };

    inner i;

    void print() { 
        std::cout << __FUNCTION__ << std::endl;
    }
};

int main()
{
    outer o;
    o.i.val();

    return 0;
}

This way, I can do something like

template <typename T>
class example {
    outer *c = nullptr;
public:
    void fn() {
        c->print();
    }
};

if I have

class outer {
    // other code
public:
    example<int> ie;
    // other code
};

Why is this not counting correctly?

I am reading text from a text file and need to know the number of characters in the file in total. I thought this should work but it always seems to be overcounting. For example I typed this into my text file:

thisisatestthisisa thisisa

And the program returned a total of 32.

int main() {

fstream inFile;
string inputString;

inFile.open("text.txt", ios::in);

unsigned int total = 0;
if (inFile) {
    while (inFile)
    {
        getline(inFile, inputString);

        unsigned int tempStringLength = inputString.length();
        total += tempStringLength;
    }
    cout << "total is: " << total << endl;
}
else {
    cerr << "Unable to open file text.txt";
    exit(1);
}

    return 0;

}

what does this ''(const vector

I'm facing some issue in understanding the following segment of code (const vector<vector<int> > &A). Will it define a 2D array?

What triggers and End of File?

I'm pretty new to programming, and recently, my class started file handling using C++. My question is what triggers an end of file? Just like there is "\n" for a new line character, is there something specific that the compiler looks at to know if it is eof? An answer with lots of juicy details is much appreciated!

Wait for a user input for 5 seconds and use a default value otherwise in c++

well, I'm working on a project that asks the user to input a number for 5 seconds and if the user fails to enter the number in 5 seconds the program aborts itself. I'm really stuck because when I ask the input from cin function it stays until the user enters the number.

I've tried sleep functions but it doesn't work

time_t futur = time(NULL) + 5;
while(true)//time(NULL) < futur)
{    
cout<<"\n-Press 0 to De-Activate Auto Abort... ";
chrono::duration<int, std::milli> timespan(5000);
this_thread::sleep_for(timespan);
if(time(NULL) > futur)
{   
cin>>Abort;
if(Abort==0)
{
break;
}
else
exit(0);
}

constexpr works on Ubuntu, but not MacOS

I have this code which compiles fine on Ubuntu, but when I try to compile it on MacOS I get this error:

Constexpr variable 'HeuristicNames' must be initialized by a constant expression

#define LSHPair std::pair<const char *, LISTSCHED_HEURISTIC>
static constexpr LSHPair HeuristicNames[] = {
    LSHPair("CP", LSH_CP),    LSHPair("LUC", LSH_LUC),
    LSHPair("UC", LSH_UC),    LSHPair("NID", LSH_NID),
    LSHPair("CPR", LSH_CPR),  LSHPair("ISO", LSH_ISO),
    LSHPair("SC", LSH_SC),    LSHPair("LS", LSH_LS),
    LSHPair("LLVM", LSH_LLVM)};

LISTSCHED_HEURISTIC is an enum.

I take this error to mean that some part of the right hand side of the assignment is not a constexpr, so the resulting variable can't be a constexpr. However I don't have a firm enough grasp of the rules around constexpr to understand why, or how to fix it.

I also don't get why this is different on MacOS than on Ubuntu. Can anyone shed some light on this?

Why am I getting a conversion function error?

I have to read in an external file called text.txt. The file could contain a lot of data (and def > 83 chars) and I want to ignore the spaces. Then I need to get the total amount of chars in the file (not incl. spaces). I have to use strlen. I am getting a conversion type error which is confusing because I thought strlen returns an int. The error is where I have made the text bold.

int main() {

fstream inFile;
string inputString;

inFile.open("text.txt", ios::in);

if (inFile) {
    getline(inFile, inputString, ' ');
    while (inFile)
    {
        int tempStringLength = strlen(**inputString**);
        int total = 0;
        total += tempStringLength;
    }
}
else
    cerr << "Unable to open file text.txt";
    exit(1);

    return 0;

}

I expect the total to be the total # of chars in the file.

vendredi 26 juillet 2019

Why this code is doing wrong calculations?

When tried to debug this code I noticed that the value of sum as mentioned in code tend to give wrong results. I cant understand why this is happening. I know I would get a lot of downvotes and my question too would be closed, but I'm in dire need of solution...

I've already tried debugging through the code and can't understand what's wrong with the code

#include <iostream>
using namespace std;

int main()
{
long long int t,j,n,l,count=0,sum=0;
cin>>t;
string s;
//char i;
while(t>0)
{
    l=0;
    sum=0;
   count=0;
    cin  >>  s;
    n= s.length();
    for(j=0;j<n;j++)
    {
        if(s[j]=='a' || s[j]=='e' || s[j]=='i' || s[j]=='o' || s[j]=='u' || s[j]=='A'|| s[j]=='E' || s[j]=='I' ||s[j]=='O' || s[j]=='U')
        {
              count++;
             l=j;

             cout<<"l="<<j<<endl;
             cout<<"j="<<j<<endl;
             cout<<"n="<<n<<endl;
             cout<<"n-1="<<n-1<<endl;
             cout<<"j+1="<<j+1<<endl;

            sum=sum+((n-l)*(j+1));

            cout<<"SUM is="<<sum << endl;
        }
    }
     if(l==0)
        {
            sum=0;
        }
        cout<<"Second part Sum="<<endl;
    cout<<sum<<endl;
    t--;
}

}

Program is working correctly and efficiently, No error messages, it's running well but there seems to be a dilemma about the calculations of sum...[![enter image description here][1]][1]

Generate 3D Mesh from extruded Polygon

How to generate a 3D Mesh from a "2.5D" polygon with an additionally given extrusion? Preferably using a mature and well tested library in C++.

Background: I'm given a Geojson file which contains a simple type polygon geometry, including x,y,z data. I'm also given an "extrusion" parameter as part of the Feature Properties.

I was looking at CGAL, seems a good fit for the mesh generation. But I'm not sure about how to generate a geometry from the extruded 2.5D data, and I'm not sure what intermediate geometry type to use.

How do I properly pass this pointer to std::thread

ALL,

In myclass.cpp

MyClass::Initialize()
{
    m_thread = new std::thread( &Foo::func, *this );
}

In foo.cpp:

void Foo::func(MyClass &obj)
{
    // some processing
    // which involves modifying `obj`
}

I am getting a compiler error on gcc:

error: no type named 'type' in 'class std::result_of<std::_Mem_fn<void (Foo::*)(MyClass&)>(Foo*, MyClass)>'
       typedef typename result_of<_Callable(_Args...)>::type result_type;
                                                             ^

TIA!

Is it safe to use a vector as a queue with multithreading?

Can a vector be written to by multiple threads without worrying about any potential race conditions between the threads trying to push_back a value at the same time? The underlying hardware/os will take care of everything and ensure theres no potential for the program crashing or failing right?

Just wanted to experiment with a simple example that didnt use locks mutexes or atomics.

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

using namespace std;

std::vector<int> myvector;


void append(int value)
{
  myvector.push_back(value);
}


int main()
{

 int val1=1;
 int val2=2;
 int val3=3;

 std::thread t1(append,val1);
 std::thread t2(append,val2);
 std::thread t3(append,val3);

 t1.join();
 t2.join();
 t3.join();



 for(int x=0; x<myvector.size(); ++x)
        std::cout<<myvector[x]<<endl;


 return 0;

}

Running the program many times gives expected results of various combinations of push_backs by the threads

Enum Class Operator Overload no match found for operator

I'm attempting to overload some operators for an Enum class. I get a compiler error saying it's unable to find the operator

In Enum.h

enum class SomeEnum : unsigned
{
    Test0 = 0,
    Test1  = (1 << 0),
    Test2  = (1 << 1),
};

In Enum.cpp

#include "Enum.h"
#include <type_traits>
SomeEnum operator|(SomeEnum lhs, SomeEnum rhs)
{
    return static_cast<SomeEnum > (
        static_cast<std::underlying_type<SomeEnum >::type>(lhs) |
        static_cast<std::underlying_type<SomeEnum >::type>(rhs)
    );
}

in main.cpp

#include "Enum.h"
int main()
{
  SomeEnum blah = SomeEnum::Test1 | SomeEnum::Test2; 
}

The compiler spits out an error saying: no match for 'operator|' (operand types are 'SomeEnum ' and 'SomeEnum ')

Extending namespace std to implement make_unique when using C++11

I came across a codebase that is fixed on C++11 features but implements std::make_unique. That is been done extending namespace std to add the feature if C++14 is not use, i.e. wrapping the implementation around

#if defined(__cplusplus) && __cplusplus < 201402L

namespace std {
  ...
}

#endif

I know that is undefined behavior to extend namespace std (with some exception). Is the case above still acceptable or should it be avoided in any case?

jeudi 25 juillet 2019

Passing lambda to asio async_wait

Why passing a lambda to asio asyn_wait() needs auto ... parameter, whereas passing a function doesn't require such a thing (ie just function name would be ok) as in timer.async_wait( &print );

int main()
{
    boost::asio::io_service io_service;

    boost::asio::deadline_timer timer( io_service, boost::posix_time::seconds(5) );
    timer.async_wait( []( auto ... ){   //# ?
        std::cout << timestamp() << ": timer expired\n";
    });

    std::cout << timestamp() << ": calling io_service run\n";

    io_service.run();

    std::cout << timestamp() << ": done\n";

    return 0;
}

It is possible to turn off thread safety in C++

I'm building an IO intensive distributed system, and I plan to make the process stateless in order to provide a single threaded, but scalable, runtime. I started the project in C, with libuv, and it worked great, with awesome performances. However, the development is taking much time, as C requires a lot of boilerplate code.

Therefore, I'm evaluating C++ as an alternative, however, I haven't found any way to opt out of thread safe structure such as std::shared_ptr. Is there any way, in clang or gcc, to disable atomic access to the standard library structure, as to have a single threaded process without any mutex/atomic overhead?

Erase item from vector passed to new thread C++

I have a program that saves in a vector a reference and the thread id of the newly created thread.

void remote_forwading_thread(std::vector<std::pair<std::thread::id, std::thread>>& thread_vector) {
  [...]
   for (const auto& th : thread_vector) {
        if (th.first == std::this_thread::get_id()) {
            thread_vector.erase(th); <--- ERROR
            break;          
        }
    }
}

std::vector<std::pair<std::thread::id, std::thread>> thread_vector;
[...]
std::thread t(remote_forwading_thread, &thread_vector);
thread_vector.emplace_back(std::make_pair(t.get_id(), std::move(t)));

The errors I'm getting are:

1>C:\Users\user\Documents\code\project\src\client.cpp(214,79): error C2100: illegal indirection 1>C:\Users\user\Documents\code\project\src\client.cpp(220,35): error C2664: 'std::_Vector_iterator>> std::vector<_Ty,std::allocator<_Ty>>::erase(std::_Vector_const_iterator>>,std::_Vector_const_iterator>>)': cannot convert argument 1 from 'const std::pair' to 'std::_Vector_const_iterator>>' 1>C:\Users\user\Documents\code\project\src\client.cpp(220,35): error C2664: with 1>C:\Users\user\Documents\code\project\src\client.cpp(220,35): error C2664: [ 1>C:\Users\user\Documents\code\project\src\client.cpp(220,35): error C2664: _Ty=std::pair 1>C:\Users\user\Documents\code\project\src\client.cpp(220,35): error C2664: ] 1>C:\Users\user\Documents\code\project\src\client.cpp(220,33): message : No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

What am I doing wrong?

c++ - Convert character array to int

Trying to convert a character array to int data type in c++11. Why is the int value i different than the character array value?

// Example program
#include <iostream>
#include <string>

int main()
{
    char value[] = "51093843802";
    printf("%s\n", value);
    int i = std::atoi(value);
    printf("%d\n", i);
}



51093843802
-445763750

Adding namespace to enum types in flatbuffer schema

I am working on a tool to convert json schema to flatbuffer schema (.fbs). I have a Json schema which is perfectly valid. While I try to achieve that I am facing the issue of duplicated enumeration. So I'm thinking of adding namespaces to my enums and tables in my fbs. Is this possible?

Is it possible to set Thread Priority using std::thread constructor?

I was wondering if we could set the priority for a thread during std::thread construction. As long as I have seen from the CppReference, I do not find any constructor to set priority. If so, then how do I set the priority in platforms like Windows and Unix.

Do we have a better/unified way to set the priority?

Should "if (argc < 2 || argc > 2)" be fine with 2 arguments? & terminate called after throwing an instance of 'std::out_of_range' error

This is a continuation of my previous question: error: no matching function for call to, which allowed the code to compile without any errors

I am new to C++ and I am trying to debug this code from my supervisor.

The original code took a csv file as input, containing rows and columns of integers and strings. Now we're reading in a txt file having the shape:

TEXT 0; INT; INT; INT; INT; ... 0; INT; INT; INT; INT; ... 18 more lines of the above numbers and semicolons

In that file I replaced in one instance the semicolons by line breaks and in another by empty spaces, because I was not sure which we needed.

  • It seems to have an issue with if (argc < 2 || argc > 2) . It throws the "Usage: ./a.o <> <>" error message. However, both are strict inequalities. Shouldn't this if be fine with 2 arguments? In the original code it read if (argc < 2 || argc > 3) , which I changed it back to.

  • Both txt files (line breaks & spaces) seem to produce the same error message below

Error message: (For the int threshold I tried various values)

Registering only edges shorter than int.
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 1) >= this->size() (which is 1)
Aborted (core dumped)

Ideas:

I am aware what this error message means when we have a simple case, for example:

#include <vector>

int main()
{
    std::vector<int> v;
    v.push_back(123); // v has 1 element  [0 to 0]
    int x4 = v.at(3); // exception
}

We get an exception, because v has 1 element and element 3 does not exist.

However, in my code I am not sure what exactly to look for.

The original code read a csv with lines and columns, but in this case a matrix form with empty spaces in between is probably causing issues. Does that mean that I just want a txt file looking like a column vector? That is one file I tried, so it might be that the code is not happy with the amount of columns?

Relevant function:

int main(int argc, char** threshold_and_distanceMatrixfilename)
{
    if (argc < 2 || argc > 3) 
    {
        std::cerr << "Usage: ./distanceMatrixToSageGraph.o <threshold> 

            <distanceMatrix_file_calculated_fromDGEsingleCell_data>" << std::endl;
            return -1;
    }
    string distanceMatrixfilename = threshold_and_distanceMatrixfilename[2];
    int threshold = std::stoi(threshold_and_distanceMatrixfilename[1]);
    std::ifstream distanceMatrixFile(distanceMatrixfilename);

    if (!distanceMatrixFile)
    {
        std::cerr << "Error opening distanceMatrix file: " << distanceMatrixfilename << std::endl;
        return -1;
    }
    string row;
    std::getline(distanceMatrixFile, row); // discard the first row, which specifies the format of the file.
    vector<vector<int>> the_entries;

    while (std::getline(distanceMatrixFile, row))
    {
        std::stringstream row_as_stringstream(row);
        int i; i = 0;
        vector<string> row_as_vector;

        while (row_as_stringstream.good())
        {
            string substr;
            getline(row_as_stringstream, substr, ',');
            row_as_vector.push_back( std::stoi(substr) );
        };
        the_entries.push_back(row_as_vector); //LINE 104
    };
}

Whole code:

// Convert distanceMatrix tables of protein interactions to SAGE graph.
///////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <fstream>
#include <sstream>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <list>
#include <vector>
#include <tuple>
#include <algorithm>
using namespace std;

void writeGraphInSageFormat(string name, std::vector<std::vector<int>> TheEdges) 
{
    //////////////////////////////////////////////////////////////////////////////////////
    // Write out the edges in SAGE format.
    ///////////////////////////////////////////////////////////////////////////////////////
    int edgeNumber = TheEdges.size();
    ofstream d1sageFile(name, ios::out);
    d1sageFile << "g = Graph([" << endl;

    for (int n = 0; n < edgeNumber; n++) {
        d1sageFile << "(" << TheEdges[n][0] + 1 << "," << TheEdges[n][1] + 1 << ")," << endl;
    }
    d1sageFile << "])" << endl;
    d1sageFile << "g.show()" << endl;
    d1sageFile.close();
    std::cout << "SAGE graph written into the file " << name << std::endl;
}

std::vector<std::vector<int>> ConvertEntriesMatrixToEdges(vector<vector<int>> the_entries, int threshold) 
{
    ////////////////////////////////////////////////////////////////////////////////////////////
    // Construct the edge-vertex incidence matrix (d_1) from the distanceMatrix entries matrix:
    ////////////////////////////////////////////////////////////////////////////////////////////
    std::vector<std::string> proteinNames;
    std::vector<std::vector<int>> TheEdges;
    std::cout << "Registering only edges shorter than " << threshold << "." << std::endl;
    int thisDistance;
    for (int i = 0; i < the_entries.size(); i++)
    {
        for (int j = i + 1; j < the_entries.size(); j++)
        {
            // we could use the_entries.size() instead of the_entries.at(i).size(), because this is a square matrix.
            thisDistance = the_entries.at(i).at(j);
            if (thisDistance < threshold) 
            {
                std::vector<int> CurrentEdge(2);
                CurrentEdge[0] = i;
                CurrentEdge[1] = j;
                TheEdges.push_back(CurrentEdge);
            };
        };
    };
    return TheEdges;
}

///////////////////////////////////////////
// Main Program: Extract edges from a distanceMatrix file.
///////////////////////////////////////////
int main(int argc, char** threshold_and_distanceMatrixfilename)
{
    if (argc < 2 || argc > 3)
    {
        std::cerr << "Usage: ./distanceMatrixToSageGraph.o <threshold> <distanceMatrix_file_calculated_fromDGEsingleCell_data>" << std::endl;
        return -1;
    }
    string distanceMatrixfilename = threshold_and_distanceMatrixfilename[2];
    int threshold = std::stoi(threshold_and_distanceMatrixfilename[1]);
    std::ifstream distanceMatrixFile(distanceMatrixfilename);
    if (!distanceMatrixFile) {
        std::cerr << "Error opening distanceMatrix file: " << distanceMatrixfilename << std::endl;
        return -1;
    }
    string row;  //LINE 88
    std::getline(distanceMatrixFile, row); // discard the first row, which specifies the format of the file.
    vector<vector<int>> the_entries;

    while (std::getline(distanceMatrixFile, row))
    {
        std::stringstream row_as_stringstream(row);
        int i; i = 0;
        vector<string> row_as_vector;
        while (row_as_stringstream.good())
        {
            string substr;
            getline(row_as_stringstream, substr, ',');
            row_as_vector.push_back( std::stoi(substr) );
        };
        the_entries.push_back(row_as_vector); //LINE 104
    };
    ////////////////////////////////////////////////////////////
    // Now we assemble the entries to an edges matrix, and write it into a Sage file:
    ////////////////////////////////////////////////////////////
    std::vector<std::vector<int>> TheEdges = ConvertEntriesMatrixToEdges(the_entries, threshold);    
    char outputFilename[60]; strcpy(outputFilename, distanceMatrixfilename.c_str()); strcat(outputFilename, "AtThreshold"); string thrshld = std::to_string(threshold); strcat(outputFilename, thrshld.c_str()); strcat(outputFilename, ".txt");
    writeGraphInSageFormat(outputFilename, TheEdges);
    return 0;
}