mercredi 30 mars 2022

using Raw pointer vs shared_ptr and weak_ptr for non-ownership

I have a class A which is storing instance of another class B. Class A does not need to have ownership of B. So it can store raw pointer/weak_ptr instead of sharing ownership of A. End user will be using class A and B instances, class A does not exist without B. There will be multiple instances of A which needs to store same instance of A. So semantically A should be destructed before B. So I have 3 options, how to store B instance inside A.:

  1. Store raw pointer. This will put some restrictions on the end user that certain APIs/destruction of A should happen before B. This can be documented in class header.
  2. Store weak_ptr. weak_ptr has some performance penalties every-time it is accessed or checked to be valid. I would prefer 1 over this.
  3. Store shared_ptr. Since 1 puts restrictions on the end user for managing the life-time. this will solve the problem, however shared_ptr comes with the cost and sharing ownership is not required here. Class B instance will be created during initialization and used later. So maybe if it is only about init cost of shared_ptr, it would be better instead over 1?

I am looking for the inputs which one is best practice.

Why there is unused-but-set variable-warning with pointers

I have the following code:

#include <iostream>

class Test
{
public:
    
    Test(int i)
    {
        initialize(i);
    }
    
    void initialize(int i)
    {
        std::cout<<"i: "<<i<<std::endl;
    }
};



int main()
{
    Test* obj1(nullptr);
    obj1 = new Test(2);
    
    Test* obj2(nullptr);
    obj2 = new Test(2);
    obj2->initialize(3);    
    
    return 0;
}

When I compile as such (GCC v11.2.0):

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

I see the following warning:

main.cpp: In function ‘int main()’:
main.cpp:25:15: warning: variable ‘obj1’ set but not used [-Wunused-but-set-variable]
   25 |         Test* obj1(nullptr);
      |               ^~~~

My question is why is there a warning for obj1, but not obj2 when they do almost the same thing?

Data race about map::operator[]

Is there any potential problem in this code snippet?

#include <mutex>
#include <map>
#include <vector>
#include <thread>

constexpr int FOO_NUM = 5;

int main()
{
std::map<int, std::mutex> mp;

std::vector<std::thread> vec;
for(int i=0; i<2; i++)
{
    vec.push_back(std::thread([&mp](){
    std::lock_guard<std::mutex> lk(mp[FOO_NUM]); //I think there is some potential problem here, am I right?
    //do something
     }));
}

for(auto& thread:vec)
{
thread.join();
}

As per the document,which says that:

Inserts value_type(key, T()) if the key does not exist. This function is equivalent to return insert(std::make_pair(key, T())).first->second;

I think there is a potential problem in the aforementioned code snippet. You see this may happen:

1.the first thread created a mutex, and is locking the mutex.

2.the second thread created a new one, and the mutex created in the first thread needs to be destroyed while it's still used in the first thread.

How can I initialize a custom Array class by aggregate initialization?

I have my own basic version of std::array

Here's how it looks:

template<typename T, size_t N> 
class Array {
  public:     
  Array()=default;
  T& operator[](size_t n) {return m_data[n];}     
  size_t Size() {return N;}
  private:     
  T m_data[N]; 
};

I can initialize it this way:

    Array<int, 3> arr;
    arr[0] = 11;
    arr[1] = 22;
    arr[2] = 33;

But what if I'd like to initialize it in aggregate, like this:

Array<int, 3> arr = { 1, 2, 3 };

How could I go about doing this?

Qt - QGraphicsScene MouseEvent is offset

I am trying to test a MouseEvent for a QGraphicsScene, but for some reason, the area at which the program registers the click is offset. Here is my code:

//var declaration
editorScene = new QGraphicsScene(this);
    ui->spriteGraphicsEditor->setScene(editorScene);

...

//registers a click on the graphics editor
void MainWindow::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton){
        // Detect if the click is in the view.
        QPoint remapped = ui->spriteGraphicsEditor->mapFromParent( event->pos() );
        if ( ui->spriteGraphicsEditor->rect().contains( remapped ) )
        {
             QPointF mousePoint = ui->spriteGraphicsEditor->mapToScene( remapped );
             qDebug() << mousePoint;
        }
    }
}

And here is a screenshot of the program(it is still a rough work-in-progress) The blue box shows the approximate area you can click on

It appears that the gray bar on the top is causing the error, as if the area is being defined before the GraphicsScene is being put into place. Why might this happen?

The line where segfault is indicated by coredump shows correct data when printed in gdb

My application crashes randomly on a line 3182 i.e

if(ObjOpnClsStrategy[strIdx].ObjFVStrikesParams[FVStrikeIdx].FastExecMode==1)

But when I print the line in the dump, using gdb, the value and structures seem correct.enter image description here

mardi 29 mars 2022

RegEx: how to batch delete virtual keyword in derived method by Regex?

I'm trying to delete the virtual keyword in the derived method which is an override. Should I use virtual, override, or both keywords?

now I have the several scenario:

virtual void test1() const override;

virtual int test2() override { xxx }

virtual void test3(int p1,
                    int p2,
                    int p3) const override;
virtual void test4(int p1,
                    int p2,
                    int p3,
                    int p4) const override;

virtual void testn(int p1,
                    int p2,
                    int p3,
                    int p4,
                    ......,
                    int pn) const override;

--> I need to delete the virtual keyword for the whole project code(hundreds of files)

void test1() const override;

int test2() override { xxx }

void test3(int p1,
                    int p2,
                    int p3) const override;
void test4(int p1,
                    int p2,
                    int p3,
                    int p4) const override;

void testn(int p1,
                    int p2,
                    int p3,
                    int p4,
                    ......,
                    int pn) const override;

Because there are lots of places that need to modify, I plan to use RegExp to do it. I try the following RegExp:

\bvirtual\b.*\s.*\s.*\s.*\s.*\s.*\s.*\boverride\b

but it seems \s.* need to know the number, is there anyone familiar with RegExp who can help me how to write the expression? and also how to replace and delete the virtual keyword by RegExp? enter image description here

Forward initializer list to map attribute(s)

I would like to use initializer lists to initialize some attributes, here is the code:

#include <initializer_list>
#include <string>
#include <iostream>
#include <map>


using namespace std;

typedef struct A {
  A(initializer_list<pair<string,string>> l1,
    initializer_list<pair<string,string>> l2) : att1(l1), att2(l2)
  {
  }
  map<string, string> att1;
  map<string, string> att2;
} A;

int main (int argc, char *argv[])
{
  A a{
    ,
    ,
  };
  for (auto &[key, value]: a.att1)
    cout << key << ": " << value;
  cout << endl;

  for (auto &[key, value]: a.att2)
    cout << key << ": " << value;
  cout << endl;
  return 0;
}

The compilation fails:

initializer.cpp:11:49: error: no matching constructor for initialization of 'map<std::string, std::string>' (aka 'map<basic_string<char, char_traits<char>, allocator<char>>, basic_string<char, char_traits<char>, allocator<char>>>')
    initializer_list<pair<string,string>> l2) : att1(l1), att2(l2)

How can I forward an initializer list (multiple if possible) from the constructor to initialize some attributes?

Edit: I know that since this is a struct it provide an initializer_listconstructor for its members, but this is a toy example and in the real case I use a class with private members.

C++ user-defined conversions, ref-qualifiers and overload resolution

Please, help me understand what's wrong with this piece of code:

#include <string>
#include <utility>

class Sample
{
public:
    explicit Sample(std::string data):
        _data(std::move(data))
    {}

    operator const std::string &() const & { return _data; }
    operator std::string &&() && { return std::move(_data); }

private:
    std::string _data;
};

int main()
{
    auto sample1 = Sample{"a"};
    const auto sample2 = Sample{"b"};
    auto sample3 = Sample{"c"};

    auto s1 = std::string{sample1};
    auto s2 = std::string{sample2};
    auto s3 = std::string{std::move(sample3)};

    return 0;
}

The problem is with s3. The compiler says sth like that:

<source>: In function 'int main()':
<source>:27:45: error: call of overloaded 'basic_string(<brace-enclosed initializer list>)' is ambiguous
   27 |     auto s3 = std::string{std::move(sample3)};
      |                                             ^
In file included from /opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/string:55,
                 from <source>:1:
/opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/bits/basic_string.h:565:7: note: candidate: 'std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(std::__cxx11::basic_string<_CharT, _Traits, _Alloc>&&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]'
  565 |       basic_string(basic_string&& __str) noexcept
      |       ^~~~~~~~~~~~
/opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/bits/basic_string.h:456:7: note: candidate: 'std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(const std::__cxx11::basic_string<_CharT, _Traits, _Alloc>&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]'
  456 |       basic_string(const basic_string& __str)
      |       ^~~~~~~~~~~~
Compiler returned: 1

As I understand, both of the operators for some reason participate in overload resolution for an rvalue. Why is that happening? Should ref-qualifiers leave only one overload for lvalue and the other for rvalue? Am I missing something?

A few other notes:

  1. The behaviour is different across different compilers/versions. I tested it with godbolt and here is that I found:
    • gcc 8.3 and older - compiles fine
    • gcc 8.4 and newer - fails to compile
    • clang - I couldn't find a version where it compiles
    • MSVC - compiles fine on newest versions
  2. if I refactor operators to normal member functions, it all works as intended

Thank You for Your time, looking forward to any replies :)

Stopping multiple threads at once

What do I miss in the program below with threads waiting for a condition_variable_any to determine when to stop ? In the program listed below, the threads stop in an impredictable way; some before the call to notify_all and some don't stop at all.

The condition variable used is defined as below:

static std::mutex interrupt_mutex;
static std::condition_variable_any interrupt_cv;

The threads check if it is time to stop as below:

std::unique_lock<std::mutex> lock(interrupt_mutex);
const auto cv_status = interrupt_cv.wait_for(lock, std::chrono::milliseconds(1000));
const auto timeout_expired = cv_status == std::cv_status::timeout;
if (!timeout_expired)
{
    quit = true;
}

The main thread signals the threads to stop as below:

std::unique_lock<std::mutex> lock(interrupt_mutex);
interrupt_cv.notify_all();

A possible output looks like:

Thread  1> Received interrupt signal at iteration 2
Thread  1> Terminate
Thread  2> Received interrupt signal at iteration 2
Thread  2> Terminate
Thread  4> Received interrupt signal at iteration 2
Thread  4> Terminate
**** Requesting all threads to stop ****
Waiting for all threads to complete...

Below the complete code that reproduces the problem:

#include <thread>
#include <vector>
#include <mutex>
#include <condition_variable>

static std::mutex interrupt_mutex;
static std::condition_variable_any interrupt_cv;

