mardi 31 mai 2022

To find the string that are not matching using regex pattern

I want to return a bool value for the unmatched string

QRegExp rx("(?!test)");
bool unmatched = rx.exactMatch("txt"); false
if(rx.isValid()){
  return unmatched;
}

It returns false every time no matter what string is passed. How can I match the same values?

C++ get and set item in map as value inside unordered_map?

std::unordered_map<string, tuple<int, vector<int>>> combos;

I want to retrieve items inside tuple and also to increase or set their value. e.g.

if(v_intersection.size()==5){
                string stringval = join(v_intersection, ",");
                if (combos.find(stringval) == combos.end()) // if key is NOT present already
                {
                    combos[stringval]get<0>(combos[stringval]) = 1; // initialize the key with value 1
                }
                else
                {
                    combos[stringval]++; // key is already present, increment the value by 1
                }
            }

I want to set int (the first parameter of tuple) to 1 and also increase it by 1 when needed.

It is not inside a for loop but in a if conditional clause.

How to do that?

I tried combos[stringval]get<0>(combos[stringval]) = 1; but it is not working.

What if I want to add items inside the vector from that map? How to do it?

Also, if you have any idea on how to do this using something else other than nested maps with tuples, please give to me your advise.

Thank you in advance!

It is not duplicate, please check it out. There are some topics but asking for something else not nested maps with tuples as values.

Emplacing an instance with constant fields fails to compile (C++)

I have an example_class with two constant fields. When I try to emplace an object of that class into a std::vector, I get various errors such as "error: object of type 'example_class' cannot be assigned because its copy assignment operator is implicitly deleted". Does anyone know what is going on here? If I remove the const in example class, the code compiles without problems.

#include <vector>
#include <iostream>

using namespace std;

class example_class {
    public:
    example_class(int v1, int v2) : val1(v1), val2(v2) {}

    private:
    const int val1, val2;
};

int main() {

    vector<example_class> *vec = new vector<example_class>();
    vec->emplace(vec->begin() + 1, 13131, 12313);

    return 0;
}

lundi 30 mai 2022

Threads are pushing all of work onto one thread

Hey so I am having some issue again with my code, whenever I attempt to run it the code does run smoothly as it should, though for whatever reason it appears as if all the work is being pushed onto the one thread when in reality it shouild be evenly split between each thread. What I want it to do instead is to give each thread a slice of the mandelbrot to generate, rather than pushing it all onto the one thread. The main issue I feel is within the main function and not the others as they are all working as intended, all help is much appreciated.

#include <cstdint>
#include <cstdlib>
#include <complex>
#include <fstream>
#include <iostream>
#include <vector>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <atomic>

// Import things we need from the standard library
using std::chrono::duration_cast;
using std::chrono::milliseconds;
using std::complex;
using std::cout;
using std::endl;
using std::ofstream;

// Define the alias "the_clock" for the clock type we're going to use.
typedef std::chrono::steady_clock the_clock;


// The size of the image to generate.
const int WIDTH = 1920;
const int HEIGHT = 1200;

// The number of times to iterate before we assume that a point isn't in the
// Mandelbrot set.
// (You may need to turn this up if you zoom further into the set.)
const int MAX_ITERATIONS = 500;

// The image data.
// Each pixel is represented as 0xRRGGBB.
uint32_t image[HEIGHT][WIDTH];

std::atomic<double> progress;
std::atomic_bool progressDone = false;
std::mutex locking;
std::condition_variable conditionMet;
std::atomic_int partsDone = 0;
int noOfThreads;

// Write the image to a TGA file with the given name.
// Format specification: http://www.gamers.org/dEngine/quake3/TGA.txt

void progress_bar() {

    while (!progressDone) {

        cout << "Current Progress is at: " << progress.load() << "%\n";
        std::this_thread::sleep_for(std::chrono::milliseconds(100));

    }

    cout << "Mandelbrot is finished! Take a look.";

}

void write_tga(const char *filename)
{
    ofstream outfile(filename, ofstream::binary);

    uint8_t header[18] = {
        0, // no image ID
        0, // no colour map
        2, // uncompressed 24-bit image
        0, 0, 0, 0, 0, // empty colour map specification
        0, 0, // X origin
        0, 0, // Y origin
        WIDTH & 0xFF, (WIDTH >> 8) & 0xFF, // width
        HEIGHT & 0xFF, (HEIGHT >> 8) & 0xFF, // height
        24, // bits per pixel
        0, // image descriptor
    };
    outfile.write((const char *)header, 18);

    for (int y = 0; y < HEIGHT; ++y)
    {
        for (int x = 0; x < WIDTH; ++x)
        {
            uint8_t pixel[3] = {
                image[y][x] & 0xFF, // blue channel
                (image[y][x] >> 8) & 0xFF, // green channel
                (image[y][x] >> 16) & 0xFF, // red channel
            };
            outfile.write((const char *)pixel, 3);
        }
    }

    outfile.close();
    if (!outfile)
    {
        // An error has occurred at some point since we opened the file.
        cout << "Error writing to " << filename << endl;
        exit(1);
    }
}


// Render the Mandelbrot set into the image array.
// The parameters specify the region on the complex plane to plot.
void compute_mandelbrot(double left, double right, double top, double bottom, double start, double finish)
{
    for (int y = start; y < finish; ++y)
    {
        for (int x = 0; x < WIDTH; ++x)
        {
            // Work out the point in the complex plane that
            // corresponds to this pixel in the output image.
            complex<double> c(left + (x * (right - left) / WIDTH),
                top + (y * (bottom - top) / HEIGHT));

            // Start off z at (0, 0).
            complex<double> z(0.0, 0.0);

            // Iterate z = z^2 + c until z moves more than 2 units
            // away from (0, 0), or we've iterated too many times.
            int iterations = 0;
            while (abs(z) < 2.0 && iterations < MAX_ITERATIONS)
            {
                z = (z * z) + c;

                ++iterations;
            }

            if (iterations == MAX_ITERATIONS)
            {
                // z didn't escape from the circle.
                // This point is in the Mandelbrot set.
                image[y][x] = 0x000000; // black
            }
            else if (iterations == 0) {

                image[y][x] = 0xFFFFFF;

            }
            else
            {
                // z escaped within less than MAX_ITERATIONS
                // iterations. This point isn't in the set.
                image[y][x] = 0xFFFFFF; // white
                image[y][x] = 16711680 | iterations << 8 | iterations;
            }

            progress = progress + double((1.0 / (WIDTH*HEIGHT)) * 100.0);
        }
    }
    partsDone += 1;
}


int main(int argc, char *argv[])
{
    cout << "Please wait..." << endl;

    cout << "How many threads do you want to use?: ";
    std::cin >> noOfThreads;

    // Start timing
    std::vector<std::thread*> threads;
    the_clock::time_point start = the_clock::now();

    std::thread progressive(progress_bar);

    for (int slice = 0; slice < noOfThreads; slice++) {

        // This shows the whole set.
        threads.push_back(new std::thread(compute_mandelbrot, -2.0, 1.0, 1.125, -1.125, HEIGHT * (slice / noOfThreads), HEIGHT * ((slice + 1) / noOfThreads)));

        // This zooms in on an interesting bit of detail.
        //compute_mandelbrot(-0.751085, -0.734975, 0.118378, 0.134488, 0, HEIGHT/16);

    }

    // Stop timing

    for (std::thread* t : threads) {

        t->join();
        cout << "My ID is: " << t->get_id() << endl;
        delete t;

    }

    if (partsDone == noOfThreads) {

        progressDone = true;

    }

    conditionMet.notify_one();

    progressive.join();

    the_clock::time_point end = the_clock::now();

    // Compute the difference between the two times in milliseconds
    auto time_taken = duration_cast<milliseconds>(end - start).count();
    cout << "Computing the Mandelbrot set took " << time_taken << " ms." << endl;

    write_tga("output.tga");

    std::this_thread::sleep_for(milliseconds(3000));

    return 0;
}

dimanche 29 mai 2022

Copy constructor's member initializer not requiring a member

