mercredi 30 novembre 2022

boost::asio Strictly sequential invocation of event handlers using strand

I have a question regarding to the usage of strand in boost::asio framework. The manuals refer the following

In the case of composed asynchronous operations, such as async_read() or async_read_until(), if a completion handler goes through a strand, then all intermediate handlers should also go through the same strand. This is needed to ensure thread safe access for any objects that are shared between the caller and the composed operation (in the case of async_read() it's the socket, which the caller can close() to cancel the operation). This is done by having hook functions for all intermediate handlers which forward the calls to the customisable hook associated with the final handler:

Let's say that we have the following example Strand runs in a async read socket operation . Socket read the data and forwards them to a async writer socket. Two operation are in the same io_service. Is this write operation thread safe as well?Is is called implicity in the same strand? Or is it needed to explicitly call async_write in the strand

read_socket.async_read_some(my_buffer,
    boost::asio::bind_executor(my_strand,
      [](error_code ec, size_t length)
      {
           write_socket.async_write_some(boost::asio::buffer(data, size), handler);
      }));

Is the async_write_some sequential executing in the following example or needs strand as well?

mardi 29 novembre 2022

Passing method with variadic arguments as template parameter for a function

Suppose to have the following definitions

struct Cla {
  void w(int x){}
};

template <typename C, void (C::*m)(int)> void callm(C *c, int args) {}


template <typename C, typename... A, void (C::*m)(A...)>
void callmv(C *c, A &&...args) {}

int main(){
  callm<Cla, &Cla::w>(&cla, 3);
  callmv<Cla, int, &Cla::w>(&cla, 3);
}

The first function (callm) is ok. The second (callmv), however, does not compile, and g++ gives the following error message

test.cpp: In function ‘int main()’:
test.cpp:84:28: error: no matching function for call to ‘callmv<Cla, int, &Cla::w>(Cla*, int)’
   84 |   callmv<Cla, int, &Cla::w>(&cla, 3);
      |   ~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~
test.cpp:52:6: note: candidate: ‘template<class C, class ... A, void (C::* m)(A ...)> void callmv(C*, A&& ...)’
   52 | void callmv(C *c, A &&...args) {}
      |      ^~~~~~
test.cpp:52:6: note:   template argument deduction/substitution failed:
test.cpp:84:28: error: type/value mismatch at argument 2 in template parameter list for ‘template<class C, class ... A, void (C::* m)(A ...)> void callmv(C*, A&& ...)’
   84 |   callmv<Cla, int, &Cla::w>(&cla, 3);
      |   ~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~
test.cpp:84:28: note:   expected a type, got ‘&Cla::w’

What is the correct syntax? (I already checked Methods as variadic template arguments )

how does std::vector deal with the call to destructor?

When tring to implement std::vector, I get confused with the implicit call to destructor.

Then element in vector maybe:

  • T
    • a Class Obecjt,
  • T*, shared_ptr<T>
    • a Smart/Simple Pointer to Class Obecjt
  • int
    • built-in type
  • int *
    • pointer to built-in type

When calling resize(),reserve() ,erase()or pop_back(), the destructor might be called.

I wonder how does std::vector deal with the call to destructor.

I found, only when the type is a build-in pointer won't std::vector call the destructor(Of course if it have one).

Does std::vector implement it by distinguishing type and determine whether or not call the destructor?

Below are some experiments about the question:

Example 1, the element is Object.

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

struct Tmp {
    ~Tmp() { cerr << "Destructor is called." << endl; }
};

int main (void)
{
    std::vector<Tmp>arr;
    Tmp tmp = Tmp();
    cerr << "Capacity:" << arr.capacity() << endl;//0
    arr.push_back (tmp);
    cerr << "Capacity:" << arr.capacity() << endl;//1
    arr.push_back (tmp);
    cerr << "Capacity:" << arr.capacity() << endl;//2
    cerr << "popback start------------" << std::endl;
    arr.pop_back();
    arr.pop_back();
    cerr << "popback end--------------" << endl;
}

the output is:

Capacity:0
Capacity:1
Destructor is called.
Capacity:2
popback start------------
Destructor is called.
Destructor is called.
popback end--------------
Destructor is called.

Example 2, the element is builtin-in pointer to obecjt:

...
std::vector<Tmp>arr;
Tmp * tmp = new Tmp;
...

The destructor won't be called automatically:

Capacity:0
Capacity:1
Capacity:2
popback start------------
popback end--------------

Example 3, shared_ptr

std::vector<shared_ptr<Tmp>>arr;
auto tmp = make_shared<Tmp>();

... //after being copied, the references count should be 3.
tmp = nullptr; //References count reduced by 1

cerr << "popback start------------" << std::endl;
arr.pop_back();//References count reduced by 1
arr.pop_back();//References count reduced by 1
cerr << "popback end--------------" << endl;

The destructor of shared_ptr will be called. When the references reduced to 0, the destructor of Tmp will be called:

Capacity:0
Capacity:1
Capacity:2
popback start------------
Destructor is called.
popback end--------------

lundi 28 novembre 2022

Reserve 2D std::vector of Widgets

For some legacy code reasons, I have to live with below code

// Header.h

class Widget
{
   // bunch of primitive types 
   // no fancy C++11 ish member functions

};

class BigWidget
{
   std::vector<std::vector<Widget>> w2dlist;
};

// Source.cpp

void someFunction()
{
   // some runtime calculations of numRows and numCols

    w2dlist.reserve(numRows);

    for (auto& r : w2dlilst)
    {
        r.reserve(numCols);
    }
    
    for (int i = 0; i < numRows; i++) 
    {
        w2dlist.emplace_back();   // emplace some default constructed objects
        
        for (int j = 0; j < numCols; j++) 
        {
===>>>            w2dlist[i].emplace_back(); // do the same 
        }
    }
}

I can not change the Widget/BigWidget class with rule of 4/5 members. But the profiler is pointing the line in the inner loop as one of the hotspots.

How can I improve this ?

I have tried below tricks

  1. default construct Widget as Widget{} while emplace'in , the static checker (and eventually runtime) point to stack overflow and crashes the app
  2. default construct/reserve 2D vector in BigWidget constructor, profiler then shifts the hotspot to this operation
  3. Meyer's singleton while emplacin' the Widgets :D , profiler is merciless

Profiler/Compiler : Visual Studio 2019 (C++17)

OS : Windows

When inheriting a Base class privately, can I declare the Base classes Basse class public?

I have a class "SuperBase" with public methods and a class "Base", that derives from SuperBase, also with public methods. I cannot alter these, as they come from an external project.

I want my own class "Derived" to inherit privately from Base, but still keep SuperBase public.

External Code (cannot be changed):

class SuperBase
{
public:
   void printSuperBase() const
   {
      std::cout << "Super Base Class\n";
   }
};

class Base : public SuperBase
{
public:
   void print() const
   {
      std::cout << "Base Class\n";
   }
};

My own code (can be changed):

class Derived: private Base
{
public:
   void print() const
   {
      std::cout << "Derived Class\n";
   }
};

void function(SuperBase const& sb)
{
   sb.printSuperBase();
}


int main() 
{
   Derived D{};
   D.print();    //prints "Derived Class\n"
   function(D);  //cannot access SuperBase, as Base was included privately
}

Note that I cannot override any of the Base class methods, as they are not declared virtual.

Including both, Base and SuperBase does not work as this makes SuperBase ambiguous.

class Derived: private Base, public SuperBase
{
public:
   void print() const
   {
      std::cout << "Derived Class\n";
   }
};

void function(SuperBase const& sb)
{
   sb.printSuperBase();
}


int main() 
{
   Derived D{};
   D.print();    //prints "Derived Class\n"
   function(D);  //base class SuperBase is ambiguous
}

Including Base publicly and declaring it's methods as private does not work either, as I now can pass Derived to functions using Base, that can access all privately declared methods

class Derived: public Base
{
public:
   void print() const
   {
      std::cout << "Derived Class\n";
   }
private:
   using Base::print; //declare base method private to make it inaccessible
};

void function2(Base const& b)
{
   b.print();          //prints "Base Class\n", but shall be inaccessible instead.
   b.printSuperBase();
}


int main() 
{
   Derived D{};
   D.print();    //prints "Derived Class\n"
   function2(D); //D gets passed as Base class, but shall not be allowed
}

asio HTTPS request response body is gibberish

i'm trying to send a get request to get some information, and I am using asio and a https request and ssl. When I send the request, I get a fully formed header, but the response is just non printable unicode characters. Despite the response not being readable, it has the same amount of characters as what the response is supposed have. Below is my code, and the response I get.

#include <string>
#include <iostream>
#include <chrono>

#include "asio.hpp"
#include "asio/ssl.hpp"

using namespace std;

float getTickerValue(const string& ticker)
{
    float tickerPrice;
    string host = "query1.finance.yahoo.com";
    string portNumber = "80";

    typedef asio::ssl::stream<asio::ip::tcp::socket> ssl_socket;

    // Create a context that uses the default paths for
    // finding CA certificates.
    asio::ssl::context ctx(asio::ssl::context::sslv23);
    ctx.set_default_verify_paths();

    // Open a socket and connect it to the remote host.
    asio::io_service io_service;
    ssl_socket sock(io_service, ctx);
    asio::ip::tcp::resolver resolver(io_service);
    asio::ip::tcp::resolver::query query(host, "https");
    asio::connect(sock.lowest_layer(), resolver.resolve(query));
    sock.lowest_layer().set_option(asio::ip::tcp::no_delay(true));

    // Perform SSL handshake and verify the remote host's
    // certificate.
    sock.set_verify_mode(asio::ssl::verify_peer);
    sock.set_verify_callback(asio::ssl::rfc2818_verification(host));
    sock.handshake(ssl_socket::client);

    // ... read and write as normal ...
    {
        string request = "GET /v11/finance/quoteSummary/" + ticker + "?modules=financialData HTTP/1.1\r\n"
                                                                     "Host: " + host + "\r\n"
                                                                     "Connection: close\r\n\r\n";
        sock.write_some(asio::buffer(request.data(), request.size()));

        using namespace std::chrono_literals;
        std::this_thread::sleep_for(200ms);  // THIS IS TEMPORARY

        size_t bytes = sock.lowest_layer().available();
        cout << "Bytes avalible: " << bytes << endl;

        if (bytes > 0) {
            vector<char> vBuffer(bytes);
            sock.read_some(asio::buffer(vBuffer.data(), vBuffer.size()));
            for (auto c: vBuffer) {
                cout << c;
            }
        }
    }
    return tickerPrice;
}

response from code

Thanks!

dimanche 27 novembre 2022

Qt calling tryLock() multiple times on the same mutex from the same thread (5.13.2 ver.)

I have a question about the method bool QMutex::tryLock(int timeout). I notice that the description of this method in different (i.e. 5.15 and 6.4) versions are slightly different.

  • In  5.15 ver., the document says "Calling this function multiple times on the same mutex from the same thread is allowed if this mutex is a recursive mutex. If this mutex is a non-recursive mutex, this function will always return false when attempting to lock the mutex recursively."

  • In 6.4 ver., the document says "Calling this function multiple times on the same mutex from the same thread will cause a dead-lock."

I'm using Qt 5.13.2 version now. Is it alright to call tryLock multiple times on the same thread? Or the document of 5.15 ver. is incorrect. Thanks!

refs:

I sent a mail to the QT Team, but haven't receive the feedback yet.

C++: free(): double free detected in tcache 2 problem when merging two linked list

I am trying merge two list in C++. My implementation are below:

listnode.h

#ifndef __LISTNODE_H
#define __LISTNODE_H

template< class NODETYPE > class List;

template <class NODETYPE>
class ListNode
{
    friend class List< NODETYPE >;
private:
    NODETYPE data;
    ListNode* next;

public:
    ListNode(const NODETYPE &);
    ~ListNode() {};
    NODETYPE getData() const;
    ListNode<NODETYPE>* getNext() const;
};

template< class NODETYPE >
ListNode<NODETYPE>::ListNode(const NODETYPE& data)
    :data(data),
     next(0)
{ }  // empty ctor body

template< class NODETYPE >
NODETYPE ListNode<NODETYPE>::getData() const { return data; }

template< class NODETYPE >
ListNode<NODETYPE>* ListNode<NODETYPE>::getNext() const { return next; }

#endif

list.h

#ifndef __LIST_H
#define __LIST_H

#include "listnode.h"
#include <iostream>
#include <new>
#include <cstdlib>

template <class NODETYPE>
class List
{
private:
    ListNode<NODETYPE>* firstPtr;
    ListNode<NODETYPE>* lastPtr;
    ListNode<NODETYPE>* getNewNode(const NODETYPE&);

public:
    List();
    ~List();
    void insertFromFront(const NODETYPE&);
    void insertAtBack(const NODETYPE&);
    bool removeFromFront(const NODETYPE&);
    bool removeFromBack(const NODETYPE&);
    bool isEmpty() const;
    void print() const;
    ListNode<NODETYPE>* getFirstNode() const;
    ListNode<NODETYPE>* getLastNode() const;
    void sort();
    void concatenate(List<NODETYPE>);
};

template< class NODETYPE >
List<NODETYPE>::List()
    : firstPtr(0),
      lastPtr(0)
{// empty ctor body}

template< class NODETYPE >
List<NODETYPE>::~List() {
    
    ListNode<NODETYPE> *iter = firstPtr, *temp;
    if(!isEmpty()) {
        while (iter) {
            temp = iter;
            iter = iter->next;
            delete temp;
        }
    }
}

template< class NODETYPE >
void List<NODETYPE>::insertFromFront(const NODETYPE& value) {

    ListNode<NODETYPE> *newNode = getNewNode(value);
    
    if (newNode) {
        if (isEmpty())
            firstPtr = lastPtr = newNode;
        else {
            newNode -> next = firstPtr; // newNode->next points whereever firstPtr points to.
            firstPtr = newNode;         // firstPtr now demonstrates the first nodeç
        }
    } else {
        std::cerr << "Allocation failed!" << std::endl;
        exit(EXIT_FAILURE);
    }
}

template< class NODETYPE >
void List<NODETYPE>::insertAtBack(const NODETYPE& value) {

    ListNode<NODETYPE> *newNode = getNewNode(value);
    if (newNode) {
        if(isEmpty())
            firstPtr = lastPtr = newNode;
        else {
            
            lastPtr -> next = newNode;
            lastPtr = newNode;
            
        }   
    } else {
        std::cerr << "Allocation fails!" << std::endl;
        exit(EXIT_FAILURE); // terminate the program
    }
}

template< class NODETYPE >
bool List<NODETYPE>::removeFromFront(const NODETYPE& value) {

    ListNode<NODETYPE>* temp;
    
    if(isEmpty()) {
        return false;
    }

    if(firstPtr == lastPtr) { // if only one node present
        value = firstPtr -> data;
        firstPtr = lastPtr = 0;
        return true;
    }

    temp = firstPtr;
    value = temp -> data;
    firstPtr = firstPtr -> next;
    delete temp;

    return true;

} 

template< class NODETYPE >
bool List<NODETYPE>::removeFromBack(const NODETYPE& value) {

    if (isEmpty())
        return false;
    
    if(firstPtr == lastPtr) { // if only one node present
        value = lastPtr->data;
        firstPtr = lastPtr = 0;
        return true;
    }

    ListNode<NODETYPE> *iter = firstPtr;
    while (iter != lastPtr)
        iter = iter->next;
    
    lastPtr = iter;             // alter the point lastPtr points to.
    value = iter->next->data;   // grab the value of last node
    delete iter->next;          // delete the last node
    
    return true;

}

template< class NODETYPE >
bool List<NODETYPE>::isEmpty() const {
    return firstPtr == 0;
}

template< class NODETYPE >
void List<NODETYPE>::print() const {
    ListNode<NODETYPE> *iter = firstPtr;
    while(iter) {
        std::cout << iter->data << ' ';
        iter = iter->next;
    }
    std::cout << std::endl << std::endl;
}

template< class NODETYPE >
void List<NODETYPE>::sort() {
    NODETYPE min = firstPtr -> data;
    for (ListNode<NODETYPE>* i = firstPtr; i != 0; i = i -> next) {
        for (ListNode<NODETYPE>* j = i -> next; j != 0; j = j -> next) {
            if(j->data < i->data){
                NODETYPE temp = i->data;
                i->data = j->data;
                j->data = temp;
            }
        }
    }
}

template< class NODETYPE >
ListNode<NODETYPE>* List<NODETYPE>::getNewNode(const NODETYPE &value) {
    return new ListNode<NODETYPE>(value);
}

template< class NODETYPE >
ListNode<NODETYPE>* List<NODETYPE>::getFirstNode() const { return firstPtr; }

template< class NODETYPE >
ListNode<NODETYPE>* List<NODETYPE>::getLastNode() const { return lastPtr; }

template< class NODETYPE >
void List<NODETYPE>::concatenate(List<NODETYPE> l) {
    
    ListNode<NODETYPE>* iter = l.getFirstNode(); // first node of the second linked list
    while (iter != 0){
        insertAtBack(iter->getData());
        iter = iter->next;
    }
    sort(); // to sort in ascending order
    //std::cout << "lastPtr->data:" << lastPtr->data << std::endl;
}

#endif

main.cpp

#include <iostream>
#include "list.h"
#include <cstdlib>
#include <ctime>

template < class NODETYPE>
List<NODETYPE> mergeHandler(List<NODETYPE> list1, List<NODETYPE> list2) {
    
    List<NODETYPE> resultList;
    NODETYPE min = list1.getFirstNode()->getData();
    for (ListNode<NODETYPE>* i = list1.getFirstNode(); i != 0; i = i -> getNext()) {
        
    }
    resultList.print();
    return resultList;
}

int main(int argc, char *argv[]) {
    
    List< int > intList1, intList2/*, mergedList*/;
    srand(time(NULL));
    
    for (size_t i = 0; i < 10; i++) 
        intList1.insertFromFront(1 + rand() % 100);
    
    for (size_t i = 0; i < 10; i++) 
        intList2.insertFromFront(1 + rand() % 100);
    
    //intList1.print();
    //intList1.sort();
    intList1.print();

    //intList2.print();
    //intList2.sort();
    intList2.print();

    intList1.concatenate(intList2);
    intList1.sort();
    intList1.print();

    return 0;
}

The problem is, as mentioned, that at the end of the program, it yields

free(): double free detected in tcache 2
Aborted (core dumped)

I couldn't understand the problem. Because I created new nodes to the first list and add the values of the second list. So even if I delete the same values, I delete the values stored exactly different addresses. In of the question, reccomends of implementing copy ctor and = operator. However, I couldn't get and implement it because I use the normal constructor, but when I implement this ctor

public:
.
.
.
List(List<NODETYPE> &rhs){std::cout << "Do nothing in copy ctor" << std::endl;}

It strangly outputs Do nothing in copy ctor even though I use the normal consturctor. How can I handle this issue? I have already a concatenate method and wanna use it, because when I use copy ctor, it throws a segmentation fault error.

Is abseil strcat overload useless?

In Abseil StrCat, it has a few of overload functions like

ABSL_MUST_USE_RESULT inline std::string StrCat() { return std::string(); }

ABSL_MUST_USE_RESULT inline std::string StrCat(const AlphaNum& a) {
  return std::string(a.data(), a.size());
}

ABSL_MUST_USE_RESULT std::string StrCat(const AlphaNum& a, const AlphaNum& b);
ABSL_MUST_USE_RESULT std::string StrCat(const AlphaNum& a, const AlphaNum& b,
                                        const AlphaNum& c);
ABSL_MUST_USE_RESULT std::string StrCat(const AlphaNum& a, const AlphaNum& b,
                                        const AlphaNum& c, const AlphaNum& d);

// Support 5 or more arguments
template <typename... AV>
ABSL_MUST_USE_RESULT inline std::string StrCat(
    const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d,
    const AlphaNum& e, const AV&... args) {
  return strings_internal::CatPieces(
      {a.Piece(), b.Piece(), c.Piece(), d.Piece(), e.Piece(),
       static_cast<const AlphaNum&>(args).Piece()...});
}

The CatPieces which supports multiple parameters by using initializer_list. These functions' implementation all similar. I can't see any optimisation happening for particular overload. Why not just provide one variadic parameter function to cover all?

Thanks

samedi 26 novembre 2022

Storing multiple strings in nested structure

I have 2 structures named Phone and Patient, respectively:

struct Phone{
    char description[4];
    char number[10];
};

struct Patient{
    int id;
    char name[15];
    struct Phone phone;
};

Now, on creating a patient's array like:

struct Patient patient = [
    {1024, "Shaggy Yanson", {"CELL","3048005191"} },
]

Upon printing the phone description value, I get the output as CELL3048005191.

NOTE: I cannot change the array

I want to know what is causing the problem. Is it the structure definition?

Basic types say `uint8_t` could be inherited? [duplicate]

Here is the simple code snippet which works well:

#include <iostream>

enum class Color : uint8_t {
    Blue = 1,
    Red = 2,
};

std::ostream &operator<< (std::ostream& os, const Color& color)
{
    switch(color)
    {
        case (Color::Blue):
        {
            os<< "blue";
            break;
        }
        case (Color::Red):
        {
            os << "red";
            break;
        }
        default:
        {
            break;
        }
    }

    return os;
}

int main()
{
    std::cout << Color::Blue << std::endl;
}

And the aforementioned code snippet is seen from this more complicated one.

My question is whether basic types say uint8_t could be inherited or not.

Adding -std=c++0x to the compiler arguments doesn't work in Vivado HLS

I am using Vivado HLS 2018.2 to design an FPGA, and I have verified my design with C-simulation. However, when I run C synthesis to get a resource utilization report, I get the following error.

    In file included from /opt/Xilinx/Vivado/2018.2/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/array:34:
/opt/Xilinx/Vivado/2018.2/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/bits/c++0x_warning.h:32:2: error: This file requires compiler and library support for the upcoming ISO C++ standard, C++0x. This support is currently experimental, and must be enabled with the -std=c++0x or -std=gnu++0x compiler options.
#error This file requires compiler and library support for the upcoming \
 ^
1 error generated.\n
C preprocessor failed.

If it's a compiler problem, how did the C simulation run perfectly? Moreover, I have added std=c++0x to the input arguments to the compiler (Project>Project Settings>Simulation>Input Arguments), yet I get the same error when running synthesis. I also tried editing the script.tcl file for the project by adding -argv {std=c++0x} to the csynth_design and csim_design commands. Please help if you know a solution or a workaround to this. Thanks.

vendredi 25 novembre 2022

multiple clients one tcp server select()

im a beginner to tcp client-server architecture. I am making a client server application in c++ I need the server to be able to accept messages from multiple clients at once. I used this IBM example as my starter for the server server: https://www.ibm.com/docs/en/i/7.1?topic=designs-example-nonblocking-io-select

the client side is irrelevent but this is my source client: https://github.com/bozkurthan/Simple-TCP-Server-Client-CPP-Example/blob/master/tcp-Client.cpp

the problem is with the server side it allows multiple clients to connect but not asynchronously, so the server will connect with the second client after the first one finishes. I want the server to watch for messages from both clients.

I tried to read about select() on the internet but I couldnt find anything to make the IBM code async. How can I edit the server code to allow the clients to connect and interact at the same time.

which code is better when we use c++ std::unordered_map?

Here is the code.

1.

std::unordered_map<std::string, std::unordered_map<std::string, double>> ab_map;
for (int i = 0; i < 30000; i++) {
    std::unordered_map<std::string, double>& item = ab_map[std::to_string(i)];
    for (int j = 0; j < 10; j++) {
        item.emplace(std::to_string(j), 10.0);
    }
}
    std::unordered_map<std::string, std::unordered_map<std::string, double>> ab_map;
    for (int i = 0; i < 30000; i++) {
        std::unordered_map<std::string, double> item;
        for (int j = 0; j < 10; j++) {
            item.emplace(std::to_string(j), 10.0);
        }
        ab_map.emplace(std::to_string(i), std::move(item));
    }
    

    I think the second usage is better. But after executing the code and calculating the cost time. I found that the first one is better. Why?

    test1: first: 183947 microseconds; second: 186965 microseconds

    test2: first: 226307 microseconds; second: 268437 microseconds

    mercredi 23 novembre 2022

    Related type for the arguments of template function

    How can I tell the compiler that U is equivalent to either std::vector<T> or T?

    template<typename T, typename U> std::vector<T> foo(T t, U){return t;}
    

    Where does a segmentation fault occur if the debugger points to a function definition?

    To elaborate, I am currently writing a program that requires a function that is provided by the professor. When I run the program, I get a segmentation fault, and the debugger I use (gdb) says that the segmentation fault occurred at the definition of the function that, like I said, was provided by the professor.

    So my question here is, is the definition itself causing the fault, or is it somewhere else in the program that called the function causing the fault?

    I attempted to find a spot in the program that might have been leading to it, such as areas that might have incorrect parameters. I have not changed the function itself, as it is not supposed to be modified (as per instructions). This is my first time posting a question, so if there is any other information needed, please let me know.

    When I use sorting predicate for multimap, , an error will be reported when calling "count". Is this an official bug?

    here is my code:

    #include <iostream>
    #include <map>
    #include <string>
    using namespace std;
    
    template <typename T>
    struct DescendingSort {
        bool operator () (const T key1, const T key2) {
            return (key1 > key2);
        }
    };
    
    int main()
    {
        multimap<int, string, DescendingSort<int>> m;
        m.insert(make_pair(3, "three"));
        m.insert(make_pair(3, "drei"));
    
        cout << m.count(3) << "\n\n";  // error
        return 0;
    }
    

    If my code is wrong, where is the problem? (I run the code in c++11)

    mardi 22 novembre 2022

    C++ I’m struggling to find a solution to this excercise [closed]

    there are N chickens, the corresponding chickens every t1, t2, ..., tn seconds will lay 1 egg. Write a program to calculate the minimum time to bake X cakes, knowing that 1 cake only uses 1 egg.

    -Line 1: 2 integers x (0<x<10^15) and N (0<N<20) -Line 2: N integers, 0<ti<500 (i= 1…N)

    Testcase: INPUT 3 2 50 70 OUTPUT 100

    can someone help me with this exercise?

    lundi 21 novembre 2022

    Isn't pass by reference and pass by address confusing? [closed]

    fun(&n){
      *n =...
    }
    and 
    fun(&n){
      n =...
    }
    

    Isn't pass by reference and pass by address confusing?

    Autosys job failing with code C0000374 but process exit with 0 return code

    Backend c++ process exit with return code 0 but in autosys job is failing with exit code 3884

    enter image description here enter image description here

    can someone please tell what could be the possible reason for this job failure.

    dimanche 20 novembre 2022

    how to access my boost variant having datatypes and containers as well

    I'm trying to create a template to access the datatype and containers from boost variant. how can I return the type from the different templates?

    Anybody tell me how to find the reason of std::unorded_set insert failed in this situation? [closed]

    enter image description here It seems __bucket_list's length is less than __chash, but why?

    result of p _bucket_list

    why bucket length is 23 and ptr in bucket is 0?

    Is that a bug of std::unordered_set?

    (sorry that i cant dump text or code from my work machine)

    How to dump a derived class object into file then load it back?

    I want to dump some derived class into file, then dump it back.

    here the the class definition:

    // base.h
    #include <string>
    class Base {
     public:
      virtual std::string show_string() = 0;
      int b;
    };
    
    class A : public Base {
     public:
      std::string show_string() override { return "this is A"; }
      int a;
    };
    

    the dumper code is:

    #include <bits/stdc++.h>
    #include "./base.h"
    using namespace std;
    
    int main() {
      std::fstream f;
      f.open("a.bin", std::ios::out);
      for (int i = 0; i < 10; ++i) {
        A a;
        a.a = i;
        a.b = i - 1;
        f.write((char*)&a, sizeof(a));
      }
      f.close();
    }
    

    the loader code is:

    #include <bits/stdc++.h>
    #include "./base.h"
    using namespace std;
    
    int main() {
      std::fstream f;
      f.open("a.bin", std::ios::in);
      char buff[65536];
      f.write(buff, sizeof(buff));
      A* a = (A*)buff;
      cout << a->show_string() << endl;
      f.close();
    }
    

    the loader crashed, I think the problem happened because there is a virtual pointer in A, which lost the address when it is loaded back.

    so, how can i make it correct?

    samedi 19 novembre 2022

    Compiling out strings used in print statements in multi-level log - C++

    I'm looking for a way to compile print strings out of my binary if a specific macro-based condition is met.

    here, _dLvl can be conditionally set equal or lower than the maximum allowed level.

    
    enum DEBUG_LEVELS : int
    {
        DEBUG_NONE,
        DEBUG_ERRORS,
        DEBUG_WARN,
        DEBUG_INFO,
        DEBUG_VERBOSE
    };
    
    #define MAX_LEVEL  DEBUG_WARN
    
    int _dLvl = DEBUG_ERRORS;
    
    template <typename... Args> void E(const char * _f, Args... args){
        if (_dLvl >= DEBUG_ERRORS){
            printf(_f, args...);
        }
    }
    template <typename... Args> void W(const char * _f, Args... args){
        if (_dLvl >= DEBUG_WARN){
            printf(_f, args...);
        }
    }
    template <typename... Args> void I(const char * _f, Args... args){
        if (_dLvl >= DEBUG_INFO){
            printf(_f, args...);
        }
    }
    template <typename... Args> void V(const char * _f, Args... args){
        if (_dLvl >= DEBUG_VERBOSE){
            printf(_f, args...);
        }
    }
    
    int main(){
        E("This will print\n");
        W("This might be printed based on _dLvl, existence of this string is ok.\n");
        I("This wont print ever, the existence of this string is memory waste\n");
        V("Same as I\n");
    }
    

    What adds to the challenge that I've multiple instances of a logger class, where each instance would have a different MAX level, see this question for a more clear example of multi-instances.

    Here's a solution for my situation (but an ugly and unmanageable onewherein it requires a special macro per instance to be used differently within the source code):

    #if (WIFI_LOG_MAX_LEVEL >= 1)
    #define w_log_E(f_, ...) logger.E((f_), ##__VA_ARGS__)
    #else
    #define w_log_E(f_, ...)
    #endif
    
    #if (WIFI_LOG_MAX_LEVEL >= 2)
    #define w_log_W(f_, ...) logger.W((f_), ##__VA_ARGS__)
    #else
    #define w_log_W(f_, ...)
    #endif
    
    #if (WIFI_LOG_MAX_LEVEL >= 3)
    #define w_log_I(f_, ...) logger.I((f_), ##__VA_ARGS__)
    #else
    #define w_log_I(f_, ...)
    #endif
    
    #if (WIFI_LOG_MAX_LEVEL >= 4)
    #define w_log_V(f_, ...) logger.V((f_), ##__VA_ARGS__)
    #else
    #define w_log_V(f_, ...)
    #endif
    

    Is there any trick to solve it?

    std::function Error : error: static assertion failed: Wrong number of arguments for pointer-to-member?

    I have a tricky problem and I'm working on it for several hours but can't find a cause and solution of it. Hope someone help me.

    I have to demonstrate function being called inside another function( pls see the comment in seminar.cpp)

    Below are the files ( I have separated it into header and code files)

    main.cpp

    #include <iostream>
    #include <functional>
    #include "seminar.h"
    
    int main()
    {
        Tom::Car::Car car;
        Nor::Driving drivingnow;
        std::vector<uint8_t> X = car.road(drivingnow);
        for(int i = 0 ; i < X.size() ; i++){
            std::cout<<unsigned(X[i])<<" ";
        }
    
        return 0;
    }
    

    seminar.h

    #pragma once
    #include "dist.h"
    #include <vector>
    #include <bits/stdc++.h>
    namespace Tom
    {
        namespace Car
        {
    
            class Car
            {
            public:
                std::vector<uint8_t> road(Nor::Driving &driving);
                
            };
        } // namespace Car
    } // namespace Tom
    

    seminar.cpp

    #include "seminar.h"
    #include <algorithm>
    #include <functional>
    
    namespace Tom
    {
        namespace Car
        {
            std::vector<uint8_t> drive(Nor::Range &range)
            {
                std::vector<uint8_t> s;
                s.push_back(range.z);
                s.push_back(range.zz);
                return s;
            }
    
            template <typename T, typename B, typename L>
            std::vector<uint8_t> Content(T Sec, B Byte, L Func)
            {
                Nor::Range Rom;
                std::vector<uint8_t> z = Func(Rom);
                return z;
            }
    
            std::vector<uint8_t> Car::road(Nor::Driving &driving)
            {
                std::function<std::vector<uint8_t>(Nor::Range &)> Func = &drive;
    
                return Content(driving, 1, Func);  // passing drive function into content
            }
    
        } // namespace Car
    } // namespace Tom
    

    dist.h

    namespace Nor
    {
    
    class Driving{
    public:
      int x = 1;
    };
    
    class Range{
    public:
      int z = 50;
      int zz = 100;
    };
    
    }
    

    The above code and file structure works correctly and give me the correct expected output ie 50 100 Live here


    Now I want to do more separation ie I want the implementation of drive function to move in another file ie in type.cpp

    type.cpp

    #include <algorithm>
    #include "seminar.h"
    
    #include <functional>
    
    namespace Tom
    {
        namespace Car
    
        {
            std::vector<uint8_t> Car::drive(Nor::Range &range)
            {
                std::vector<uint8_t> s;
                s.push_back(range.z);
                return s;
            }
    
        } // namespace Car
    } // namespace Tom
    

    seminar.h

    #pragma once
    #include "dist.h"
    #include <vector>
    #include <bits/stdc++.h>
    namespace Tom
    {
        namespace Car
        {
    
            class Car
            {
            public:
                std::vector<uint8_t> road(Nor::Driving &driving);
                std::vector<uint8_t> drive(Nor::Range &range);
            };
        } // namespace Car
    } // namespace Tom
    

    seminar.cpp

    #include "seminar.h"
    #include <algorithm>
    
    #include <functional>
    
    namespace Tom
    {
        namespace Car
        {
            
    
            template <typename T, typename B, typename L>
            std::vector<uint8_t> Content(T Sec, B Byte, L Func)
            {
                Nor::Range Rom;
                std::vector<uint8_t> z = Func(Rom);
                return z;
            }
    
            std::vector<uint8_t> Car::road(Nor::Driving &driving)
            {
                std::function<std::vector<uint8_t>(Nor::Range &)> Func = &drive;
    
                return Content(driving, 1, Func);
            }
    
        } // namespace Car
    } // namespace Tom
    

    Live here After doing this I am getting an below error:

    seminar.cpp: In member function ‘std::vector<unsigned char> Tom::Car::Car::road(Nor::Driving&)’:
    seminar.cpp:22:71: error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function.  Say ‘&Tom::Car::Car::drive’ [-fpermissive]
       22 |             std::function<std::vector<uint8_t>(Nor::Range &)> Func = &drive;
          |                                                                       ^~~~~
    seminar.cpp:22:71: error: conversion from ‘std::vector (Tom::Car::Car::*)(Nor::Range&)’ to non-scalar type ‘std::function(Nor::Range&)>’ requested
    

    Taking reference from this answer

    I tried this way :

    std::function<std::vector<uint8_t>(Nor::Range)> f = std::bind(&Car::drive, this);
    

    And Got this error:

    /usr/include/c++/9/functional:775:7: error: static assertion failed: Wrong number of arguments for pointer-to-member
      774 |       static_assert(_Varargs::value
          |                               ~~~~~
      775 |       ? sizeof...(_BoundArgs) >= _Arity::value + 1
          |       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      776 |       : sizeof...(_BoundArgs) == _Arity::value + 1,
          |       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    seminar.cpp: In member function ‘std::vector<unsigned char> Tom::Car::Car::road(Nor::Driving&)’:
    seminar.cpp:23:73: error: conversion from ‘std::_Bind_helper (Tom::Car::Car::*)(Nor::Range&), Tom::Car::Car*>::type’ {aka ‘std::_Bind (Tom::Car::Car::*(Tom::Car::Car*))(Nor::Range&)>’} to non-scalar type ‘std::function(Nor::Range)>’ requested
       23 |            std::function<std::vector<uint8_t>(Nor::Range)> f = std::bind(&Car::drive, this);
          |                                                                ~~~~~~~~~^~~~~~~~~~~~~~~~~~~
    seminar.cpp:25:40: error: ‘Func’ was not declared in this scope
       25 |             return Content(driving, 1, Func);
    

    See here live


    I don't know correctly what I am doing wrong in moving the implementation of drive function can someone please help with implementing the corrrect way.

    Note:: I'm fine if the solution uses another way to pass the function ie by not using std::function . Thanks

    vendredi 18 novembre 2022

    Exception unhanded [closed]

    System.InvalidOperationException: 'The file located at C:\Users\Ghosts\Videos\never give up.mp3 is not a valid wave file.'

    this appearing when I try to run my Gui's program, could anyone help, please ?

    I specify buttons for programs when they are pressed, you can choose an MP3 file in your device and play it for you, but after choosing it does not work, it says System.InvalidOperationException: 'The file located at C:\Users\Ghosts\Videos\never give up.mp3 is not a valid wave file.' I am working with c++

    Std::function ERROR:: "ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function"?

    I have a little tricky problem and I'm working on it for several hours but can't find a cause and solution of it. Hope someone help me.

    I have to demonstrate function being called inside another function( pls see the comment in seminar.cpp)

    Below are the files ( I have separated it into header and code files)

    main.cpp

    #include <iostream>
    #include <functional>
    #include "seminar.h"
    
    int main()
    {
        Tom::Car::Car car;
        Nor::Driving drivingnow;
        std::vector<uint8_t> X = car.road(drivingnow);
        for(int i = 0 ; i < X.size() ; i++){
            std::cout<<unsigned(X[i])<<" ";
        }
    
        return 0;
    }
    

    seminar.h

    #pragma once
    #include "dist.h"
    #include <vector>
    #include <bits/stdc++.h>
    namespace Tom
    {
        namespace Car
        {
    
            class Car
            {
            public:
                std::vector<uint8_t> road(Nor::Driving &driving);
                
            };
        } // namespace Car
    } // namespace Tom
    

    seminar.cpp

    #include "seminar.h"
    #include <algorithm>
    #include <functional>
    
    namespace Tom
    {
        namespace Car
        {
            std::vector<uint8_t> drive(Nor::Range &range)
            {
                std::vector<uint8_t> s;
                s.push_back(range.z);
                s.push_back(range.zz);
                return s;
            }
    
            template <typename T, typename B, typename L>
            std::vector<uint8_t> Content(T Sec, B Byte, L Func)
            {
                Nor::Range Rom;
                std::vector<uint8_t> z = Func(Rom);
                return z;
            }
    
            std::vector<uint8_t> Car::road(Nor::Driving &driving)
            {
                std::function<std::vector<uint8_t>(Nor::Range &)> Func = &drive;
    
                return Content(driving, 1, Func);  // passing drive function into content
            }
    
        } // namespace Car
    } // namespace Tom
    

    dist.h

    namespace Nor
    {
    
    class Driving{
    public:
      int x = 1;
    };
    
    class Range{
    public:
      int z = 50;
      int zz = 100;
    };
    
    }
    

    The above code and file structure works correctly and give me the correct expected output ie 50 100 Live here


    Now I want to do more separation ie I want the implementation of drive function to move in another file ie in type.cpp

    type.cpp

    #include <algorithm>
    #include "seminar.h"
    
    #include <functional>
    
    namespace Tom
    {
        namespace Car
    
        {
            std::vector<uint8_t> Car::drive(Nor::Range &range)
            {
                std::vector<uint8_t> s;
                s.push_back(range.z);
                return s;
            }
    
        } // namespace Car
    } // namespace Tom
    

    seminar.cpp

    #include "seminar.h"
    #include <algorithm>
    
    #include <functional>
    
    namespace Tom
    {
        namespace Car
        {
            
    
            template <typename T, typename B, typename L>
            std::vector<uint8_t> Content(T Sec, B Byte, L Func)
            {
                Nor::Range Rom;
                std::vector<uint8_t> z = Func(Rom);
                return z;
            }
    
            std::vector<uint8_t> Car::road(Nor::Driving &driving)
            {
                std::function<std::vector<uint8_t>(Nor::Range &)> Func = &drive;
    
                return Content(driving, 1, Func);
            }
    
        } // namespace Car
    } // namespace Tom
    

    Live here After doing this I am getting an below error:

    seminar.cpp: In member function ‘std::vector<unsigned char> Tom::Car::Car::road(Nor::Driving&)’:
    seminar.cpp:22:71: error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function.  Say ‘&Tom::Car::Car::drive’ [-fpermissive]
       22 |             std::function<std::vector<uint8_t>(Nor::Range &)> Func = &drive;
          |                                                                       ^~~~~
    seminar.cpp:22:71: error: conversion from ‘std::vector (Tom::Car::Car::*)(Nor::Range&)’ to non-scalar type ‘std::function(Nor::Range&)>’ requested
    

    I don't know correctly what I am doing wrong in moving the implementation of drive function can someone please help with implementing the corrrect way.

    Note:: I'm fine if the solution uses another way to pass the function ie by not using std::function . Thanks

    how do I make a program with a break in it [closed]

    Write a program that accepts three integer inputs. The first input will be the starting number, the second input will be the ending number, and the third input will serve as the max number.

    Using a loop, add the numbers from the starting number until the ending number. If the running sum is greater than or equal to the max number, break out of the loop. Print the running sum every iteration until it stops.

    The type of loop is of your preference. Figure out what suits best for this problem. the output should be like this: Enter·starting:·1 Enter·ending:·10 Enter·limit:·15 1 3 6 10 15

    and this is my code

    #include <iostream>
    using namespace std;
    int main(){
        int s,e,m,sum;
        cout << "Enter starting: ";
        cin >> s;
        cout << "Enter ending: ";
        cin >> e;
        cout << "Enter limit: ";
        cin >> m;
           cout << s<<endl;
           int b=s;
    for (int a=1;a<e;a++){
          int sum=b+s;
          sum+=a;
          if(sum>=e){
                break;
          }
          cout << sum << endl;
          b=sum;
    }}
    

    and the output i get is: Enter starting: 1 Enter ending: 10 Enter limit: 15 1 3 6

    jeudi 17 novembre 2022

    Missing VTABLE error while creating an inventory system for my game [closed]

    I am making an inventory system for my game, however I keep getting this error telling me I am missing vtables, however I define both Inventory::toString() and Item::toString() in my code.

    Error :

    2 warnings generated.
    Undefined symbols for architecture arm64:
      "Item::toString() const", referenced from:
          Inventory::toString() const in Inventory-a887cf.o
      "vtable for Item", referenced from:
          Item::Item(Item const&) in Inventory-a887cf.o
      NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
    
    ld: symbol(s) not found for architecture arm64
    clang: error: linker command failed with exit code 1 (use -v to see invocation)
    make: *** [all] Error 1
    

    Inventory.h

    #pragma once
    
    #include "items/Item.h"
    
    class Inventory
    {
        private:
            Item** items;
    
            int max_size;
            int current_size;
    
            // Private Functions
            void initialize(const unsigned from = 0);
            void expand();
    
        public:
            // Constructor
            Inventory(unsigned max_size = 10);
            Inventory(const Inventory& other);
            ~Inventory();
    
            // Operators
            void operator = (const Inventory& other);
            Item& operator[] (const unsigned index);
    
            // Accessors
            const unsigned& size() const;
            const unsigned& capacity() const;
            Item& at(const unsigned index) const;
    
    
            // Modifiers
    
    
            // Public Functions
            void add(const Item& item);
            void remove(const Item& index);
            std::string toString() const;
    };
    

    Inventory.cpp

    #include "Inventory.h"
    #include <sstream>
    
    // Public Functions
    void Inventory::initialize(const unsigned from) {
        for(size_t i = 0; i < this->max_size; i++) {
            this->items[i] = nullptr;
        }
    };
    
    void Inventory::expand() {
        this->max_size *= 2;
    
        Item** temp = new Item*[this->max_size];
        for(size_t i = 0; i < this->max_size; i++) {
            temp[i] = this->items[i];
        }
    
        delete[] this->items;
        this->items = temp;
    
        this->initialize(this->current_size);
    };
    
    // Constructor
    Inventory::Inventory(unsigned max_size) {
        this->max_size = max_size;
        this->current_size = 0;
        this->items = new Item*[max_size];
    
        this->initialize();
    };
    
    Inventory::Inventory(const Inventory& other) {
        this->max_size = other.max_size;
        this->current_size = other.current_size;
        this->items = new Item*[this->max_size];
    
        this->initialize();
    
        for(size_t i = 0; i < this->current_size; i++) {
            this->items[i] = other.items[i];
        }
    };
    
    // Destructor
    Inventory::~Inventory() {
        for(size_t i = 0; i < this->max_size; i++) {
            delete this->items[i];
        }
        delete[] this->items;
    };
    
    // Operators
    void Inventory::operator=(const Inventory& other) {
        if(this != &other) {
            for(size_t i = 0; i < this->current_size ; i++) {
                delete this->items[i];
            }
            delete[] this->items;
    
            this->max_size = other.max_size;
            this->current_size = other.current_size;
            this->items = new Item*[this->max_size];
    
            this->initialize();
    
            for(size_t i = 0; i < this->current_size; i++) {
                this->items[i] = other.items[i];
            }
        }
    };
    
    Item& Inventory::operator[](const unsigned index) {
        if(index < 0 || index >= this->current_size) {
            throw "Index out of bounds!";
        }
        return *this->items[index];
    };
    
    const unsigned& Inventory::size() const {
        return this->current_size;
    };
    
    const unsigned& Inventory::capacity() const {
        return this->max_size;
    };
    
    Item& Inventory::at(const unsigned index) const {
        if(index < 0 || index >= this->current_size) {
            throw "Index out of bounds!";
        }
        return *this->items[index];
    }; 
    
    // Functions
    void Inventory::add(const Item& item) {
        if(this->current_size >= this->max_size) {
            this->expand();
        }
        this->items[this->current_size++] = new Item(item);
    };
    
    void Inventory::remove(const Item& index) {
        
    };
    
    std::string Inventory::toString() const {
        std::stringstream ss;
    
        for(size_t i = 0; i < this->current_size; i++) {
            ss << this->items[i]->toString() << std::endl;
        }
    
        return ss.str();
    }
    

    Item.h

    #pragma once
    
    #include <iostream>
    
    enum ItemType
    {
        MATERIAL = 0,
        TOOL = 1,
        FOOD = 2,
    };
    
    enum ItemRarity
    {
        COMMON = 0,
        UNCOMMON = 1,
        RARE = 2,
        EPIC = 3,
        LEGENDARY = 4,
        HOLY_SHIT = 5,
    };
    
    class Item
    {
        private:
            int id;
            unsigned type;
            unsigned rarity;
            unsigned value;
    
            std::string name;
            std::string description;
    
            void generate();
    
        public:
            // Constructor
            Item(std::string name, unsigned type, unsigned rarity, unsigned value, std::string description);
            
            // Destructor
            virtual ~Item();
    
            int size;
            bool isStackable;
    
            int max_stack_size;
            int current_stack_size;
    
            // Accessors
            const int& getId() { return this->id; }
            const unsigned& getType() { return this->type; }
            const unsigned& getRarity() { return this->rarity; }
            const unsigned& getValue() { return this->value; }
            const std::string& getName() { return this->name; }
            const std::string& getDescription() { return this->description; }
    
            // Functions
            const std::string toString() const;
    };
    
    

    Item.cpp

    #include "Item.h"
    #include <sstream>
    
    void Item::generate() {
        
    }
    
    // Constructor
    Item::Item(std::string name, unsigned type, unsigned rarity, unsigned value, std::string description) {
        this->name = name;
        this->description = description;
        this->id = id;
        this->type = type;
        this->rarity = rarity;
        this->value = value;
    }
    
    // Destructor
    Item::~Item() {
        
    }
    
    // Accessors
    
    const int & Item::getId() {
        return this->id;
    }
    
    const unsigned & Item::getType() {
        return this->type;
    }
    
    const unsigned & Item::getRarity() {
        return this->rarity;
    }
    
    const unsigned & Item::getValue() {
        return this->value;
    }
    
    const std::string & Item::getName() {
        return this->name;
    }
    
    
    const std::string & Item::getDescription() {
        return this->description;
    }
    
    // Functions
    const std::string Item::toString() const {
        std::stringstream ss;
    
        ss << "Name: " << this->name 
        << " | Description: " << this->description 
        << " | Value: " << this->value 
        << " | Rarity: " << this->rarity << " | Type: " 
        << this->type;
    
        return ss.str();
    }
    
    

    I checked that both were defined and they are. I am confused as to what a vtable I have never seen an error like this before.

    How would one go about serializing a shared_ptr

    Here is a situation I am dealing with :

    1. There exists a function f() in process P1
    2. There exists a function g() in process P2
    3. f() in P1 wants to provide g() in P2 with objects like shared_ptr or unique_ptr or weak_ptr

    One part of IPC is message serialization and I am interested to know answers to following questions :

    a) Is it even possible to serialize these C++-11 smart pointer constructs as these in essence can be recursive constructs for instance a shared_ptr could be a shared_ptr to the root of a tree which in essence is a recursive data structure?

    b) What libraries exist to do this?

    c) How would g() then go about de-serializing these constructs?

    P.S. : I did some research on Google before posting this but I am not able to find a definitive resource on this topic and hence a little confused. Thanks in advance!

    Readings done


    1. Read about serialization and de-serialization
    2. Read about how boost tries to do serialization of smart pointers : https://theboostcpplibraries.com/boost.serialization-pointers-and-references

    Same parameter type constructors auto deduction

    I have a class whose constructor accepts const string &. When I use auto to define a object with string as parameter. The type deduction result is a string, instead of my custom class. Which rule does apply here?

    class AB{
        public:
        AB(const string& a){
            
        }
    };
    
    int main()
    {
        string a {"a"};
        auto b("b"s);
        
        cout<<a<<endl<<b<<endl;
        return 0;
    }
    

    mercredi 16 novembre 2022

    unique_ptr is copying when raw pointer is passed into its constructor

    I am trying to understand how unique pointers work in modern C++.

    When I went through the documentations (cppreference and others), I was able to understand that unique_ptr will transfer ownership and not share it. But I am not able to understand why unique_ptr is acting strange when working with a raw pointer passed into its constructor.

    For example:

    #include <iostream>
    #include <memory>
    
    class foo{
        int x;
    public:
        foo(): x(0) {}
        foo(int a): x(a) {}
        foo(const foo& f): x(f.x) {}
    };
    
    int main(){
        foo *ptr = new foo(5);
        std::unique_ptr<foo> uptr(ptr);
        std::cout << ptr << "\n";
        std::cout << uptr.get() << "\n";
        return 0;
    }
    

    Output below:

    0x5c7bc80
    0x5c7bc80
    

    Queries:

    • Is the raw pointer being passed into the copy constructor? Isn't the copy constructor deleted (=delete)? Why is the raw pointer printing the same address as unique_ptr?
    • Is this a design flaw of unique_ptr?
    • How do I overcome this issue?
    • What is the use of std::make_unique()? I tried change the line std::unique_ptr<foo> uptr(ptr); to std::unique_ptr<foo> uptr(std::make_unique<foo>(*ptr)); but nothing changed.

    Anyone can help me to free memory leak in this code?

    This is the code it occupies 4 alloc & free only 3, Anyone can help me to do Its urgent

    /* Citation and Sources...
    Final Project Milestone 2
    Module: Menu
    Filename: Parking.cpp
    Version 1.0
    Author: Swati Gupta
    Revision History
    -----------------------------------------------------------
    Date Reason
    2022/11/13 Preliminary release
    -----------------------------------------------------------
    I have done all the coding by myself and only copied the code 
    that my professor provided to complete my project milestones.
    -----------------------------------------------------------*/
    #define _CRT_SECURE_NO_WARNINGS
    #include <cstring>
    #include <iostream>
    #include <iomanip>
    #include <fstream>
    #include "Parking.h"
    #include "Menu.h"
    
    using namespace std;
    namespace sdds {
        Parking::Parking(const char* datafile) :m_datafile(nullptr), m_parkingMenu("Parking Menu, select an action:"), m_vehicleMenu("Select type of the vehicle:", 1) {
            if (datafile != nullptr && datafile[0] != '\0') { 
                m_datafile = new char[strlen(datafile) + 1];
                strcpy(m_datafile, datafile);
                if (load()) {
                    m_parkingMenu.add("Park Vehicle");
                    m_parkingMenu.add("Return Vehicle");
                    m_parkingMenu.add("List Parked Vehicles");
                    m_parkingMenu.add("Find Vehicle");
                    m_parkingMenu.add("Close Parking (End of day)");
                    m_parkingMenu.add("Exit Program");
                    m_vehicleMenu.add("Car");
                    m_vehicleMenu.add("Motorcycle");
                    m_vehicleMenu.add("Cancel");
                    
                } 
            }
            else 
            { 
                cout << "Error in data file" << endl;
                m_datafile = nullptr;
            }
        }
        void Parking::parkVehicle() {
            m_vehicleMenu.display();
            int option = 0;
            cin >> option;
            if (option == 1) { 
                cout << "---------------------------------" << endl;
                cout << "Parking Car" << endl;
                cout << "---------------------------------" << endl<<endl;
            } 
            else if (option == 2) { 
                cout << "---------------------------------" << endl;
                cout << "Parking Motorcycle" << endl;
                cout << "---------------------------------" << endl<<endl;
            } 
            else if (option == 3) {
                cout << "---------------------------------" << endl;
                cout << "Cancelled parking" << endl;
                cout << "---------------------------------" << endl<<endl;
            } 
        }
        void Parking::returnVehicle() { 
            cout << "---------------------------------" << endl;
            cout << "Returning Vehicle" << endl;
            cout << "---------------------------------" << endl<< endl;
        }
        void Parking::listParkedVheicles() { 
            cout << "---------------------------------" << endl;
            cout << "Listing Parked Vehicles" << endl;
            cout << "---------------------------------" << endl<< endl;
        }
        void Parking::FindVehicle() {
            cout << "---------------------------------" << endl;
            cout << "Finding a Vehicle" << endl;
            cout << "---------------------------------" << endl<< endl;
        }
        bool Parking::closeParking() {
            bool check = false;
            char choice;
            char* option = nullptr;
            cout << "This will close the parking; All the vehicles will be removed!" << endl;
            cout << "Are you sure? (Y)es/(N)o: ";
            option = new char[7];
            do {
                cin >> option;
                if ((option[0] != 'Y' && option[0] != 'y' && option[0] != 'N' && option[0] != 'n') || strlen(option) > 1)
                { 
                    cout << "Invalid response, only (Y)es or (N)o are acceptable, retry: ";
                }
                else 
                { 
                    check = true; 
                }
                cin.clear();
                cin.ignore(1000, '\n');
            }
            while (!check);
            cout << "Ending application!" << endl;
            choice = tolower(option[0]);
            delete[] option;
            option = nullptr;
            return choice == 'y';
        }
        bool Parking::exitParkingApp() {
            bool check = false;
            cout << "This will terminate the application and save the data!" << endl;
            cout << "Are you sure? (Y)es/(N)o: ";
            char ori;
            do {
                cin >> ori;
                if ((ori == 'Y') || (ori == 'y'))
                { 
                    check = true; 
                }
                else if ((ori == 'N')||(ori == 'n'))
                {
                  run();
                }
                else
                { 
                    cout << "Invalid response, only (Y)es or (N)o are acceptable, retry: ";
                }
                cin.clear();
                cin.ignore(1000, '\n');
            }
            while (!check);
            cout << "Exiting application!" << endl;
            cout <<"---------------------------------\n";
            cout<<"Saving data into ParkingData.csv\n";
            cout<<"---------------------------------\n" << endl;
            exit(1);
            return ori == 'y';
            
            
        }
        void Parking::parkingStatus() const { 
            cout << "****** Valet Parking ******" << endl;
        }
        Parking::~Parking() { 
            save();
            setEmpty(); 
        }
        bool Parking::load() {
            if (!isEmpty())
            cout<<"---------------------------------\n";
            cout << "loading data from " << m_datafile << endl;
            cout<<"---------------------------------\n\n";
            return (!isEmpty());
        }
        void Parking::save() {
            if (!isEmpty()) { 
                cout <<"---------------------------------\n";
                cout<<"Saving data into ParkingData.csv\n";
                cout<<"----------------------------------";
            }
        }
        bool Parking::isEmpty() const { 
            return m_datafile == nullptr;
        }
        void Parking::setEmpty() { 
            delete[] m_datafile;m_datafile = nullptr; 
        }
        int Parking::run() {
            bool done = false;
            int selection = 0;
            while (!isEmpty() && !done) {
                parkingStatus();
                m_parkingMenu.display();
                cin >> selection;
                if (selection == 1) { 
                    parkVehicle(); 
                }
                else if (selection == 2) { 
                    returnVehicle(); 
                }
                else if (selection == 3) {
                    listParkedVheicles();
                }
                else if (selection == 4) {
                    FindVehicle();
                }
                else if (selection == 5) { 
                    done = closeParking();
                }
                else if (selection == 6) { 
                    done = exitParkingApp();
                }
            }
            if (m_datafile == nullptr) {
                return 1;
            }
            else 
            {
                return 0;
            }
        }
    }
    

    It is aparking system where we can use some random option coz of dummy code

    run your program as follows to check for possible memory leaks (assuming your executable name is ms):

    valgrind --show-error-list=yes --leak-check=full --show-leak-kinds=all --track-origins=yes ms --show-error-list=yes: show the list of detected errors --leak-check=full: check for all types of memory problems --show-leak-kinds=all: show all types of memory leaks identified (enabled by the previous flag) --track-origins=yes: tracks the origin of uninitialized values (g++ must use -g flag for compilation, so the information displayed here is meaningful). To check the output, use a program that can compare text files. Search online for such a program for your platform, or use diff available on Just free memory block, for avoid the memory leak. thanks

    Globally array declaration c++ [closed]

    I want to make a global 2d array in c++ and fill that array using memset function of c++.

    #include <bits/stdc++.h>
    using namespace std;
    int t[5][5];
    memset(t, -1, sizeof(t));
    int main(){
     return 0;
    }
    

    Defining the array using memset outside the main function is not working it is giving the error.

    prog.cpp:11:7: error: expected constructor, destructor, or type conversion before ( token memset(t, -1, sizeof(t));

    What does this error mean and how to solve this?

    mardi 15 novembre 2022

    option(YAML_CPP_BUILD_TESTS "Enable testing" ON) ON?OFF? in yaml-cpp

    When I compile yaml-cpp, the "undefined reference ..." occurs.

    undefined reference to `testing::internal::EqFailure(char const*, char const*, std::__cxx11::basic_string

    ......

    undefined reference to`testing::internal::GetBoolAssertionFailureMessage[abi:cxx11]

    However, when option(YAML_CPP_BUILD_TESTS "Enable testing" ON) is changed to option(YAML_CPP_BUILD_TESTS "Enable testing" OFF) in CmakeLists.txt, yaml-cpp can be compiled successfully.

    The version of GCC is 9.5.0. It seems to be about the criterion of C++11. Can anyone explain the reason for this phenomenon?

    Any answer is appreciated.

    lundi 14 novembre 2022

    function printGraph prints too many Nodes

    I'm trying to make a program that print the nodes and the edges from graph and shows the shortest path from declared node to all others. The problem is that the print function I create prints too many Nodes with name 0 and edge with weight 0 and I don't know why. Here is the function to add edge in the nodes and function that should be print the graph correctly.

    `

    #include <iostream>
    #include <vector>
    #include <queue>
    using namespace std;
    
    void addEdge(vector<vector<pair<int, int>>>& graph, int u, int v, int w)
    {
        graph[u].push_back(make_pair(v, w));
        graph[v].push_back(make_pair(u, w));
    }
    
    void printGraph(vector<vector<pair<int, int>>> adj, int V)
    {
        int v, w;
        for (int u = 0; u < V; u++)
        {
            cout << "Node " << u << " makes an edge with \n";
            for (auto it = adj[u].begin(); it != adj[u].end(); it++)
            {
    
                v = it->first;
                w = it->second;
                cout << "\tNode " << v << " with edge weight ="
                    << w << "\n";
            }
            cout << "\n";
        }
    }
    
    int main()
    {
        vector<vector<pair<int, int>>> graph(9, vector<pair<int, int>>(9));
        addEdge(graph, 0, 1, 4);
        addEdge(graph, 0, 7, 8);
        printGraph(graph,1);
        return 0;
    }
    

    `

    I tried to find the similar problem but without success.

    g++ std=c++11 : is anything wrong in allocating/deallocating a 2d array this way

    I'm using g++ -std=c++11 and this compact approach to allocate/deallocate 2d arrays :

    int(*MyArray)[Ydim]=new int[Xdim][Ydim];
    delete[] MyArray;
    

    Everything seems to be working fine (compile time and run time). I know there are many ways to do the same but this is compact and seems to be doing the job. Is anything wrong with it?

    Everything seems to work...but worried about subtle problems (memory leakage...)

    Xdim and Ydim are compile time constants

    [COVERITY][C++] Non-static class member "A._M_elems" is not initialized in this constructor nor in any functions that it calls

    I am having an issue with a coverity warning that occurs in the constructor of my C++11 class.

    In the class Model, I define the type Trajectory and declare it privately.

    template<unsigned int T, unsigned int K>
    class Model
    {
    public:
        typedef Eigen::Matrix<float, DEGREE, AXIS> State;
        typedef Eigen::Matrix<float, AXIS_COUNT, K> Sample;
        typedef std::array<std::array<Sample, T>, DEGREE> Trajectory;
    
    private:
        Settings _settings;
        State _state;
        Trajectory _trajectory;
    
    ...
    

    Later in the constructor section I define two constructors, the second one inherits from the first one. In the first one, I initialize the _trajectory variable in the double for loop.

    ...
    
    public:
        Model(const Settings& settings, const State& initialState) :
         _settings(settings),
         _state(initialState)
        {
            for (unsigned int i = 0; i < DEGREE; i++)
                for (unsigned int j = 0; j < T; j++)
                    _trajectory[i][j].setZero();
        };
        Model(const Settings& settings) :
         Model(settings, State::Zero()){};
    
        ~Model() = default;
    
    ...
    

    This class is called by a handler which initializes Model with the second constructor. Everything works fine, however, once I run the coverity check, I receive the following error.

    
    Non-static class member "_trajectory._M_elems" is not initialized in this constructor nor in any functions that it calls.
    

    It is called at the line Model(settings, State::Zero()){};

    I have tried many options but I cannot figure out how to initialize _trajectory properly without receiving this error.

    I have tried this:

    public:
        Model(const Settings& settings, const State& initialState) :
         _settings(settings),
         _state(initialState),
         _trajectory({})
    

    this

    public:
        Model(const Settings& settings, const State& initialState) :
         _settings(settings),
         _state(initialState),
         _trajectory()
    

    this

    public:
        Model(const Settings& settings, const State& initialState) :
         _settings(settings),
         _state(initialState),
         _trajectory(Trajectory)
    

    and other combinations. None works.

    Waiting for some legend to give me a hint.

    What is the correct Expression to find bigger Element by pair key and the biggest of all values

    What is the correct Compare Statement to find the biggest Value of a Vector full of pairs that are bigger than a specific defined int.

    int x = 5;
    auto pos = max_element(ownCards.begin(),
                ownCards.end(),
                [&x](pair<int, int> p1, pair<int, int> p2) 
    { return p1.first > x && p1.second > p2.second; });
    

    From the fact that my vector is sorted, I have the upper_bound function still taken to help, this makes the code clearer and faster, still not fast enough unfortunately.

    auto start = upper_bound(ownCards.begin(), ownCards.end(), ownCards[j]);
    
                auto pos = max_element(start,
                                       ownCards.end(),
                                       [&x](pair<int, int> p1, pair<int, int> p2) { return p1.second > p2.second; });
    

    C++ requires a type specifier for all declarations while assigning values to array of strings [duplicate]

    I am a new to C++. I have a class as follows compiling which is throwing "C++ requires a type specifier for all declarations" as the values for array of string elements are being assigned after the array of string is dynamically allocated.

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    class bank {
    
    protected:
        string* Checkperson = new string[3];
        string managerUsername = "manager";
        string managerPassword = "M@n@ger";
        Checkperson[0] = "First";    //the error is here
        Checkperson[1] = "Last";     //the error is here
        Checkperson[2] = "Manager";  //the error is here
        string* searchFiles(string username, string password) {
            string* person = new string[3];
            for(int i = 0; i < 3; i++) {
                person[i].clear();
            }
            if((username == managerUsername) && (password == managerPassword)) {
                for(int i = 0; i < 3; i++) {
                    person[i] = Checkperson[i];
                }
            }
            return person;
        }
    };
    

    Compiling this I get the errors:

    ./bank.cpp:17:2: error: C++ requires a type specifier for all declarations
            Checkperson[0] = "First";
            ^
    ./bank.cpp:18:2: error: C++ requires a type specifier for all declarations
            Checkperson[1] = "Last";
            ^
    ./bank.cpp:19:2: error: C++ requires a type specifier for all declarations
            Checkperson[2] = "Manager";
            ^
    

    I tried the following and it worked fine but since I am trying to learn c++ would like to know why the previous method didn't work.

    string Checkperson[3] = {"First", "Last", "Manager"};
    

    dimanche 13 novembre 2022

    relaxed memory ordering for thread stop flags

    The author in the video on atomic ops has the following snippet. While the load to the stop flag is not relaxed, the store cannot be relaxed. My question is if the reason for store not to be relaxed has to do with it potentially being visible after the join of threads / if there is some other reason?

    Worker threads:

    while (!stop.load(std::memory_order_relaxed)) {
        // do something (that's independent of stop flag)
    }
    

    Main thread:

    int main() {
      launch_workers();
      stop = true; // <-- not relaxed
      join_threads();
      // do something  
    }
    

    samedi 12 novembre 2022

    Expression must be a modifiable lvalue - class function [closed]

    I was looking to learn some OOP concepts and i'm stuck with this error

    #include <iostream>
    using namespace std;
    
    class Employee
    {
    private:
        string name;
        int salary;
    
    public:
        Employee()
        {
            name = "";
            salary = 0;
        }
        int getSalary()
        {
            return salary;
        }
    };
    
    int main()
    {
        Employee e1;
        e1.getSalary() = 7000;
        cout << e1.getSalary();
        return 0;
    }
    

    From what I understood, if I add & to method getSalary() it will be a setter and getter at the same time. I am confused why I need to add & to getSalary() method to work properly. What's the point of reference in this case?

    How to correctly pass a function with parameters to another function?

    I have the following code to demonstrate a function been called inside another function.

    The below code works correctly:

    #include <iostream>
    
    int thirds()
    {
        return 6 + 1;
    }
    template <typename T, typename B>
    int hello(T x, B y , int (*ptr)() ){
        
        int first = x + 1;
        int second = y + 1;
        int third = (*ptr) (); ;
        
        return first + second + third;
    }
    int add(){
        
         int (*ptr)() = &thirds;
        return hello(1,1, thirds);
    }
    int main()
    {
        std::cout<<add();
        return 0;
    }
    

    Now I want to pass one number as a parameter from add function ie into thirds function (thirds(6)).

    I am trying this way:

    #include <iostream>
    
    int thirds(int a){
        return a + 1;
    }
    
    template <typename T, typename B>
    int hello(T x, B y , int (*ptr)(int a)() ){
        
        int first = x + 1;
        int second = y + 1;
        int third = (*ptr)(a) (); ;
        
        return first + second + third;
    }
    
    int add(){
        
         int (*ptr)() = &thirds;
        return hello(1,1, thirds(6)); //from here pass a number
    }
    
    int main()
    {
        
        std::cout<<add();
    
        return 0;
    }
    

    My expected output is:

    11
    

    But It is not working. Please can someone show me what I am doing wrong?

    vendredi 11 novembre 2022

    Getting Segmentation violation signal error on copying vector elements?

    I have the following code for doing a http post request. I am getting the response in const std::vector<json> value ...The below code works correctly

    RpcResponseAndContext<std::vector<Largest>>
    Connection::getLargestAccounts() const {
      const json params = {};
      const auto reqJson = jsonRequest("getLargest", params);
      const json res = sendJsonRpcRequest(reqJson);
      const std::vector<json> value = res["value"];
      std::vector<Largest> accounts_list;
      accounts_list.reserve(value.size());
      for (const json &account : value) {
        accounts_list.push_back(account);
      }
      return {res["context"], accounts_list};
    }
    

    To improve the appending of elements into accounts_list vector..I am trying to use std::copy() But getting this error: FATAL ERROR: test case CRASHED: SIGSEGV - Segmentation violation signal

    I am trying this way:

    RpcResponseAndContext<std::vector<Largest>>
    Connection::getLargestAccounts() const {
      const json params = {};
      const auto reqJson = jsonRequest("getLargest", params);
      const json res = sendJsonRpcRequest(reqJson);
      const std::vector<json> value = res["value"];
      std::vector<Largest> accounts_list;
      accounts_list.reserve(value.size());
      std::copy(value.begin(), value.end(), accounts_list.begin());
      return {res["context"], accounts_list};
    }
    

    What I am doing wrong ?

    Is there any difference between clicking the run button in the upper right corner of vscode and typing the ./ command in the terminal?

    To run a c++ program in vscode, is there any difference between typing ./ab in the terminal and clicking the run button in the upper right corner? When I use the first method, it can run normally, and the result is output in the terminal, but when I click the run button, it will let me give him permission to access the folder and the output result is in the debug console.

    This is what happens when the run button is clicked

    Why does "C++ allocator" show call stack error?

    I am practicing with C++ allocator on MSVC from C++ primer example. It seems to be a call stack error, which I am not able to resolve. Here is the code, and with output image I am getting.

    std::allocator<string> alloc;
    constexpr size_t n = 10;        // Capacity
    
    auto const p = alloc.allocate(n);
    cout << "type id:   " << typeid(p).name() << endl;
    
    string s;
    auto q = p;
    while (cin >> s && q != p + n)
    {
        alloc.construct(q++, s);
    }
    const size_t sz = q - p;
    
    for (auto pos = p; pos != q; ++pos)
    {
        cout << *pos << endl;
    }
    
    while (q != p)
    {
        alloc.destroy(--q);
    }
    alloc.deallocate(p, n);
    

    I'm trying to run a cpu scheduler program on vs code but I'm unable to get an output. The terminal flickers but I can't get an actual result [closed]

    This was the code I used. There were no error problems generated

    
    #include <iostream>
    #include <string>
    #include <fstream>
    #include <sstream>
    #include <vector>
    #include <unistd.h>
    #include <queue>
    #include <stdio.h>
    #include <stdlib.h>
    #include <chrono>
    #include <math.h>
    #include "Process.h"
    using namespace std;
    
    void readFile(string fileName, vector<Process>&processes);
    void sortProcesses(vector<Process>&processes);
    void addWaitTime(deque<Process>&schedule, int count);
    void addTurnaroundTime(deque<Process>&schedule, int count);
    void addWaitTime(priority_queue<Process>&schedule, int count);
    void addTurnaroundTime(priority_queue<Process>&schedule, int count);
    void addTurnaroundTime(priority_queue<Process>&schedule, int count);
    void removeProcess(priority_queue<Process>&schedule, Process p);
    void FCFS(vector<Process>processes);
    void SRTF(vector<Process>processes);
    void RR(int quantum, vector<Process>processes);
    
    int main(int argc, const char * argv[]){
        string randomize;
        int quantum = 1;
        stringstream ss;
        
        vector<Process>processes;
        string algorithm = argv[2];
        readFile(argv[1], processes);
        
        sortProcesses(processes);
        
        if(algorithm == "rr" || algorithm == "RR"){
            ss << argv[3];
            ss >> quantum;
        }
        
        if(algorithm == "FCFS" || algorithm == "fcfs"){
            cout << "-First Come First Served Algorithm-" << endl;
            FCFS(processes);
        }else if(algorithm == "SRTF" || algorithm == "srtf"){
            cout << "-Shortest Remaining Time First-" << endl;
            SRTF(processes);
        }else if(algorithm == "RR" || algorithm == "rr"){
            cout << "-Round Robin-" << endl;
            RR(quantum, processes);
        }else{
            cout << "Invalid algorithm name." << endl;
        }
        return 0;
    }
    
    void readFile(string fileName, vector<Process>&processes){
        int PID, arrivalTime, CPUTime;
        string tempLine, word;
        ifstream infile;
        infile.open(fileName);
        if(infile){
            getline(infile, tempLine);
            while(!infile.eof()){
                Process *process = new Process();
                infile >> PID;
                process->setPID(PID);
                infile >> arrivalTime;
                process->setArrivalTime(arrivalTime);
                infile >> CPUTime;
                process->setCPUTime(CPUTime);
                processes.push_back(*process);
                delete process;
            }
        }else{
            cout << "Could not open file with file name \"" << fileName << "\"." << endl;
        }
        infile.close();
        processes.pop_back(); 
    }
    
    void sortProcesses(vector<Process>&processes){
        
        Process temp;
        for(int i = 0 ; i < ( processes.size() - 1 ); ++i){
            for(int j = 0 ; j < processes.size() - i - 1; ++j){
                if(processes[j].getArrivalTime() > processes[j + 1].getArrivalTime()){ //smallest to largest
                    temp = processes[j];
                    processes[j] = processes[j + 1];
                    processes[j + 1] = temp;
                }
            }
        }
    }
    
    void addWaitTime(deque<Process>&schedule, int count){
        for(int i = 0; i < schedule.size(); ++i){
            schedule[i].addWaitTime(count);
        }
    }
    
    void addTurnaroundTime(deque<Process>&schedule, int count){
        for(int i = 0; i < schedule.size(); ++i){
            schedule[i].addTurnaroundTime(count);
        }
    }
    
    void addWaitTime(priority_queue<Process>&schedule, int count){
        Process temp;
        for(int i = 0; i < schedule.size(); ++i){
            temp = schedule.top();
            temp.addWaitTime(count);
            schedule.pop();
            schedule.push(temp);
        }
    }
    
    void addTurnaroundTime(priority_queue<Process>&schedule, int count){
        Process temp;
        for(int i = 0; i < schedule.size(); ++i){
            temp = schedule.top();
            temp.addTurnaroundTime(count);
            schedule.pop();
            schedule.push(temp);
        }
    }
    
    void removeProcess(priority_queue<Process>&schedule, Process p){
        vector<Process>copy;
        
        for(int i = 0; i < schedule.size(); ++i){
            copy.push_back(schedule.top());
            schedule.pop();
        }
        
        for(int i = 0; i < copy.size(); ++i){
            if(copy[i].getPID() == p.getPID()){
                copy.erase(copy.begin() + i);
            }
        }
        
        for(int i = 0; i < copy.size(); ++i){
            schedule.push(copy[i]);
        }
    }
    
    void FCFS(vector<Process>processes){
        int i = 0, time = 0, c = 0;
        double averageCPU = 0, avgWait = 0, avgTurn = 0, totalSwitch = 0;
        string hold;
        cout << "Number of processes: " << processes.size() << endl;
        cout << "Hit enter to begin FCFS" << endl;
        getline(cin, hold);
        cout << "-- Grantt Chart -- (PID->CPU Burst Time)" << endl << "|";
        
        for(int i = 0; i < processes.size(); ++i){
            averageCPU += processes[i].getCPUTime();
        }
        while(i < processes.size()){
            processes[i].addWaitTime(abs(time - processes[i].getArrivalTime()));
            while(true){
                if(processes[i].getCPUTime() > c){
                    ++time;
                    ++c;
                }else{
                    processes[i].addTurnaroundTime(processes[i].getWaitTime() + processes[i].getCPUTime());
                    processes[i].incNumOfContextSwitching();
                    processes[i].setTimeOfCompletion(time);
                    c = 0;
                    break;
                }
            }
            ++i;
        }
        
        for(int i = 0; i < processes.size(); ++i){
            cout << " " << processes[i].getPID() << "->" << processes[i].getCPUTime() << " |";
        }
        
        cout << endl << endl << "---- Process List ----" << endl;
        
        for(int i = 0; i < processes.size(); ++i){
            cout << i + 1 << ":" << endl;
            if(processes[i].getPID() / 10 < 1){
                cout << "----  PID: " << processes[i].getPID() << "   ----" << endl;
            }else if(processes[i].getPID() >= 100){
                cout << "----  PID: " << processes[i].getPID() << " ----" << endl;
            }else{
                cout << "----  PID: " << processes[i].getPID() << "  ----" << endl;
            }
            cout << "Time of completion: " << processes[i].getTimeOfCompletion() << "ms" << endl;
            cout << "Time spent waiting: " << processes[i].getWaitTime() << "ms" << endl;
            cout << "  Turn Around time: " << processes[i].getTurnaroundTime() << "ms" << endl;
            cout << "  Context Switches: " << processes[i].getNumOfContextSwitching() << endl << endl;
            
            avgWait += processes[i].getWaitTime();
            avgTurn += processes[i].getTurnaroundTime();
            totalSwitch += processes[i].getNumOfContextSwitching();
        }
        
        cout << "___________STATS___________" << endl;
        cout << "  Average CPU burst time: " << ceil(averageCPU / processes.size()) << "ms" << endl;
        cout << "       Average wait time: " << ceil(avgWait / processes.size()) << "ms" << endl;
        cout << "Average turn around time: " << ceil(avgTurn / processes.size()) << "ms" << endl;
        cout << "   Average response time: " << ceil(avgWait / processes.size()) << "ms" << endl;
        cout << "  Total context switches: " << totalSwitch << endl;
    }
    
    void SRTF(vector<Process>processes){
        int time = 0, runTime = 0;
        double avgWait = 0, avgTurn = 0, averageCPU = 0, totalSwitch = 0;
        string hold;
        bool firstRun = true, change = false;
        priority_queue<Process>schedule;
        Process run;
        vector<Process>copy;
        vector<Process>finished;
        cout << "Number of processes: " << processes.size() << endl;
        cout << "Press [ENTER] to begin SRTF" << endl << endl;
        getline(cin, hold);
        
        cout << "-- Gnatt Chart -- (PID->CPU Burst Time)" << endl << "|";
        
        for(int i = 0; i < processes.size(); ++i){
            Process *p = new Process();
            copy.push_back(*p);
            delete p;
        }
        
        for(int i = 0; i < processes.size(); ++i){
            copy[i] = processes[i];
        }
        
        while(true){
            if(processes[0].getArrivalTime() > time){
                ++time;
            }else{
                break;
            }
        }
        
        while(finished.size() < processes.size()){
            while(true){
                if(copy[0].getArrivalTime() <= time && !copy.empty()){
                    schedule.push(copy[0]);
                    copy.erase(copy.begin());
                }else{
                    break;
                }
            }
            if(firstRun){
                run = schedule.top();
                schedule.pop();
                firstRun = false;
            }
            if(!schedule.empty() && schedule.top().getCPUTime() < run.getCPUTime()){
                run.incNumOfContextSwitching();
                cout << " " << run.getPID() << "->" << runTime << " |";
                schedule.push(run);
                run = schedule.top();
                change = true;
                schedule.pop();
            }else if(run.getCPUTime() <= 0){
                run.incNumOfContextSwitching();
                run.setTimeOfCompletion(time);
                cout << " " << run.getPID() << "->" << runTime << " |";
                finished.push_back(run);
                run = schedule.top();
                change = true;
                schedule.pop();
            }else{
                run.setCPUTime(run.getCPUTime() - 1);
                run.addTurnaroundTime(1);
                addTurnaroundTime(schedule, 1);
                addWaitTime(schedule, 1);
            }
            
            ++runTime;
            ++time;
            
            if(change){
                change = false;
                runTime = 0;
            }
        }
        
        cout << endl << endl << "---- Process List ----" << endl;
        
        for(int i = 0; i < finished.size(); ++i){
            cout << i + 1 << ":" << endl;
            if(finished[i].getPID() / 10 < 1){
                cout << "----  PID: " << finished[i].getPID() << "   ----" << endl;
            }else if(finished[i].getPID() >= 100){
                cout << "----  PID: " << finished[i].getPID() << " ----" << endl;
            }else{
                cout << "----  PID: " << finished[i].getPID() << "  ----" << endl;
            }
            
            cout << "Time of completion: " << finished[i].getTimeOfCompletion() << "ms" << endl;
            cout << "Time spent waiting: " << finished[i].getWaitTime() << "ms" << endl;
            cout << "  Turn Around time: " << finished[i].getTurnaroundTime() << "ms" << endl;
            cout << "  Context Switches: " << finished[i].getNumOfContextSwitching() << endl << endl;
            
            averageCPU += processes[i].getCPUTime();
            avgWait += finished[i].getWaitTime();
            avgTurn += finished[i].getTurnaroundTime();
            totalSwitch += finished[i].getNumOfContextSwitching();
        }
        cout << "___________STATS___________" << endl;
        cout << "  Average CPU burst time: " << ceil(averageCPU / processes.size()) << "ms" << endl;
        cout << "       Average wait time: " << ceil(avgWait / finished.size()) << "ms" << endl;
        cout << "Average turn around time: " << ceil(avgTurn / finished.size()) << "ms" << endl;
        cout << "   Average response time: " << ceil(avgWait / finished.size()) << "ms" << endl;
        cout << "  Total context switches: " << totalSwitch << endl;
        exit(0);
    }
    
    void RR(int quantum, vector<Process>processes){
        int time = 0, counter = 0, runTime = 0;
        double avgWait = 0, avgTurn = 0, averageCPU = 0, totalSwitch = 0;
        string hold;
        bool next = false, change = false;
        Process *run = nullptr;
        deque<Process>schedule;
        vector<Process>copy;
        vector<Process>finished;
        cout << "Number of processes: " << processes.size() << endl;
        cout << "Press [ENTER] to begin RR quantum " << quantum << endl;
        getline(cin, hold);
        
        cout << "-- Gnatt Chart -- (PID->CPU Burst Time)" << endl << "|";
        
        for(int i = 0; i < processes.size(); ++i){
            Process *p = new Process();
            copy.push_back(*p);
            delete p;
        }
        
        for(int i = 0; i < processes.size(); ++i){
            copy[i] = processes[i];
        }
        
        while(true){
            if(copy[0].getArrivalTime() > time){
                ++time;
            }else{
                break;
            }
        }
        
        while(!copy.empty() || !schedule.empty() || counter != 0){
            while(true){
                if(copy[0].getArrivalTime() <= time && !copy.empty()){
                    schedule.push_back(copy[0]);
                    copy.erase(copy.begin());
                }else{
                    break;
                }
            }
            
            if(counter <= 0){
                run = &schedule.front();
                schedule.pop_front();
                run->incNumOfContextSwitching();
            }else if(counter == quantum){
                if(run->getCPUTime() <= 0){
                    run->setTimeOfCompletion(time);
                    cout << " " << run->getPID() << "->" << runTime << " |";
                    change = true;
                    finished.push_back(*run);
                    counter = -1;
                    next = true;
                    --time;
                }else{
                    cout << " " << run->getPID() << "->" << runTime << " |";
                    change = true;
                    schedule.push_back(*run);
                    counter = -1;
                    next = true;
                    --time;
                }
            }
            
            if(!next){
                if(run->getCPUTime() <= 0){
                    cout << " " << run->getPID() << "->" << runTime << " |";
                    change = true;
                    run->setTimeOfCompletion(time);
                    finished.push_back(*run);
                    counter = -1;
                    --time;
                }else{
                    addTurnaroundTime(schedule, 1);
                    addWaitTime(schedule, 1);
                    run->addTurnaroundTime(1);
                    run->setCPUTime(run->getCPUTime() - 1);
                }
            }
            
            if(next){
                next = false;
            }
            
            ++runTime;
            ++counter;
            ++time;
            
            if(change){
                change = false;
                runTime = 0;
            }
        }
        
        cout << endl << endl << "---- Process List ----" << endl;
        
        for(int i = 0; i < finished.size(); ++i){
            cout << i + 1 << ":" << endl;
            if(finished[i].getPID() / 10 < 1){
                cout << "----  PID: " << finished[i].getPID() << "   ----" << endl;
            }else if(finished[i].getPID() >= 100){
                cout << "----  PID: " << finished[i].getPID() << " ----" << endl;
            }else{
                cout << "----  PID: " << finished[i].getPID() << "  ----" << endl;
            }
            cout << "Time of completion: " << finished[i].getTimeOfCompletion() << "ms" << endl;
            cout << "Time spent waiting: " << finished[i].getWaitTime() << "ms" << endl;
            cout << "  Turn Around time: " << finished[i].getTurnaroundTime() << "ms" << endl;
            cout << "  Context Switches: " << finished[i].getNumOfContextSwitching() << endl << endl;
            
            averageCPU += processes[i].getCPUTime();
            avgWait += finished[i].getWaitTime();
            avgTurn += finished[i].getTurnaroundTime();
            totalSwitch += finished[i].getNumOfContextSwitching();
        }
        
        cout << "___________STATS___________" << endl;
        cout << "  Average CPU burst time: " << ceil(averageCPU / processes.size()) << "ms" << endl;
        cout << "       Average wait time: " << ceil(avgWait / finished.size()) << "ms" << endl;
        cout << "Average turn around time: " << ceil(avgTurn / finished.size()) << "ms" << endl;
        cout << "   Average response time: " << ceil(avgWait / finished.size()) << "ms" << endl;
        cout << "  Total context switches: " << totalSwitch << endl;
    
    cin.get()
    }
    
    
    
    

    this is what I'm getting

    [Running...]
    [Done.]
    
    

    The program should be able to calculate the following information using the collected data: 1. Average CPU burst time 2. Average waiting time 3. Average turn around time 4. Average response time 5. Total number of Context Switching performed But I'm not getting that

    jeudi 10 novembre 2022

    C++11 with Xcode

    ALL,

    I am trying to compile following code (from header file):

    class Foo
    {
    public:
        auto &GetString() const { return m_str1; }
    private:
        std::wstring m_str1;
    };
    

    On the Mac with Xcode it gives following:

    'auto' return without trailing return type; deduced return types are C++14 extension.
    

    As far as I know auto is C++11 feature and shouldn't need anything from C++14.

    What am I missing?

    TIA!!

    When does c++ right value destruct in this scenario?

    Here is the code:

    class SomeType {
    public:
    SomeType() {}
    ~SomeType() {}
    
    std::string xxx;
    }
    bool funtion_ab() {
        SomeType(); // This is a right val; 
        // The right val destructs here when I test the code. I want to make sure that it would always destructs here.
        int a = 0, b = 10;
        ....// other code
        return true; 
    } 
    

    Please tell me if you know the truth. Thank you!