int main()
{
    std::vector<std::thread> thread_handles;
    for (int thread_idx = 0; thread_idx < 4; ++thread_idx)
    {
        thread_handles.emplace_back(std::thread([thread_idx](const int thread_id)
        {
            int num_iterations = 0;
            auto quit = false;
            while (!quit)
            {
                // Fake processing time during the lock for testing purpose
                std::this_thread::sleep_for(std::chrono::milliseconds(200));
                ++num_iterations;

                // Check if need to stop with a timeout of 200ms 
                {
                    std::unique_lock<std::mutex> lock(interrupt_mutex);
                    const auto cv_status = interrupt_cv.wait_for(lock, std::chrono::milliseconds(1000));
                    if (const auto timeout_expired = cv_status == std::cv_status::timeout; !timeout_expired)
                    {
                        printf("Thread %2d> Received interrupt signal at iteration %d\n", thread_id, num_iterations);
                        quit = true;
                    }
                }
            }

            printf("Thread %2d> Terminate\n", thread_id);
        }, thread_idx + 1));
    }

    std::this_thread::sleep_for(std::chrono::seconds(5));

    // Signals all threads to stop
    {
        printf("**** Requesting all threads to stop ****\n");
        std::unique_lock<std::mutex> lock(interrupt_mutex);
        interrupt_cv.notify_all();
    }

    // Wait until all threads stop
    printf("Waiting for all threads to complete...\n");
    std::ranges::for_each(thread_handles, [](std::thread& thread_handle)
    {
        thread_handle.join();
    });

    printf("Program ends\n");
    return 0;
}

Converting STEP files to XML files [closed]

I'm working on a project and I shoold convert STEP files into XML files using C++, how can I convert them ?

Thank you in advance.

lundi 28 mars 2022

Is there a Queue deque concept avaliable in thread for OpenCV Videowrite writer

I am trying to Write a mp4 file with h264 after writing some text in video frame i have implemented the queue deque concept with boost thread i have tried in both windows and ubuntu. windows with thread in deque works some what fine but same code in Ubuntu based system throws segfault any help will be appreciated

void AddQueue(const Mat &image)
{
    m_tempQueue.push(image);
}
void DeQue(string destFile,int width, int height, int fps) //called with thread 
{
    string szFuncName = "VideoOverlay::DeQue";
        std::unique_lock<std::mutex> mlock(m_Img_Mutex);

    try {
        VideoWriter videocc(destFile, VideoWriter::fourcc('m', 'p', '4', 'v'), fps, cv::Size(width, height));
        while (true)
        {
            if (!m_tempQueue.empty()) {
                cv::Mat image(m_tempQueue.front());
                videocc.write(image);

    //          CLog::AddLogDebug(str(boost::format("Pull : %1%") % m_tempQueue.size()));
                if(!m_tempQueue.empty())
                    m_tempQueue.pop();

                if (m_tempQueue.empty() && !m_ProcessQueue)
                {
                    videocc.release();
                    break;
                }
            }
            else if (!m_ProcessQueue)
            {
                if(videocc.isOpened())
                    videocc.release();
                break;
            }
            //m_Img_Mutex.unlock();
        }
    }catch (...){
        CLog::AddLogDebug(str(boost::format("Error caught at function: %1%")%szFuncName));
//      m_statusCode= 300;
    }
}

//Call method.....
m_thread = std::thread(&VideoOverlay::DeQue, this,destFile,width,height,fps);
//will be called before reading image

The deque thread will run until m_ProcessQueue or image is empty at m_tempQueue

I am looking for samples also

Does std::string needs explicit resizing or does it handles resizing itself?

I am trying to write a std::string in a file and then reading it back. Why do i need to resize the string while reading back the text (see the commented line below while reading back the string)? Doesn't the string handles its size automatically?

#include <iostream>
#include <fstream>

int main()
{
    {
        std::ofstream ofile("c:\\out.txt", std::ios_base::binary);

        if (!ofile.is_open())
        {
            std::cout << "Failed to open the file";
            return 1;
        }

        std::string s = "Hello World";

        try
        {
            ofile.write(s.data(), s.size());
            if (ofile.fail())
            {
                std::cout << "Failed to write the file";
                return 1;
            }
        }
        catch (std::ios_base::failure& e)
        {
            std::cout << e.what();
        }



        ofile.close();
    }

    {
        std::ifstream ifile("c:\\out.txt", std::ios_base::binary);
        if (!ifile.is_open())
        {
            std::cout << "Unable to open input file";
            return 1;
        }
        ifile.seekg(0, std::ios::end);
        auto length = ifile.tellg();
        ifile.seekg(0, std::ios::beg);

        std::string outstr;
        //outstr.resize(length);
        try
        {
            ifile.read(reinterpret_cast<char*>(&outstr.front()), length);
        }
        catch (std::ios_base::failure& e)
        {
            std::cout << e.what();
        }

        std::cout << outstr;
    }
    return 0;
}

Can we use standard C++ threads with wxWidgets and Gtkmm

I have built a GUI application using wxWidgets. In that application, i have also used worker threads etc, for which i used wxThread. Now, i am learning about std::thread in the standard C++. I have also just started learning gtkmm. And i want to use std::thread in my GUI applications. My question is that is it possible and recommended to use std::thread in a wxWidgets and gtkmm based GUI application.

Basically i want to apply what i have learned about std::thread in practical projects.

I have also read this which says:

In C++11 programs, consider using std::thread instead of this class.

My second question is that, does the above quote means that we should(and are allowed to) use std::thread in a wxWidgets based project if we're using C++11(as i am in my project) and std::thread should have higher preference over wxThread when using C++11 in wxWidgets.

can dynamic binding happen without using pointer and using regular object in c++

#include<iostream>
using namespace std;
class Base{
    public:
    virtual void fun(){
        cout<<"Base"<<endl;
    }
};
class Derived:public Base{
    public:
    virtual void fun(){
        cout<<"Derived"<<endl;
    }
};
int main(){
    Derived d1;

    d1.fun(); // which binding work here? static binding or dynamic binding
    return 0;
}

In the above code I just want to know which binding will work in d1.fun() and why that binding happens ?
Please answer clearly if you know

std::thread(&foo::bar ..) throws an error after converting bar from static to non-static method [duplicate]

I have class foo. The bar method used to be static and I was able to create new threads with the code below. I

class foo
{
public:
    static void bar(std::unique_ptr<std::vector<std::string>> pData)
    {
        // do things here
    }
};
auto pDdata = std::unique_ptr<std::vector<std::string>>(new std::vector<std::string>);
std::thread newThread = std::thread(&foo::bar, std::move(pData));

Then I changed the bar method a little. Notice that due to the size_data declaration, bar is no longer static.

    void bar(std::unique_ptr<std::vector<std::string>> pData)
    {
        unsigned short int size_data = pData.get()->size();
        // do things here
    }

At this point, the compiler started giving an error.

/usr/include/c++/7/thread:240:2: error: no matching function for call to ‘std::thread::_Invoker<std::tuple<void ...

Then, I tried changing

std::thread newThread = std::thread(foo::bar, ...)

and I started receiving the following error.

error: invalid use of non-static member function

I'm not sure what's wrong. Any help is appreciated.

Implementation of a parser of nested and optional structure in boost spirit

I would like to implement a parser for a nested (and optional) structure with boos::spirit as "namespace" in C++ language.

What is the simplest way to do it?

Does “M&M rule” applies to std::atomic data-member?

"Mutable is used to specify that the member does not affect the externally visible state of the class (as often used for mutexes, memo caches, lazy evaluation, and access instrumentation)." [Reference: cv (const and volatile) type qualifiers, mutable specifier]

This sentence made me wonder:

