mardi 30 avril 2019

How to add info from txt file to hash table

How to implement the addInfo function. We have to find and sort the lines based on their serial number using chaining hash function. But before I need to do addInfo. For example: the first line "1009 1 "Royal Queen" 2015 160" the serial number is 1009 and if there is other ships that have the serial number ended with 9 we have to display them together. Here is the code that I have so far:

#include <iostream>
#include <fstream>
using namespace std;
struct ShipRecord
{
    int serialNum;
    int shipType;
    string name;
    int year;
    int cap;
    ShipRecord *next;
    ShipRecord(int x)
    {
        serialNum = x;
        next = nullptr;
    }
};
const int SIZE = 10;
class HashMgr
{
    ShipRecord *head = nullptr;
    ShipRecord *tail = nullptr;
public:
    HashMgr()
    {
        ShipRecord * hashTable[SIZE] = {nullptr};

        string line;
        ifstream myfile;
        myfile.open("shipRecords.txt");
        if(myfile.is_open())
        {
            while (!myfile.eof())
            {
                getline (myfile, line);
                addInfo(line);
            }
            myfile.close();
        }
    }
addInfo(string line)
    {}
displayOne(int serialNum)
    {}
displayAll()
    {}
int main()
{
    HashMgr hm;
    hm.displayAll();
    hm.displayOne(1009);
    hm.displayOne(1010);
    hm.displayOne(1019);
    hm.displayOne(1029);
    hm.displayOne(1039);
    hm.displayOne(1014);
    hm.displayOne(1008); /// Prompt a message to that the record does not exist
    hm.deleteOne(1009);
    hm.deleteOne(1039);
    hm.displayAll();
    return 0;
}
/*
Here is the txt.file
  1009 1 "Royal Queen"     2015 160
 1010   2  "Carnival"        2016  1600
 1019  1  "Ocean King"       2013  110
 1029 2 "Royal Prince"     2012 2000
 1039 2 "Royal Princess"  2010 2100
 1014 2 "Royal Caribbean" 2016 1600
*/

C++ pthread_join() causes segmentation fault

I am creating n POSIX threads and pushing them to a pthread_t vector. When I am joining them by iterating through the vector, I get a segmentation error. I checked and verified that the number of threads created is equal to the number of threads that I was trying to join. What may cause the segmentation fault? I will appreciate any help. Here is the sample:

std::vector<pthread_t> threadVector;

for (int i=0; i<inp1.size(); i++){
    pthread_t thread;
    threadVector.push_back(thread);
    int ii = pthread_create(&thread, NULL, mythread1, &(inp1[i]));
}

for (int i=0; i<inp2.size(); i++){
    pthread_t thread;
    threadVector.push_back(thread);
    int ii = pthread_create(&thread, NULL, mythread2, &(inp2[i]));
}

std::cerr<<inp1.size()+inp2.size()<<","<<threadVector.size()<<std::endl; 

for (auto& th : threadVector) 
    pthread_join(th, NULL);

C++ : What is done in the following example? Is it multiple Inheritance? [duplicate]

This question already has an answer here:

MainWindow::MainWindow(const char* f, QWidget* p) : QMainWindow(p), m_database() {
    // ................
}

Why is m_database used before the curly brackets? It can't be multiple Inheritance since m_database is not a class?

It is declared in the .h file like this.

private:
    BRLCAD::ConstDatabase m_database;

Qt5: call to non-static member function without an object when using dropMimeData

I am trying to implement a drag and drop function between rows of a QTableView. I am using this source as guideline for the implementation. However I have some problems when implementing dropMimeData to extend the drag and drop to the entire QTableView but there is a non static member function without an object argument error.

Here the part of the code that is throwing the error and that I am not sure how to take care:

tablemodel.h

class TableModel : public QAbstractListModel
{
    Q_OBJECT
public:
    TableModel();
    // additional functions....
    bool dropMimeData(const QMimeData *data, Qt::DropAction action,
                      int row, int column, const QModelIndex &parent);

private:
    QList<QStringList> m_data;

};

tablemodel.cpp

bool TableModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)
{
    Q_UNUSED(parent);
    Q_UNUSED(column);
    if(row == -1) {
        row = rowCount();
    }
    return QAbstractTableModel::dropMimeData(data, action, row, 0, parent); // <-- Error here
}

on the line return QAbstractTableModel::dropMimeData(data, action, row, 0, parent); the compiler throws the error of:

call to non-static member function without an object argumenmt

Thank you for shedding light on this problem

How to install SFML 2.5 to Clion on windows 10

I have problem with install sfml 2.5 to clion. I read this tutorial: https://www.sfml-dev.org/tutorials/2.5/compile-with-cmake.php , but i dont know how to connect this. At the beginning i connected sfml 2.5 by using cmake.gui. Can you explain me how to do this?

SFINAE works with deduction but fails with substitution

Consider the following MCVE

struct A {};

template<class T>
void test(T, T) {
}

template<class T>
class Wrapper {
    using type = typename T::type;
};

template<class T>
void test(Wrapper<T>, Wrapper<T>) {
}

int main() {
    A a, b;
    test(a, b);     // works
    test<A>(a, b);  // doesn't work
    return 0;
}

Here test(a, b); works and test<A>(a, b); fails with:

<source>:11:30: error: no type named 'type' in 'A'
    using type = typename T::type;
                 ~~~~~~~~~~~~^~~~
<source>:23:13: note: in instantiation of template class 'Wrap<A>' requested here
    test<A>(a, b);  // doesn't work
            ^
<source>:23:5: note: while substituting deduced template arguments into function template 'test' [with T = A]
    test<A>(a, b);  // doesn't work

LIVE DEMO

Question: Why is that? Shouldn't SFINAE work during substitution? Yet here it seems to work during deduction only.

How to tell if expression is evaluated at compile time or runtime?

I have a rather big Map object and I want to have a separate list that has the keys sorted. This will be used in many other source files of my poject.

The question is about how do I know when a decalaration/definition is a compile time job. Where should I look to find if this is the case? I mean how to tell?

In the following example, is the list in the source file a compile time job or it happens at runtime?

Also, is there a way that I make the sorting operation at compile time?

// global.h    
extern QMap<int, QString> G_MAP;
extern QList<int> G_MAP_SKEYS_SORTED; 

// global.cpp
QMap<int, QString> G_MAP = { /* some data */ };
QList<int> G_MAP_SKEYS_SORTED = G_MAP.keys();

// main.cpp
int mian() {
  // Somewhere I do the sort
  std::sort(G_ListRegistersSorted.begin(), G_ListRegistersSorted.end());
}

c++: Is it legal to define an unnamed struct?

Is the following code legal:

struct
{
    int  x;
};

This code simply defines an unnamed structure. I do not intent to create objects of this type, nor do I need this structure in any other way. It simply appears in the source as a side effect of some complex macro expansion.

Useless though it is, I see no problem with it. Just another piece of code that can be compiled and then optimized out completely.

However, in the real world the outcome is quite different from my expectations:

gcc 8.3 reports an error:

error: abstract declarator '<unnamed struct>' used as declaration

clang 8.0.0 reports an error too:

error: anonymous structs and classes must be class members
warning: declaration does not declare anything [-Wmissing-declarations]

Only MSVC 2017 sees no problem with such source.

So, the question is: who's right? Is there a relevant quote from the Standard that explicitly forbids such declarations?

lundi 29 avril 2019

trying to get current time in millisecond - and i get wrong year

trying to get current time in millisecond - and i get wrong year. I get all the time and data right - but the year is always 1650 (!)

   std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now();

   long long nowDateWithTime = now.time_since_epoch().count();

Standard deviation programing code for OpenMP, MPI and Pthread using C/C++?

Calculate mean, standard deviation using MPI,OpenMP and Pthread in parallel programming.

GCC interprets uint8_t and uint16_t as signed?

My test code:

#include <cstdint>
#include <cstdio>

int main() {
    const constexpr uint8_t x = 64;
    printf("%u", x);
}

Here is how I compiled with GCC 8.2:

g++ -Wall test_format.cpp -o test_format -O3 -std=c++17 -Wformat-signedness

And here is GCC's output:

test_format.cpp: In function ‘int main()’:
test_format.cpp:6:9: warning: format ‘%u’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int’ [-Wformat=]
  printf("%u", x);
         ^~~~

Tho, if I try to print an uint32_t, it has no error/warning.

I wonder why GCC expects uint8_t to be signed int.

Thanks.

C++: Array in Tuple in Vector - How to refer to the array elements and how to sort the vector

I have a setup like this.

std::vector<std::tuple<std::array<int,64>,int>> frequentLines;

There is a vector which has tuples. Each tuple is made of an array of 64 ints and another int which represents the frequency of every array.

My first question is, how do I refer to the array elements?

I know that when you have an array in a tuple you would have something like this.

for (uint i=0; i<64; i++) {     
    get<1>(foo)[i]
}

I'm not sure how to refer to the array elements while having everything in a vector.

I tried

for (uint i=0; i<frequentLines.size(); i++) {
    for (int j=0; j<64; j++) {
        std::get<0>(frequentLines)[i][j]
    }
}

but it's not working.

My second question is what would be an efficient way to sort this vector based on the frequency of each array of ints (i.e., based on the second element (int) of the tuple)?

In C++ is it possible to disambiguate between an array ref and a pointer?

I have this code:

template <typename T, ::std::size_t size>
using ary_t = T[size];

template <typename T, ::std::size_t size>
constexpr int call_me(ary_t<T const, size> &a)
{
    int total = 10;
    for (::std::size_t i = 0; i < size; ++i) {
        total += a[i];
    }
    return total;
}

template <typename T>
constexpr int call_me(T const *a)
{
    int total = 0;
    for (int i = 0; a[i]; ++i) {
        total += a[i];
    }
    return total;
}

#if 0
int t1()
{
    return call_me("a test");
}
#endif

int t2()
{
    char const * const s = "a test";
    return call_me(s);
}

and it works, but when remove the #if 0 section around t1 it fails to compile because of an ambiguity in which template to use. Is there any way to force the array version of call_me to be used preferentially?

I've tried a number of different tricks to make this work. I've tried adding , int... to the template argument list for the pointer version. I've tried removing the const. I've tried both. I've even tried making the pointer version into a C-style varargs function (aka int call_me(T const *a, ...)). Nothing seems to work.

I'd be happy with an answer that requires what is currently believed will make it into C++2a.

Pointers to static variables must respect canonical form?

Assuming I have the following example:

struct Dummy {
    uint64_t m{0llu};

    template < class T > static uint64_t UniqueID() noexcept {
        static const uint64_t uid = 0xBEA57;
        return reinterpret_cast< uint64_t >(&uid);
    }
    template < class T > static uint64_t BuildID() noexcept {
        static const uint64_t id = UniqueID< T >()
               // dummy bits for the sake of example (whole last byte is used)
               | (1llu << 60llu) | (1llu << 61llu) | (1llu << 63llu);
        return id;
    }
    // Copy bits 48 through 55 over to bits 56 through 63 to keep canonical form.
    uint64_t GetUID() const noexcept {
        return ((m & ~(0xFFllu << 56llu)) | ((m & (0xFFllu << 48llu)) << 8llu));
    }
    uint64_t GetPayload() const noexcept {
        return *reinterpret_cast< uint64_t * >(GetUID());
    }
};

template < class T > inline Dummy DummyID() noexcept {
    return Dummy{Dummy::BuildID< T >()};
}

Knowing very well that the resulting pointer is an address to a static variable in the program.

When I call GetUID() do I need to make sure that bit 47 is repeated till bit 63?

Or I can just AND with a mask of the lower 48 bits and ignore this rule.

I was unable to find any information about this. And I assume that those 16 bits are likely to always be 0.

This example is strictly limited to x86_64 architecture (x32).

error: invalid operands to binary expression ('Entry' and 'Entry') [duplicate]

This question already has an answer here:

I wrote a program that compares two entries using a structure. It returns true if they are the same ,and returns false if they are different. But when I run the program, it gives me the error: invalid operands to binary expression ('Entry' and 'Entry') if (e1 == e2).

It seems like it's not possible to use the comparison operator for structures?

My code:

#include <iostream>
using namespace std;

struct Entry
{
  string firstname;
  string lastname;
  char dorm;
  int age;
};

Entry equal(Entry e1, Entry e2)
{
  if (e1 == e2)
    return true
  else
    return false
}

int main()
{
  Entry e1 = {"Harry", "Potter", 'C', 25};
  Entry e2 = {"James", "Bond", 'D', 40};

  if (equal(e1, e2))
    cout << "same" << endl;
  else
    cout << "different" << endl;

  return 0;
}

Spin wait C++11

I have the following struct

struct info {
 unsigned long a;
 unsigned long b;
};

atomic <info> data;

used by a writer thread and a reader thread. The reader has to respond to the new values as fast as possible. To do that I’ve implemented the following in the reader :

while (true) {
  auto value = data.load();
  // do some operations given these new values
}

This operation is very processor intensive. I’ve opted for this method because I believe it’s faster than, for example, using a condition variable and then waiting for the reader thread to be awakened when data changes. Also, the data updates quite frequently, hundreds of times per second. Is there a better way to do this while still having the fastest reaction time?

How to pass a vector into a function and initialize it in the pass field?

I need to pass a vector into a constructor, but the vector is initialized in the constructor, and when I accept a vector, I am getting an error that says no matching constructor for initialization. How would I edit the constructor to accept this?

class Polynomial {

public:
    Polynomial(const vector<int>& vec) {
//Stuff 
};

int main() {
   Polynomial p1({17});
   Polynomial p2({5, 4, 3, 2, 1});
}

Can I prevent implicit conversions of a derived class to a base class? [duplicate]

This question already has an answer here:

If I have eg:

class Base {}; 
class Derived : public Base {};

And a function:

Derived create_derived();

I'd like this to be ill-formed:

Base base = create_derived();

How can I do this?

Template function overload resolution of T vs. SomeClass

I want to understand why the void handleParam(const Str& name, Table<T> value) template overload never gets instantiated (note that the code below is illustrative). I'm sure there is a perfectly good reason why it doesn't work, I just want to understand that reason. I'm aware of (and using) the workaround using an intermediate templated struct. But if something like the below was possible it would simplify my code a lot.

class TypeHandler
{
public:
    TypeHandler(OtherClass& bi) : _bi(bi) { }

    template <typename T> void handleParam(const Str& name, Table<T> value)
    {
        // Never gets instantiated.
    }

    template <typename T> void handleParam(const Str& name, T value)
    {

    }
}

template<typename HandlerType>
void HandleParamValue::handleTab(DataBlock& data, HandlerType& handler) {

    ...

    // Table of floats.
    Table<float> tab;
    handler.handleParam<Table<float>>(param_name, tab);

    // etc.
    ...
}

template<typename HandlerType>
void ParamStore::Iterate(HandlerType& handler) {
    for (...) {

        ...

        if (is_table(type)) {
            HandleParamValue::handleTab<HandlerType>(_datablock, handler);
        }
        else {
            HandleParamValue::handle<HandlerType>(_datablock, handler);
        }
    }
}

// Kick the whole thing off.
TypeHandler handler(_some_instance);
_param_store->Iterate(handler);

Why values of array cannot be printed using foreach loop in called function when array is passed as argument in caller function? [duplicate]

This question already has an answer here:

I am trying to print values of array in called function using foreach loop but facing compilation error. Using c++11 compiler in linux platform and using VIM editor.

Tried using C-style for loop and it worked, when the size is passed from calling function

#include <iostream>
using namespace std;

void call(int [], int);

int main()
{
    int arr[] = {1,2,3,4,5};
    int size = sizeof(arr)/sizeof(arr[0]);
    call(arr,size);
}

void call(int a[],int size)
{    
    for(int i =0 ; i<size; i++)
        cout << a[i];
}

For-each loop used in the below code, which fails to compile.

#include <iostream>
using namespace std;

void call(int []);

int main()
{
    int arr[] = {1,2,3,4,5};
    call(arr);
}

void call(int a[])
{
    for ( int x : a ) 
        cout << x << endl;
}

For-each loop in C++11 expects to know the size of array to iterate ? If so, how it will be helpful with respect to traditional for loop. Or something wrong i coded here?

I would look forward for your help. Thanks in advance.

Multithreading with very low latencies for calls between threads

I'm starting on a new robot control software for our robotic system which has to read out values from multiple, independent sensors and control the motors accordingly.

The software will be running on an i5 PC with PREEMPT_RT Ubuntu. Each sensor device comes with an SDK which I want to run in a separate thread. As soon as they get new values from their sensors (can be up to 50 doubles at once from one sensor) they should update those values in a superior control thread. The update rate depends on the sensor, but will be as fast as 1 kHz. As soon as the "main sensor" got new values and sent them to the control thread, the thread of the main sensor should trigger the control loop in the control thread (with a non-blocking call). The control thread should then compute new values for the motors with the currently stored sensor values and transmit them to the motors. The main sensor that will trigger the control loop is also getting new data at a 1 kHz rate, so this often the control thread must be performed.

I'm unsure now how to approach this. Do you think the threads functionality from C++11 can already solve this? Or should I use something like pthreads or boost? The main requirements are super low latency (~ 10 µs) to send data (up to 50 doubles) from one thread to another, and the ability to trigger a function (non-blocking) in another thread.

As soon as the sensor threads sent the current data to the control thread, they should continue monitoring the hardware to check for new sensor values and retrieve them. Some of the sensor threads perform extra computations and filtering on the sensor data, that's why I want them to run in extra threads, then taking advantage of the quadcore processor.

A question about the increase in std::atomic

In the process of using std::atomic, I encountered a problem, ask everyone, if execute long long i = data++ in both threads; the type of data is atomic, the value of i will not The same ?

How to ensure moving without impeding RVO?

When returning an object from a function one of the following cases can happen since C++11, assuming move- and copy-constructors are defined (see also the examples at the end of this post):

  1. it qualifies for copy-elision and compiler performs RVO.
  2. it qualifies for copy-elision and compiler doesn't perform RVO, but then ...
  3. it qualifies for the usage of move constructor and is moved.
  4. none of the above and the copy-constructor is used.

The advice for the first 3 cases is not to use the explicit std::move, because move is performed anyway and could prevent possible RVO, see for example this SO-post.

However, in the 4. case an explicit std::move would improve the performance. But as somebody who is fluent in reading neither the standard nor the resulting assembler, it takes a lot of time to differentiate between cases 1-3 and 4.

Thus my question: Is there are a way to handle all of the above cases in an unified manner, such that:

  1. RVO is not impeded (case 1)
  2. if RVO is not performed, move-constructor is used (cases 2,3 and 4)
  3. if there is no move-constructor, copy-constructor should be used as fallback.

Here are some examples, which also can be used as test cases.

All examples use the following helper-class-definition:

struct A{
    int x;
    A(int x_);
    A(const A& a);
    A(const A&& a);
    ~A();
};

1. example: 1.case, RVO performed, live-demonstration, resulting assembler:

A callee1(){
    A a(0);
    return a;
}

2. example: 1.case, RVO performed, live-demonstration, resulting assembler:

A callee2(bool which){
    return which? A(0) : A(1);
}

3. example: 2.case, qualifies for copy-elision, RVO not performed, live-demonstration, resulting assembler:

A callee3(bool which){
    A a(0);
    A b(1);
    if(which)
      return a;
    else
      return b; 
}

4. example: 3.case, doesn't qualify for copy-elision (x is a function-parameter), but for moving, live-demonstration, resulting assembler:

A callee4(A x){
    return x; 
}

5. example: 4.case, no copy-elision or implicit moving (see this SO-post), live-demonstration, resulting assembler:

A callee5(bool which){
    A a(0);
    A b(1);
    return which ? a : b;
}

6. example: 4.case, no copy-elision or implicit moving, live-demonstration, resulting assembler:

A callee6(){
    std::pair<A,int> x{0,1};
    return x.first;
}

Size of parent and child class with same members

I'm writing some network code in C++11, and I have a doubt about the size of some packets.

Is the size of the following two structures guaranteed by the standard to be the same? even without attribute((packed)); (that I know it's non standard).

struct A
{
uint16_t a;
} __attribute__((packed));

template<class T>
struct B : A
{
T getA() { return static_cast<T>(a);}
} __attribute__((packed));

Thanks!

why child object can be assigned to base but not base to child, how it differs when two class are differ different [duplicate]

This question already has an answer here:

As c++ standard says,

copy assignment is implicitly declared if not declared by user,

If this is the case, when we declare two class one is base and one child , then for both class "copy assignment" is declared. So if its true then

when

 Base b;
    child c;
    b = c // success (but according to me it should failed)
    c = b // error 

(why its failure , as c is inheriting b , then it should have both assignment operator overloaded function). many place its explained like animal and dog example , buts not the technical prospective view.

dimanche 28 avril 2019

String not reversing in C++

I wrote a program that reverses the string that is inputted by the user, but it doesn't work. I did it using string reverse_name(name.rbegin(), name.rend()) from Reverse the string in C++, but it doesn't work and gives me the error:

no viable conversion from 'std::__cxx11::basic_string<char,
      std::char_traits<char>, std::allocator<char> >::reverse_iterator' (aka
      'reverse_iterator<__normal_iterator<char *, std::__cxx11::basic_string<char> > >') to
      'std::__cxx11::string' (aka 'basic_string<char>')
  string reversed_word = (word.rbegin(), word.rend());

My code:

#include <iostream>
using namespace std;

int main()
{
  string word, reversed_word;
  cin >> word;

  reversed_word = (word.rbegin(), word.rend());
  cout << reversed_word;

  return 0;
}

Running consumer threads sequentially

I have a queue which stores words read from a text file. I'm using producer-consumer thread model to achieve this.

thread one - producer thread, read words from text file and push it to queue.
thread two & three - consumer threads, pop word from queue.

Now i wants to run the consumer threads sequentially one after other.

expected output:

$ ./a.out sample.txt
word one thread one
word two thread two
word three thread one
word four thread two
.
.
.

As of now, I have tried with std::condition_variable with Predicate, but i'm getting different output for each time.
I'm new to multi-threading and knows that this is not the right way to implement multi-threading, but i wants to achieve this for learning purpose. Please find my code below

#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <iostream>
#include <string>
#include <fstream>

// for reading file
std::fstream file;
std::string word;

// used as predicate in condition variables 
int thread_number{0};

template <typename T>
class Queue
{
  public:
  T pop_one()
  {
   std::unique_lock<std::mutex> mlock(mutex_);
   cond_.wait(mlock, [] {return thread_number == 0;});
   while (queue_.empty())
   {
    cond_.wait(mlock, [] {return thread_number == 0;});
   } 
   auto item = queue_.front();
   queue_.pop();
   thread_number = 1;
   return item;
  }