This is my class:
(I know currently it violates the rule of three because it doesn't yet have an explicitly defined copy assignment operator.)

#include <iostream>

template <class T>
class die
{
private:
    int sideCount;
    T* valueOfSides;
public:
    die() : sideCount(0), valueOfSides(nullptr) {}
    die(int sideCount, T* valueOfSides) : sideCount(sideCount), valueOfSides(nullptr)
    {
        this->valueOfSides = new T[sideCount];

        for (int i = 0; i < sideCount; ++i)
            this->valueOfSides[i] = valueOfSides[i];
    }

    die(const die& that) : sideCount(that.sideCount), valueOfSides(nullptr) //<- WARNING
    {
        valueOfSides = new T[sideCount];

        for (int i = 0; i < sideCount; ++i)
            valueOfSides[i] = that.valueOfSides[i];
    }

    void printValueOfSides() //Unrelated but I will leave this method here if you decide to use it
    {
        for (int i = 0; i < sideCount; ++i)
            std::cout << "valuesOfSides[" << i << "] = " << valueOfSides[i] << std::endl;
    }

    ~die() { delete[] valueOfSides; }
};

The warning at the copy constructor's initializer list is:
die(const die& that) : sideCount(that.sideCount), valueOfSides(nullptr)<-here The value (I'm guessing nullptr) is never used. When I remove valueOfSides(nullptr) from the copy constructor's initializer list the warning goes away. I know code works without it but for the sake of completion when a die object is created using the copy constructor

int main()
{
    die<int> d1(4, array);
    die<int> d2(d1);

    return 0;
}

I want it first to be initialized with the nullptr then assigned to the values in the constructor's parameter. As its being done with the parameterized constructor.
So my questions are:

  • Why do I get this warning In the copy constructor but not In the parameterized constructor?
  • I include valueOfSides pointer in the member initializer of all the constructors for the sake of completion and because I believe it is good practice to initialize the members even though they will get assigned in the body of the constructor. Is this a good practice or a habit? Or should I just give up Initializing valuesOfSides when it is not necessary to initialize? In this case, only include it in the member initializer of the default constructor and not in the parameterized and copy constructor?
  • For my second question, Am I accurate with my depictions of initialization and assignment of members?

c++ shared pointer as key to map causes crash

So I'm working on a project for University in CPP, the idea is to utilize STL and smart pointers as much as possible(in an efficient matter of course).

I have created a map which contains a shared pointer to object of type Movie, and a vector of doubles. I have added a Comparison Class so the map compares the objects themselves and not pointers. When I initialize the map all is good, values are stored properly and I'm able to print them out. but when trying to access from a different function I get a EXC_BAD_ACCESS. while debugging I can still see the information exists so from my understanding its not that the pointers all went out of scope and the memory is freed.

Im adding the add and get functions,

typedef std::shared_ptr<Movie> sp_movie;

RecommenderSystem::get_movie (const std::string &name, int year) const
{
  const auto movie (std::make_shared<Movie> (name, year));
  const auto it=_database.find (movie);
  return it->first;
}


sp_movie RecommenderSystem::add_movie (const std::string &name, int year,
                              FeaturesVec &features)
{
  auto movie = std::make_shared<Movie> (name, year);
  _database.insert (std::make_pair (movie, features));
  return movie;
}

The exception gets thrown from _database.find call. This is the constructor and comparator:

struct DatabaseComp {
    bool operator() (const sp_movie &m1, const sp_movie &m2) const
    { return *m1 < *m2; }
};
/**
 * Key : sp_movie, Value : FeaturesVec(Just a fancy name for double vector)
 */
typedef std::map<sp_movie, FeaturesVec, DatabaseComp> MovieDatabase;

class RecommenderSystem {
 private:
  MovieDatabase _database = MovieDatabase (DatabaseComp ());
 public:
  /**
   * Constructor
   */
  explicit RecommenderSystem () = default;

Any ideas about what could be causing this?

EDITS The comparison operator for the Movie class itself :

bool operator< (const Movie &lhs) const
  {
    return this->_movie_year < lhs._movie_year
           || (this->_movie_year == lhs._movie_year && this->_movie_name <= lhs._movie_name);
  }

Crashing example , the program crashes on get_name method

int main ()
{
  RecommenderSystem rs;
  rs.add_movie ("Matrix1", 1999, {5, 5, 5, 5});
  rs.add_movie ("Matrix2", 2000, {4, 5, 4, 5});
  auto m = rs.get_movie ("Matrix1", 1999);
  std::cout << m->get_name () << " : " << m->get_year () << std::endl;
  rank_map rm (0, &sp_movie_hash, &sp_movie_equal);
  rm.insert (std::make_pair (m, 5.0));
  RSUser rs_user ("John", rm, std::make_shared<RecommenderSystem> (rs));
}

samedi 28 mai 2022

re-throwing an exception from inside a terminatrion handler

Is the following code according to the standard ?

#include <iostream>
#include <exception>

using namespace std;

int main()
{
    auto terminationHandler = []()
    {
        try
        {
            rethrow_exception( current_exception() );
        }
        catch( exception const &exc )
        {
            cout << exc.what() << endl;
        }
        catch( ... )
        {
        }
    };
    set_terminate( terminationHandler );
    try
    {
        throw bad_alloc();
    }
    catch( ... )
    {
        terminate();
    }
}

This would be a nice aid for fatal situations that you still have some error-message.

I've got a function called exc_terminate() that's called like this:

exc_terminate( [&]() { ... do anything in local context ... } );

The lambda is executed within a try-catch-block and if an exception occurs the code terminates. I use this f.e. when a thread can't communicate with another thread because the synchronization-functions signalled a system_error.

Can someone tell me what this program is doing line by line? [closed]

This program is trying to determine the fitness of a puzzle by determining the number of conflicts in a puzzle (how many duplicate entries there are in each row, column, and 3- by-3 block). A solved Sudoku should have a "howFit" value of zero.

#include "Sudoku.h"
#include "SudokuFitness.h"
int howFit(shared_ptr<Puzzle> &_p) {
// cast to Sudoku Puzzle
shared_ptr<Sudoku> p = dynamic_pointer_cast<Sudoku>(_p);
int tot = 0;

// update tot helper
// tot is the total conflict number
auto update_tot = [&tot](int cnt[]) {
    for (int i=0; i<10; ++i) {
        if (cnt[i] > 1) tot += cnt[i];
    }
};

// check row
for (int i=0; i<9; ++i) {
    int cnt[10] = {0};
    for (int j=0; j<9; ++j) {
        ++cnt[p->value(i, j)];
    }
    update_tot(cnt);
}

// check column
for (int i=0; i<9; ++i) {
    int cnt[10] = {0};
    for (int j=0; j<9; ++j) {
        ++cnt[p->value(j, i)];
    }
    update_tot(cnt);
}

// check block
for (int k=0; k<9; ++k) {
    int x = (k / 3) * 3;
    int y = (k % 3) * 3;
    int cnt[10] = {0};
    for (int i=x; i<x+3; ++i) {
        for (int j=y; j<y+3; ++j) {
            ++cnt[p->value(i, j)];
        }
    }
    update_tot(cnt);
}

return tot;
}

Can someone explain what this program is doing line by line? if possible. I'd appreciate it. Thank you so much!

I'm especially confused about this line:
auto update_tot = [&tot](int cnt[]) {

the code still print 0 and it can't calculate the required task

#include <iostream>
using namespace std;

int main()
{
    int n, G;
    float num[500], sum=0.0, average,Grades;

    cout << "Enter the numbers of data: ";
    cin >> n;

    while (n > 500 || n <=  0)
    {
        cout << "Error! number should in range of (1 to 500)." << endl;
        cout << "Enter the number again: ";
        cin >> n;
    }

    for(G = 0; G < n; ++G)
    {
        cout << G + 1 << ". Enter number: ";
        cin >> num[G];
        sum += num[G];
    }


    average = sum / n;
    Grades = num[G] >= average;
    
    cout<<endl;
    
    cout << "Grades Average = " << average << endl;
    cout << "Grades above or equal the Average : " <<Grades<< endl;
    cout << "Number of grades above the Average = "<<(int) Grades;
    
    return 0;
}

i coded this code but the Number of grades above the Average and Grades above or equal the Average don't work it just print 0

i tried to print the Grades >= the avg but it print 0

also num of Grades also print 0

where is the error ?

Must I either mark the destructor of the base class as virtual function or mark it as protected function?

As per this article, which says that[emphasis mine]:

Making base class destructor virtual guarantees that the object of derived class is destructed properly, i.e., both base class and derived class destructors are called.

As a guideline, any time you have a virtual function in a class, you should immediately add a virtual destructor (even if it does nothing). This way, you ensure against any surprises later.

I think even if your base class has no virtual function,you should either add a virtual destructor or mark the destructor of the base class as protected.Otherwise, you may face memory leak when trying to delete a pointer pointed to a derived instance. Am I right?

For example,here is the demo code snippet:

#include<iostream>

class Base {
public:
 Base(){};
 ~Base(){std::cout << "~Base()" << std::endl;}; 
};

class Derived : public Base {
private:
  double val;
public:
 Derived(const double& _val){};
 ~Derived(){std::cout << "~Derived()" << std::endl;}; //It would not be called
};

void do_something() {
 Base* p = new Derived{1};
 delete p;  
}

int main()
{
    do_something();
}

Here is the output of the said code snippet:

~Base()

Could anybody shed some light on this matter?

vendredi 27 mai 2022

Conversion between Iterator and ConstIterator

I have a linked list that contains a pointer to the first and last node and size which indicates how many nodes are there in the list. I've implemented both Iterator and ConstIterator, ATM ConstIterator only works for const lists, and Iterator for lists, and I want it that Iterator to work for both lists and const lists, this is what I've done so far:

Node class:

template<class T>
class Node {
    public:
        Node(const T& t);
        ~Node()=default; // Destructor set to default
        Node(const Node&) = default; // Copy Constructor set to default
        Node& operator=(const Node&) = default; // Assignment operator set to default
        T& getData();
        const T& getData() const;
        Node* getNext() const;
        void setNext(Node<T>* newNext);
    private:
        T m_data;
        Node* m_nextNode;
};

template<class T>
Node<T>::Node(const T& t) {
    this->m_data=t;
    this->m_nextNode=nullptr;
}

template<class T>
Node<T>* Node<T>::getNext() const {
    return this->m_nextNode;
}

template<class T>
T& Node<T>::getData() {
    return this->m_data;
}

template<class T>
const T& Node<T>::getData() const {
    return this->m_data;
}

template<class T>
void Node<T>::setNext(Node<T>* newNext) {
    this->m_nextNode=newNext;
}

Queue class:

template<class T>
class Queue {
    public:
        static const int SIZE_EMPTY=0;
        Queue();
        ~Queue(); // Destructor
        Queue(const Queue&); // Copy Constructor
        Queue& operator=(const Queue&); // Assignment operator
        void pushBack(const T& t);
        T& front();
        const T& front() const;
        void popFront();
        int size() const;
        class Iterator;
        Iterator begin();
        Iterator end();
        class ConstIterator;
        ConstIterator begin() const;
        ConstIterator end() const;
        class EmptyQueue {};
    private:
        Node<T>* m_head;
        Node<T>* m_tail;
        int m_size;
};

template<class T>
Queue<T>::Queue() {
    this->m_head=nullptr;
    this->m_tail=nullptr;
    this->m_size=Queue<T>::SIZE_EMPTY;
}

template<class T>
Queue<T>::~Queue() {
    while(this->m_head) {
        this->popFront();
    }
}

template<class T>
Queue<T>::Queue(const Queue<T>& queue) {
    this->m_head=nullptr;
    this->m_tail=nullptr;
    this->m_size=Queue<T>::SIZE_EMPTY;
    for(typename Queue<T>::ConstIterator i = queue.begin();i != queue.end();++i) {
        try {
            this->pushBack(*i);
        } catch(typename Queue<T>::ConstIterator::InvalidOperation& e) {
            throw e;
        }
    }
}

template<class T>
void Queue<T>::pushBack(const T& t) {
    try {
        Node<T>* newNode=new Node<T>(t);
        if(this->m_size==Queue<T>::SIZE_EMPTY) {
            this->m_head=newNode;
            this->m_tail=newNode;
        } else {
            this->m_tail->setNext(newNode);
            this->m_tail=newNode;
        }
        this->m_size+=1;
    } catch(std::bad_alloc& e) {
        throw e;
    }
}

Queue<T>::Iterator class:

template<class T>
class Queue<T>::Iterator {
    public:
        T& operator*();
        Iterator& operator++();
        Iterator operator++(int);
        bool operator==(const Iterator& iterator) const;
        bool operator!=(const Iterator& iterator) const;
        Iterator(const Iterator&)=default;
        Iterator& operator=(const Iterator&)=default;
        class InvalidOperation {};
    private:
        Node<T>* node;
        Iterator(Node<T>* node);
        friend class Queue<T>;
};

template<class T>
Queue<T>::Iterator::Iterator(Node<T>* node) {
    this->node=node;
}

template<class T>
T& Queue<T>::Iterator::operator*() {
    if(this->node==nullptr) {
        throw Queue<T>::Iterator::InvalidOperation();
    }
    return this->node->getData();
}

template<class T>
typename Queue<T>::Iterator& Queue<T>::Iterator::operator++() {
    if(this->node==nullptr) {
        throw Queue<T>::Iterator::InvalidOperation();
    }
    this->node=node->getNext();
    return *this;
}

template<class T>
typename Queue<T>::Iterator Queue<T>::Iterator::operator++(int) {
    if(this->node==nullptr) {
        throw Queue<T>::Iterator::InvalidOperation();
    }
    Iterator result = *this;
    ++*this;
    return result;
}

template<class T>
bool Queue<T>::Iterator::operator==(const Iterator& iterator) const {
    return this->node==iterator.node;
}

template<class T>
bool Queue<T>::Iterator::operator!=(const Iterator& iterator) const {
    return !(*this==iterator);
}

template<class T>
typename Queue<T>::Iterator Queue<T>::begin() {
    return this->m_head;
}

template<class T>
typename Queue<T>::Iterator Queue<T>::end() {
    return nullptr;
}

Queue<T>::ConstIterator class:

template<class T>
class Queue<T>::ConstIterator {
    public:
        const T& operator*();
        ConstIterator& operator++();
        ConstIterator operator++(int);
        bool operator==(const ConstIterator& constIterator) const;
        bool operator!=(const ConstIterator& constIterator) const;
        ConstIterator(const ConstIterator&)=default;
        ConstIterator& operator=(const ConstIterator&)=default;
        class InvalidOperation {};
    private:
        const Node<T>* node;
        ConstIterator(const Node<T>* node);
        friend class Queue<T>;
};

template<class T>
Queue<T>::ConstIterator::ConstIterator(const Node<T>* node) {
    this->node=node;
}

template<class T>
const T& Queue<T>::ConstIterator::operator*() {
    if(this->node==nullptr) {
        throw Queue<T>::ConstIterator::InvalidOperation();
    }
    return this->node->getData();
}

template<class T>
typename Queue<T>::ConstIterator& Queue<T>::ConstIterator::operator++() {
    if(this->node==nullptr) {
        throw Queue<T>::ConstIterator::InvalidOperation();
    }
    this->node=node->getNext();
    return *this;
}

template<class T>
typename Queue<T>::ConstIterator Queue<T>::ConstIterator::operator++(int) {
    if(this->node==nullptr) {
        throw Queue<T>::ConstIterator::InvalidOperation();
    }
    ConstIterator result = *this;
    ++*this;
    return result;
}

template<class T>
bool Queue<T>::ConstIterator::operator==(const ConstIterator& constIterator) const {
    return this->node==constIterator.node;
}

template<class T>
bool Queue<T>::ConstIterator::operator!=(const ConstIterator& constIterator) const {
    return !(*this==constIterator);
}

template<class T>
typename Queue<T>::ConstIterator Queue<T>::begin() const {
    return this->m_head;
}

template<class T>
typename Queue<T>::ConstIterator Queue<T>::end() const {
    return nullptr;
}

main for tests:

    Queue<int> queue1;
    for (int i = 1; i <= 10; i++) {
        queue1.pushBack(i);
    }
    const Queue<int> constQueue = queue1;
    for(Queue<int>::Iterator i = constQueue.begin(); i != constQueue.end(); ++i) {
        std::cout << *i << std::endl;
    }

Counter and ID attribute of class stored in vector

I have a dilemma regarding my revoming database function code. Whenever I remove the database in vector with unique, I cannot think of writing the code that could fill the gap with the removed number (like I removed database ID3 and I want that the IDs of further databases would increment to have a stable sequence, so the database with ID4 would become ID3). I also don't know how to decrement my static int counter. File:

**void Database::RemoveDB()
{
    int det;
    cout << "Enter the ID of the base that you want to remove:\n";
    std::cout << "The bases are:\n";
    printids();
    cin >> det;
    auto iter = std::find_if(std::begin(DbMain),  std::end(DbMain), [&](Natobase& nb)
    { return nb.get_ID() == det; });
    if (iter !=  DbMain.end())
    {
        DbMain.erase(iter);
    }
}**
std::istream &operator>>(std::istream &re, Natobase &product)
{
    std::cout << "Enter the name of the base: \n";
    re >> product.name;
    std::cout << "Enter the city where it is located: \n";
    re >> product.city;
    std::cout << "Enter the country where it is located: \n";
    re >> product.country;
    std::cout << "Enter the number of guns held: \n";
    re >> product.rifles;
    std::cout << "Enter the number of tanks stationing: \n";
    re >> product.tanks;
    std::cout << "Enter the number of planes stationing: \n";
    re >> product.planes;
    std::cout << "Enter the number of launchers stationing: \n";
    re >> product.launcher;
    product.get_counter();
    product.ID = product.counter;
    return re;
}
void Database::printids()
{
    for (auto it = std::begin(DbMain); it != std::end(DbMain); ++it)
    {
        std::cout << std::endl;
        printnames(std::cout, *it) << std::endl;
    }
}
std::ostream &printnames(std::ostream &pr, Natobase &pro)
{
    pr << "\nID:" << pro.ID << "\nName:" << pro.name;
    return pr;
}

Header file:

#ifndef OOPLABPROJECT_NATOBASE_H
#define OOPLABPROJECT_NATOBASE_H
#include <string>
#include <vector>
#include "Natobase.h"

class Natobase{
    friend std::ostream &tosave(std::ostream &, const Natobase &);
    friend std::istream &toim(std::istream &, Natobase &);
    friend std::ostream &printnames(std::ostream &, Natobase &);
    friend std::istream &operator>>(std::istream &, Natobase &);
    friend class Database;
public:
    Natobase() = default;
    Natobase(std::string n, std::string ci, std::string co, int ri, int tan, int pla, int lan); //read-only
    Natobase(std::string init); //initialisation

    const std::string &get_name() const { return this->name; }
    const std::string &get_city() const { return this->city; }
    const std::string &get_country() const { return this->country; }
    const int &get_rifle() const { return this->rifles; }
    const int &get_tanks() const { return this->tanks; }
    const int &get_planes() const { return this->planes; }
    const int &get_launch() const { return this->launcher; }
    const int &get_ID() const { return this->ID; }
private:

    std::string name;
    std::string city;
    std::string country;
    int rifles;
    int tanks;
    int planes;
    int launcher;
    static int counter;
    int ID;
    static int get_counter()
    {
        counter++;
        return counter;
    };
};
std::ostream &tosave(std::ostream &, const Natobase &); //save data into txt file
std::istream &toim(std::istream &, Natobase &);// to read the data from txt file
std::ostream &printnames(std::ostream &, Natobase &); //used for edit and remove function in Database class
std::ostream &operator<<(std::ostream &, const Natobase &); //input attributes
std::istream &operator>>(std::istream &, Natobase &); //output attributes
////////////////////////
class Database {
public:
    Database() = default;
    void print_data();
    void read_data();
    void saveDB();
    void openDB();
    void EditDB();
    void RemoveDB();
    void printids();
    void compare();
private:
    std::vector<Natobase> DbMain;
};


#endif //OOPLABPROJECT_NATOBASE_H

Here is a pyramid model could you make the c program [closed]

   A
 2 3 5
B C D E F
 7 11 13
   G
17 19 23 

this is pyramid model

jeudi 26 mai 2022

c++: invalid initialization of reference of type ‘int&’ from expression of type ‘const int’ [closed]

I have a linked list that contains a pointer to the first and last node and size which indicates how many nodes are there in the list.

I'm trying to build a function that receives two arguments. The first argument is a linked list, and the second is a void function that changes the data in all nodes.

but i get this error when i try to compile: invalid initialization of reference of type ‘int&’ from expression of type ‘const int’ from this line return this->m_node->getData(); in T& Queue<T>::Iterator::operator*()

Node class:

template<class T>
class Node {
    public:
        Node(const T& t);
        ~Node()=default; // Destructor
        Node(const Node&) = default; // Copy Constructor set to default
        Node& operator=(const Node&) = default; // Assignment operator set to default
        T& getData();
        const T& getData() const;
        Node* getNext() const;
        void setNext(Node<T>* newNext);
    private:
        T m_data;
        Node* m_nextNode;
};

template<class T>
Node<T>::Node(const T& t) {
    this->m_data=t;
    this->m_nextNode=nullptr;
}

template<class T>
T& Node<T>::getData() {
    return this->m_data;
}

template<class T>
const T& Node<T>::getData() const {
    return this->m_data;
}

Queue class:

template<class T>
class Queue {
    public:
        static const int SIZE_EMPTY=0;
        Queue();
        ~Queue(); // Destructor
        Queue(const Queue&) = default; // Copy Constructor set to default
        Queue& operator=(const Queue&) = default; // Assignment operator set to default
        void pushBack(const T& t);
        T& front();
        const T& front() const;
        void popFront();
        int size() const;
        class Iterator;
        Iterator begin() const;
        Iterator end() const;
        class EmptyQueue {};
    private:
        Node<T>* m_head;
        Node<T>* m_tail;
        int m_size;
};

template<class T>
Queue<T>::Queue() {
    this->m_head=nullptr;
    this->m_tail=nullptr;
    this->m_size=0;
}

template<class T>
void Queue<T>::pushBack(const T& t) {
    this->m_size+=1;
    Node<T>* newNode=new Node<T>(t);
    this->m_tail=newNode;
    if(this->m_size==1) {
        this->m_head=newNode;
    } else {
        Node<T> *tempNode=this->m_head;
        while(tempNode->getNext()) {
            tempNode=tempNode->getNext();
        }
        tempNode->setNext(newNode);
    }
}

template<class T>
void transform(Queue<T>& queue, void (*transformer)(T&)) {
    if(queue.size()==Queue<T>::SIZE_EMPTY) {
        return;
        //throw Queue<T>::EmptyQueue();
    }
    for(Queue<int>::Iterator i = queue.begin();i != queue.end();++i) {
        transformer(*i); 
    }
}

Queue<T>::Iterator class:

template<class T>
class Queue<T>::Iterator {
    public:
        T& operator*();
        Iterator& operator++();
        Iterator operator++(int);
        bool operator==(const Iterator& iterator) const;
        bool operator!=(const Iterator& iterator) const;
        Iterator(const Iterator&)=default;
        Iterator& operator=(const Iterator&)=default;
        class InvalidOperation {};
    private:
        const Node<T>* m_node;
        Iterator(const Node<T>* m_node);
        friend class Queue<T>;
};

template<class T>
Queue<T>::Iterator::Iterator(const Node<T>* m_node) {
    this->m_node=m_node;
}


template<class T>
T& Queue<T>::Iterator::operator*() {
    return this->m_node->getData();
}

Edit: main:

static void setFortyTwo(int& n)
{
    n = 42;
}

int main() {
    Queue<int> queue5;
    for (int i = 1; i <= 5; i++) {
        queue5.pushBack(i);
    }
    transform(queue5, setFortyTwo);
    return 0;
}

How is a vector

I am not efficient in C++ and I am looking to know what is the right way in modern C++ or efficient place to return a vector and use the result. Here is my program. How can I make this more efficient in terms of memory copying, etc?

#include <vector>

std::vector<int> get_space_pos(const std::string &s){
    std::vector<int> results;
    std::vector<char> v(s.begin(), s.end());
    for(int i=0; i< v.size(); i++)
    {
        if ( v[i] == ' ')
         {
             results.push_back(i);
         }
    }
    return results;
}

int main() {    
    const std::string s = "My name is great";
    const std::vector<int> res = get_space_pos(s); // Is this a bad practice?? do I need to do some move or something more efficient.
                                                   // are the results here going to copy as a reference to res or a deep copy?
    for( auto &elem : res)
    {
        std::cout<<elem<<std::endl;
    }

    return 0;
}

How to find all references of a class methods in C++

We have a C++ codebase which is using a Qt library. We are thinking to replace the Qt with stl implementations or some other open source shared library. We need all references of Qt class methods in the code which will help us in mapping the right replacement for each Qt Class. Is there any script or any IDE which provides this information.

Thanks

How do I generate random numbers between -1 and +1 in c++? [closed]

How do I use srand and rand to generate random number between -0.5 and +0.5?

srand( (signed)time( NULL ) );
double z =  (float) rand()/RAND_MAX;

What changes should I make in the above code?

Why can an array of char be a template parameter but a const char* can't

I'm trying to pass a literal string as a template parameter in a C++14 project. Google told me that I can do as below:

struct Test {
    static const char teststr[];

    template<const char* str>
    void p() {std::cout << str;}
};

const char Test::teststr[] = "Hello world!";

int main() {
    Test t;
    t.p<Test::teststr>();
}

It did work.

However, if I use const char*, instead of const char []. It won't work.

struct Test {
    static const char* teststr;

    template<const char* str>
    void p() {std::cout << str;}
};

const char* Test::teststr = "Hello world!";

int main() {
    Test t;
    t.p<Test::teststr>();
}

Now it doesn't work. The compiler told me that 'Test::teststr' is not a valid template argument because 'Test::teststr' is a variable, not the address of a variable.

Well, I don't know what it meant.

mercredi 25 mai 2022

iterator operator++ overload compiling error

I have a linked list that contains a pointer to the first and last node and size which indicates how many nodes are there in the list. I've implemented iterator for Queue that points to the address of the node, I've already succeeded implementing begin(),end() and ==,!=, and tested too, but I'm unable to implement ++() and ++(int) operators for the iterators, i want the ++ operator to change the address of the node to the next one in the linked list, i get the following error when i try to compile: no matching function for call to ‘Node<int>::getNext() const’ and how can i make the iterator operator overload to work without typing typename at the start of the declaration

Node class:

template<class T>
class Node {
    public:
        Node(const T& t);
        ~Node()=default; // Destructor
        Node(const Node&) = default; // Copy Constructor set to default
        Node& operator=(const Node&) = default; // Assignment operator set to default
        T& getData();
        const T& getData() const;
        Node* getNext();
        void setNext(Node<T>* newNext);
    private:
        T m_data;
        Node* m_nextNode;
};

template<class T>
Node<T>::Node(const T& t) {
    this->m_data=t;
    this->m_nextNode=nullptr;
}

template<class T>
Node<T>* Node<T>::getNext() {
    return this->m_nextNode;
}

Queue class:

template<class T>
class Queue {
    public:
        static const int DEFAULT_FIRST_INDEX=0;
        static const int SIZE_EMPTY=0;
        Queue();
        ~Queue(); // Destructor
        Queue(const Queue&) = default; // Copy Constructor set to default
        Queue& operator=(const Queue&) = default; // Assignment operator set to default
        void pushBack(const T& t);
        T& front();
        const T& front() const;
        void popFront();
        int size() const;
        class Iterator;
        Iterator begin() const;
        Iterator end() const;
        class EmptyQueue {};
    private:
        Node<T>* m_head;
        Node<T>* m_tail;
        int m_size;
};

Queue<T>::Iterator class:

template<class T>
class Queue<T>::Iterator {
    public:
        const T& operator*() const;
        Iterator& operator++();
        Iterator operator++(int);
        bool operator==(const Iterator& iterator) const;
        bool operator!=(const Iterator& iterator) const;
        Iterator(const Iterator&)=default;
        Iterator& operator=(const Iterator&)=default;
        class InvalidOperation {};
    private:
        const Node<T>* m_node;
        Iterator(const Node<T>* m_node);
        friend class Queue<T>;
};

template<class T>
Queue<T>::Iterator::Iterator(const Node<T>* m_node) {
    this->m_node=m_node;
}

template<class T>
typename Queue<T>::Iterator& Queue<T>::Iterator::operator++() {
    this->m_node=m_node->getNext();
    return *this;
}

a value of type "int" cannot be assigned to an entity of type "Node

I have a linked list that contains a pointer to the first and last node and size which indicates how many nodes are there in the list. I have a function that returns the first node.

I want to be able to change the m_data in the first node using queue1.front() = 3;. However, I am getting

invalid conversion from ‘int’ to ‘Node<int>*’

error while compiling

template <class T>
class Node {
public:
    Node(const T& t);
    ~Node() = default;            // Destructor
    Node(const Node&) = default;  // Copy Constructor set to default
    Node& operator=(const Node&) =
        default;  // Assignment operator set to default
    T& getData();
    const T& getData() const;
    Node* getNext();
    void setNext(Node<T>* newNext);

private:
    T m_data;
    Node* m_nextNode;
};

template <class T>
Node<T>::Node(const T& t) {
    this->m_data = t;
    this->m_nextNode = nullptr;
}
template <class T>
class Queue {
public:
    static const int SIZE_EMPTY = 0;
    Queue();
    ~Queue();                       // Destructor
    Queue(const Queue&) = default;  // Copy Constructor set to default
    Queue& operator=(const Queue&) =
        default;  // Assignment operator set to default
    void pushBack(const T& t);
    Node<T>*& front();
    const Node<T>*& front() const;
    void popFront();
    int size() const;
    class EmptyQueue {};

private:
    Node<T>* m_head;
    Node<T>* m_tail;
    int m_size;
};

template <class T>
Node<T>*& Queue<T>::front() {
    if (this->m_size == Queue<T>::SIZE_EMPTY) {
        throw Queue<T>::EmptyQueue();
    }
    return this->m_head;
}

template <class T>
void Queue<T>::pushBack(const T& t) {
    this->m_size += 1;
    Node<T>* newNode = new Node<T>(t);
    this->m_tail = newNode;
    if (this->m_size == 1) {
        this->m_head = newNode;
    } else {
        Node<T>* tempNode = this->m_head;
        while (tempNode->getNext()) {
            tempNode = tempNode->getNext();
        }
        tempNode->setNext(newNode);
    }
}
int main() {
    Queue<int> queue1;
    queue1.pushBack(1);
    queue1.front() = 3;
}

mardi 24 mai 2022

Using nested class without "parent_class::"

I have a base_class

class Base {

}

class Derived : public Base {
   void derived_function(Strange& strange) {
      strange.private_function(); //inaccessible error as only base is friend
   }
}

class Strange : public StrangeBase{
friend class Base;
private:
  void private_function();
}

I don't like the solution of adding access function to Base class

//I dont like solution below
class Base {
protected:
  access_private_function(Strange& strange) {
    strange.private_function(); // worksn - but I don't like it!
  }
}

as a solution I would like to define all Dervied class as nested to Strange like this

class Strange : public StrangeBase{
friend class Base;
private:
  void private_function();
public:
  class Derived : public Base {
     void derived_function(Strange& strange) {
        strange.private_function(); //now accessible :)
     }
  }
}

However, now when I want to use Dervied externally to Stange class I need to always write the parent class with "::"

  new Strange::Derived()

is there a way to avoid parent:: prefix like in "using namespace std" for example?

lundi 23 mai 2022

How do I use move-semantics to reallocate resources from class constructor?

To enable me to read a binary file I have made this class. I would like to not copy a temporary for which I am trying to use move semantics. But this code produces "access violation error".

#include <fstream>
#include <iostream>

class myClass
{
public:
    std::istream& myStream;
    static myClass create(const char* path);
    myClass(myClass&&) noexcept = default;
    myClass(std::istream& input);
    myClass() = default;
};

myClass myClass::create(const char* path)
{
    std::ifstream input{ path, std::ios::binary | std::ios::in };
    if (!input.is_open()) throw std::runtime_error("Error - couldn't open file");
    return std::move(myClass(input));
}

myClass::myClass(std::istream& input) :
    myStream(input)
{

}
int main()
{
    const char* path = R"(file.bin)";
    myClass cr{myClass::create(path)};

    for (int i = 0; i < 10; ++i)
        cr.myStream.seekg(i);

    return 0;
}

How to define the different template structs with different enums

I've two enums as below:

enum TTT {t = 2};

enum XXX {x = 2};

I'm trying to make some struct to help me get the name of an enum. Here is what I've done:

template<TTT>
struct StrMyEnum {
    static char const* name() { return "unknown"; }
};

template<>
struct StrMyEnum<t> {
    static char const* name() { return "tt"; }
};

It works. Now I can get the name of the enum t: StrMyEnum<t>::name().

However, if I write another group of template structs for XXX, it doesn't seem to work.

template<XXX>
struct StrMyEnum {
    static char const* name() { return "unknown"; }
};

template<>
struct StrMyEnum<x> {
    static char const* name() { return "xx"; }
};

Now I get a compile error: could not convert 'x' from 'XXX' to 'TTT'. It seems that the compiler is trying to match the StrMyEnum<x> with TTT...

I don't know why.

So template can't distinguish the different enums? Is it possible to write some structs for different enums?

SpGEMM in CUDA 11.4

I copied an example here and did SpGEMM which works fine with CUDA 11.1. However, when I switch to 11.4, I get run time errors such as

` 3: ** On entry to cusparseCsrSetPointers() parameter number 2 (csrRowOffsets) had an illegal value: NULL pointer

3: ** On entry to cusparseCreateCsr() parameter number 5 (csrRowOffsets) had an illegal value: NULL pointer

3: ** On entry to cusparseSpGEMM_workEstimation() parameter number 5 (matA) had an illegal value: NULL pointer

3: ** On entry to cusparseSpGEMM_compute() parameter number 5 (matA) had an illegal value: NULL pointer

3: ** On entry to cusparseCsrSetPointers() parameter number 2 (csrRowOffsets) had an illegal value: NULL pointer

3: ** On entry to cusparseSpGEMM_copy() parameter number 5 (matA) had an illegal value: NULL pointer`

How would the official example here change in CUDA 11.4?

move constructor and move assignment

I have this code

class GameViewModel
{
public:
    GameViewModel(PlayerData& playerData, std::unique_ptr<WeaponData> WeaponData) : m_playerData(playerData), m_WeaponData(std::move(WeaponData)){}

    PlayerData& GetPlayerData() const { return m_playerData; }
    // I want to do:
    //void SetPlayerData(PlayerData playerData) { m_playerData = playerData); }
    WeaponData& GetWeaponData() const { return *m_WeaponData; }
    
    bool IsVisible() const;
    int GetColour() const { return m_playerData.m_Envelope.GetColour(); }

private:
    PlayerData& m_playerData;
    std::unique_ptr<WeaponData> m_WeaponData;
};

I'd like to update the member variable m_playerData, (see SetPlayerData) but I get a C2280 attempting to ref a deleted function. I need to define my own move constructor and move assignment. I've looked at: Copy constructor for a class with unique_ptr but how do I initialize m_playerData in the move constructor?

How to find map value present in the string c++ here need to match map value to substring of a string

below are map variables in code.

boardSelectMap.insert(std::pair<std::string, std::string>("boardtype1", "RBCM_CLEO"));
        boardSelectMap.insert(std::pair<std::string, std::string>("boardtype2", "RBCM_AIVI2_C2"));
        boardSelectMap.insert(std::pair<std::string, std::string>("boardtype3", "RBCM_AIVI2_ADR3"));
        boardSelectMap.insert(std::pair<std::string, std::string>("boardtype4", "RBCM_AIVI2_SBR"));
        boardSelectMap.insert(std::pair<std::string, std::string>("boardtype5", "RBCM_AIVI2_C1"));
        boardSelectMap.insert(std::pair<std::string, std::string>("boardtype6", "RBCM_AIVI2_C3"));
        boardSelectMap.insert(std::pair<std::string, std::string>("boardtype7", "RBCM_AIVI2_CCS1_1_B0"));
        boardSelectMap.insert(std::pair<std::string, std::string>("boardtype8", "RBCM_AIVI2_J32V_B0"));

std::string boardFileContent = "as*. RBCM AIVI2 C2*.-3gb board based on r8a7796";

Here i need to find boardSelectMap[boardtype2] or "RBCM_AIVI2_C2" is selected i am not to do it with find()

the difference of automatic and dynamic variables rules in zero initialization

code like this,

#include <iostream>
 
class obj
{
public:
    int v;
};

int main(int argc, char *argv[])
{
    obj o1; 
    std::cout << o1.v << std::endl; // print 32766, indeterminate values
    obj *o2 = new obj();
    std::cout << o2->v << std::endl; // print 0,but why?

    int v1;
    std::cout << v1 << std::endl; // print 22024, indeterminate values
    int *v2 = new int;
    std::cout << *v2 << std::endl; // print 0,but why?
    return 0;
}

I know the global or static variables will be initialize zero.
and automatic does the indeterminate values.
but the heap object use new keyword, has any reference to explain it?

dimanche 22 mai 2022

Cannot access member variable in method call

I'm building a parser for PE files and I've encountered a somewhat weird error. Here is the minimal example

#include <iostream>
#include <vector>
#include <string.h>
#include <istream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <cstdint>


class BinaryDataSegment {
protected:
    std::vector<uint8_t>* binary_data;   
    int data_size;

public:   
    BinaryDataSegment(){
        data_size = 0;
    }

    BinaryDataSegment(std::istream& field_data, int reserve_size) {
        binary_data = new std::vector<uint8_t>();
        binary_data->reserve(reserve_size);
        std::copy(std::istream_iterator<uint8_t>(field_data), std::istream_iterator<uint8_t>(), std::back_inserter(*binary_data));
        data_size = binary_data->size();
    }

    template<typename D>
    D Read(int position){
        if (position + sizeof(D) > data_size){
            throw std::overflow_error("attempting to read outsite binary data");
        }
        D temp;
        std::cout << binary_data->data()+position << std::endl; // Segmentation fault here: binary_data is not accessible
        memcpy(&temp, binary_data->data()+position, sizeof(D));
        return temp;
    }

    ~BinaryDataSegment(){
        delete binary_data;
    }
};

class PEFile {
protected:
    BinaryDataSegment data;

public:
    PEFile(std::istream& file_stream, int reserve=0){
        data = BinaryDataSegment(file_stream, reserve);
    }
    int dos_header;

    void parse(){
        dos_header = data.Read<int>(0);
    }
};

int main(){
    std::ifstream in_file = std::ifstream("anyFile.txt", std::ios::binary);
    PEFile foo = PEFile(in_file, 0);
    foo.parse(); // Segmentation fault

    BinaryDataSegment bar = BinaryDataSegment(in_file, 0);
    bar.Read<int>(0); // This works correctly
    
}

When I call the Read<int> function from main, it works correctly, but when I do it from the PEFile class, the same function call fails with a Segmentation fault. GDB says that the memory of binary_data is not accessible, even though it looks like it should be. My question is: why does this unexpected behavior happen?

I compiled without warnings using:

g++ -Wall -std=c++11 example.cpp

When running the example, make sure to replace "anyFile.txt" with a real local file. Thank you.

samedi 21 mai 2022

Sorting an array whose elements are attached to another array [duplicate]

I have an array (say) arr1 = [9,4,2,5] and another array arr2 = [1,6,3,7]

I want to sort arr2 and I also want to change swap elements of arr1 as per arr2.

so think of it as the elements of at same index of both arrays are attached. like 9 of arr1 and 1 of arr2 are attached. similarly, the other elements are.

so if arr2 is sorted which is [1,3,6,7] I want arr1 to have elements in this order [9,2,4,5]

Is there a way to do that directly in c++ using stl?

Why does the do{}while(choice != 9) loop in my program go in infinite loop when I enter a string with more than a word? [closed]

I am a beginner in C++ and I am trying to make a To-Do program. But when I am selecting 1 Create a To-do and entering more than a word, the do{}while(choice != 9) loop goes into an infinite loop showing the menu repeatedly. I tried using cin.ignore() and was able to enter a string of more than a word but then a second time if I try to enter a string(1 Create a To-do) it again goes to an infinite loop.

Below is my code, it's not complete but I have written the code for 1st two options in the menu. Please if anyone can help me figure out where to use cin.ignore() and how to use it, it would be really helpful. Thanks.

#include <iostream>
#include <map>
#include <vector>
#include <string>

using namespace std;





// =======================  USER CLASS  ============================================================================================
class User{
    string fname;
    int id;vector<string> current;
     vector<string> done;
   public:
     static int count;
     
     string pass;

     User() { count++; id = count; }


    void setfname(string fn) { fname = fn; }

    string getfname() { return fname; }

    int getid() { return id; }

    void greetnewux() { 
        cout << "\n\n>>>>> Welcome, " << fname << endl;
        cout << ">>>>> Your ID is : " << id << endl;
        cout << "(Note: Please remember this id, it will be needed in Login)" << endl;
    
    }

    void createtodo(string todo) {
        current.push_back(todo);
        cout << "\n\tSuccessfully Entered!!";
        cout << "!!!!!!!!!!!!!!!!Out of User Create todo";
        
    }

    void setpass(string p) { pass = p; cout << "\nPASSWORD SUCCESSFULLY SET!"; }
     
    void deletetodo(int i) {
        int input = 0;
        switch (i) {

        case 1:
            cout << "\n<<<<<<< INCOMPLETE TO-DOS >>>>>>>\n\n";
            i = 0;
            while (i < current.size()) {
                cout << i + 1 << " " << current[i] << endl;
                i++;
            }

            cout << "\n\nENTER THE TO-DO NUMBER TO DELETE : ";
            cin >> input;
            if(input<=current.size() && input!=0){
            current.erase(current.begin()+(input-1));
            cout << "\n\tSuccessfully DELETED!!";
            }
            else { cout << "\n\n!!! INVALID INPUT !!! NUMBER NOT PRESENT IN LIST "; }
            break;

        case 2:
            cout << "\n<<<<<<< COMPLETED TO-DOS >>>>>>>\n\n";
            i = 0;
            while (i < done.size()) {
                cout << i + 1 << " " << done[i] << endl;
                i++;
            }

            cout << "\n\nENTER THE TO-DO NUMBER TO DELETE : ";
            cin >> input;
            if (input > done.size() + 1 && input != 0) {
                done.erase(done.begin() + (input - 1));
                cout << "\n\tSuccessfully DELETED!!";
            }
            else { cout << "\n\n!!! INVALID INPUT !!! NUMBER NOT PRESENT IN LIST "; }
            break;

        }
        






    }





};
int User::count = 0;



// =======================  ADMIN CLASS  ============================================================================================
class Admin {
    
     public:
         int random;
         int id;
         map<int, User> DB;
         static vector<string> motivation;

    Admin() { }

    bool ifpresent(int i){
      
       if (DB.find(i) == DB.end()) {return false; }
       else { return true; }
    }

    bool checkpass(string p, int i){ 
    
       if (DB[i].pass == p) {
           User& ux = DB[i]; id = i;
          cout << "\nWelcome back, "<<ux.getfname()<<" !";
          random = rand() % motivation.size();
          string sel_elem = motivation[random];
          cout << "\n\n\t" << sel_elem << "\n";
         
          return true;
       }
       else {
          cout << "\n\n\t!!!WRONG PASSWORD!!!";
          return false;

       }

    }

    void createtodo() { 
        User& ux = DB[id];
        string todo;
        cout << "\nEnter the to-do: ";
        
        getline(cin, todo);
       
        ux.createtodo(todo);
        cout << "!!!!!!!!!!!!!!!!Out of Admin Create todo";
        
    };
    bool createacc() {

        User u; string fn; string p;
        cout << "\nEnter Your First Name: ";
        cin >> fn;
        u.setfname(fn);
        cout << "\nFirst Name: " << fn;
        cout << "\nSet your Password: ";
        cin >> p;
        u.setpass(p);

        DB[u.getid()] = u; //Entering User in DataBase

        u.greetnewux();
        random = rand() % motivation.size();
        string sel_elem = motivation[random];
        cout << "\n\n\t" << sel_elem << "\n";
        return true;


    };

    void deltodo(){
        int i;

        auto& u = DB[id];
        cout << "\n\nDo you want to Delete: ";
        cout << "\n1 An incompleted to-do?";
        cout << "\nOR";
        cout << "\n2 A completed to-do?";

        cin >> i;
        if (i == 1 || i == 2) { u.deletetodo(i); }
        else { cout << "\n\n!!! INVALID INPUT !!! Please enter 1 or 2 !!"; }
 
    }


    
    ~Admin() { }

};

vector<string> Admin::motivation = { "“You do not find the happy life. You make it”",
                                    "“The most wasted of days is one without laughter.” ",
                                    "“Make each day your masterpiece.”",
                                    "“Happiness is not by chance, but by choice.”",
                                    "“It is never too late to be what you might have been.”",
                                    "“Dream big and dare to fail.”",

};





// =======================  MAIN FUNCTION  ============================================================================================
int main()
{
    Admin A;
    int id;  string pass;
    int input; int choice;
    bool flag = true;
    cout << "\n\n*************************************** TO DO APP ***************************************\n\n\n\n";
    do {
        cout << "\n\n1 Login";
        cout << "\n\n2 Create Account\n\n";
        cout << "Enter 1 or 2 : ";
        
        cin >> input;

        switch(input){
        case 1:
            cout << "\n\t\t\t<<<<<<< LOGIN PAGE >>>>>>>\n\n";
            cout << "\nEnter your id: ";
            cin >> id;
 

            if (A.ifpresent(id)) {

                cout << "\nid " << id; cout << "\nEnter Password: "; cin >> pass;

                if (A.checkpass(pass, id)) {

                    flag = false;
                }
                cout << "\n\n\t!!! ENTER CORRECT DETAILS !!!!\n\n";

            }
            else { cout << "\n\n\t!!!Account Not Found!!!\n\n"; }


            break;

        case 2:

            cout << "\n\t\t\t<<<<<<< ACCOUNT CREATION PAGE >>>>>>>\n\n";
            if (A.createacc()) { flag = true; };

            break;

        default:
            cout << "\n\n\t\t!!! INVALID INPUT !!! Please enter 1 or 2 !!";
            break;
        
        
        }

    } while (flag);





   do{
       cout << "\n\n**ENTER THE NUMBER**\n";
       cout << "\n1 Create a To-do";
       cout << "\n2 Delete a To-do";
       cout << "\n3 Mark as Done";
       cout << "\n4 Mark as Not done";
       cout << "\n5 Show Completed To-do";
       cout << "\n6 Show Remaining To-do";
       cout << "\n7 Remove all To-do";

       cout << "\n\n  8 Clear Screen";
       cout << "\n  9 Log Out [>\n\n";
       cout << "Enter: ";
      
       cin >> choice; 

       switch (choice) {
       case 1:
           
           A.createtodo();
           break;
       case 2:
           A.deltodo();
           break;
       case 3:
           break;
       case 4:
           break;
       case 5:
           break;
       case 6:
           break;
       case 7:
           break;
       case 8:
           system("cls");
           break;
       case 9:
           cout << "\n\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< LOGGED OUT >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>n\n\n\n\n\n\n";
           
           break;
       default:
           cout << "\n\nINVALID INPUT";

       }


   } while (choice != 9);


}

Differences between how libc++ and libstdc++ handle `function`s

I am trying to move a functor into a lambda inside an object, like this:

#include <functional>
#include <iostream>

#include "boost/stacktrace.hpp"

#define fwd(o) std::forward<decltype(o)>(o)

struct CopyCounter {
  CopyCounter() noexcept = default;
  CopyCounter(const CopyCounter &) noexcept {
    std::cout << "Copied at " << boost::stacktrace::stacktrace() << std::endl; 
    counter++;
  }
  CopyCounter(CopyCounter &&) noexcept = default;

  CopyCounter &operator=(CopyCounter &&) noexcept = default;
  CopyCounter &operator=(const CopyCounter &) noexcept {
    std::cout << "Copied at " << boost::stacktrace::stacktrace() << std::endl;
    counter++;
    return *this;
  }

  inline static size_t counter = 0;
};

struct Argument : CopyCounter {};

struct Functor : CopyCounter {
  int operator()(Argument) { return 42; }
};

class Invoker {
  std::function<void()> invoke_;
  int result_;

public:
  template <class Functor, class... Args>
  Invoker(Functor&& f, Args&&... args) {
    invoke_ = [this, f = fwd(f), ...args = fwd(args)]() mutable { 
      result_ = f(fwd(args)...);
    };
  }
};

int main() {
  Functor f;
  Argument a;
  auto i = Invoker(std::move(f), std::move(a));
  assert(CopyCounter::counter == 0);
  return 0;
}

Somewhat surprisingly, the last assert fails on libc++, but not libstdc++. The stacktrace hints at the two copies that are performed:

Copied at  0# CopyCounter at /usr/include/boost/stacktrace/stacktrace.hpp:?
 1# 0x00000000004C812E at ./src/csc_cpp/move_functors.cpp:38
 2# std::__1::__function::__value_func<void ()>::swap(std::__1::__function::__value_func<void ()>&) at /usr/lib/llvm-10/bin/../include/c++/v1/functional:?
 3# ~__value_func at /usr/lib/llvm-10/bin/../include/c++/v1/functional:1825
 4# __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6
 5# _start in ./bin/./src/csc_cpp/move_functors

Copied at  0# CopyCounter at /usr/include/boost/stacktrace/stacktrace.hpp:?
 1# std::__1::__function::__value_func<void ()>::swap(std::__1::__function::__value_func<void ()>&) at /usr/lib/llvm-10/bin/../include/c++/v1/functional:?
 2# ~__value_func at /usr/lib/llvm-10/bin/../include/c++/v1/functional:1825
 3# __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6
 4# _start in ./bin/./src/csc_cpp/move_functors

It seems like inside the library the functor and the argument get copied in swap, during the move-assignment of invoke_. There are two questions:

  1. Why is this the desired behaviour and what can be the motivation behind this design solution?
  2. What is a good way to update the code to reach the same semantics as in libstdc++?

Curl Upload Stuck

I'm using curl-7.65.0 (Static) with Microsoft Visual Studio 2013. I have the following method to upload files to the FTP server.

bool uploadFile(string sourcePath, string url, string & error)
{
    FILE * file;
    file = fopen(sourcePath.c_str(), "rb");
    if (!file)
    {
        error = "Can not open source file";
        return false;
    }

    struct stat fileInformation;
    if (fstat(fileno(file), &fileInformation) != 0)
    {
        error = "Can not get source file information";
        return false;
    }

    CURL * curl;
    auto curlResultCode = CURLE_FAILED_INIT;
    curl = curl_easy_init();
    if (curl)
    {
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
        curl_easy_setopt(curl, CURLOPT_READDATA, file);
        curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, curl_off_t(fileInformation.st_size));
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
        curl_easy_setopt(curl, CURLOPT_FTP_CREATE_MISSING_DIRS, CURLFTP_CREATE_DIR_RETRY);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
        curl_easy_setopt(curl, CURLOPT_TIMEOUT, 3600L);
        curlResultCode = curl_easy_perform(curl);
    }

    curl_easy_cleanup(curl);
    fclose(file);
    error = curl_easy_strerror(curlResultCode);
    return curlResultCode != CURLE_OK ? false : true;
}

When i call the uploadFile with following parameters:

sourcePath: c:/file.zip

url: ftp://user:password@127.0.0.1:21/files/2022/05/20/myfile.zip

I see the directories are created in the FTP server but the file is not uploading and eventually, I get the CURLE_OPERATION_TIMEDOUT error.

Here is the log from the FTP server (XLight FTP Server)

05/21/2022 17:26:29 (not login 127.0.0.1<--127.0.0.1:21) "220 Xlight FTP Server 3.5 ready..."
05/21/2022 17:26:29 (not login 127.0.0.1-->127.0.0.1:21) "USER user"
05/21/2022 17:26:29 (not login 127.0.0.1<--127.0.0.1:21) "331 Password required for user"
05/21/2022 17:26:30 (not login 127.0.0.1-->127.0.0.1:21) "PASS *****"
05/21/2022 17:26:30 (user 127.0.0.1<--127.0.0.1:21) "230 Login OK"
05/21/2022 17:26:30 (user 127.0.0.1-->127.0.0.1:21) "PWD"
05/21/2022 17:26:30 (user 127.0.0.1<--127.0.0.1:21) "257 "/""
05/21/2022 17:26:30 (user 127.0.0.1-->127.0.0.1:21) "CWD files"
05/21/2022 17:26:30 (user 127.0.0.1<--127.0.0.1:21) "550 Can't change directory to "/files"."
05/21/2022 17:26:30 (user 127.0.0.1-->127.0.0.1:21) "MKD files"
05/21/2022 17:26:30 (user 127.0.0.1<--127.0.0.1:21) "257 "/files/" directory created."
05/21/2022 17:26:30 (user 127.0.0.1-->127.0.0.1:21) "CWD files"
05/21/2022 17:26:30 (user 127.0.0.1<--127.0.0.1:21) "250 Directory successfully changed"
05/21/2022 17:26:30 (user 127.0.0.1-->127.0.0.1:21) "CWD 2022"
05/21/2022 17:26:30 (user 127.0.0.1<--127.0.0.1:21) "550 Can't change directory to "/files/2022"."
05/21/2022 17:26:30 (user 127.0.0.1-->127.0.0.1:21) "MKD 2022"
05/21/2022 17:26:30 (user 127.0.0.1<--127.0.0.1:21) "257 "/files/2022/" directory created."
05/21/2022 17:26:30 (user 127.0.0.1-->127.0.0.1:21) "CWD 2022"
05/21/2022 17:26:30 (user 127.0.0.1<--127.0.0.1:21) "250 Directory successfully changed"
05/21/2022 17:26:31 (user 127.0.0.1-->127.0.0.1:21) "CWD 05"
05/21/2022 17:26:31 (user 127.0.0.1<--127.0.0.1:21) "550 Can't change directory to "/files/2022/05"."
05/21/2022 17:26:31 (user 127.0.0.1-->127.0.0.1:21) "MKD 05"
05/21/2022 17:26:31 (user 127.0.0.1<--127.0.0.1:21) "257 "/files/2022/05/" directory created."
05/21/2022 17:26:31 (user 127.0.0.1-->127.0.0.1:21) "CWD 05"
05/21/2022 17:26:31 (user 127.0.0.1<--127.0.0.1:21) "250 Directory successfully changed"
05/21/2022 17:26:31 (user 127.0.0.1-->127.0.0.1:21) "CWD 20"
05/21/2022 17:26:31 (user 127.0.0.1<--127.0.0.1:21) "550 Can't change directory to "/files/2022/05/20"."
05/21/2022 17:26:31 (user 127.0.0.1-->127.0.0.1:21) "MKD 20"
05/21/2022 17:26:31 (user 127.0.0.1<--127.0.0.1:21) "257 "/files/2022/05/20/" directory created."
05/21/2022 17:26:31 (user 127.0.0.1-->127.0.0.1:21) "CWD 20"
05/21/2022 17:26:31 (user 127.0.0.1<--127.0.0.1:21) "250 Directory successfully changed"
05/21/2022 17:26:31 (user 127.0.0.1-->127.0.0.1:21) "EPSV"
05/21/2022 17:26:31 (user 127.0.0.1<--127.0.0.1:21) "229 Entering Passive Mode (|||53237|)"
05/21/2022 17:26:33 (user 127.0.0.1-->127.0.0.1:21) "TYPE I"
05/21/2022 17:26:33 (user 127.0.0.1<--127.0.0.1:21) "200 Type set to I."

Can you tell me what's wrong here?

Update 1: I also added the read callback function but still same result.

size_t read_callback(char *ptr, size_t size, size_t nmemb, void *userdata)
{
    FILE *readhere = (FILE *)userdata;
    curl_off_t nread;

    /* copy as much data as possible into the 'ptr' buffer, but no more than
    'size' * 'nmemb' bytes! */
    size_t retcode = fread(ptr, size, nmemb, readhere);

    nread = (curl_off_t)retcode;

    fprintf(stderr, "*** We read %" CURL_FORMAT_CURL_OFF_T
        " bytes from file\n", nread);
    return retcode;
}

curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);
curl_easy_setopt(curl, CURLOPT_READDATA, (void *)file);

Thanks in advance

vendredi 20 mai 2022

Question about the thread-safety of using shared_ptr

As it's well known that shared_ptr only guarantees access to underlying control block is thread safe and no guarantee made for accesses to owned object.

Then why there is a race condition in the code snippet below:

std::shared_ptr<int> g_s = std::make_shared<int>(1);
void f1()
{
    std::shared_ptr<int>l_s1 = g_s; // read g_s
}

void f2()
{
    std::shared_ptr<int> l_s2 = std::make_shared<int>(3);
    std::thread th(f1);
    th.detach();
    g_s = l_s2; // write g_s
}

In the code snippet above, the owned object of the shared pointer named g_s are not accessed indeed.

I am really confused now. Could somebody shed some light on this matter?

Garbage when converting character to string using concatenation

I am converting a character to a string by concatenating it with an empty string (""). But it results in undefined behaviour or garbage characters in the resultant string. Why so?

char c = 'a';
string s = ""+c;
cout<<s<<" "<<s.size()<<"\n";

jeudi 19 mai 2022

The loop in the DateEntry function does not work. for (int i = 0, i

The DateEntry function does not work properly. Allocated memory for data recording but the cycle ends quickly or endless depending on where to put the system ("pause"). Tried everything and so I can not understand the mistake. Loop: for (int i = 0; i <n; i++).

Function: DateEntry(Date* (&d), int &n);

Screen Error: enter image description here

My code:

Functions.cpp

#include "Functions.h"

void DataEntry(Date* (&d), int& n)
{
    cout << "Введiть скiльки маршутiв ви хочете добавити: ";
    cin >> n;

    d = new Date[n];
    int choose_m;
    for (int i = 0; i < n; i++) {
        cout << "Введiть iнформацiю про маршут:" << endl;
        cout << "Номер маршуту: ";
        cin >> d[i]._trans.num_t;
        cout << "Пункт Призначення: ";
        cin >> d[i]._trans.destination;
        cout << "Дистанцiя: ";
        cin >> d[i]._trans.distance;
        cout << "Мiсто виЇзду: ";
        cin >> d[i]._trans.city;

        cout << "Введiть iнформацiю про бiлет: " << endl;
        cout << "Номер бiлету: ";
        cin >> d[i]._tick.ID_tick;
        cout << "Мiсце продажi: ";
        cin >> d[i]._tick.place;
        cout << "Цiна: ";
        cin >> d[i]._tick.price;

        cout << "Введiть iмя Диспетчера: ";
        cin >> d[i]._dis.D_name; 
        
        cout << "Водiй: " << endl;
        cout << "Введiть iмя водiя: ";
        cin >> d[i]._driv.d_name;
        cout << "Номер телефону: ";
        cin >> d[i]._driv.num_phone;

        cout << "Автобус: " << endl;
        cout << "Номернi знаки автобуса: ";
        cin >> d[i]._b.num_bus;
        cout << "Модель: ";
        cout << "[0] - BMW" << endl;
        cout << "[1] - Mercedes" << endl;
        cout << "[2] - Hyundai" << endl;
        cin >> choose_m;
        switch (choose_m)
        {
        case 0: d[i]._b.model = "BMW"; break;
        case 1: d[i]._b.model = "Mercedes"; break;
        case 2: d[i]._b.model = "Hyundai"; break;
        }
        cout << "Колiр автобуса: "; 
        cin >> d[i]._b.color;

        cout << "_______________________________________" << endl;
    }
}
void Print(Date* d, int n)
{
    int _choose_;
    for (int i = 0; i < n; i++)
    {
        cout << "Перевезення #" << i + 1 << endl;
        cout << "Номер маршуту: " << d[i]._trans.num_t << "Номер бiлета:" << d[i]._tick.ID_tick << "Диспетчер: " << d[i]._dis.D_name << "Водiй: " << d[i]._driv.d_name << "Автобус:" << d[i]._b.num_bus << endl;
    }
    cout << "Вивести детальнiшу iнформацiю про маршут?" << endl;
    cout << "[1] - Так\t [2] - Нi" << endl;
    cin >> _choose_;

    int num_tt;
        switch (_choose_)
        {
        case 1: 
            cout << "Введiть номер маршуту: ";
            cin >> num_tt;
            system("cls");
            for (int i = 0; i < n; i++)
            {
                if (d[i]._trans.num_t == num_tt)
                {
                    int _choose_2;
                    cout << "Виберiть яку iнформацiю вивести: " << endl;
                    cout << "[0] - Маршут" << endl;
                    cout << "[1] - Бiлет" << endl;
                    cout << "[2] - Диспетчер" << endl;
                    cout << "[3] - Водiй" << endl;
                    cout << "[4] - Автобус" << endl;
                    cin >> _choose_2;
                    switch (_choose_2)
                    {
                    case 0:
                        for (int i = 0; i < n; i++) {
                            cout << "Маршут: " << endl;
                            cout << d[i]._trans.num_t << endl;
                            cout << d[i]._trans.destination << endl;
                            cout << d[i]._trans.distance << endl;
                            cout << d[i]._trans.city << endl;
                        }
                        break;
                    case 1: 
                        for (int i = 0; i < n; i++) {
                            cout << "Бiлет: " << endl;
                            cout << d[i]._tick.ID_tick << endl;
                            cout << d[i]._tick.price << endl;
                            cout << d[i]._tick.place << endl;
                        }
                        break;
                    case 2: 
                        for (int i = 0; i < n; i++) {
                            cout << "Диспетчер:" << endl;
                            cout << d[i]._dis.D_name << endl;
                        }
                        break;
                    case 3: 
                        for (int i = 0; i < n; i++)
                        {
                            cout << "Водiй: " << endl;
                            cout << d[i]._driv.d_name << endl;
                            cout << d[i]._driv.num_phone << endl;
                        }
                        break;
                    case 4: 
                        for (int i = 0; i < n; i++)
                        {
                            cout << "Автобус: " << endl;
                            cout << d[i]._b.num_bus << endl;
                            cout << d[i]._b.model << endl;
                            cout << d[i]._b.color << endl;
                        }
                        break;
                    }
                }
            }
        }
}
void EditDate(Date* (&d), int n)
{
    for (int i = 0; i < n; i++)
    {
        cout << "Перевезення #" << i + 1 << endl;
        cout << "Номер маршуту: " << d[i]._trans.num_t << "Номер бiлета:" << d[i]._tick.ID_tick << "Диспетчер: " << d[i]._dis.D_name << "Водiй: " << d[i]._driv.d_name << "Автобус:" << d[i]._b.num_bus << endl;
    }

    int _n;
    cout << "Введiть номер перевезання який хочете змiнити: ";
    cin >> _n;
    _n--;

    system("cls");
    int choose_m;
    if (_n > -0 && _n < n) {

        cout << "Введiть iнформацiю про маршут:" << endl;
        cout << "Номер маршуту: ";
        cin >> d[_n]._trans.num_t;
        cout << "Пункт Призначення: ";
        cin >> d[_n]._trans.destination;
        cout << "Дистанцiя: ";
        cin >> d[_n]._trans.distance;
        cout << "Мiсто виЇзду: ";
        cin >> d[_n]._trans.city;

        cout << "Введiть iнформацiю про бiлет: " << endl;
        cout << "Номер бiлету: ";
        cin >> d[_n]._tick.ID_tick;
        cout << "Мiсце продажi: ";
        cin >> d[_n]._tick.place;
        cout << "Цiна: ";
        cin >> d[_n]._tick.price;

        cout << "Введiть iмя Диспетчера: ";
        cin >> d[_n]._dis.D_name;

        cout << "Водiй: " << endl;
        cout << "Введiть iмя водiя: ";
        cin >> d[_n]._driv.d_name;
        cout << "Номер телефону: ";
        cin >> d[_n]._driv.num_phone;

        cout << "Автобус: " << endl;
        cout << "Номернi знаки автобуса: ";
        cin >> d[_n]._b.num_bus;
        cout << "Модель: ";
        cout << "[0] - BMW" << endl;
        cout << "[1] - Mercedes" << endl;
        cout << "[2] - Hyundai" << endl;
        cin >> choose_m;
        switch (choose_m)
        {
        case 0: d[_n]._b.model = "BMW"; break;
        case 1: d[_n]._b.model = "Mercedes"; break;
        case 2: d[_n]._b.model = "Hyundai"; break;
        }
        cout << "Колiр автобуса: ";
        cin >> d[_n]._b.color;

        cout << "_______________________________________" << endl;
    }
}

Functions.h

#pragma once
#include <iostream>
#include <string>

using namespace std;

struct Transportation // Маршут
{
    int num_t;
    string destination;
    int distance;
    int city;
};
struct Tickets // Бiлет
{
    int ID_tick;
    string place;
    double price;
};

struct Dispatcher // Диспетчер
{
    string D_name;
};

struct Driver // Водiй
{
    string d_name;
    int num_phone;
};
struct Bus {
    int num_bus;
    string model;
    string color;

};

struct Date {
    Transportation _trans;
    Tickets _tick;
    Dispatcher _dis;
    Driver _driv;
    Bus _b;
};

void DataEntry(Date* (&d), int &n);
void Print(Date* d, int n);
void EditDate(Date* (&d), int n);

Source.cpp

#include "Functions.h"

int start;
void Menu()
{
    cout << "Меню:" << endl;
    cout << "[0] - Вивести iнформацiю про касу" << endl;
    cout << "[1] - Створити новий маршут" << endl;
    cout << "[2] - Змiнити маршут" << endl;
    cout << "[3] - Вихiд" << endl;
    cin >> start;
}

void main() {
    setlocale(LC_ALL, "Russian");
    Menu();

    int amountofD = 0;
    string filename;

    Date* d = new Date[amountofD];
    while (start != 3)
    {
        switch (start)
        {
        case 0: 
            system("cls");

            if (amountofD != 0)
            {
                Print(d, amountofD);
            }
            else
            cout << "iнформацiя не iснує" << endl;
            system("pause");
            system("cls");
            Menu();
            break;
        case 1:
            DataEntry(d, amountofD);
            system("pause");
            system("cls");
            Menu();
            break;
        case 2: 
            system("cls");
            EditDate(d, amountofD); 
            Menu();
            break;
        }
    }
}

should a function return the pointer of a newly created object, or a unique_ptr of that object?

I remember watching Herb Sutter on conference talks, some years ago, trying to make a guideline along these lines:

if a function creates a new object on the heap, then it should always return it as a unique_ptr.

The idea was that it was safer, and intention-revealing.

To my surprise, this guideline seems to be missing from the CPP core guidelines today.

  • Has there been an issue with this guideline? Has it been abandoned?

  • Should we write functions like:

MyObject *create(Params p) {
  return new MyObject(p);
}

or

unique_ptr<MyObject> create(Params p) {
  return make_unique<MyObject>(p);
}

Is gRPC suitable for my needs on highly limiting IoT device?

I'm working on secure IoT device and arose a need to implement remote service (Service for internal use). So I'm trying to find out if gRPC would be suitable to me. Since device being secure it gives a lot of limitations. All the user software on device runs in sandbox-like environment, so standard means to access file system, networking etc. does not work. I have to use provided SDK to access files and create TCP/TLS connections. Also device internally uses protobuf 2.5.0 so trying to add newer protobuf library creates confilcts. Another limitation is C++11 (GNU ARM 5.3.1 compiler) and I need to use provided IDE which creates specific package to upload to device. On the server side we also use custom TLS library which uses remote HSM for cryptography.

Is it hard to write gRPC networking and TLS layers suitable for my needs? Or is it not worth the hassle and I should look for different protocol (suggestions are welcome)? Is there any other pitfalls?

So far I found out that protobuf 2.5.0 does not have "google/protobuf/util/json_util.h" and "google/protobuf/util/type_resolver_util.h" so I'm limited to gRPC 1.16 which does not use those headers.

How These 2 Almost Same code are different?

This Code is giving error Heap-Use-After-Free

for (auto it = mp.begin();it != mp.end();it++)
{
    if(it->second+ttl<=currentTime)
    {
        mp.erase(it);
    }
}

But this code

for (auto it = mp.begin();it != mp.end();)
{
    if(it->second+ttl<=currentTime)
    {
        mp.erase(it++);
    }
    else
    {
        ++it;
    }
}

Does Not give ans error. Can you please explain why? Both look basically the same to me. Please Help

mercredi 18 mai 2022

If statement giving parenthesis error in my triangle exercise

Learning C++ and doing a basic triangle exercise.

Can anyone check my code if I done everything right and explain why I am getting this error: suggest parenthesis around ‘&&’ within ‘||’

#include <iostream>

int main()
{
    // enter 3 numbers for sides of triangle
    int a, b, c;
    std::cout << "Input three numbers: " << std::endl;
    std::cin >> a;
    std::cin >> b; 
    std::cin >> c;
  
    // check what kind of traingle it is and output result
    if(a == b  && b == c){
        std::cout << "You have an equalateral triangle." << std::endl;
    }else if(a == b && b !=c || a!=b && b==c || a==c && b!=c){
        std::cout << "You have an iso triangle." << std::endl;
    }else{
        std::cout << "You have an scalene triangle." << std::endl;
    } 
}

mardi 17 mai 2022

Execution speed of code with `function` object as compared to using template functions

I know that std::function is implemented with the type erasure idiom. Type erasure is a handy technique, but as a drawback it needs to store on the heap a register (some kind of array) of the underlying objects.

Hence when creating or copying a function object there are allocations to do, and as a consequence the process should be slower than simply manipulating functions as template types, right?

To check this assumption I have run a test function that accumulates n = cycles consecutive integers, and then divides the sum by the number of increments n. First coded as a template:

#include <iostream>
#include <functional>
#include <chrono>
using std::cout;
using std::function;
using std::chrono::system_clock;
using std::chrono::duration_cast;
using std::chrono::milliseconds;

double computeMean(const double start, const int cycles) {
    double tmp(start);
    for (int i = 0; i < cycles; ++i) {
        tmp += i;
    }
    return tmp / cycles;
}

template<class T>
double operate(const double a, const int b, T myFunc) {
    return myFunc(a, b);
}

and the main.cpp:

int main()
{
    double init(1), result;
    int increments(1E9);
    // start clock
    system_clock::time_point t1 = system_clock::now();

    result = operate(init, increments, computeMean);
    // stop clock
    system_clock::time_point t2 = system_clock::now();

    cout << "Input: " << init << ", " << increments << ", Output: " << result << '\n';
    cout << "Time elapsed: " << duration_cast<milliseconds>(t2 - t1).count() << " ms\n";
    return 0;
}

I run this a hundred times and get a mean result of 10024.9 ms.

Then I introduce the function object in the main, plus a template specialization for operate so I can recycle the code above:

\\ as above, just add the template specialization
template<>
double operate(const double a, const int b, function<double (const double, const int)> myFunc) {
    cout << "nontemplate called\n";
    return myFunc(a, b);
}

\\ and inside the main
int main()
{
    //...
    // start clock
    system_clock::time_point t1 = system_clock::now();

    // new lines
    function<double (const double, const int)> computeMean =
        [&](const double init, const int increments) {
            double tmp(init);
            for (int i = 0; i < increments; ++i) {
                tmp += i;
            }
            return tmp / increments;
        };
    // rest as before
    // ...
}

I expected the function version to be faster, but the average is about the same, actually even slower, result = 9820.3 ms. I checked the standard deviations and they are about the same, 1233.77 against 1234.96.

What sense can be made of this? I would have expected the second version with the function object to be slower than the template version.

Here the whole test can be run on GDB.

it's not reaching end of file while reading the file and loop runs for infinite [duplicate]

while loop in ifstream does not stop even if the the condition is to stop at the end of file also i intended to read the string till it reach either full stop or max 75 character limit for a line then print rest on next line but after printing first line correctly it doesnt read anything

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

int main()
{   
    system("cls");
    
    char para[]="The default behaviour of ifstream type stream (upon opening files) allows user to read contents from the file. if the file mode is ios::in only then reading is performed on a text file and if the file mode also includes ios::binary along with ios::in then, reading is performed in binary mode. No transformation of characters takes place in binary mode whereas specific transformations take place in text mode. ";
   puts(para);
    char line[75];
    int a=strlen(para);
    cout<<endl<<"Size of paragraph: "<<a<<endl;
  
    ofstream fout;
    fout.open("out.txt");
    fout.write(para,a);
        fout.close();

    ifstream fin;
    fin.open("out.txt");
    int b=0;
    //char q;
    cout<<endl;
//this loop has the problem
    while (!fin.eof())
    {    
        b++;
        fin.getline(line,74,'.');
        //  if(fin.eof())
        //     break;
     
        cout<<b<<" : "<<line<<"\n";
       
    }
    fin.close();

    return 0;
}

C++11 delay the execution of thread

I'd like to crate some threads (with c++11) and collect them in a 'vector'. Then I'd like to fire them up, not immediately upon construction of the associated thread object, but after specified time. And this is my problem, how can I delay the execution of thread?

It is possible to do something like that? I appreciate any hints.

jpeg_dynamic_io/png_dynamic_io in Boost depreciated

#include <boost/gil/extension/io/jpeg_dynamic_io.hpp>
#include <boost/gil/extension/io/png_dynamic_io.hpp>

Is the header file depreciated in boost

fatal error C1083: Cannot open include file: 'boost/gil/extension/io/png_dynamic_io.hpp': No such file or directory

Why isn't the user-defined copy constructor invoked? [duplicate]

See the code in http://cpp.sh/8bsdl:

// copy constructor: deep copy
#include <iostream>
#include <string>
using namespace std;

class Example5 {
    string* ptr;
  public:
    Example5 (const string& str) : ptr(new string(str)) {cout << "constructor" << '\n';}
    ~Example5 () {delete ptr;}
    // copy constructor:
    Example5 (const Example5& x) : ptr(new string(x.content())) {cout << "copy constructor" << '\n';}
    // access content:
    const string& content() const {return *ptr;}
};

int main () {
    // cout << "copy constructor" << '\n';
  Example5 foo ("Example1");
  Example5 baz ("Example2");
  Example5 bar = foo; // default copy constructor
  bar = baz; // default copy assignment

  cout << "bar's content: " << bar.content() << '\n';
  return 0;
}

I defined a customized copy constructor, but it seems that it never gets called (In fact, the program doesn't produce any output, not even from the constructor...).

The same thing happens when I commented out line 12 where I hope to invoke the default copy constructor. Can anyone tell me what's wrong here?

lundi 16 mai 2022

getline unreliable on macOS?

as a school project I have to code a video game with SDL2, imgui and SFML and I'm facing a really weird problem :

getline seems unreliable on macOS but not on linux

Let me explain, when I compile and run my code, I am able to read my configuration file properly and display the data on screen : it is working everytime on my linux computer but on my macbook it is working like 1 time out of 5.

My configuration file :configuration file

how the information is supposed to be displayed (working properly on linux but not everytime on macOS) : how it is when it works

The code :

    // Récupération des derniers paramètres
    std::ifstream fichierSauvegardeR ("data/save.txt");
    if (fichierSauvegardeR.is_open())
    {
      getline(fichierSauvegardeR, strNbDes);
      strcpy(buf_nb_des, strNbDes.c_str());

      getline(fichierSauvegardeR, strNbJoueurs);
      strcpy(buf_nb_joueurs, strNbJoueurs.c_str());

      // getline(fichierSauvegardeR, strNomJoueur);
      // strcpy(noms_joueurs[0], strNomJoueur.c_str());

      for (int i = 0; i < nbJoueurs; i++) {
        if(!getline(fichierSauvegardeR, strNomJoueur))
        {
          break;
        }
        else
        {
          strcpy(noms_joueurs[i], strNomJoueur.c_str());
        }
      }
      fichierSauvegardeR.close();

    }

Note that, the first 2 lines of the configuration file are always properly read (even on macOS), what doesn't work is the other lines (I've tried replacing the "\n" by std::endl and it didn't changed anything)

dimanche 15 mai 2022

cout the unique values on console stored in single variable

I am new in C++. This is my program, which is generating a random number from 1 to 270:

#include <iostream>
#include <ctime>
#include <cstdlib>

void myFuncB(int par)
{
    std::cout << "unique = " << par; //print the unique number      
}

void myFuncA()
{   
    int paremeter = 0;
    std::cout << "Random numbers generated between 1 and 270:" << "\n";
    for(int i = 0; i < 270; i++)
    {
        paremeter = rand() % 270;
        std::cout << "paremeter=" << paremeter << "\n";
        // myFuncB(paremeter);
    }    
}

int main() {
    srand(time(0));  // Initialize random number generator.
    myFuncA();
    return 0; 
}

I want myFuncB(int par) to print the unique values only, not repeating any int value.

How can I do this without using a data structure like an array?

Default empty constractor

I am trying to create a very basic class with the default contructor:

    class Point {
    public:
          Point() = default;//con 1
          explicit Point(double x): x_axis(x), y_axis(0){}//con 2
          Point(const Point &other) = default;
          ~Point() = default;
    private:
           double x_axis;
           double y_axis;
    }

But when I try to use the default contructor in the main functtion it generates a random juck value for x_axis:

    Point p1;//generates random value
    Point p2{};//works as intended

so my question is, why is that? when I do the other contructor (con 2) like so:

    explicit Point(double x = 0): x_axis(x), y_axis(0){}

both of them work as intended. so technically I have 2 questions,

  1. why in the first try, no brackets generated a random value but {} worked, and in the second try they both worked
  2. what even is calling the default constructor with {}?

Why `std::make_shared` does not work anymore when the class inherits class `enable_shared_from_this`? [duplicate]

Why std::make_shared does not work anymore when the class Widget inherits class enable_shared_from_this?

Here is the code snippet:

#include<memory>
#include<vector>
#include<iostream>

class Widget:public std::enable_shared_from_this<Widget>
{
public:
    std::vector<int> vec;
    int var;
};

int main()
{
    auto wp{std::make_shared<Widget>()}; 
    //auto wp1{std::make_shared<Widget>(std::vector{1,2,3}, 9)}; //why his line compiles if class Widget does not inherit class enable_shared_from_this<Widget> 
}

What's more, auto wp1{std::make_shared<Widget>(std::vector{1,2,3}, 9)}; works well if you remove the inheritance.

TED's answer:

It's because there is a constructor added by enable_shared_from_this which removes the possibility to do aggregate initialization. In order to support creating it from make_shared, add the necessary constructors:

public:
    Widget() = default;
    Widget(const std::vector<int>& v, int i) : vec(v), var(i) {}

It works indeed.But I still don't know why there is a constructor added by enable_shared_from_this?