"Guideline: Remember the “M&M rule”: For a member-variable, mutable and mutex (or atomic) go together." [Reference: GotW #6a Solution: Const-Correctness, Part 1 (updated for C ++11/14)]

I understand why “M&M rule” applies to std::mutex data-member: to allow const-functions to be thread-safe despite they lock/unlock the mutex data-member, but does “M&M rule” applies also to std::atomic data-member?

Ensure destroy function is called

Somebody use shared pointer to ensure that the aforementioned handle are destroyed when it's no longer needed.

In practice, the implementation of InitDemoStruct() DestroyStruct() struct DemoStruct are opaque to me.They are provided by others.

Although this code snippet works as expected, but it looks strange indeed:

It's commonly seen that a smart pointer points to a specific class or struct, e.g: std::shared_ptr<struct DemoSt> ptr2object; Recently, I saw such usage. Use smart pointer to pointer to a pointer of a specific class or struct, e.g:std::shared_ptr<struct DemoSt*> ptr2point_of_object;

UPDATED: There is an answer provided by nwp.

Here is the aforementioned code snippet:

#include <memory>
#include <iostream>

struct DemoStruct;
using DemoStructHandle = DemoStruct* ;

//In practice, the implementation of  `InitDemoStruct()` `DestroyStruct()` `struct DemoStruct` is opaque to me.
//They are provided by others.
struct DemoStruct{
};


void InitDemoStruct(DemoStructHandle* handle_ptr){
    *handle_ptr = new DemoStruct(); 
    //may do some other meaningful init in InitDemoStruct(); 
    };


void DestroyStruct(DemoStructHandle* handle_ptr){
    std::cout << "Destroy() is called" << std::endl;
    if(handle_ptr==nullptr){
        return;
    }

    delete *handle_ptr;
}

//I use shared pointer to ensure that the aforementioned handle is destroyed when it's no longer needed.
std::shared_ptr<DemoStructHandle> MakeDemoStructHandlePtr(void)
{  
    return std::shared_ptr<DemoStructHandle>(new DemoStructHandle(nullptr), [](DemoStructHandle* pHandle){
        DestroyStruct(pHandle);
        delete pHandle;});
}


int main()
{
    std::shared_ptr<DemoStructHandle> demo_class_handle_ptr = MakeDemoStructHandlePtr();
    InitDemoStruct(demo_class_handle_ptr.get());           
}

dimanche 27 mars 2022

Conversion of data of types ( uint8_t, uint16_t and uint32_t ) to int32_t and viceversa

I am new to Embedded Linux platform and C++14. Need to convert different data of types ( uint8_t, uint16_t and uint32_t ) to int32_t and back to the original datatypes ( uint8_t uint16_t and uint32_t ) from int32_t. Is this possible and suggest the ways to do this

Changing this encryption application to handle multiple files

Currently trying to modify this code to handle multiple input files iteratively.

The current functionality takes a single file as input and outputs a single encrypted file, but I would like to improve on this program by allowing it to potentially loop through the current folder, and encrypting all files beginning with 'inputdatafile'

If the current folder has 'inputdatafile1', 'inputdatafile2', 'inputdatafile3'... and so on how could I handle this dynamically?

#include <cassert>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <chrono>
#include <ctime>
#include <time.h>
using namespace std;

/// <summary>
/// encrypt or decrypt a source string using the provided key
/// </summary>
/// <param name="source">input string to process</param>
/// <param name="key">key to use in encryption / decryption</param>
/// <returns>transformed string</returns>
std::string encrypt_decrypt(const std::string& source, const std::string& key)
{
    // get lengths now instead of calling the function every time.
    // this would have most likely been inlined by the compiler, but design for perfomance.
    const auto key_length = key.length();
    const auto source_length = source.length();

    // assert that our input data is good
    assert(key_length > 0);
    assert(source_length > 0);

    std::string output = source;
    
    // loop through the source string char by char
    for (size_t i = 0; i < source_length; ++i)
    {// transform each character based on an xor of the key modded constrained to key length using a mod
        output[i] = source[i]^key[i % key_length];
    }

    // our output length must equal our source length
    assert(output.length() == source_length);

    // return the transformed string
    return output;
}

std::string read_file(const std::string& filename)
{
    std::string file_text = "John Q. Smith\nThis is my test string";

    // TODO: implement loading the file into a string
    //open file_text
    std::ifstream ifile(filename);
    //read the file entirely into string
    std::getline(ifile, file_text, '\0');
    //return text
    return file_text;
}

std::string get_student_name(const std::string& string_data)
{
    std::string student_name;

    // find the first newline
    size_t pos = string_data.find('\n');
    // did we find a newline
    if (pos != std::string::npos)
    { // we did, so copy that substring as the student name
        student_name = string_data.substr(0, pos);
    }

    return student_name;
}

void save_data_file(const std::string& filename, const std::string& student_name, const std::string& key, const std::string& data)
{
    //  TODO: implement file saving
    //  file format
    //  Line 1: student name
    //  Line 2: timestamp (yyyy-mm-dd)
    //  Line 3: key used
    //  Line 4+: data

    //file stream
    std::fstream myFile;

    //open file in write mde
    myFile.open("student.txt", ios::out);

    //time object to enter time
    time_t my_time = time(NULL);
    //auto start = std::chrono::system_clock::now();
    //auto legacyStart = std::chrono::system_clock::to_time_t(start);

    //in case file is opening get an error
    if (myFile.is_open()) {
        // get the date time
        auto t = std::time(nullptr);
        struct tm buf;
        auto tm = localtime_s(&buf, &t);

        // open the file
        std::ofstream stream(filename);

        // write student name
        stream << student_name << std::endl;

        // write timestamp
        stream << std::put_time(&buf, "%Y-%m-%d") << std::endl;

        // write key
        stream << key << std::endl;

        // write data
        stream << data << std::endl;

        // force all buffers to be written to disk
        stream.flush();

        // close the stream - we are done
        stream.close();
    }
    else {
        cout << "Error in opening the file";
    }
}

int main()
{
    std::cout << "Encyption Decryption Test!" << std::endl;

    // input file format
    // Line 1: <students name>
    // Line 2: <Lorem Ipsum Generator website used> https://pirateipsum.me/ (could be https://www.lipsum.com/ or one of https://www.shopify.com/partners/blog/79940998-15-funny-lorem-ipsum-generators-to-shake-up-your-design-mockups)
    // Lines 3+: <lorem ipsum generated with 3 paragraphs> 
    //  Fire in the hole bowsprit Jack Tar gally holystone sloop grog heave to grapple Sea Legs. Gally hearties case shot crimp spirits pillage galleon chase guns skysail yo-ho-ho. Jury mast coxswain measured fer yer chains man-of-war Privateer yardarm aft handsomely Jolly Roger mutiny.
    //  Hulk coffer doubloon Shiver me timbers long clothes skysail Nelsons folly reef sails Jack Tar Davy Jones' Locker. Splice the main brace ye fathom me bilge water walk the plank bowsprit gun Blimey wench. Parrel Gold Road clap of thunder Shiver me timbers hempen halter yardarm grapple wench bilged on her anchor American Main.
    //  Brigantine coxswain interloper jolly boat heave down cutlass crow's nest wherry dance the hempen jig spirits. Interloper Sea Legs plunder shrouds knave sloop run a shot across the bow Jack Ketch mutiny barkadeer. Heave to gun matey Arr draft jolly boat marooned Cat o'nine tails topsail Blimey.

    const std::string file_name = "inputdatafile.txt";
    const std::string encrypted_file_name = "encrypteddatafile.txt";
    const std::string decrypted_file_name = "decrytpteddatafile.txt";
    const std::string source_string = read_file(file_name);
    const std::string key = "password";

    // get the student name from the data file
    const std::string student_name = get_student_name(source_string);

    // encrypt sourceString with key
    const std::string encrypted_string = encrypt_decrypt(source_string, key);

    // save encrypted_string to file
    save_data_file(encrypted_file_name, student_name, key, encrypted_string);

    // decrypt encryptedString with key
    const std::string decrypted_string = encrypt_decrypt(encrypted_string, key);

    // save decrypted_string to file
    save_data_file(decrypted_file_name, student_name, key, decrypted_string);

    std::cout << "Read File: " << file_name << " - Encrypted To: " << encrypted_file_name << " - Decrypted To: " << decrypted_file_name << std::endl;

    // students submit input file, encrypted file, decrypted file, source code file, and key used
}

Priority of template constructor

I have the template class Foo:

template<class T>
class Foo {
public:
    Foo() = default;
    Foo(const Foo&) = default;
    Foo(Foo&&) = default;
    Foo& operator=(Foo&&) = default;
    Foo& operator=(const Foo&) = default;

    template<class U, typename = typename std::enable_if<
            !std::is_same<typename std::decay<U>::type, Foo>::value>::type>
    Foo(U&&) {

    }
};

int main() {
    Foo<int> ff;
    Foo<char> dd(ff); //here I want a compiler error
    Foo<int> e(15); //it should work
    return 0;
}

I'm trying to add constraints about template constructor, however this code compiles so I think I'm missing something, what's the proper way to add the enable_if?

samedi 26 mars 2022

How to convert string having characters or ip address to integer and back from integer to the original string

I need to convert a string having characters and digits( eg,an ipaddress or xyz123) to integer to store in DB and while retrieving needs to convert the integer to the same string as xyz123. How can I do this in C++14.

I have used the stoi function to convert from string to int and it's creasing with the error terminate called after throwing an instance of 'std::invalid_argument' what(): stoi

Also using atoi(str.c_str()) outputs only the digits in the string.

While converting this integer to string, I am getting back only the digits and cannot construct the original string which I have converted.

Is it correct overloaded operator declaration? [duplicate]

I am learing for exam and need to know if this declaration of operator+ is correct, it works as I wish but I am not sure how it works.

#include <iostream>
using namespace std;

class name {
private:
    string word;

public:
    name(const string& a1) :word(a1) {}

    friend name& operator+(const string& la, name& ra);
    friend ostream& operator<<(ostream& out, const name& r);
};

ostream& operator<<(ostream& out, const name& r) {
    return out<<r.word;
}

name& operator+(const string& la, name& ra) {
    ra.word = la + ra.word;
    return ra;
}

int main() {
    name obj("overflow");
    obj = "stack" + obj;
    cout << obj << endl;
}

I was just editing my operator+ until it compiles and somehow this one comiples.

vendredi 25 mars 2022

Strange race condition when calling pthread_getschedparam from within a C++11 std::thread's thread-function?

I have some (not-very-portable) code that allows me to use the pthread library's pthread_getschedparam() and pthread_setschedparam() functions to set the priority of a C++11 thread, at least on platforms where C++11's threads are implemented on top of PThreads.

I call these two pthread-functions from within the C++11's thread-entry function itself.

However, I've noticed a strange race-condition like problem: sometimes pthread_getschedparam() returns error code ESRCH/3 (aka "No such process"). If I then repeat the call in a loop, it eventually works.

This seems very odd to me, since I'm calling these functions from within the very thread that the functions occasionally think doesn't exist.

Below is a toy example program that reproduces the fault for me (both under MacOS12.3 and Ubuntu 20):

#include <thread>
#include <pthread.h>
#include <stdio.h>
#include <string.h>

static void InternalThreadEntryFunc(std::thread * threadPtr)
{
   int schedPolicy;
   sched_param param;

   int ret = 1;
   int errors = 0;
   while(ret != 0)
   {
      ret = pthread_getschedparam(threadPtr->native_handle(), &schedPolicy, &param);
      if (ret != 0) {errors++; printf("ret=%i [%s]\n", ret, strerror(ret));}
   }
   if (errors) printf("errors=%i\n", errors);
}

int main(int, char **)
{
   while(1)
   {
      std::thread thread;

      thread = std::thread(InternalThreadEntryFunc, &thread);
      thread.join();
   }

   return 0;
}

The output I get from the above program looks like this (with more output being printed periodically, every few seconds):

$ ./a.out 
ret=3 [No such process]
errors=1
ret=3 [No such process]
ret=3 [No such process]
errors=2
ret=3 [No such process]
ret=3 [No such process]
ret=3 [No such process]
ret=3 [No such process]
ret=3 [No such process]
errors=5
ret=3 [No such process]
errors=1
[...]

Does anyone know what is causing these errors, or what I might do to resolve them elegantly? (simply retrying the call until it works is the non-elegant solution, of course)

GDI OBJECTS LEAK

I encounter a problem with GDI OBJECTS increasing. How can I solve this problem?

The DeleteObject() function doesn`t help.

vvv PROBLEM PICTURE BELOW vvv

PROBLEM PICTURE

// Other Events

GetClientRect(hAnimationStars, &Dimensions);

AnimationStarsDC = BeginPaint(hAnimationStars, &ps);

MemoryDC = CreateCompatibleDC(AnimationStarsDC);
HBITMAP Bitmap = CreateCompatibleBitmap(AnimationStarsDC, Dimensions.right, Dimensions.bottom);

SelectObject(MemoryDC, Bitmap);
SetBkMode(MemoryDC, TRANSPARENT);
FillRect(MemoryDC, &Dimensions, CreateSolidBrush(BackgroundColor));

// Draw Operations

BitBlt(AnimationStarsDC, 0, 0, Dimensions.right, Dimensions.bottom, MemoryDC, 0, 0, SRCCOPY);

while (!DeleteDC(MemoryDC));
while (!DeleteObject(Bitmap));
    
EndPaint(hAnimationStars, &ps);

// Other Events

arithmetic operator overload c++ for different types

I have a class 'number' with one member 'm_value' of type int64_t. I already overloaded += operator, there is code:

number& operator+=(const number& right);

and it works fine with different types (e.g. int, int64_t, short, etc). In same way I overloaded + operator:

number operator+(const number& right);

But when I try to add class object with int64_t variable, it gives following error:

use of overloaded operator '+' is ambiguous (with operand types 'number' and 'int64_t' (aka 'long'))

Of course, I can overload the operator for other types, but I'm wondering if there is another solution for this problem and why, in the case of the first operator, the conversion from one type to another occurs automatically?

Thanks in advice!

UPD: Here is class header:

class number {
private:
    int64_t m_value;
public:
    number();
    number(int64_t value);
    number(const number& copy);
 
    number& operator=(const number& other);
 
    number& operator++();
    number operator++(int);
 
    number& operator--();
    number operator--(int);
 
    number& operator+=(const number& right);
    number& operator-=(const number& right);
    number& operator*=(const number& right);
    number& operator/=(const number& right);
    number& operator%=(const number& right);
 
    number& operator&=(const number& right);
    number& operator|=(const number& right);
    number& operator^=(const number& right);
 
    number operator+(const number& right);
    number operator-(const number& right);
    number operator*(const number& right);
    number operator/(const number& right);
    number operator%(const number& right);
    
    number operator&(const number& right);
    number operator|(const number& right);
    number operator^(const number& right);
 
    operator bool() const;
    operator int() const;
    operator int64_t() const;
    operator std::string() const;
 
    friend std::ostream& operator<<(std::ostream& out, const number& num);
    friend std::istream& operator>>(std::istream& in, number& num);
};

signal: killed / std::bad_alloc What is making it order a kill

This code is meant to solve this Question. The Results show me getting test case 2&3 right but all the other cases provided a "std::bad alloc" and even when i run the cases on my side it says "Killed" in terminal! I have no idea what the problem is.

//Includes-------------------------------------------
#include <iostream>     //for using cout
#include <cmath>//for math
#include <math.h>
#include <algorithm>
#include <stdio.h>
#include <locale>
#include <vector>

using namespace std;
//Includes-------------------------------------------

//var------------------------------------------------
int n,k,inp,nhold,plates,platesb,platesc,moves;
vector<int> s1,s2,s3;
//var------------------------------------------------

void complete(){
    cout<<"\n WORKED!🍻\n";
}

void plateexe(){
    while(1!=0){
        platesb=(s2.size())-1;
        platesc=(s3.size())-1;
        if(s3[platesc]==1){
            moves++;
            s1.push_back(s3[platesc]);
            s3.pop_back();
        }
        if(s2[platesb]==1){
            moves++;
            s1.push_back(s2[platesb]);
            s2.pop_back();
        }
        if(s2[platesb]!=1){
            if(s3[platesc]!=1){
                break;
            }
        }
    }
}

int main(){
    cin>>n;
    nhold=n;
    while(n!=0){
        n--;
        cin>>inp;
        s1.push_back(inp);
    }
    n=nhold;
    s2.push_back(moves);
    s3.push_back(moves);
    while(n!=0){
        plates=(s1.size())-1;
        platesb=(s2.size())-1;
        platesc=(s3.size())-1;
        n--;
        if(s1[plates]==3){
            if(s3[platesc]==1){
                while(s3[platesc]==1){
                    moves++;
                    s2.push_back(s3[platesc]);
                    s3.pop_back();
                }
                moves++;
                s3.push_back(s1[plates]);
                s1.pop_back();
            }else{
                moves++;
                s3.push_back(s1[plates]);
                s1.pop_back();
            }
        }else if(s1[plates]==2){
            if(s2[platesb]==1){
                while(s2[platesb]==1){
                    moves++;
                    s3.push_back(s2[platesb]);
                    s2.pop_back();
                }
                moves++;
                s2.push_back(s1[plates]);
                s1.pop_back();
            }else{
                moves++;
                s2.push_back(s1[plates]);
                s1.pop_back();
            }
        }else if(s1[plates]==1){
            if(s1[plates-1]==2){
                moves++;
                s3.push_back(s1[plates]);
                s1.pop_back();
            }else if(s1[plates-1]==3){
                moves++;
                s2.push_back(s1[plates]);
                s1.pop_back();
            }else{
                if(plates!=0){
                    moves++;
                    s2.push_back(s1[plates]);
                    s1.pop_back();
                }else{
                    if(s1[plates]==1){
                        s2.push_back(s1[plates]);
                        s1.pop_back();
                        platesb=(s2.size())-1;
                        s1.push_back(s2[platesb]);
                        s2.pop_back();
                    }
                }
            }
        }
    }
    plateexe();
    cout<<moves;
}

`

When I was writing it i hadn't added added the code below:

if(plates!=0){
                    moves++;
                    s2.push_back(s1[plates]);
                    s1.pop_back();
                }else{
                    if(s1[plates]==1){
                        s2.push_back(s1[plates]);
                        s1.pop_back();
                        platesb=(s2.size())-1;
                        s1.push_back(s2[platesb]);
                        s2.pop_back();
                    }
                }

I gave me a simple not right answer but good for 2&3 but now its giving me this bad alloc error/ signal: killed.

jeudi 24 mars 2022

Initialize POD with two arrays using a factory function in C++11

I need to POD-initialize a struct of multiple arrays from a factory function. How do I forward its parameters to the brace-init list that is required to create the POD-struct (C++11)? I get this error:

<source>: In instantiation of 'constexpr generic_option<N, K> create_option(const int (&&)[N], const int (&&)[K]) [with long unsigned int N = 2; long unsigned int K = 2]':
<source>:209:32:   required from here
<source>:204:48: error: array must be initialized with a brace-enclosed initializer
  204 |     return generic_option<N, K>{to_wait, to_set};
      |                                                ^
<source>:204:48: error: array must be initialized with a brace-enclosed initializer
<source>:205:1: error: body of 'constexpr' function 'constexpr generic_option<N, K> create_option(const int (&&)[N], const int (&&)[K]) [with long unsigned int N = 2; long unsigned int K = 2]' not a return-statement
  205 | }
      | ^