  T pop_two()
  {
   std::unique_lock<std::mutex> mlock(mutex_);
   cond_.wait(mlock, [] {return thread_number == 1;});
   while (queue_.empty())
   {
    cond_.wait(mlock, [] {return thread_number == 1;});
   }
   auto item = queue_.front();
   queue_.pop();
   thread_number = 0;
   return item;
  }

  void push(const T& item)
  {
   std::unique_lock<std::mutex> mlock(mutex_);
   queue_.push(item);
   mlock.unlock();
   cond_.notify_one();
  }

  bool is_empty()
  {
   return queue_.empty();
  }

  private:
   std::queue<T> queue_;
   std::mutex mutex_;
   std::condition_variable cond_;
};

// creating queue object in global scope  
Queue<std::string> q;

// read and push words to queue 
void write_()
{
 while(file >> word)
 {
  q.push(word);
 }
}

// pop word from queue - consumer thread one
void read_one()
{
 while(!q.is_empty())
 {
  std::cout <<q.pop_one() << " thread 1" << std::endl;
 }
}

// pop word from queue - consumer thread two
void read_two()
{
 while(!q.is_empty())
 {
  std::cout <<q.pop_two() << " thread 2" << std::endl;
 }
}

int main(int argc, char const *argv[])
{
 file.open(argv[1]);
 std::thread wt(write_);
 std::thread rt1(read_one);
 std::thread rt2(read_two);
 wt.join();
 rt1.join();
 rt2.join();
 return 0;
}

Compilation error while passing queue of packaged_tasks as reference

Having a compilation error when I am trying to pass a queue containing packaged_task objects to a thread as a reference. I modified sample code to pass it to a function and the same compilation error observed

void runtasks(std::queue< packaged_task<int()> >& que)
{
    while(!que.empty())
    {
        auto task = std::move(que.front());
        que.pop();
        task();
    }
}

int main()
{
    std::queue< packaged_task<int()> > que;
    packaged_task<int()> t1(std::bind(factorial,1));
    packaged_task<int()> t2(std::bind(factorial,4));
    que.push(std::move(t1));
    que.push(std::move(t2));
    runtasks(que);
    return 1;
}

/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/include/c++/bits/stl_construct.h: In instantiation of 'void std::_Construct(_T1*, _Args&& ...) [with _T1 = std::packaged_task; _Args = {const std::packaged_task&}]': /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/include/c++/bits/stl_uninitialized.h:75:18: required from 'static _ForwardIterator std::__uninitialized_copy<_TrivialValueTypes>::__uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = std::_Deque_iterator, const std::packaged_task&, const std::packaged_task*>; _ForwardIterator = std::_Deque_iterator, std::packaged_task&, std::packaged_task*>; bool _TrivialValueTypes = false]' /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/include/c++/bits/stl_uninitialized.h:126:15: required from '_ForwardIterator std::uninitialized_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = std::_Deque_iterator, const std::packaged_task&, const std::packaged_task*>; _ForwardIterator = std::_Deque_iterator, std::packaged_task&, std::packaged_task*>]' /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/include/c++/bits/stl_uninitialized.h:281:37: required from '_ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, std::allocator<_Tp>&) [with _InputIterator = std::_Deque_iterator, const std::packaged_task&, const std::packaged_task*>; _ForwardIterator = std::_Deque_iterator, std::packaged_task&, std::packaged_task*>; _Tp = std::packaged_task]' /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/include/c++/bits/stl_deque.h:944:36: required from 'std::deque<_Tp, _Alloc>::deque(const std::deque<_Tp, _Alloc>&) [with _Tp = std::packaged_task; _Alloc = std::allocator >]' /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/include/c++/bits/stl_queue.h:96:11: required from here /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/include/c++/bits/stl_construct.h:75:7: error: use of deleted function 'std::packaged_task<_Res(_ArgTypes ...)>::packaged_task(const std::packaged_task<_Res(_ArgTypes ...)>&) [with _Res = int; _ArgTypes = {}]' { ::new(static_cast(__p)) _T1(std::forward<_Args>(__args)...); } ^ In file included from ../src/SmartPointers.cpp:16:0: /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/include/c++/future:1507:7: note: declared here packaged_task(const packaged_task&) = delete; ^ make: *** [src/subdir.mk:23: src/SmartPointers.o] Error 1

Why non deductible template parameters is problematic?

Trying to compile this piece of code results in an error.

template <typename T>
struct MyClass;

template <typename T, std::size_t sz>
struct MyClass<T> {
    static void print() {
        std::cout << "Partially specialized" << std::endl;
    }
};

error: template parameters not deducible in partial specialization

Trying to make it possible to deduce sz solves the problem. For example:

template <typename T, std::size_t sz>
struct MyClass<T[sz]> {
    static void print() {
        std::cout << "Partially specialized" << std::endl;
    }
};

My question is, how does the compiler interprets such a program and what's the rational behind not allowing to have the first structure?

Further clarification: I am thinking that if the inital code was compilable, we could use it in a manner such as: MyClass<int, 4>::print().

Reading a text file with C++ to read in the value that follows a specific key word

I am attempting to write a generic text file reader in C++17 that will search a text file, line by line, for a specific key word and the code should read in the data point that follows that key word. I am writing it with a template function within a class so that it can read in any data type. In this example lets say that I have the following text file titled test.txt.

- test.txt file
integer key: 4
Float key: 6.04876
Double Key: 12.356554545476756565
String Key: test

The header file containing the template class looks like this. In this case the ReadTextFile class inherits another class to assist with checking the file status.

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>

#ifndef read_files_hpp
#define read_files_hpp

class FileStatus
{
public:
    template <class container>
    bool file_exists(const container& file_name);
    template <class file_container>
    bool is_file_open(const file_container& file);
};
template <class container>
bool FileStatus::file_exists(const container& file_name)
    std::ifstream ifile(file_name.c_str());
    return (bool)ifile;
}

template <class file_container>
bool FileStatus::is_file_open(const file_container& file)
{
    return file.is_open();
}
// ----------------------------------------------------------------


class ReadTextFile : public FileStatus
{
public:
    template <class dtype, class container1, class container2>
    dtype read_key_words(const container1& file_name, const
                         container2& key_word);
};

template <class dtype, class container1, class container2>
dtype ReadTextFile::read_key_words(const container1& file_name,
                                   const container2& key_word)
{
    int j = 3;
    if (bool i = file_exists(file_name) != 1) {
        std::cout << "FATAL ERROR: " << file_name <<
        " not found" << std::endl;
        return -1;
    }
    std::ifstream file(file_name);
    if (is_file_open(file))
    {
        std::string line;
        while (std::getline(file, line))
        {
            std::cout << line.c_str() << std::endl;
        }
    }
    return j;
}
// ================================================================
// ================================================================
#endif

The calling program main.cpp looks like this;

#include <iostream>
#include <fstream>
#include "read_files.hpp"
int main() {
    std::string file_name("../data/unit_test/keys.txt");
    std::string key_word("integer key:");
    int j;
    j = txt_file.read_key_words<int>(file_name, key_word);
}

In this test case the class is being instantiated as type int so until the program is completely written I am returning the variable int j = 3; from the function read_key_words(). At present the code can read the file test.txt which is in the same directory and correctly read in each line. I would like the code to parse each line to recognize if the phrase integer key: is present and then read the variable that follows it, as the data type that the function is instantiated for, which in this case is an integer. How can I make this happen within the code?

Could this be a memory leak?

Does using a new then setting to null cause memory leaks?

Ive tried the following code but have no idea if it causes any leak or not

#include <iostream>

using namespace std;

int main()
{

   int* x = new int;
   int y = 1;
   x = &y;

   x = nullptr; // has the memory allocated to x gone now?

   x =&y;       // did i recover what was lost?

   delete x;   

   return 0;
}

// the cout<<*x gives 1 as expected

gcc-make-run: Grammar Not Supported

I have been trying to learn C++11 and when I try to compile my code in Atom, it gives me the error "gcc-make-run: Grammar Not Supported, only C, C++ and Makefile are supported". I have no idea what it means and found nothing about it on Google.

I have the gcc-make-run 0.2.12 package and my compiler flag is:

-pedantic-errors -std=c++11

Here's my code:

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

int main()
{
  string filename, line;
  cin >> filename;

  ifstream fin;
  fin.open("bitch.txt");
  if (fin.fail()){
    cout << "Error in opening bitch.txt!"
    exit(1);
  }

  while (getline(fin, line)){
    cout << line << endl;
  }
  fin.close();
  return 0;
}