My code:

template <size_t N, size_t K>
struct generic_option
{
    int to_wait_[N];
    int to_set_[K];
};

template <size_t N, size_t K>
constexpr generic_option<N, K> create_option(const int (&&to_wait)[N], const int (&&to_set)[K]) {
    return generic_option<N, K>{to_wait, to_set};
}

int main()
{
    create_option({1,4}, {2,3});
}

The reason for this post is that I can find information on how to initialize a struct of arrays with brace initializers using literals. But I can't seem to find a resource that states how to initialize them using compile time variables such as the ones passed to the factory function.

Pybind11 : available array_t constructors

I want to create an array_t from a double* and size.

I did not find a constructor mentioned explicitely in the docs.

I tried to copy this thread : PyBind11 : returning c++ array as numpy array changes values

But when I try, I get an error : fatal error: no matching constructor for initialization of 'py::array_t' py::array_t test = py::array_t({size, DIM},{DIM*8, 8}, data);

where size and dim are unsigned int and data is a double*.

How can I construct an array_t, and, more importantly, where is this information available ?

How to use ... in a class template specialization?

This is an example with ... in the middle position of a template, however I cant understand what it means.

template <typename T, T f> class Invalid;
template <typename T1, typename... Args, T1 (*f)(Args...)>
class Invalid<T1 (*)(Args...), f>
{};

The following also works for me and is easy to comprehend.

template <typename... Args> class Invalid;
template <typename T1, typename... Args>
class Invalid<T1 (*)(Args...), T1>
{};

Why would I use the first one instead of the second?

How to create/destroy objects in "modern" C++?

I am porting C# app into C++ linux app. I am confused with construction and destruction in "modern" (C++11 ?). I always thought you have to use new/delete but now it appears C++ recommendation is not to do so (is this correct or I read a wrong blog?).

What I have roughly (there are 6 subclasses of B and BRec atm):

class ARec : public BRec
class A : public B
. . .
class Factory
  BRec GetRecord(WrapperStruct s)
  {
    if(s.Type == 'A')
    {
      A* a = (A*)s.Data;
      auto rec = ARec((ushort)a->Num);
      rec.OtherField = a.OtherField;
      return rec;
    }
. . .
main

// separate pthread
void* Logger(void* arg) {

    int* thread_state = (int*)arg;

    auto f = Factory();

    WrapperStruct item;

    while (true)
    {
      q->try_dequeue(item);

      auto rec = f.GetRecord(item);
      auto bytes = f.GetBytes(rec);

      // write bytes to file ...

      delete bytes;

      if(*thread_state == -1)
        pthread_exit(0);
    }

Question - how does compiler would know when to delete s.Data in factory method? Same - rec if it was created in a class method and then crossed to other method (while in Logger)? Is there a simple guide how to manage variables' memory in C++11 ?

EDIT: s.Data contains ref to an object created in a 3rd party dll and can be of different types hence the s.Type field

mercredi 23 mars 2022

In symbol table how to mark variable out of scope?

I am writing a toy compiler, which compile a c/c++ like language to c++. I am using bison, but in this structure is hard to handle when variable became out of scope.

In the source lanugage in the whole main function there can be only one variable with the same name, it is good, but there is a problem what I cannot solve.

I cannot make c++ code like this, because c++ compiler throw semantical error: 'var' was not declared in this scope.

    int main()
    {
        if (true)
        {
            int var = 4;
        }
        if (true)
        {
            var = 5;
        }
    }

The source language has while, if and if/else statements. I have to throw semantical error if a declared variable is assinged in out of scope. For example:

This should be semantical error, so I cannot generetad this code:

int main()
{
    while(0)
    {
        int var = 1;
    }

    if (1)
    {
        var = 2;
    }
}

This also have to be semantical error:

int main()
{
    if (0)
    {
        int var = 1;
    }
    else
    {
        if (1)
        {
            var = 5;
        }
    }
}

And this is allowed, I can generate this code:

int main()
{
    if (0)
    {

    }
    else
    {
        int var = 1;
        if (1)
        {
            while (0)
            {
                while (0)
                {
                    var = 2;
                }
            }
        }
    }
}

I tried lot of things, but I cannot solve when there is nested if, if/else or while.

I read tons of tutorials about symbol table, but none of them can explain properly how to manage a variable if it is become out of scope.

If you familiar with this topic and with bison, please do not just give me hints, like "use stack, and mark a variable if it become out of scope". I found lot of article about it. Instead of please give me pseudocode or concrate implementation sketch.

I think it cannot be so much difficult, because in the whole main function there can be one variable with the same name as I wrote.

Symbol table:

struct SymbolType
{
    int lineNumber;
    std::string identifier;
    int identifierValue;
    Type type;
    int functionArgumentNumber;
    Type functionReturnType;
    Type markType;
    bool outOfScope;
};

    class Symbol
    {
        public:
            void AddVariable(int _lineNumber, std::string _identifier, int _identifierValue, Type _type, int _functionArgumentNumber, Type _functionReturnType, Type _markType, bool _outOfScope);
            void AddMarker(int _lineNumber, std::string _scopeName, Type _markType);
            bool FindVariable(std::string _identifier);
            int FindVariableValue(std::string _identifier);
            void Remove();
            void Print();
            std::vector<SymbolType> symbolTable;

        private:
            int lineNumber;
            std::string identifier;
            int identifierValue;
            Type type;
            int functionArgumentNumber;
            Type functionReturnType;
            Type markType;
            bool outOfScope;
    };

GDB not updating variable

I am working on a c++ code for solving fluid dynamics problems,

I am changing a templated class to store two static variables. I am also creating two separate functions to change the corresponding value:

static int sizeOfTensor;
static void setSize(const int& newSize);

static int hOp;
static void sethOp(const int& newSize);

And their corresponding implementation:

template <class Cmpt, int length>
int  myTensor<Cmpt, length>::sizeOfTensor = length;

template <class Cmpt, int length>
void myTensor<Cmpt, length>::setSize(const int& newSize)
{
sizeOfTensor = newSize;
}

template <class Cmpt, int length>
int  myTensor<Cmpt, length>::hOp = length;

template <class Cmpt, int length>
void myTensor<Cmpt, length>::sethOp(const int& newSize)
{
    hOp = newSize;
}

When I execute these functions in the code:

myTensor<double,4> a;

myTensor<double,4>::sethOp(2);

myTensor<double,4>::setSize(3);

std::cout << myTensor<double,4>::hOp << std::endl;

In gdb the variable sizeOfTensor will change its value but the hOp won't. However, if I ask to print the value it is the correct one.

Why is this happening?!

Best Regards

C++11 How to create template function to convert primitives and std::vector to std::string with minimum specializations?

The point where I stuck is described in the title.

But, maybe, there are another solution of my global problem.

There are template base class, which do some work, and I need to print results for debugging purposes.


template<typename ResultType>

class Foo

{

public:

    void PrintResult()

    {

        std::cout<<toString<ResultType>(result)<<std::endl;

    }

    virtual void Do(std::vector<void*> args)=0;

    virtual ~Foo(){}

protected:

    ResultType result;

};

I need mostly to print primitives, std::string, and std::vector of primitives, strings or vectors.

I decided to use templates for this, but I can not specialize template for std::vector. I don't know why it choose wrong overload.


#include <iostream>

#include <sstream>

#include <vector>

template <typename T>

std::string toString(const T& obj)

{

    return std::to_string(obj);

}

template <typename T>

std::string toString(const std::vector<T>& obj)

{

    std::stringstream ss;

    ss<<"[";

    for(size_t i=0;i<obj.size();++i)

    {

        ss<<toString<T>(obj[i]);

        if(i!=obj.size()-1)

            ss<<", ";

    }

    ss<<"]";

    return ss.str();

}

int main()

{

    int intValue = 42;

    std::vector<int> vectorOfInts;

    std::vector<std::vector<double>> vectorOfVectorsOfDoubles;

    std::cout<<toString<int>(intValue)<<std::endl;

    std::cout<<toString<std::vector<int>>(vectorOfInts)<<std::endl;

    std::cout<<toString<std::vector<std::vector<double>>>(vectorOfVectorsOfDoubles)<<std::endl;

    return EXIT_SUCCESS;

}

Errors:


./main.cpp:-1: In instantiation of ‘std::__cxx11::string toString(const T&) [with T = std::vector<int>; std::__cxx11::string = std::__cxx11::basic_string<char>]’:

./main.cpp:33: required from here

./main.cpp:8: error: no matching function for call to ‘to_string(const std::vector<int>&)’

     return std::to_string(obj);

            ~~~~~~~~~~~~~~^~~~~

./main.cpp:-1: In instantiation of ‘std::__cxx11::string toString(const T&) [with T = std::vector<std::vector<double> >; std::__cxx11::string = std::__cxx11::basic_string<char>]’:

./main.cpp:34: required from here

./main.cpp:8: error: no matching function for call to ‘to_string(const std::vector<std::vector<double> >&)’

     return std::to_string(obj);

            ~~~~~~~~~~~~~~^~~~~

Compiler:

GCC 4.8 (C++, x86 64bit)

Is there any possibilities not to specialize template function with all primitives and vectors?

I tried adapt solution from C++ How to specialize a template using vector<T>? with fix for c++11 from https://ru.stackoverflow.com/questions/500735/stdenable-if-t

But I still get errors:

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

template<bool C, class T = void>
using enable_if_t = typename std::enable_if<C, T>::type;

template<typename T>
struct is_vector
{
    static constexpr bool value = false;
};

template<template<typename...> class C, typename U>
struct is_vector<C<U>>
{
    static constexpr bool value =
        std::is_same<C<U>,std::vector<U>>::value;
};

template <typename T>
enable_if_t<!is_vector<T>::value,std::string> toString(T& obj)
{
    return std::to_string(obj);
}

template <typename T>
enable_if_t<is_vector<T>::value,std::string> toString(std::vector<T>& obj)
{
    std::stringstream ss;
    ss<<"[";
    for(size_t i=0;i<obj.size();++i)
    {
        ss<<toString<T>(obj[i]);
        if(i!=obj.size()-1)
            ss<<", ";
    }
    ss<<"]";
    return ss.str();
}

int main()
{
    int intValue = 42;
    std::vector<int> vectorOfInts;
    std::vector<std::vector<double>> vectorOfVectorsOfDoubles;

    std::cout<<toString<int>(intValue)<<std::endl;
    std::cout<<toString<std::vector<int>>(vectorOfInts)<<std::endl;
    std::cout<<toString<std::vector<std::vector<double>>>(vectorOfVectorsOfDoubles)<<std::endl;
    return EXIT_SUCCESS;
}
./main.cpp:-1: In function ‘int main()’:
./main.cpp:50: error: no matching function for call to ‘toString<std::vector<int, std::allocator<int> > >(std::vector<int>&)’
     std::cout<<toString<std::vector<int>>(vectorOfInts)<<std::endl;
                                                       ^
./main.cpp:23: candidate: template<class T> enable_if_t<(! is_vector<T>::value), std::__cxx11::basic_string<char> > toString(T&)
 enable_if_t<!is_vector<T>::value,std::string> toString(T& obj)
                                               ^~~~~~~~
./main.cpp:23: note:   template argument deduction/substitution failed:
./main.cpp:29: candidate: template<class T> enable_if_t<is_vector<T>::value, std::__cxx11::basic_string<char> > toString(std::vector<T>&)
 enable_if_t<is_vector<T>::value,std::string> toString(std::vector<T>& obj)
                                              ^~~~~~~~
./main.cpp:29: note:   template argument deduction/substitution failed:
./main.cpp:50: note:   cannot convert ‘vectorOfInts’ (type ‘std::vector<int>’) to type ‘std::vector<std::vector<int>, std::allocator<std::vector<int> > >&’
     std::cout<<toString<std::vector<int>>(vectorOfInts)<<std::endl;
                                                       ^
./main.cpp:51: error: no matching function for call to ‘toString<std::vector<std::vector<double, std::allocator<double> >, std::allocator<std::vector<double, std::allocator<double> > > > >(std::vector<std::vector<double> >&)’
     std::cout<<toString<std::vector<std::vector<double>>>(vectorOfVectorsOfDoubles)<<std::endl;
                                                                                   ^
./main.cpp:23: candidate: template<class T> enable_if_t<(! is_vector<T>::value), std::__cxx11::basic_string<char> > toString(T&)
 enable_if_t<!is_vector<T>::value,std::string> toString(T& obj)
                                               ^~~~~~~~
./main.cpp:23: note:   template argument deduction/substitution failed:
./main.cpp:29: candidate: template<class T> enable_if_t<is_vector<T>::value, std::__cxx11::basic_string<char> > toString(std::vector<T>&)
 enable_if_t<is_vector<T>::value,std::string> toString(std::vector<T>& obj)
                                              ^~~~~~~~
./main.cpp:29: note:   template argument deduction/substitution failed:
./main.cpp:51: note:   cannot convert ‘vectorOfVectorsOfDoubles’ (type ‘std::vector<std::vector<double> >’) to type ‘std::vector<std::vector<std::vector<double> >, std::allocator<std::vector<std::vector<double> > > >&’
     std::cout<<toString<std::vector<std::vector<double>>>(vectorOfVectorsOfDoubles)<<std::endl;
                                                                                   ^

mardi 22 mars 2022

Getting garbage values when printing a string character by character

So, I was trying to code a problem and It required me to copy a string from certain index to another string.

After an hour of debugging, I found that my string was actually consisting of garbage values.

Can anyone explain why? I have been using this approach forever and It's the first time I faced this issue.

Original Problem is unrelated to this question so I am just sharing my approach.

My approach was :

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

int main(){

   string s;
   cin>>s;

   int idx;
   cin>>idx;

   string ans;

   for(int i=idx;i<ans.length();i++){
       ans+=s[i];
   }

   cout<<ans<<endl;

}

Input:
   ()(()
   1
    

Output:
   0d0a 290d 0a28 2828

Regarding R values

#include <iostream>
#include <ctime>
#include <chrono>
#include "Person.h"
#include "SmartPerson.h"
using namespace std;

void print_name(const Person& test);
void print_name_2(const Person&& test);

int main()
{
    print_name(Person{ 21, "Juan", "Hispanic" });

    return 0;
}

void print_name(const Person& test)
{
    cout << "L value!" << endl;
    cout << test.get_name() << endl;
}
void print_name_2(const Person&& test)
{
    cout << "R value!" << endl;
    cout << test.get_name() << endl;
} 

Why is the function print_name called instead of print_name_2 in the above case? Even though it was an R-value being passed? I also want to know, what the purpose of a reference to a constant R-value is.

The value of a must be 56 but when i run this program i am getting 0

#include <iostream>
using namespace std;
class CSR {
private:
    int complaintsResolved;
    static int totalComplaintsResolved;

public:
    void setComplaintsResolved(int cpsResolved)
    {
        if (cpsResolved < 0)
            return;
        complaintsResolved = cpsResolved;
    }
    static void setTotalCpsResolved(int totalCpsResolved)
    {
        totalComplaintsResolved = totalCpsResolved;
    }
    int getComplaintsResolved()
    {
        return complaintsResolved;
    }
    static int getTotalCpsResolved()

    {
        return totalComplaintsResolved;
    }
};
int CSR::totalComplaintsResolved = 0;

void calcTotalComplaints(CSR employees[7])
{
    int a = 0;
    for (int i = 0; i < 7; i++)
        a += employees[i].getTotalCpsResolved();
    cout << a;
    CSR::setTotalCpsResolved(a);
}
int main()
{
    CSR employees[7];
    for (int i = 0; i < 7; i++) {

        employees[i].setComplaintsResolved((i + 1) * 2);
    }
    calcTotalComplaints(employees);
}

Test Cases

TEST(Q5, second)
{
    CSR employees[7];
    for (int i = 0; i < 7; i++) {
        employees[i].setComplaintsResolved((i + 1) * 2);
    }
    calcTotalComplaints(employees);
    ASSERT_EQ(56, CSR::getTotalCpsResolved());

I am trying to test this program on google test but test cases fails. This code is supposed to give me 56 in the output but i am getting 0 in output kindly look into this and tell me where is the mistake? Also tell me about the scope of static variables like how can i access private static variable outside the class

C++ Instance new Lua table with __index

I was trying to create exemplar of table in C++ which is defined in Lua. In short, i was trying to rewrite this behavior in C++

function Account:new (o)
    o = o or {}   -- create object if user does not provide one
    setmetatable(o, self)
    self.__index = self
    return o
end

int FLua::CreateTable(const char* name)
{
    LogLua(ELogVerbosity::Warning, "Creating new exemplar of table", name);

    lua_createtable(L, 0, 1);
    luaL_getmetatable(L, name);
    lua_setfield(L, -2, "__index");

    int index = luaL_ref(L, LUA_REGISTRYINDEX);

    return index;
}

This code doesnt work.

lundi 21 mars 2022

function call operator in class or method?

class foo
{
public:
    struct bar
    {
        bar() {}
        int bar_var;
    };

    operator std::vector<bar>() {
        return m_list;
    }

private:
    std::vector<bar> m_list;
    int foo_var;
};

Here defined a class foo, what is the semantic "operator std:vector<bar>()" mean here? I don't think it is an overloaded function call operator.

Compile with the above code works OK

Is there an issue with "cache coherence" on C++ multi-threading on a *Single CPU* (Multi-Core) on Windows?

Is it possible (A single CPU case: Windows can run on top of Intel / AMD / Arm CPU), that thread-1 runs on core-1 store a bool variable (for example) and it stays in L1 cache, and thread-2 runs on core-n uses that bool variable, and it looks on another instance of it (the instance that is in the memory?

Code example (For demonstrating the issue, lets say that the std::atomic_bool was just a bool):

#include <thread>
#include <atomic>
#include <chrono>

std::atomic_bool g_exit{ false }, g_exited{ false };

using namespace std::chrono_literals;

void fn()
{
    while (!g_exit.load(std::memory_order_relaxed))
    {
        // do something (lets say it took 5s)
        std::this_thread::sleep_for(5s);
    }

    g_exited.store(true, std::memory_order_relaxed);
}

int main()
{
    std::thread wt(fn);
    wt.detach();

    // do something (lets say it took 2s)
    std::this_thread::sleep_for(2s);

    // Exit

    g_exit.store(true, std::memory_order_relaxed);

    for (int i = 0; i < 5; i++) { 
        std::this_thread::sleep_for(1s);
        if (g_exited.load(std::memory_order_relaxed)) {
            break;
        }
    }
}

does #include

Most of the time, I had to include several header files at the start of my code, but then I found this header file, So is there any other header that exists?

is there a way to round down float type in c++?

i want to ask how could i round down float type variable.
(with using printf)

for example,
float x = 3.35;
printf("%.1f", x);

in this situation, it will print out 3.4 but i want it to print 3.3.
is there any way to do it?
(without using turnc or floor function)

Protobuf requires at least C++11

I have a protobuf file with below content and generated pb.h & pb.cc files out of them.

Proto file content:

syntax = "proto3";

package person;

message Person{
    string name = 1;
    map<string, string> mp = 2;
}

I have a main.cpp file where i am trying to import generated code however i am getting "Protobuf requires at least C++11" error.

main.cpp content:

#include <string>
#include <map>
#include "./person.pb.h"
using namespace std;

int main() {
  
  string greeting = "bishnu";
  cout << greeting;
  map<string, string> m;
  return 0;
}

I am using macbook, intel chip and VS Stdio IDE.

I dont know what the issue is. Can somebody help me get this sorted? Any pointer to right document would also be helpful.

dimanche 20 mars 2022

std::binding a loop variable to a lambda and executing it with a std::async

I have a fairly simple scenario:

int num_threads = 4;
auto my_helper = [&](const int thread_number) -> int {
    return thread_number;
};

std::future<int> futures[num_threads];
for (int i = 0; i < num_threads; i++) {
  futures[i] = std::async(std::launch::async, std::bind(my_helper, i));
}

for (int i = 0; i < num_threads; i++) {
  futures[i].wait();
  printf("%d\n", futures[i].get());
}

This prints out:

1
2
3
4

and not the expected:

0
1
2
3

I thought it was something to do with i being bound as a reference, so I changed to std::launch::deferred instead of std::launch::async, but I get the same result.

Why is my integer being incremented unexpectedly?

Find the number in vector using Hash Table [closed]

I was doing a Competitive Programming Question and in that I have to find a number in a vector . We can Find the number or the next largest number. I used Binary Search to find that but the compiler is still showing a TLE Error. So I Researched and find out that Hash Table can perform searching in O(1). Can you Please tell me a way or help me out to find the number in less time than Binary Search. Thanks For The Help!

How to add a value at some list[x][y] in C++?

I am trying to add some value at cost[x][y] and the list must be a pointer type. I declared the list like this:

list<int>* cost = new list<int>[V]; // V being user input

And here I'm trying to add the value "c" at the place of cost[x][y]. How am I supposed to add that .When I try to use iterator as below it says

  1. "Debug Assertion Failed"

  2. "Unable to increment end point iterator"

The Code:

    void addCost(int x, int y, int c) // adds cost in cost[x][y] and cost[y][x] indicies
    {
        auto it = cost[x].begin();
        advance(it, y);
        *it = c;
    }

implementation of the graph class

I tried to implement class the graph T in c++ visual studio, writing a program

template <class T>
class Graph;

template <class T>
class Vertex
{
private:
     T data;
     Vertex<T>* next;
public:
     friend class Graph<T>;
     Vertex(T dat, Vertex<T>* nex)
     {
          data = dat;  next = nex;
     }
 };


 template <class T>
 class Graph
 {
 public:
     Vertex<T>* head;
     Graph() : head(NULL)
     {
     }



     void insert(T data)
     {
           Vertex<T>* ptr = new Vertex<T>(data, head);
           head = ptr;
     }
 };

And I get an error:

NULL: ID not found

what should I do to fix this?

print string without underscore and exclamation mark characters

The problem description is this and output should be like below:

int main(){
    char sentence[256] = "lab_ Ex_am 2 of _the Ceng140 Course!";
    print_sentence(sentence);
}

Output:

lab Exam 2 of the Ceng140 Course

Fastest way for getting last index of item in vector in C++?

Let's say you have a vector of ints, unsorted and with multiple repeating items, like so:

vector<int> myVec{1, 0, 0, 0, 1, 1, 0, 1,0,0}

What is the fastest way to get the last index of 1 which is 8 for this example, other than looping through it from its end?

Would this be different if the vector would contain other items than 0 and 1?

What is the fastest way to do this in C++?

Thank you!

samedi 19 mars 2022

Object C++ tab[i] new object values assign

When I try to assign values in main() to tab[i] I get memory leak. You can change anything in code, but class need to stay as string, string, double and "K2 tab[4];" stay as it is. Under main() you have a view on data.txt file.

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

class K2 {
    string* words;
    double number;

public:
    K2() :words(nullptr), number(0.0) {}
    K2(const string& a1, const string& a2, const double& a3) :number(a3) {
        words[0] = a1;
        words[1] = a2;
    }

    K2& operator=(const K2& r) {
        words[0] = r.words[0];
        words[1] = r.words[1];
        number = r.number;
        return *this;
    }

friend
ostream& operator<<(ostream& out, const K2& r);
};
ostream& operator<<(ostream& out, const K2& r) {
    return out << r.words[0] << " " << r.words[1] << " " << r.number << endl;
}

int main() {
    K2 tab[4];

    string a, b;
    double c;
    ifstream file;
    file.open("data.txt");
    for (int i = 0; i < 4; i++) {
        file >> a >> b >> c;
        tab[i] = K2 (a, b, c); // <- memory leak
    }
    file.close();
}
/*
data.txt:
white coffe 3.50
black tea 1.50
orange juice 3.00
dark chocolate 5.25
*/

Does shared_ptr a = make_shared() create a copy of the shared_ptr before constructor is run?

This might be a stupid question.

Let's say we're in C++11 land and we use make_shared() to create a smart pointer. We then use this smart pointer to initialize a variable with like this:

std::shared_ptr<class> = make_shared(/* args to c'tor of class*/ );

Now I know two things:

  1. Assignement is not initialization. In this case we have initialisation. This would mean in the above case probably the copy constructor is called for the shared_ptr which is returned by make_shared.
  2. Copy elision is only mandatory in C++17.

Does this mean that on every instance of make_shared a temporary copy of the shared_ptr is created and inserted into the copy constructor? Because this would mean for thread safety that a lock would have to be taken across the initialisation in case other threads preempt the thread and call shared_ptr::use_count() member function?

Array manipulation performance: OpenCV or STL?

I'm doing some image processing using OpenCV in C++. But some tasks can be done using both OpenCV and C++ STL. Can I say OpenCV has always (or at least most of the time) better speed performance for array and matrix manipulation than STL algorithms?

vendredi 18 mars 2022

How to enable C++17 standard in VSCode C++ Extension

I want to switch the c++11 to c++17 in vs code. I tried following instructions, but it didn't work.

tasks.json

"version": "2.0.0",
"tasks": [
    
    {
        "type": "cppbuild",
        "label": "C/C++: g++ build active file",
        "command": "/usr/bin/g++",
        "args": [
            "-g",
            "-Wall",
            "-std=c++17",
            "${fileDirname}/*.cpp",
            "-o",
            "${fileDirname}/${fileBasenameNoExtension}"
        ],
        "options": {
            "cwd": "${fileDirname}"
        },
        "problemMatcher": [
            "$gcc"
        ],
        "group": {
            "kind": "build",
            "isDefault": true
        },
        "detail": "compiler: /usr/bin/g++"
    }
]

c_cpp_properties.json

"configurations": [
    {
        "name": "Mac",
        "includePath": [
            "${workspaceFolder}/**"
        ],
        "defines": [],
        "macFrameworkPath": [
            
      "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks"
        ],
        "compilerPath": "/usr/bin/g++",
        "cStandard": "c11",
        "cppStandard": "c++17",
        "intelliSenseMode": "${default}"
    }
],
"version": 4

launch.json

// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
    {
        "name": "g++ - Build and debug active file",
        "type": "lldb",
        "request": "launch",
        "program": "${fileDirname}/${fileBasenameNoExtension}",
        "args": [
            
        ],
        "cwd": "${fileDirname}",
        "preLaunchTask": "C/C++: g++ build active file"
    }
]

settings.json

"C_Cpp.errorSquiggles": "Enabled",
"C_Cpp.default.cppStandard": "c++17",
"files.associations": {
    "*html": "html",
    "iostream": "cpp",
    "iosfwd": "cpp",
    "ostream": "cpp",
    "istream": "cpp",
    "fstream": "cpp",
    "new": "cpp",
    "__bit_reference": "cpp",
    "__config": "cpp",
    "__debug": "cpp",
    "__errc": "cpp",
    "__functional_base": "cpp",
    "__hash_table": "cpp",
    "__locale": "cpp",
    "__mutex_base": "cpp",
    "__node_handle": "cpp",
    "__nullptr": "cpp",
    "__split_buffer": "cpp",
    "__string": "cpp",
    "__threading_support": "cpp",
    "__tree": "cpp",
    "__tuple": "cpp",
    "algorithm": "cpp",
    "array": "cpp",
    "atomic": "cpp",
    "bit": "cpp",
    "bitset": "cpp",
    "cctype": "cpp",
    "chrono": "cpp",
    "cmath": "cpp",
    "complex": "cpp",
    "cstdarg": "cpp",
    "cstddef": "cpp",
    "cstdint": "cpp",
    "cstdio": "cpp",
    "cstdlib": "cpp",
    "cstring": "cpp",
    "ctime": "cpp",
    "cwchar": "cpp",
    "cwctype": "cpp",
    "deque": "cpp",
    "exception": "cpp",
    "functional": "cpp",
    "initializer_list": "cpp",
    "iomanip": "cpp",
    "ios": "cpp",
    "iterator": "cpp",
    "limits": "cpp",
    "list": "cpp",
    "locale": "cpp",
    "map": "cpp",
    "memory": "cpp",
    "mutex": "cpp",
    "numeric": "cpp",
    "optional": "cpp",
    "queue": "cpp",
    "ratio": "cpp",
    "set": "cpp",
    "sstream": "cpp",
    "stack": "cpp",
    "stdexcept": "cpp",
    "streambuf": "cpp",
    "string": "cpp",
    "string_view": "cpp",
    "system_error": "cpp",
    "tuple": "cpp",
    "type_traits": "cpp",
    "typeinfo": "cpp",
    "unordered_map": "cpp",
    "utility": "cpp",
    "vector": "cpp",
    "thread": "cpp"
}

Also changed to c++17 in the C/C++ Configurations (UI).

I'm having trouble compiling my work due to this issue. Having this warning generated:

Executing task: C/C++: g++ build active file < Starting build... /usr/bin/g++ -g -Wall -std=c++17 /Users/aziznosirov/Documents/cpp_udemy/btp305_w2_p1/*.cpp -o /Users/aziznosirov/Documents/cpp_udemy/btp305_w2_p1/w2_p1 /Users/aziznosirov/Documents/cpp_udemy/btp305_w2_p1/w2_p1.cpp:43:14: warning: ISO C++11 does not allow conversion from string literal to 'char *' [-Wwritable-strings] t.addEvent(" 0-arg Constructor");

You can see although it says c++17 on the compiler when building, it still generates a warning mentioning c++11.

Any help would be appreciated. Thanks.

Map

Can i use this in my code like :

Map<int, pair<vector<string>, vector<float>>> T;

Is this the right practice to write STL??

assign from a const reference vs std::move()

Given the following snippet, what happens in each case (w.r.t. copying):


std::string GetString() {
 return "my string";
}

class MyObj {
...
std::string* mutable_str(); 
...
};

// 1) Assigning the value hold by reference 'a', makes a copy.
const std::string& a = GetString(); 
*Obj.mutable_str() = a

// 2) Not a copy, 'b' is a temporary. 
std::string b = GetString(); 
*Obj.mutable_str() = std::move(b);

Is my understanding correct?

jeudi 17 mars 2022

Pointer to a pointer and dereferencing in c++

int (*streamSize) (std::string ,tePddLocation ); //this is function pointer 

Here i am using function pointer in fallowing way can some body what does it mean

*(int**)(&streamsize)=dynamic_symbol() //here i am typecasting dynamic_symbol() as it returns 
// void* that is address of dlsym and if and other possible ways please do let me know

Is it necessary to use OPENSSL_malloc for OpenSSL function parameters?

Most OpenSSL objects are allocated by special functions like SSL_new, BN_new, etc. You cannot use 'new' or the other modern C++ functions to allocated those objects.

Some functions need pre-allocated byte buffers to read/write binary data. For example, the second parameter of BN_hex2bn is just a binary buffer. It is an input parameter. is it safe to pass a std::vector::data() to there?

Some functions need a writable buffer which has size enough for multiple OpenSSL object. I usually find the following examples on the Internet:

OPENSSL_OBJECT* buffer = (OPENSSL_OBJECT*)OPENSSL_malloc(sizeof(OPENSSL_OBJECT) * number);
A_FUNCTION(buffer, number); // buffer is an output parameter

Although descriptions of the functions do not say anything about OPENSSL_malloc. They do not say how the buffer must be allocated.

The OpenSSL_malloc man does not say if it is necessary.

OPENSSL_malloc(), OPENSSL_realloc(), and OPENSSL_free() are like the C malloc(), realloc(), and free() functions. OPENSSL_zalloc() calls memset() to zero the memory before returning.

Can you use C++ objects like std::vector, std::unique_ptr for OpenSSL function buffers? Is there any theoretical issues?

use a lambda to start a thread which is a class attribut

I would like to assign a name to a thread, the thread itself must do this. T his is a class member of the class foo. I would like to start this thread with a lambda but unfortunately I get the error message: no match for call to '(std::thread) (foo::start()::<lambda()>)

Can someone explain to me where the problem is? Previously I had created a temporary tread object, and put this with move on the thread "manage", however, I can then give no name.

class foo {

    public:

        int start()
        {
            this->manage([this](){
            auto nto_errno = pthread_setname_np(manage.native_handle(),"manage");           // Give thread an human readable name (non portable!)
              while(1){
                  printf("do work");
              }
            });
            return 1;
        }

    private:
        int retVal;

        std::thread manage;

};

c++ code is working but it's not calculating correct compound interest and giving garbage value [closed]

Program- Assume that a bank maintains two kinds of accounts for customers, one called as saving second account and adult as current account. The savings compound interest and withdrawal facilities, but no checkbook facility. The current account provides checkbook facility but no interest current account holders should also maintain a minimum balance and if the balance falls below this level, a service charge is imposed. Create a class account that stores customer name, account number and type of account. From this derive the class says. cur_acct and sav_acct to make them more specific to their requirements. Include necessary member functions in order to achieve the following tasks.

  1. Accept deposit from a customer and update the balance.
  2. Display the balance.
  3. Compute and deposit
  4. Permit withdrawal and update the balance.
  5. Check for the minimum balance, imposed penalty, necessary, and update the balance. code-

Output: 1

#include<iostream>
#include<math.h>

using namespace std;

class account
{
    public:
        char name[20], atype[2];
        long acc_no, bal, d_amt, w_amt;

        void get()
        {
            cout << "Enter Customer Name=";
            cin >> name;
            cout << "Enter Account Number=";
            cin >> acc_no;
            cout << "Enter type of account:Saving(s) or Current(c)=";
            cin >> atype;
            cout << "Enter Account balance=";
            cin >> bal;
        }

        void display()
        {
            cout << "\nCustomer Name = " << name;
            cout << "\nAccount no = " << acc_no;
            cout << "\nAccount type = " << atype;
            cout << "\nAccount balance = " << bal;
        }

        void deposit()
        {
            cout << "\nplease enter deposit amount=";
            cin >> d_amt;
            bal += d_amt;
            cout << "\nUpdated account balance is=" << bal;
        }

        void exit()
        {
            cout << "Thank you for visiting. :)";
        }
};

//saving account

class sav_acct: public account
{
    public:
        int t, r;
        float ci;

        void compound()
        {
            cout << "enter rate of interest=" << endl;
            cin >> r;
            cout << "Enter time=" << endl;
            cin >> t;
            ci = bal * pow( 1 + r / 100, t );
            cout << "compound interest is=" << ci << endl;
            //cout<<"New balance is="<<bal;
        }

        void withdraw()
        {
            cout << "\nEnter the amount you want to withdraw=";
            cin >> w_amt;

            if ( w_amt > bal )
            {
                cout << "\nInsufficient balance";
            }
            else
            {
                bal = bal - w_amt;
                cout << "\nUpdated account balance is=" << bal;
            }
        }
};

//current account

class cur_acct: public account
{
    public:
        void min_bal()
        {
            if ( bal < 500 )
            {
                cout << "\nPenality imposed: \nnew balance is:" << bal - 50;
            }
            else
            {
                cout << "\nNo penalty imposed";
            }
        }

        void withdraw()
        {
            cout << "\nEnter the amount you want to withdraw=";
            cin >> w_amt;

            if ( w_amt > bal )
            {
                cout << "\nInsufficient balance";
            }
            else
            {
                bal = bal - w_amt;
                cout << "\nUpdated account balance is=" << bal;
            }
        }
};

int main()
{
    sav_acct s1;
    cur_acct c1;

    int num;

    c1.get();
    c1.display();

    while ( 1 )
    {
        cout << "\n\nWelcome to VMOU Bank" << endl;
        cout << "Enter the following options:\n";
        cout << " 1: Deposit \n 2: Withdraw \n 3: Calculate Compound \n 4: Balance Check \n 5: EXIT \n";
        cin >> num;

        switch ( num )
        {
            case 1:
                c1.deposit();
                break;

            case 2:
                c1.withdraw();
                break;

            case 3:
                s1.compound();
                break;

            case 4:
                c1.min_bal();
                break;

            case 5:
                c1.exit();
                break;

            default:
                cout << "Enter valid option";
        }
    }

    return 0;
}

mercredi 16 mars 2022

I need help in my c++ code, the code is working but it's not calculating correct compound interest?

Program- Assume that a bank maintains two kinds of accounts for customers, one called as saving second account and adult as current account. The savings compound interest and withdrawal facilities, but no checkbook facility. The current account provides checkbook facility but no interest current account holders should also maintain a minimum balance and if the balance falls below this level, a service charge is imposed. Create a class account that stores customer name, account number and type of account. From this derive the class says. cur_acct and sav_acct to make them more specific to their requirements. Include necessary member functions in order to achieve the following tasks.

  1. Accept deposit from a customer and update the balance.
  2. Display the balance.
  3. Compute and deposit
  4. Permit withdrawal and update the balance.
  5. Check for the minimum balance, imposed penalty, necessary, and update the balance. code-
#include<iostream

#include<math.h>

using namespace std;

class account

{

public:

char name[20], atype[2];

long acc_no, bal, d_amt, w_amt;

void get()

{

cout<<"Enter Customer Name=";

cin>>name;

cout<<"Enter Account Number=";

cin>>acc_no;

cout<<"Enter type of account:Saving(s) or Current(c)=";

cin>>atype;

cout<<"Enter Account balance=";

cin>>bal;

}

void display()

{

cout<<"\nCustomer Name = "<<name;

cout<<"\nAccount no = "<<acc_no;

cout<<"\nAccount type = "<<atype;

cout<<"\nAccount balance = "<<bal;

}

void deposit()

{

cout<<"\nplease enter deposit amount=";

cin>>d_amt;

bal+=d_amt;

cout<<"\nUpdated account balance is="<<bal;

}

void exit()

{

cout<<"Thank you for visiting. :)";

}

};

//saving account

class sav_acct:public account

{

public:

int t,r;

float ci;

void compound()

{

cout<<"enter rate of interest="<<endl;

cin>>r;

cout<<"Enter time="<<endl;

cin>>t;

ci=bal*pow(1+r/100,t);

cout<<"compound interest is="<<ci<<endl;

//cout<<"New balance is="<<bal;

}

void withdraw()

{

cout<<"\nEnter the amount you want to withdraw=";

cin>>w_amt;

if (w_amt>bal)

{

cout<<"\nInsufficient balance";

}

else

{

bal=bal-w_amt;

cout<<"\nUpdated account balance is="<<bal;

}

}

};

//current account

class cur_acct:public account

{

public:

void min_bal()

{

if(bal<500)

{

cout<<"\nPenality imposed: \nnew balance is:"<<bal-50;

}

else

{

cout<<"\nNo penalty imposed";

}

}

void withdraw()

{

cout<<"\nEnter the amount you want to withdraw=";

cin>>w_amt;

if (w_amt>bal)

{

cout<<"\nInsufficient balance";

}

else

{

bal=bal-w_amt;

cout<<"\nUpdated account balance is="<<bal;

}

}

};

int main()

{

sav_acct s1;

cur_acct c1;

int num;

c1.get();

c1.display();

while(1)

{

cout<<"\n\nWelcome to VMOU Bank"<<endl;

cout<<"Enter the following options:\n";

cout<<" 1: Deposit \n 2: Withdraw \n 3: Calculate Compound \n 4: Balance Check \n 5: EXIT \n";

cin>>num;

switch(num)

{

case 1: c1.deposit();break;

case 2: c1.withdraw();break;

case 3: s1.compound();break;

case 4: c1.min_bal();break;

case 5: c1.exit();break;

default: cout<<"Enter valid option";

}

}

return 0;

}

How to iterate through of all AST node in order to apply optimizitation?

I am making a toy compiler. The source language is an imperative language, the output language is C++ code with some optimization.

I have AST for inner representation.

I want to implement some optimization, first of all a basic loop unrolling optimization.

I have a base class, every statement class derived from it.

I know that I should use visitor pattern in order to make AST -> AST transofrmation.

So I want to make changes in every WhileStatement class. There can be inner WhileStatements, like this:

VarDeclaration
PrintStatement
CallFunction
WhileStatement
    IfStatement
        WhileStatement
        PrintStatement
PrintStatement

I can get the first level statements from bison. That is clear that I need to apply somehow the visitor pattern to process the inner statements.

First of all, I know the basic of visitor pattern, but I cannot apply it in my code properly. Good news, only WhileStatement, IfStatement and IfElseStatement can have (inner) list of statements

I share my code, I hope this time it will be enough to give me help.

So the base class:

class Statement
{
    public:
        virtual ~Statement();
        virtual void TypeCheck() = 0;
        virtual StatementType GetType() const = 0;
        virtual std::string GetCode() const = 0;
        virtual void accept(visitor& v) = 0;
};

WhileStatement class (IfStatement is almost looks like this):

class WhileStatement : public Statement
{
    public:
        WhileStatement(Expression* _exp, std::list<Statement*>* _statementList);
        ~WhileStatement();
        void TypeCheck();
        Expression* GetExpression() const;
        std::string GetCode() const;
        StatementType GetType() const;
        virtual void accept(visitor& v) override
        {
            v.visit(*this);
        }
    private:
        Expression* exp;
        std::list<Statement*>* statementList;
};

Please do not judge me because of this: std::list<Statement*>* bison can operate only with this type so this type is fix, I think I cannot use this std::list<Statement*> &statementList

My basic Loop unrolling optimization, it works well with the outer statements:

void LoopUnrollingOptimization(std::list<Statement*>* &outerStatements, int optimizationNumber)
{
    std::list<Statement*>::iterator it;
    for (it = outerStatements->begin(); it != outerStatements->end(); ++it)
    {
        Expression* exp = dynamic_cast<WhileStatement*>(*it)->GetExpression();
        std::list<Statement*>* statementList = dynamic_cast<WhileStatement*>(*it)->GetStatementList();
        int whileStatements = statementList->size();
            
        std::list<Statement*>::iterator it2 = statementList->begin();
        IfStatement* optimizedIf = new IfStatement(exp, "break;");
    
        statementList->push_back(optimizedIf);
        
        int size = statementList->size() * optimizationNumber;
        
        for (int i = 0; i < size; ++i)
        {
            if (size - 1 == i)
            {
                break;
            }
            statementList->push_back((*it2));
            ++it2;
        }
    }
}

I call this function in my grammar file (.y).

I implemented a visitor pattern:

class visitor
{
    public:
        virtual void visit(IfStatement& ifStatement) = 0;
        virtual void visit(WhileStatement& whileStatement) = 0;
        virtual void visit(DeclareVariableStatement& declare) = 0;
        virtual void visit(IfElseStatement& ifelsestmt) = 0;
};

class visitor_concrate : public visitor
{
  public:
    void visit(IfStatement& ifStatement)
    {
        // I do not know what should I provide here, maybe this:
        ifStatements.statementList; // I think it is wrong, because it is a void method.
    };

    void visit(WhileStatement& whileStatement) override
    {

    };

    void visit(DeclareVariableStatement& declare)
    {
        // nothing maybe, because this class do not have statementList
    };
};

It is clear to me, that my task is to process every node (does not matter the depth level of it).

But I got stuck with combine the visitor pattern with my loop unrolling function. So please tell me how to combine void LoopUnrollingOptimization(std::list<Statement*>* &outerStatements, int optimizationNumber) function with the visitor pattern in order to process every node at every depth.

As I said before there can be this kind of scenario:

DeclareVarStatement
PrintStatement
IfStatement
    IfElseStatement
        IfStatement
            IfStatement
                WhileStatement
DeclareVarStatement

In this case I have to make loop unrolling optimization in the innermost WhileStatement.

I appreciate help with coding, also with hints. But because of my lack of knowledge, I would be happy if someone could write me a working code or a pseudocode.

Thank you in advance!

Why can't a constexpr "variable" be seen only by a capturing lambda?

Why can't a constexpr "variable" be seen only by a capturing lambda ? For me the a constexpr "variable" should have the same meaning as a static const "variable"; and the latter one can be seen inside a lambda without any capturing.

mardi 15 mars 2022

How to template by-value returning value and by-const-ref returning const ref

Is there a way to have those two cases as a single template:

// accepts by-value, returns value
int f(bool cond, int a, int b) {
    return cond ? a : b;
}

// accepts by-const-ref, returns const ref
const std::string& f(bool cond, const std::string& a,
                     const std::string& b) {
    return cond ? a : b;
}

Using at least C++11.

Is it possible to write a function that changes based on the template type?

I'm trying to create a class that can generate a random variable. I want to be able to generate any random type based on the templated value at runtime. I figured I can do this by making this function works for ints, strings, and double data types by coding each one specifically.

Searching a set<> via Custom Criterion

The Problem

In the code below, I have found that I can insert into a set<> using a custom sorting criterion, but I cannot test for the presence of an element using set<>::find(). The following compilation error results upon a call to set<>::find():

error: no matching function for call to ‘std::setstd::shared_ptr<node_t, node_comp_t>::find(char&) const’
return children.find(c) != children.end();

This is confusing to me since element equivalence is defined by:

!(lhs < rhs) && !(rhs < lhs)

As can be seen below, I have the required operator defined.

Undesirable Alternative

As an alternative, I can search through the set<> element-by-element, but that is not preferable since doing so would run in linear time.

My Questions

  1. What am I misunderstanding?
  2. Is there a way I can search in logarithmic time, as one normally could with set<>::find()?

Code

struct node_t;
using node_sp_t = shared_ptr<node_t>;

class node_comp_t
{
   public:
      inline bool operator()(const node_sp_t &lhs, const node_sp_t &rhs) const;
};

using node_sp_set_t = set<node_sp_t, node_comp_t>;

class node_t
{
   public:
      explicit node_t(char c_p): c{c_p} {}

      inline char get_c() const
      {
         return c;
      }

      void add_child(char c)
      {
         if (!child_exists(c))
            children.insert(make_shared<node_t>(c));
      }

      bool child_exists(char c) const
      {
         // c is not of the children set element type (node_sp_t).
         // So, find() cannot be used with c.
         //
         // Why does node_comp_t not get used by find()?
         //
         // How may I search for c in logarithmic time if not by using find()?
         //
         return children.find(c) != children.end();

         // This works, but it runs in linear time!
         // for (const node_sp_t &node_sp : children)
         // {
         //    if (node_sp->get_c() == c)
         //       return true;
         // }

         // return false;
      }

   private:
      char c;
      node_sp_set_t children;
};

inline bool node_comp_t::operator()(const node_sp_t &lhs, const node_sp_t &rhs) const
{
   return lhs->get_c() < rhs->get_c();
}