Construct one list from element of another list without adding to heap memory

I am developing a memory critical application. I first generate a list, for example (C++11):

std::list<string> nodes({"Hello","Welcome", "Hi", "World"});

I need to now create a smaller list with the second and third elements of 'nodes.' Naively, I would do:

 std::list<string> sub_nodes;
 sub_nodes.push_back(*std::next(nodes.begin(),1));
 sub_nodes.push_back(*std::next(nodes.begin(),2));

But this clearly allocates memory in the heap for sub_nodes. What I wish to accomplish is to have the elements of sub_nodes occupy the same address of the elements of nodes from which they were created. In other words, I want the changes made to elements of sub_nodes reflected in those elements in nodes and vice versa. In C linked lists, this would be straight forward since the list nodes are basically pointers. How would I accomplish the same in C++?

How should I insert a value into the "middle" of another

I have two values v1 and v2 of types T1 and T2 respectively, with sizeof(T1)>sizeof(T2). Both types are plain-old-data. Now, I want to replace the k'th, k+1'th, ... k+sizeof(T2)-1'th bytes of v1 with the bytes of v2.

C++ doesn't offer this functionality inherently in the language, nor to my knowledge in the standard library (at least, not directly). What would be the best approach to implementing this generically? i.e. implementing:

template<typename T1, typename T2>
T1 replace_bytes(T1 v1, T2 v2, std::size_t k)

or

template<typename T1, typename T2>
void replace_bytes(T1& v1, T2 v2, std::size_t k)

?

My thoughts have been:

  1. Reinterpret cast into arrays of bytes
  2. Reinterpret cast into std::array of bytes
  3. Use spans
  4. Pointer arithmetic with the address of v1
  5. For not-so-large types - reinterpret as unsigned integers and use bit operations: AND with a mask, shift, OR to combine the existing and replacement bits.

Notes:

  • You may assume for the sake of simplicity that memory layout is little-endian.
  • If alignment is an issue, be explicit about your choices regarding it.
  • Efficiency/speed is of course a key issue.
  • If your suggestion requires a newer C++ language standard, that's fine, but do mention it.

samedi 27 avril 2019

How to do constructor for 2D vector in C++?

I tried initializing a 2D vector with a constructor in 3 different ways but always get an

"error: no matching function to call"

Could you tell me where I am wrong?

class Node 
{
public:
  int to;
  int length;
  Node(int to, int length) : to(to), length(length){}
};

class Graph 
{
public:
  vector<vector<Node>> nodes_list;
  int n;
  Graph();
};

Graph::Graph(){
  nodes_list = vector<vector<Node> >(n, vector<Node>(n,0x3fffffff));
}

Why the third function call of f is not calling template function?

include

using namespace std;

template void f(T x, T y) { cout << "Template" << endl; }

void f(int w, int z) { cout << "Non-template" << endl; }

int main() { f( 1 , 2 ); f('a', 'b');enter code here f( 1 , 'b'); }

Could not infer template argument when using "typename Container::value_type" as the return value

First define a generic function whose purpose is to execute a function and print out the results.

In the following, func is a reference to a function, funcName is just the function name for terminal display, inputs are arguments for func.

#define TBOLD(x) "\x1B[1m" x __RST
#define TRED(x) __KRED x __RST

template<typename ...TInputs, typename TOutput>
void test_func(TOutput func(TInputs &...), 
        const string &funcName, 
        vector<tuple<TInputs...>> inputs,
        const string &resultDelimiter = ", ")
{
    cout << funcName << endl;
    if (is_same<TOutput, bool>::value)
        cout << boolalpha;

    for (auto &input: inputs)
    {
        auto arg_idx = 0;
        apply([&arg_idx](auto &&... args)
              { ((std::cout << args << (++arg_idx == sizeof...(TInputs) ? TBOLD(TRED(" : ")) : ", ")), ...); }, input);
        cout << apply(func, input) << endl;
    }
}

Now suppose I have the following functions,

static int func1(vector<int> &arr, int &k)
{
    sort(arr.begin(),arr.end());
    return arr[k];
}

template<typename Container>
static typename Container::value_type func2(Container &arr, int &k)
{
    sort(arr.begin(),arr.end());
    return arr[k];
}

Now the following line will compile,

test_func(func1,"func1",vector<tuple<vector<int>,int>>{make_tuple(vector<int>{3,5,1,2,4},2)})

but the following won't compile and gives a message that "could not infer template argument TOutput". In my opinion, this should have provided enough information to infer the output type TOutput: the inputs argument is of type vector<tuple<vector<int>,int>>, then it should know TInputs... is <Container, int>, and then TOutput is Container::value_type.

test_func(func2,"func2",vector<tuple<vector<int>,int>>{make_tuple(vector<int>{3,5,1,2,4},2)})

If this is indeed not working, what is the right way to make the return type correctly recognized, while preserving the "generality" of this test_func to accept functions of different arguments and output?

New and Delete using pointers

Im tryng to understand if the following code actually deletes an object from memory

during ' delete z ' what is actually deleted? does the dynamicaly created integer x get deleted? does y and z get deleted also?

Thanks!

Ive run the program and different values get output when i cout x y and z

include

using namespace std;

int main() {

int* x = new int; *x=1;

int* y = x; int* z = y;

delete z;

return 0; }

im assuming the variable x is no longer on the heap?

Why I can't initiaize a string with uniform initialization?

I have a program that simulates a window; So I have the content of the window stored in a member data content which is a std::string type:

class Window {
    using type_ui = unsigned int;
    public:
        Window() = default;
        Window(type_ui, type_ui, char);
        void print()const;

    private:
        type_ui width_{};
        type_ui height_{};
        char fill_{};
        std::string content_{};
        mutable type_ui time_{};
};

Window::Window(type_ui width, type_ui height, char fill) :
    width_{ width }, height_{ height }, fill_{ fill },
    content_{ width * height, fill } { // compile-time error here?
    //content( width * height, fill ) // works ok
}

void Window::print()const {
    while (1) {
        time_++;
        for (type_ui i{}; i != width_; ++i) {
            for (type_ui j{}; j != height_; ++j)
                std::cout << fill_;
            std::cout << std::endl;
        }
        _sleep(1000);
        std::system("cls");
        if (time_ > 10)
            return;
    }
}


int main(int argc, char* argv[]) {

    Window main{ 15, 25, '*' };
    main.print();

    std::string str{5u, '*'}; // compiles but not OK
    std::string str2(5u, '*'); // compiles and OK
    cout << str << endl; // ♣* (not intended)
    cout << str2 << endl; // ***** (ok)

    std::cout << std::endl;
}

AS you can see above I couldn't initialize the member content with curly-braces-initializer-list which the compiler complains about "narrowing type". But it works with "Direct initialization".

  • Why I cannot use Curly-brace-initialization-list above in the Constructor-initializer-list to invoke std::string(size_t count, char).

  • Why this std::string str{5u, '*'}; // compiles but not OK Works but gives not intended ouptu?

  • The thing that matters me a lot is why the same initialization doesn't work on constructor-member-initialization-list but works in main (with not intended result)?

Why does std::vector allow the use of a throwable move constructor for the type it contains?

Apparently, std::move_if_noexcept() will call the move constructor, even if it is not marked as noexcept if there is no copy constructor available. As std::vector is using this function on reallocation, that could leave the vector and possibly the application in an undetermined state.

From cpprefeerence.com:

Notes

This is used, for example, by std::vector::resize, which may have to allocate new storage and then move or copy elements from old storage to new storage. If an exception occurs during this operation, std::vector::resize undoes everything it did to this point, which is only possible if std::move_if_noexcept was used to decide whether to use move construction or copy construction. (unless copy constructor is not available, in which case move constructor is used either way and the strong exception guarantee may be waived)

Why would this be allowed?

Unable to access iterator data member using object

I am trying to overload the operator+, I want to add two nodes using an iterator but I am having problems with accessing the iterator from another object.

Here is my operator+:

 type operator+(const largeInt<type> &other) {
     iter = list.end();
     other.iter = other.list.end() //need help here

     type newNumb1, newNumb2;

     newNumb1 = *iter;
     newNumb2 = other.*iter; //need help here

     return newNumb1 + newNumb2;
 }

I have this typename List<type>::Iterator iter; as a private data member inside the largeInt class.

The iterator class is saved in another class, it is nested within a linkedlist class that is why to make an Iterator object I have to do List<type>::Iterator although it works I am not able to access it using another object as shown above.

I need help two dimensional array

Here is what I have so far:

include

include

using namespace std;

int main()

{

int sumCount[6][6];

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

{

for (int j = 0; j < 6; j++)

{

sumCount[i][j] = 0;

}

}

char ch='Y';

srand(time(NULL));

while (ch == 'Y' || ch =='y')

{

int dice1 = rand() % 9 + 4;

int dice2 = rand() % 9 + 4;

sumCount[dice1 - 4][dice2 - 4] += 1;

cout << "do you want to dice more enter (Y/N): ";

cin >> ch;

}

cout << "\t4\t5\t6\t7\t8\t9" << endl;

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

{

cout << i+4 << "\t";

for (int j = 0; j < 6; j++)

{

cout << sumCount[i][j] <<"\t";

}

cout << endl;

}

system("pause");

return 0;

}

How to construct class that can replace typedef vector

I am learning classes in C++ and would like to construct my own class instead of using a 2D vector "typedef vector> C_type". I have some code written:

class T {
    public:
    int a;
    int b;
    T(int a, int b) : a(a), b(b){}

};

Now I have:

typedef vector<vector<T>> C_type;


I'd like to use a class instead and create a constructor and initialize it, something like:

class C_type {
vector<vector<T>> name;
C_type();}
C_type::C_type(){name = vector<vector<T>>(..........

I'd like to use the 2D vector as a class member. Thanks.

Using "<>" with an array?

I was reading through a programming book (C++ Plus Data Structures, Dale, Weems, Richard) and came across this snippet of code. This is in the section about class templates:

template <class ItemType>
class StackType{
    public:
        StackType();
        bool IsEmpty() const;
        bool IsFull() const;
        void Push(ItemType item);
        void Pop();
        ItemType Top() const;
    private:
        int top;
        ItemType items <MAX_ITEMS>;//RIGHT HERE!!
};

I'm particularly looking at the "items" attribute. I copied the code into my IDE and it did not compile.

My question: Is this an error in the book, or am I missing something?

I'm new to stackoverflow... Should I provide any more code?

Thanks for your time!

Is it possible to have an rvalue reference as pimpl class in C++

Hey i want to create a class with a Pimpl (Private implemenation) and normal you would so:

class A
{
private:
  class B;
  B* _pimpl = nullptr;
}

and the i would define it in the cpp file. But i have to use dynamic allocation. Would it be possible to use a rvalue reference:

class A
{
public:
  A(); //Constructor to init rvalue reference
private:
  class B;
  B&& _pimpl;
}

And then in cpp file:


class A::B
{
public:
   int C = 3u;
}

//and then the constructor of A:

A::A() : _pimpl(B()) { } //now we should have a fresh b pimpl?


Im currenty on holidays and i only have my c++ book and when i read about rvalue&&s i tought it might work? What do you guys think?

Getting compiler errors with my implementation selection

This is my first foray into template meta-programming but it's required in this particular instance because a runtime solution fails to type check the whole if/else block. I need to convert a vector of one type (e.g. int32_t) to a vector of another type (e.g. int). I've put together a compile time implementation selection using templates but can't get the syntax write.

If I directly call my VectorCast_impl functions with template parameters from main, it works in both instances. However when I call VectorCast_impl from within VectorCast I'm getting compiler errors (shown in the code comments). Is there any way to get the VectorCast function compiled without errors?

I've tried a few additional syntaxes for the VectorCast_impl calls that are listed in the code comments below. For reference I'm using g++ mingw64 on windows and icpc on RHEL6.

#include <type_traits>
#include <vector>
#include <iostream>

template <bool>  // Handle two of the same types
struct VectorCast_impl
{
    template <class Tout, class Tin>
    static std::vector<Tout> Cast(std::vector<Tin>& x)
    {
        std::cout << "Vectors are same\n";
        return x;
    }
};

template <>     // Specialization for different types
struct VectorCast_impl<false>
{
    template <class Tout, class Tin >
    static std::vector<Tout> Cast(std::vector<Tin>& x)
    {
        std::cout << "Vectors are different\n";
        return std::vector<Tout>(x.begin(), x.end());
    }
};

/* This is the desired syntax:
 * std::vector<int> inp{0,1,2};
 * std::vector<double> output = VectorCast<double>(inp);
 *
 * However, I can't get this working yet.  The syntax above is recognized by the compiler
 * but the VectorCast_impl call fails.
 */

template <class Tout, class Tin>
std::vector<Tout> VectorCast(std::vector<Tin>& x)
{
//    return std::vector<Tout>(8,-1); // works, but just a test case (not desired behavior)
//    return VectorCast_impl<std::is_same<Tin, Tout>::value>::Cast(x);  // Compiler error: couldn't deduce template parameter 'Tout'
    return VectorCast_impl<std::is_same<Tin, Tout>::value>::Cast<Tout>(x); // Compiler error: expected pirmary-expression before '>' token
}

typedef int xxxx;
int main()
{
    std::vector<int> vint{0,1,2};
    for (const auto& i: VectorCast_impl<std::is_same<int,xxxx>::value>::Cast<xxxx>(vint))
        std::cout << i << "\n";

    std::vector<double> vd = VectorCast_impl<std::is_same<int,double>::value>::Cast<double>(vint);
    std::cout << vd[1] + 1.23538 << "\n";

    vd = VectorCast<double>(vint);
    std::cout << vd[2] * 3.425 << "\n";
    return 0;
}

What does GCC compiler do to type conversion? Why the output on mac and linux are different?

I did the type conversion of variable b(declaration outside the scope) in a scope and give a new val to b, and when the scope ends, the val of b seem to be wrong.

This happens on my macbook, which version of gcc is gcc-8 (Homebrew GCC 8.3.0) 8.3.0. I tried the same code on my linux laptop whose gcc version is 5.4.0 and the code runs well.

vector<int> a = {1,2,3,4};
    int b;
    {
        size_t i = 0, b = a[i];
        //this time type of b is size_t

        ++i;
        b = a[i];

    }
    cout << "b = " << b << endl;

On my mac, the result is b = 0 On Ubuntu 16, the result is b = 1

What is the difference between two version of gcc on type conversion?

Or it is a bug?

Why can templated aliases of anonymous struct/class-es not be defined directly?

I can create the following:

using Foo = struct { /*Implementation*/ };

template<class>
using Bar = Foo;

However the following is not allowed:

template<class>
using Bar = struct { /*Implementation*/ };

The error from Clang is more helpful than GCC, and states:

error: '(anonymous struct at file:line:column)' cannot be defined in a type alias template


Any reasons why the second code example is not allowed?

Note: Any citation from the standard is also helpful.

vendredi 26 avril 2019

wxWidgets best control for drawing realtime graphics

I know there are variation for this question, but I haven't found an answer which actually clarify my doubt.

I made a little App using SDL to show some sprite animations, and it works really fine. It's important that the rendering is as smooth as possible.

Since now I need some GUI, I decided to use wxWidgets 3 to create kind of the same application but where I can now also add some GUI elements like menus, modals, etc.

After diving into the wxWidget's wiki, I found there are different ways to draw into a window.

For example:

  • wxClientDC
  • wxPaintDC
  • wxGLCanvas

I also found other kind of classes like the "Graphics Context classes" which i'm still not sure if they could be useful for what I need.

My application already uses an internal buffer which just needs to be copied. So my question is. What's the most appropriate way to do this on wxWidgets? And, how much performance/overhead does that solution impose? Thanks

Threads don't starting when compiling with optimization flag

I have written a simple Worker Pool program. When I compile it without -Ox flag it runs as expected, but when i use -Ox (x>0) or -Og threads do not start.

worker_pool.h

#ifndef WORKER_POOL_H
#define WORKER_POOL_H

#include <sema.h>

#include <condition_variable>
#include <functional>
#include <future>
#include <memory>
#include <mutex>
#include <optional>
#include <queue>
#include <thread>
#include <vector>

using namespace std;

class worker_pool {
private:
  class worker {
  private:
    worker_pool *wp;
    long id;

  public:
    worker(worker_pool *_wp, long _id) : wp(_wp), id(_id){};

    void operator()() {
      while (!wp->stop) {
        printf("monkey %d doing job\n", int(id));
        auto t = wp->fetch();
        if (!t.has_value())
          continue;
        else
          t.value()();
      }
    };
  };

  std::vector<std::thread> workers;
  std::queue<std::function<void(void)>> q;
  std::mutex mx;
  Semaphore sm;
  std::condition_variable cv_empty;
  std::mutex mx_empty;

  std::optional<std::function<void(void)>> fetch() {
    sm.wait();
    std::unique_lock l(mx);
    if (stop)
      return {};
    auto res = std::move(q.front());
    q.pop();
    if (q.empty())
      cv_empty.notify_all();
    return std::move(res);
  };

public:
  worker_pool(long tcount = std::thread::hardware_concurrency()) {
    for (long i = 0; i < tcount; i++) {
      workers.push_back(std::move(std::thread(worker(this, i))));
    }
  }

  ~worker_pool() { terminate(); }

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

  bool stop;

  template <typename F, typename... ARGS>
  auto submit(F &&f, ARGS &&... args) -> std::future<decltype(f(args...))> {
    std::lock_guard l(mx);
    auto func = std::bind(std::forward<F>(f), std::forward(args)...);
    auto task_ptr =
        std::make_shared<std::packaged_task<decltype(f(args...))()>>(func);
    q.push([task_ptr] { (*task_ptr)(); });
    sm.signal();
    return task_ptr->get_future();
  }

  void terminate() {
    stop = true;
    sm.signal(workers.size());
    for (size_t i = 0; i < workers.capacity(); i++) {
      if (workers[i].joinable())
        workers[i].join();
    }
  }

  long jobs_remaining() {
    std::lock_guard l(mx);
    return q.size();
  }

  void wait_until_empty() {
    std::unique_lock l(mx_empty);
    while (!(q.empty() || stop))
      cv_empty.wait(l, [&] { return q.empty() || stop; });
  }
};

#endif // WORKER_POOL_H

main.cpp

#include <sema.h>
#include <worker_pool.h>

#include <condition_variable>
#include <iostream>
#include <mutex>
#include <string>

using namespace std;

int main(int argc, char *argv[]) {

  printf("creating worker pool\n");
  worker_pool wp(4);
  vector<future<string>> futures;
  printf("creating jobs\n");

  for (int i = 0; i < 10; i++) {
    futures.push_back(
        wp.submit([]() { return std::move(string("Hello world")); }));
  }
  printf("waiting for jobs to finish\n");
  wp.wait_until_empty();
  for (auto &f : futures) {
    auto str = f.get();
    cout << str << endl;
  }
  printf("finished jobs\n");
  wp.terminate();

  cout << "program ended" << endl;
  return 0;
}

Compilation commands:
clang++ -std=c++17 -pthread -g -Iinclude -Llib src/main.cpp -o bin/gmain
clang++ -std=c++17 -pthread -Iinclude -Llib -O3 src/main.cpp -o bin/main
Clang version 8, GCC version 8.2.1.

How to modify Disjktra algorithm to have at least 5 vertices in shortest path

I have this Dijkstra algorithm although I want to modify it

I need to output the vertices of the shortest path, although I need to have at least 5 vertices (>=5 vertices) to the shortest path from start node to end node.

At the end of the code you'll see the Dijkstra algorithm so I would need to modify it so I could add a variable where I need to have at least X(5in my case) vertices.

#include<iostream>
#include<set>
#include<list>
#include<algorithm>

using namespace std;

typedef struct nodes {
        int dest;
        double cost;
}node;
class Graph{

    int n;


   list<node> *adjList;

   private:
      void showList(int src, list<node> lt) {
         list<node> :: iterator i;
         node tempNode;

         for(i = lt.begin(); i != lt.end(); i++) {
            tempNode = *i;
            cout << "(" << src << ")---("<<tempNode.dest << "|"<<tempNode.cost<<") ";
         }
         cout << endl;
      }
   public:
      Graph() {
         n = 0;
      }

      Graph(int nodeCount) {
         n = nodeCount;
         adjList = new list<node>[n];
      }

      void addEdge(int source, int dest, double cost) {
         node newNode;
         newNode.dest = dest;
         newNode.cost = cost;
         adjList[source].push_back(newNode);
      }

      void displayEdges() {
         for(int i = 0; i<n; i++) {
            list<node> tempList = adjList[i];
            showList(i, tempList);
         }
      }

      friend void dijkstra(Graph g, double *dist, int *prev, int start);
};

void dijkstra(Graph g, double *dist, int *prev, int start) {
   int n = g.n;

   for(int u = 0; u<n; u++) {
      dist[u] = 9999;   //set as infinity
      prev[u] = -1;    //undefined previous
   }

   dist[start] = 0;   //distance of start is 0
   set<int> S;       //create empty set S
   list<int> Q;

   for(int u = 0; u<n; u++) {
      Q.push_back(u);    //add each node into queue
   }

   while(!Q.empty()) {
      list<int> :: iterator i;
      i = min_element(Q.begin(), Q.end());
      int u = *i; //the minimum element from queue
      Q.remove(u);
      S.insert(u); //add u in the set
      list<node> :: iterator it;

      for(it = g.adjList[u].begin(); it != g.adjList[u].end();it++) {
         if((dist[u]+(it->cost)) < dist[it->dest]) { //relax (u,v)
            dist[it->dest] = (dist[u]+(it->cost));
            prev[it->dest] = u;
         }
      }
   }
}

Thank you for your help

Program is freezing up when I attempt to run it and I am not able to locate the source of the error

My program is supposed to take a text file with certain characters and give a corresponding output depending on which characters are listed. I have completed the code for all functions, but when I try to test the program it freezes up on one of the outputs which is supposed to output the list as a string.

I assume it is an issue with either my toString function or my implementation of it, but I have looked through the code multiple times and I still cannot find a solution to stop the program from freezing up at the same point.

Implementation of toString function:

 case 'P':
         if (DList == nullptr)
         {
           cout << "MUST CREATE LIST INSTANCE"
                << endl;
         }
         else
         {
           if (DList->empty())
           {
             cout << "LIST EMPTY"
                  << endl;
           }
           else
           {
             cout << DList->toString() << endl;
           }
         }
         // cout << "test P" << endl;
         break;

toString function:

string toString() const
{
  ostringstream temp;

  Node* marker = head;
  while (marker != nullptr)
  {
    temp << marker->value;
    if (marker->next != nullptr)
    {
      temp << ",";
      marker = marker->next;
    }
  }//end of while loop
  temp << '\n';
  return temp.str();
}

Text input file I am using to run:

# create first list
C
P <-- List is empty here so the program outputs correctly.
F 25
B 5
F 20
B 5
F 10
F 25
A
N
P <-- Point where program freezes up and outputs nothing.
Z
R 5
E 25
G 1
G 5
G 25
N
P
T
K
N
P
X
K
P
D
X

This is what I should be seeing in my output:

LIST CREATED
LIST EMPTY
VALUE 25 ADDED TO HEAD
VALUE 5 ADDED TO TAIL
VALUE 20 ADDED TO HEAD
VALUE 5 ADDED TO TAIL
VALUE 10 ADDED TO HEAD
VALUE 25 ADDED TO HEAD
VALUE 25 AT HEAD
LIST SIZE IS 6
25,10,20,25,5,5 <-- This is where the program freezes up and doesn't output anything
VALUE 5 AT TAIL
VALUE 5 REMOVED
VALUE 25 ELIMINATED
VALUE 1 NOT FOUND
VALUE 5 FOUND
VALUE 25 NOT FOUND
LIST SIZE IS 3
10,20,5
REMOVED HEAD
REMOVED TAIL
LIST SIZE IS 1
20
LIST CLEARED
LIST EMPTY
LIST EMPTY
LIST DELETED
MUST CREATE LIST INSTANCE

This is what I am getting:

LIST CREATED
LIST EMPTY
VALUE 25 ADDED TO HEAD
VALUE 5 ADDED TO TAIL
VALUE 20 ADDED TO HEAD
VALUE 5 ADDED TO TAIL
VALUE 10 ADDED TO HEAD
VALUE 25 ADDED TO HEAD
VALUE 25 AT HEAD
LIST SIZE IS 6
                  (Blank line where program freezes/locks up)

Efficient way to construct object with string member

Suppose I have a class ThisHasAStringMember. Assume it has a private member which is a string, and I want to efficiently get the string value, preferring a move over a copy where possible. Would the following two constructors accomplish that?

class ThisHasAStringMember
{
public:
  // ctors
  ThisHasAStringMember(const std::string str) : m_str(str) {}
  ThisHasAStringMember(std::string &&str) : m_str(std::move(str)) {}

  // getter (no setter)
  std::string value() { return m_str; }
private:
  std::string m_str;
}

Do I need the double ampersand before the str parameter in the second constructor?

Is this the right way to accomplish this?

C++ exception: std::out_of_range at memory location 0x003DF4C0

I am making a C++ program that gets phones from a list of phones and makes a vCard file off of them. However I'm having problems with the copying of the phones over to the file, which is a string replacement off of a template. How can I fix this?

I've tried looking into this site for some solutions but none of them are about ofstream, which is what I'm using to do this.

int main()
{
    string fileDest;

    string vCardTemp = "BEGIN:VCARD\nVERSION:3.0\nTEL;TYPE=WORK,MSG: phonehh\nEND:VCARD\n";

    cout << "Input file destination...\n"; 

    cin >> fileDest;

    cout << "Analyzing data...";


    ifstream inFile;
    inFile.open(fileDest);

    if (!inFile)
    {
        cout << "Error! File doesn't exist or can't be opened.";
        cin.ignore();
        exit(0);
    }

    cout << "File found. Dissecting...";

    string line;

    string finalvCard = "";
    string copy = vCardTemp;
    while (getline(inFile, line))
    {
        istringstream iss(line);

        copy.replace(copy.find("phonehh"), 7, line);

        //finalvCard += copy;
        finalvCard.append(copy);

        cout << " - " + line + " written to vCard.\n";
    }

    cout << "\n\nFinished vCard conversion. Where do we store this (include filename)?\n";

    string dest;

    cin >> dest;

    ofstream file(dest);
    file << finalvCard;

    cout << "File stored! Cya!\n";
    return 0;
}

How to properly apply rule of 5 (or zero?) to a class containing a vector of custom objects with strings

I'm having trouble wrapping my brain around ownership and maximizing performance with moves. Imagine this hypothetical set of classes emulating an Excel workbook.

namespace Excel {

class Cell
{
public:
  // ctors
  Cell() = default;
  Cell(std::string val) : m_val(val) {};
  // because I have a custom constructor, I assume I need to also
  // define copy constructors, move constructors, and a destructor.
  // If I don't my understanding is that the private string member 
  // will always be copied instead of moved when Cell is replicated 
  // (due to expansion of any vector in which it is stored)? Or will 
  // it be copied, anyways (so it doesn't matter or I could just 
  // define them as default)

  value() const { return m_val; }; // getter (no setter)
private:
  std::string m_val;
}

class Row
{
public:
  // ctors
  Row() = default;
  Row(int cellCountHint) : m_rowData(cellCountHint) {}

  // copy ctors (presumably defaults will copy private vector member)
  Row(const Row&) = default;
  Row& operator=(Row const&) = default;

  // move ctors (presumably defaults will move private vector member)
  Row(Row&& rhs) = default;
  Row& operator=(Row&& rhs) = default;

  // and if I want to append to internal vector, might I get performance
  // gains by moving in lieu of copying, since Cells contain strings of
  // arbitrary length/size?
  void append(Cell cell) { m_rowData.push_back(cell); };
  void append(Cell &&cell) { m_rowData.push_back(std::move(cell)); };
private:
  std::vector<Cell> m_rowData;
}

}

And so on:

  • A Worksheet class would contain a vector of Rows
  • A Workbook class would contain a vector of Worksheets

I felt no need to implement these last two for the MWE since they are effectively duplicative of Row (my assumption is they would be identical to the design of Row).

It's confusing to me to understand if it's ok to rely on the defaults or if I should be defining my own move constructors (and not keeping them default) to ensure the private vector member variable is moved rather than copied, but this is all very confusing to me and I can only seem to find overly simplistic examples of a class with nothing but members of built-in types.

How to properly create GSM?

I'm writing my semester project and it has to be made in C++ and I'm more into other languages. I would like to create a thing that is managing my game states, but I'm not doing well. I made the same game state managing system in Java and I would like to keep the same appropach.

gsm.h

#pragma once

#include <iostream>
#include <map>

#include "gamestate.h"

class GameStateManager {
private:
    std::map<int, GameState> gameStates;
    GameState currentState;
public:
    GameStateManager();
    void method();
    void add(int id, GameState state);
};

gsm.cpp

#include "gsm.h"
#include "playstate.h"

GameStateManager::GameStateManager() {
}

void GameStateManager::add(int id, GameState state) {
    gameStates.insert(id, state);
}

void GameStateManager::method() {
    currentState.method();
}

gamestate.h

#pragma once

#include "gsm.h"

class GameState {
protected:
    GameStateManager gsm;
public:
    GameState(GameStateManager gsm);
    virtual void method();
};

gamestate.cpp

#include "gamestate.h"

GameState::GameState(GameStateManager gsm) : gsm(gsm) { }

playstate.h

#pragma once

#include "gamestate.h"

class PlayState : public GameState {
public:
    PlayState(GameStateManager gsm);
    void method() override;
};

playstate.cpp

#include "playstate.h"
#include "gamestate.h"
#include <cstdio>

PlayState::PlayState(GameStateManager gsm): GameState(gsm) {}

void PlayState::method() {
    printf("Say hello");
}

main.cpp

#include "gamestate.h"
#include "gsm.h"
#include "playstate.h"

int main() {
    GameStateManager gsm;
    PlayState playState(gsm);
    gsm.add(0, playState);
}

I got a lot of errors like: 'GameState': undeclared identifier, syntax error: indetifier 'GameState'

Evaluation of Delegated Constructor

I'm interested in knowing the order of constructor evaluation when using delegation.

Here's a snippet of my code:

Number(){
    length = 100;
    values = new int[length];
};
Number(int len) : Number(){
    length = len;
}

Note that they both modify length, but only one applies that length to a new array (that's what delegation is for!). This code works.

My question: Why does it work? Do the constructors only apply the code that is non-redundant? Or maybe, in this situation, the default constructor is called before the code in the non-default constructor?

Thanks for your time!

How to fix Vector Position within Struct Player object so it'll work with me.position in Main?

I am teaching myself C++11 and this was one of my homework assignment, however the vector position; doesn't seem to work.

I've tried #include and std::vector, nothing seems to work.

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


struct Player
{
    string name;
    int hp;
    vector position;
}; 

int main()
{

Player me;
me.name = "Metalogic";
me.hp = 100;
me.position.x = me.position.y = me.position.z = 0;

return 0;

}

I'd like for it to cout << player << hp << position

How to concatenate parameter with colons in macro?

I want to write a macro that generates a vector with a name that consists of the name + type. So, GEN_NAME_TYPE_MEMBER(int, Id) should generate vector<int> vec_Id_int. GEN_NAME_TYPE_MEMBER(std::string, FName) should generate vector<int> vec_Id_string.

The following macro almost does it, but it fails when there is colons

#define GEN_NAME_TYPE_MEMBER(Name, Type)
    std::vector<Type> vec_##Name_##Type;

INITIAL SOLUTION

move the Type to the beginning of the name

 #define GEN_NAME_TYPE_MEMBER(Name, Type)
        std::vector<Type> Type##_##Name_vec;

Is there a way to put at the end of the name?

LLDB not showing variables values when inside a C++ class virtual method

I am currently using an open source library for Finance and building my own extension on top of it. Library dependency is built under Xcode 9.2 in Debug mode, and is included as a framework dependency to my executable. When I run lldb on my target, the debugger shows values and the stack trace for the linked library objects/methods, but as soon as a (virtual) method of the implementation of an interface/abstract class is called, LLDB ceases to show the values inside this method. It keeps showing the Debug values for normal std:: containers though.

Can someone please help me understand? Is this an issue in the current implementation of LLDB?

[C++]Loop until any of the elements of a std::vector is not encountered

I am doing a project in which I have encountered a situation in which I have to loop(inside a function) until some strings arent encountered. The strings are passed in a vector. The problem is, the number of strings is not fixed. How can I get the elements of a vector inside the condition of a loop when I dont know at what subscript to stop? It looks something like this:

while(a != vect[0] && a != vect[1] .... && a != vect[END VALUE]) //loop body Where END VALUE could be anything. Is this possible? Hope i explained my query well. I am using iterators in code. Used subscripts only to explain my query.

Thanks!

How to combine lambda expressions lambda function wrapper in C++?

When you are creating a lambda expression, its implementation creates a new class.Each lambda creates a separate class and has a different type. Even when many lambda expressions receive the same arguments and return the same type, each of them will be a different class; that is, a different type. C++ from version 11 on, incorporates a wrapper for any of the following functions with std::function and makes it easy to pass around lambda expressions: The following code snippets provides example that uses "std::function" to create the a function, which receives the function to be executed within a for_each as an argument.

#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>
using namespace std;

void run_within_for_each(std::function<void (int)> func)
{
    vector<int> numbers{ 1, 2, 3, 4, 5, 10, 15, 20, 25, 35, 45, 50 };

    for_each(numbers.begin(), numbers.end(), func);
}

int main()
{
    auto func1 = [](int y)
    {
        cout << y << endl;
    };

    auto func2 = [](int z)
    {
        cout << z * 2 << endl;
    };

    run_within_for_each(func1);
    run_within_for_each(func2);
}

The "run_within_for_each" function receives a std::function, so it is possible to call this function with a lambda expression that returns void and receives an int as an argument. The function declares the vector and executes a for_each with the received std::function as the function to be executed for each int value. The main method declares two different lambda expressions that receive an int argument and make one call to the run_within_for_each with each of these lambda expressions. In case you want to pass around a lambda expression that receives two int arguments and returns a bool value, you can use std::function. It is also possible to use std::function to specify the return type for any function. For example, the following function returns a std::function. The code returns a lambda expression that receives an int as a parameter and returns a bool value, wrapped in std::function:

std::function<bool(int)> create_function()
{
    return [](int x)
    {
        return (x < 100);
    };
}

The combination of lambda expressions with the std::function can boost your productivity and reduce a huge amount of code.

for more information please see here a wonderful article from "Gastón Hillar"

How to resolve Fatal signal 11 (SIGSEGV) code 1 in Android?

I am developing an Android application using Opencv for image processing.

The processing part is called in java through JNI functions.

I am sending to c++ two Opencv Mat objects to find matching points.

The problem is that sometimes the app works and sometimes it doesn't even while using the same images.

I already check if the images aren't empty and that they are valid before sending them to the native part.

Here is the stack trace is get in Log

2019-04-26 12:52:06.980 24955-25666/com.grimg.coffretpfe A/libc: Fatal signal 11 (SIGSEGV), code 1, fault addr 0x0 in tid 25666 (Thread-10)
2019-04-26 12:52:07.078 25766-25766/? A/DEBUG: *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
2019-04-26 12:52:07.078 25766-25766/? A/DEBUG: Build fingerprint: 'samsung/zeroltexx/zerolte:7.0/NRD90M/G925FXXU6ERF5:user/release-keys'
2019-04-26 12:52:07.078 25766-25766/? A/DEBUG: Revision: '10'
2019-04-26 12:52:07.078 25766-25766/? A/DEBUG: ABI: 'arm'
2019-04-26 12:52:07.078 25766-25766/? A/DEBUG: pid: 24955, tid: 25666, name: Thread-10  >>> com.grimg.coffretpfe <<<
2019-04-26 12:52:07.078 25766-25766/? A/DEBUG: signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x0
2019-04-26 12:52:07.078 25766-25766/? A/DEBUG:     r0 00000000  r1 00000000  r2 00000000  r3 b90a641c
2019-04-26 12:52:07.079 25766-25766/? A/DEBUG:     r4 ffffffff  r5 c09a4128  r6 b90a678c  r7 b90a6670
2019-04-26 12:52:07.079 25766-25766/? A/DEBUG:     r8 d33ee570  r9 97df7155  sl b90a6790  fp c06e3900
2019-04-26 12:52:07.079 25766-25766/? A/DEBUG:     ip c5ec4840  sp b90a6268  lr c5eb8043  pc c5eb8042  cpsr 600f0030
2019-04-26 12:52:07.081 25766-25766/? A/DEBUG: backtrace:
2019-04-26 12:52:07.081 25766-25766/? A/DEBUG:     #00 pc 00014042  /data/app/com.grimg.coffretpfe-2/lib/arm/libnative-lib.so (_Z6toGrayN2cv3MatES0_+1577)
2019-04-26 12:52:07.081 25766-25766/? A/DEBUG:     #01 pc 00014d65  /data/app/com.grimg.coffretpfe-2/lib/arm/libnative-lib.so (Java_com_grimg_coffretpfe_Activities_CompareActivity_detectFeatures+124)
2019-04-26 12:52:07.081 25766-25766/? A/DEBUG:     #02 pc 000adc99  /system/lib/libart.so (art_quick_generic_jni_trampoline+40)
2019-04-26 12:52:07.081 25766-25766/? A/DEBUG:     #03 pc 0000b0dd  /dev/ashmem/dalvik-jit-code-cache_24955_24955 (deleted)

I am running my app on a Samsung s6 edge, if this matters.

My native part contains two functions, toGray and here is the signature

double toGray(Mat captured, Mat target)

I didnt added the code because it's a lot of processing and operations

And the method I call in java is detectFeatures

extern "C" {
JNIEXPORT
jdouble
JNICALL Java_com_grimg_coffretpfe_Activities_CompareActivity_detectFeatures(
    JNIEnv *env,
    jobject instance,
    jlong addrRgba,
    jlong addrGray) {

 if (addrGray != NULL && addrRgba != NULL) {
    cv::Mat &mRgb = *(cv::Mat *) addrRgba;
    cv::Mat &mGray = *(cv::Mat *) addrGray;


    jdouble retVal;

    double conv = toGray(mRgb, mGray);

    retVal = (jdouble) conv;

    return retVal;
  }

   return -1;
 }
 }

I tried every available solution over here , but nothing works ,besides I don't really understand the problem so I don't know what to search for.

I hope you guys can help me solve this problem. Thanx in advance.

constexpr member function with std::vector data member in C++

I am trying to implement in a C++ class a constexpr member function which returns a template parameter. The code is supposed to be c++11 compatible. However I encounter compilation issues when the templated class also contains STL containers as data members such as std::vector (which are untouched by the constexpr member function).

A minimal example is given by the following code:


#include <vector>
#include <iostream>
#include <array>


template<size_t n>
struct A 
{

  constexpr size_t dimensions() const
  {
    return n;
  }
private:
  std::vector<double> a;
};


int main(int argc,char ** argv)
{
  auto a=A<3>();
  std::array<double,a.dimensions()> arr;

}

The code compiles correctly with the commands

g++ -std=c++14 -O3 quickTest.cpp -o test -Wall

clang++ -std=c++11 -O3 quickTest.cpp -o test -Wall

but fails when I use

g++ -std=c++11 -O3 quickTest.cpp -o test -Wall

with the error

quickTest.cpp:22:33: error: call to non-‘constexpr’ function ‘size_t A<n>::dimensions() const [with long unsigned int n = 3; size_t = long unsigned int]’
   std::array<double,a.dimensions()> arr;
                     ~~~~~~~~~~~~^~
quickTest.cpp:10:20: note: ‘size_t A<n>::dimensions() const [with long unsigned int n = 3; size_t = long unsigned int]’ is not usable as a ‘constexpr’ function because:
   constexpr size_t dimensions() const
                    ^~~~~~~~~~
quickTest.cpp:22:33: error: call to non-‘constexpr’ function ‘size_t A<n>::dimensions() const [with long unsigned int n = 3; size_t = long unsigned int]’
   std::array<double,a.dimensions()> arr;
                     ~~~~~~~~~~~~^~
quickTest.cpp:22:33: note: in template argument for type ‘long unsigned int’

I am using gcc 8.1.1 and clang 6.0.1

Avoiding the overheads of std::function

I want to run a set of operations over elements in a (custom) singly-linked list. The code to traverse the linked list and run the operations is simple, but repetitive and could be done wrong if copy/pasted everywhere. Performance & careful memory allocation is important in my program, so I want to avoid unnecessary overheads.

I want to write a wrapper to include the repetitive code and encapsulate the operations which are to take place on each element of the linked list. As the functions which take place within the operation vary I need to capture multiple variables (in the real code) which must be provided to the operation, so I looked at using std::function. The actual calculations done in this example code are meaningless here.

#include <iostream>
#include <memory>

struct Foo
{
  explicit Foo(int num) : variable(num) {}
  int variable;
  std::unique_ptr<Foo> next;
};

void doStuff(Foo& foo, std::function<void(Foo&)> operation)
{
  Foo* fooPtr = &foo;
  do
  {
    operation(*fooPtr);
  } while (fooPtr->next && (fooPtr = fooPtr->next.get()));
}

int main(int argc, char** argv)
{
  int val = 7;
  Foo first(4);
  first.next = std::make_unique<Foo>(5);
  first.next->next = std::make_unique<Foo>(6);
#ifdef USE_FUNC
  for (long i = 0; i < 100000000; ++i)
  {
    doStuff(first, [&](Foo& foo){ foo.variable += val + i; /*Other, more complex functionality here */ });
  }
  doStuff(first, [&](Foo& foo){ std::cout << foo.variable << std::endl; /*Other, more complex and different functionality here */ });
#else
  for (long i = 0; i < 100000000; ++i)
  {
    Foo* fooPtr = &first;
    do
    {
      fooPtr->variable += val + i;
    } while (fooPtr->next && (fooPtr = fooPtr->next.get()));
  }
  Foo* fooPtr = &first;
  do
  {
    std::cout << fooPtr->variable << std::endl;
  } while (fooPtr->next && (fooPtr = fooPtr->next.get()));
#endif
}

If run as:

g++ test.cpp -O3 -Wall -o mytest && time ./mytest
1587459716
1587459717
1587459718

real    0m0.252s
user    0m0.250s
sys 0m0.001s

Whereas if run as:

g++ test.cpp -O3 -Wall -DUSE_FUNC -o mytest && time ./mytest 
1587459716
1587459717
1587459718

real    0m0.834s
user    0m0.831s
sys 0m0.001s

These timings are fairly consistent across multiple runs, and show a 4x multiplier when using std::function. Is there a better way I can do what I want to do?

jeudi 25 avril 2019

How to dynamically set object's property based on prop name?

I hope it will be clear what I want to do.

I want to fetch data from database based on properties of provided object and then fill those properties with the retrieved data. So, if for example a user defines a class

class Person
{
   public:
      int Id;
      string Name;
};

and then when he calls MyDatabase.Instance.ExecQuery<Person>() it should return Person object filled with information.

What I did is: a user should define the class as following:

class Person : public DBEntity
{
    ENTITIY_PROP(Person , int, Id)
    ENTITIY_PROP(Person , string, Name)
};

The defined macros ensure to add the name and type of the properties to _propsMeta. Now, how do I set object's property based on it's name (see ExecQuery)?

MY INITIAL SOLUTION
I though to add map that maps property to a function that sets the property but I cannot have a map of references to functions with different signatures. Any ideas? If you think I need to change my design to accomplish what I need - let me know.

template <typename T>
void ExecQuery()
{
    static_assert(std::is_base_of<DBEntity, T>(), "a Class should inherit from DBEntity");

    const auto& props = entity->GetPropsMeta();
    auto row = GetData(props);
    T entity = new T();
    for (const auto& colName : row.Columns)
    {
        string val = row[colName];
        // TODO: SET ENTITY'S PROPERTY colName with val
    }
}

#define ENTITIY_PROP(Class, Type, Name) \
        private: \
            int _##Name; \
        public: \
            class Property_##Name { \
            public: \
                Property_##Name(Class* parent) : _parent(parent) \
                { \
                    _parent->SetPropMeta(#Name, #Type); \
                } \
                Type operator = (Type value) \
                { \
                    _parent->Set##Name(value); \
                    return _parent->Get##Name(); \
                } \
                operator Type() const \
                { \
                    return static_cast<const Class*>(_parent)->Get##Name(); \
                } \
                Property_##Name& operator =(const Property_##Name& other) \
                { \
                    operator=(other._parent->Get##Name()); return *this; \
                }; \
                Property_##Name(const Property_##Name& other) = delete; \
            private: \
                Class* _parent; \
            } Name { this }; \
            \
            Type Get##Name() const { return _##Name; } \
            void Set##Name(int value) { _##Name = value; } \

    class DBEntity
    {
    private:
        std::unordered_map<std::string, std::string> _propsMeta;

    public:
        const std::unordered_map<std::string, std::string>& GetPropsMeta() { return _propsMeta; }    
    };

Trying to do heapsort but got stuck

a new user at coding, trying to do heap sort but got stuck. the error I am getting is:

`heap.cpp: In member function ‘void heap::Heapsort()’:
heap.cpp: error: no matching function for call to ‘heap::swap(__gnu_cxx::__alloc_traits<std::allocator<int>, int>::value_type&, __gnu_cxx::__alloc_traits<std::allocator<int>, int>::value_type&)’
 swap(A[0],A[i]);
               ^
In file included from /usr/include/c++/8/vector:64,
                 from heap.cpp:2:
/usr/include/c++/8/bits/stl_vector.h:1367:7: note: candidate: ‘void std::vector<_Tp, _Alloc>::swap(std::vector<_Tp, _Alloc>&) [with _Tp = int; _Alloc = std::allocator<int>]’
       swap(vector& __x) _GLIBCXX_NOEXCEPT
       ^~~~
/usr/include/c++/8/bits/stl_vector.h:1367:7: note:   candidate expects 1 argument, 2 provided"

Please help!!I guess there is some error in the declaration of class. I am a complete noobie and this is my first course on data structures. It would be great if someone could help.I followed the heapsort code which is in cormen for most of it but the error seems to be prevalent.

#include<iostream>
#include<vector>
#include<iomanip>
using namespace std;
class heap:public vector<int>{
private:
    vector<int> &A;
    int length;
    int heap_size;
    int P(int i){return (i-1)/2;}
    int le(int i){return 2*i+1;}
    int ri(int i){return 2*i+2;}
public:
void maxheap(int i);
    void bmh(void);
    void Heapsort(void);
    heap(initializer_list<int> il):
        vector<int>(il), A(*this),length(A.size()),heap_size(0) {}
    heap(void):A(*this),length(A.size()),heap_size(0) {}// constructor 
    void show(void);

    };
void heap::maxheap(int i)
{
int largest;
int l=le(i),r=ri(i);
if(l<=heap_size-1)&&A[l]>A[i])
largest=l;
else
largest=i;
if(r<=heap_size-1&&A[r]>A[i])
largest=r;
else
largest=i;
if(largest!=i){
swap(A[largest],A[i]);
maxheap(largest);
}
};
void heap::bmh(void)
{
heap_size=length;
for(int i=length/2;i>=0;i--)
{
maxheap(i);
}
}
void heap::Heapsort(void)
{
bmh();
for(int i=length-1;i>0;i--){
swap(A[0],A[i]);
heap_size=heap_size-1;
maxheap(i);
}
}
void heap::show(void)
{
for(int i=0;i<length-1;i++)
{
cout<<A[i]<<" ";
}
cout<<endl;
}
int main()
{
    heap h<int>={16,4,10,14,7,9,3,2,8,1};
    h.show();
        //h.Build_Max_Heap();
        //h.show();
    // Test the member functions of heap class.
        h.Heapsort();
        h.show();
}

How do i specialize my template for std::string

I have the following templated function

template <typename As, typename std::enable_if<
std::is_arithmetic<As>::value, As>::type* = nullptr   > 
As getStringAs(const std::string& arg_name)
{
    std::istringstream istr(arg_name);
    As val;
    istr >> val;
    if (istr.fail())
        throw std::invalid_argument(arg_name);
    return val;
}

And i would like to use it like this:

getStringAs<float>("2.f");

What would be a good way to specialize the function for std::string so that i can write

getStringAs<std::string>("2.f");

I have tried all my known ways but they all seem to fail due to the ambiguity generated by the default type of the enable_if. For example: if i write:

template<>
std::string getStringAs<std::string>(const std::string& arg_name)
{    
}

This will not match any template overload. If i add a second type, this will generate an ambiguity error. I have tried google-in but the only thing i could find was about tag dispatch but that would make the call ugly on the user side. I was thinking at the very ugly solution of using a macro definition for replacing getStringAs with a dispatch tag.

Thank you!

How to properly apply this nested ifstream?

I want to use an ifstream function that calls another ifstream function inside it, but I have no idea why it does not work. The ifstream called first works fine, but the second one does not. This is the first one:

ifstream archivo("civilizaciones.txt");
if(archivo.is_open()){
    while(!archivo.eof()){
        string name;
        Civilizacion a;

        getline(archivo, name);

        if(archivo.eof()){ break; }
        a.setName(name);
        arreglo.push_back(a);
        c.recuperarAld(name);
    }
}

c.recuperarAld(name) Calls the following function in a class with object c:

void Civilizacion::recuperarAld(string name)
{
    ifstream aldeanoss(name + ".txt");
    if(aldeanoss.is_open()){
        while(!aldeanoss.eof()){
            Aldeano a;
            string linea;

            getline(aldeanoss,linea);

            if(aldeanoss.eof()){break;}

            a.setNombre(linea);

            getline(aldeanoss, linea);
            a.setEdad(stoul(linea));

            getline(aldeanoss, linea);
            a.setGenero(linea);

            getline(aldeanoss, linea);
            a.setSalud(stoi(linea));

            aldeanos.push_back(a);
        }
    }
}

But this second one does not seem to work, how can I fix it?

What is the difference between the 2 versions of std::enable_if

I don't understand why the first (good) version of the code compiles, but the second doesn't

I have read this, this , this, and of course this but i still do not understand why for one version it compiles, while for the other it doesn't. If somebody could please explain it (like for total dummies), I would really appreciate it.

GOOD version

template <typename As, typename std::enable_if<
std::is_arithmetic<As>::value, As>::type* = nullptr   > 
As getStringAs(const std::string& arg_name)
{
    std::istringstream istr(arg_name);
    As val;
    istr >> val;
    if (istr.fail())
        throw std::invalid_argument(arg_name);
    return val;
}

BAD version

template <typename As, typename std::enable_if_t<
std::is_arithmetic<As>::value, As> = 0   > 
As getStringAs(const std::string& arg_name)
{
    std::istringstream istr(arg_name);
    As val;
    istr >> val;
    if (istr.fail())
        throw std::invalid_argument(arg_name);
    return val;
}

Intended Usage:

int main()
{
   return getStringAs<float>("2.f");
}

Thank you very much!

How to fix error "vector iterators in range are from different containers" in c++?

I don't know where is the problem. The program crashes in this function. Can you help me?

void atrinkimas_2(vector <duomenys>& studentai, vector<duomenys> &silpni)
{
    sort(studentai.begin(), studentai.end(), tikrinimas_gal);
    std::vector<duomenys>::iterator it = std::find_if(studentai.begin(), studentai.end(), tikrinimas_5);
    std::copy(it, studentai.end(), std::back_inserter(silpni));
    studentai.resize(studentai.size() - silpni.size());
}