dimanche 31 octobre 2021

Getting SIGSEGV error in my concurrent Queue code, plus wanted to understand how can I improve it's performance if the segfault is solved

I am trying to write a single producer- single consumer queue. But to me it feels that it's not the best approach that I have used, I am new to multi-threading. Can some one please take a look and suggest few improvements. Also it is throwing segmentation fault. I have attached the case in main body it self with gdb output.

compiling the code like this

clang++ -std=c++11 ConcurrentQueue.cpp -o test -lpthread

Below is my concurrent queue code. The failed case is also given in main block.

#include <cmath>
#include <functional>
#include <iostream>
#include <mutex>
#include <stdexcept>
#include <thread>

template<typename T, uint64_t SIZE = 2048, uint64_t MAX_SPIN_ON_BUSY = 40000000>
class ConcurrentQueue {
private:
    static constexpr unsigned Log2(unsigned n, unsigned p = 0) {
        return (n <= 1) ? p : Log2(n / 2, p + 1);
    }

    static constexpr uint64_t closestExponentOf2(uint64_t x) {
        return (1UL << ((uint64_t) (Log2(SIZE - 1)) + 1));
    }

    static constexpr uint64_t mRingModMask = closestExponentOf2(SIZE) - 1;
    static constexpr uint64_t mSize = closestExponentOf2(SIZE);

    static const T mEmpty;

    T mMem[mSize];
    std::mutex mLock;
    uint64_t mReadPtr = 0;
    uint64_t mWritePtr = 0;

public:
    const T& pop() {
        if (!peek()) {
            return mEmpty;
        }

        std::lock_guard<std::mutex> lock(mLock);

        if (!peek()) {
            return mEmpty;
        }

        T& ret = mMem[mReadPtr & mRingModMask];

        mReadPtr++;
        return ret;
    }

    bool peek() const {
        return (mWritePtr != mReadPtr);
    }

    uint64_t getCount() const {
        return mWritePtr > mReadPtr ? mWritePtr - mReadPtr : mReadPtr - mWritePtr;
    }

    bool busyWaitForPush() {
        uint64_t start = 0;
        while (getCount() == mSize) {
            if (start++ > MAX_SPIN_ON_BUSY) {
                return false;
            }
        }
        return true;
    }

    void push(const T& pItem) {
        if (!busyWaitForPush()) {
            throw std::runtime_error("Concurrent queue full cannot write to it!");
        }

        std::lock_guard<std::mutex> lock(mLock);
        mMem[mWritePtr & mRingModMask] = pItem;
        mWritePtr++;
    }

    void push(T&& pItem) {
        if (!busyWaitForPush()) {
            throw std::runtime_error("Concurrent queue full cannot write to it!");
        }

        std::lock_guard<std::mutex> lock(mLock);
        mMem[mWritePtr & mRingModMask] = std::move(pItem);
        mWritePtr++;
    }
};

template<typename T, uint64_t SIZE, uint64_t MAX_SPIN_ON_BUSY>
const T ConcurrentQueue<T, SIZE, MAX_SPIN_ON_BUSY>::mEmpty = T{ };

int main(int, char**) {
    using Functor = std::function<void()>;

    ConcurrentQueue<Functor*> queue;

    std::thread consumer([ & ] {
        while (true) {
            if (queue.peek()) {
                auto task = queue.pop();
                (*task)();
                delete task;
            }
        }
    });

    std::thread producer([ & ] {
        uint64_t counter = 0;
        while (true) {
            auto taskId = counter++;
            auto newTask = new Functor([ = ] {
                std::cout << "Running task " << taskId << std::endl << std::flush;
            });
            queue.push(newTask);
        }
    });

    consumer.join();
    producer.join();
    return 0;
}

Below is gdb output

Reading symbols from test...done.
[New LWP 3242]
[New LWP 3240]
[New LWP 3241]
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Core was generated by `./test'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0  _int_malloc (av=av@entry=0x7f6500000020, bytes=bytes@entry=32) at malloc.c:3378
3378    malloc.c: No such file or directory.
[Current thread is 1 (Thread 0x7f6505f34700 (LWP 3242))]
(gdb) bt
#0  _int_malloc (av=av@entry=0x7f6500000020, bytes=bytes@entry=32) at malloc.c:3378
#1  0x00007f65067ba184 in __GI___libc_malloc (bytes=32) at malloc.c:2913
#2  0x00007f65070ace78 in operator new(unsigned long) () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#3  0x00000000004034da in main::$_1::operator() (this=0x1fc7db8) at ConcurrentQueue.cpp:108
#4  0x0000000000403475 in std::_Bind_simple<main::$_1 ()>::_M_invoke<>(std::_Index_tuple<>) (this=0x1fc7db8)
    at /usr/bin/../lib/gcc/x86_64-linux-gnu/5.4.0/../../../../include/c++/5.4.0/functional:1530
#5  0x0000000000403445 in std::_Bind_simple<main::$_1 ()>::operator()() (this=0x1fc7db8)
    at /usr/bin/../lib/gcc/x86_64-linux-gnu/5.4.0/../../../../include/c++/5.4.0/functional:1520
#6  0x0000000000403339 in std::thread::_Impl<std::_Bind_simple<main::$_1 ()> >::_M_run() (this=0x1fc7da0)
    at /usr/bin/../lib/gcc/x86_64-linux-gnu/5.4.0/../../../../include/c++/5.4.0/thread:115
#7  0x00007f65070d7c80 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#8  0x00007f65073a86ba in start_thread (arg=0x7f6505f34700) at pthread_create.c:333
#9  0x00007f650683d41d in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:109
(gdb)

Can this part of code be considered code duplicate

I want to ask about duplicates.. I know first is duplicate as would be better to extract it to a function but also second block of code if appears multiple times can be considered duplicate and needs to be extracted into separate function? I want to know the general approach and also if tools like sonar would complain about duplicates in this case. Thank you.

 struct X 
    {
        void print()
        {
            std::cout<<"print from X";
        }
        
   
        void print_2()
        {
            std::cout<<"print_2 from X";
        }
    };
    
    int main()
    {   
        
        int n1 = 10;
        for(int x = 0; x < n; x++)
        {
            std::cout<<x;
        }
        
        int n2 = 10;
        for(int x = 0; x < n2; x++)
        {
            std::cout<<x;
        }
        
        // printToN(n); printToN(n2)  // duplicate
        
        
        if (cond)
        {
            X x;
            if (cond2)
            {
                x.print();
                x.doSomething();
            }
            else
            {
                x.print_2();
            }
        }
        
        /*
        ...
        ...
        ...
        */
        // again this block of code
        if (cond)
        {
            X x;
            if (cond2)
            {
                x.print();
                x.doSomething();
            }
            else
            {
                x.print_2();
            }
        }
        
        // is this also duplicate ?
        
        
        
        return 0;
    }

sending a pointer of member of global variable to an WinHttpQueryHeaders does not change it's value

I have the following code snippet:

        // Using HttpQueryInfo to obtain the size of the buffer into dwSize.
        if (!WinHttpQueryHeaders(hRequest,
            WINHTTP_QUERY_RAW_HEADERS_CRLF,
            WINHTTP_HEADER_NAME_BY_INDEX, NULL, &st.dwSize, WINHTTP_NO_HEADER_INDEX))
        {
            // An ERROR_INSUFFICIENT_BUFFER is expected because you
            // are looking for the size of the headers.  If any other
            // error is encountered, display error information.
            DWORD dwErr = GetLastError();
            if (dwErr != ERROR_INSUFFICIENT_BUFFER)
            {
                DEBUG_PRINT(("Error %d encountered.", dwErr));
                return;
            } else {
                // enters here and prints '0' (initial value)
                DEBUG_PRINT(("size of buffer: ", &st.dwSize));
            }
        }

while st is a global object with a member dwSize.

When I'm running this part in debugging mode I see that dwSize does not change its value after the call to WinHttpQueryHeaders.

But if I create a local var DWORD dwSize = 0 and send &dwSize to WinHttpQueryHeaders, it does obtain buffer size and succeeds to change its value.

is there any reason why I shouldn't send a pointer of a global object's member to WinHttpQueryHeaders or to any other external API functions?

Basic c++ programs. More specifically its my assignment [closed]

Problem 1: A country has Currency named TIKKA and Currency Notes of amount 750, 350, 200, 85, 15, 3 and 1 TIKKA’s. Write a C++ program which: • accepts amount in TIKKA’s as input (integer). • Pass the user entered TIKKAs to a function which displays total number of Currency Notes of TIKKA 750, 450, 350, 75, 18 and 1. For example: when user enter a number 1964, the results would be like this. Currency Note : Number 750 : 2 450 : 0 350 : 1 75 : 0 18 : 2 1 : 3

Problem 2: Write a C++ program that takes up to 10-digit integer input from user (can be 1 digit, 2 digit, and so on..); passes this to a function which reverses the digits. Finally, the reversed number should be displayed in the main function. For example: when user enters 10-digit like 1234567890 your function will reverse it to 987654321. Be careful for big integer values. [use functions, decision control]

Problem 3: Read about doing multiplication using Karatsuba method (https://en.wikipedia.org/wiki/Karatsuba_algorithm ). Write a C++ program which: • Prompts user to enter two large integer numbers (x, y). Both numbers must be more than 4 digits and less than 10 digits (do input validation, don’t use strings). The entered numbers could be negative or positive. For example: 820778 and -58712979 where x is 6-digit positive number and y is 8-digit negative number. • Make a function called Karatsuba() which takes these two integers and returns the multiplication result using Karatsuba algorithm. You might need to make another helper function called getDigits() which will get an integer as input and returns number of digits of that integer. getDigits() will help you find the value of m and Bm. • Display result in the main function.

Problem 4: The information about colours is to be stored in bits of a variable called colour. The bit number 0 to 7, each represent 8 colours of a rainbow, i.e. bit 1 represents Blue, 2 represents Green, and so on (see table below). Write a C++ program that asks the user to enter a number and based on this number, an eight lined rainbow (of asterisks *) is to be displayed, such that, if the bit is ON, respective colour is displayed otherwise black line is drawn (not visible).

How to initialize an array of objects with a shared pointer

I am tryind to do something like this

struct car
{
    car(int a) : name(a) {}
    int val;
};

int main()
{
    std::map<int, std::shared_ptr<car[]>> mp;

    auto t = std::shared_ptr<car[]>(new car[100]); // Error car requires a paremeter.
}

My question is how do I pass 1 to every constructor? The following does not work

auto t = std::shared_ptr<car[]>(new car[100](1)); 

samedi 30 octobre 2021

Getting a warning when I use a class within a class in C++ [closed]

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

using namespace std;


class Course{

  public:
  string name;
  int pars[];
  Course();

};

class Runs{

  public:
  Course course; <- Error
  int scores[];
  Runs();

};

I am trying to use the classes to read lines from a badly formatted file. Why can't I use a class within a class?

No operator found even though I think I wrote one

VS 2010 is consistently giving me error C2678: binary '==' : no operator found which takes a left-hand operand of type 'const AnyColor' (or there is no acceptable conversion) for expression 'bool AnyColor::operator ==(const AnyColor &)' while trying to match the argument list '(const AnyColor, const AnyColor)'
br> Here is the entire program:

#include "stdafx.h"
#include <string.h>
#include <stdint.h>
#include <unordered_map>
#include <cstdlib>
#include <iostream>

//  ________________________________________________________________________________

typedef uint16_t    cSpace;

//  Identifiers for different color spaces
enum    {
    kCsRGB = 0,
    kCsCMYK,
    kCsGray
};

//  The color class can represent colors from a variety of spaces.
//  Up to a 4 dimensional color can be represented.
class   AnyColor    {
public:
    AnyColor(void)  {
        space = kCsRGB; // Might change; this is an initial guess to avoid meaningless values
        memset(axis, 0, sizeof(axis));
    };

    AnyColor(short type, double a, double b, double c, double d)
    {
        space   =   type;
        axis[0] =   a;
        axis[1] =   b;
        axis[2] =   c;
        axis[3] =   d;
    }

    void Set(short type, double a, double b, double c, double d)
    {
        space   =   type;
        axis[0] =   a;
        axis[1] =   b;
        axis[2] =   c;
        axis[3] =   d;
    }

    inline  bool    operator==(const AnyColor& op) // Equal only if all its members are equal
    {
        if  (space != op.space)
        {
            return  false;
        }

        for(int i = 0; 4 > i; i++)
        {
            if  (axis[i] != op.axis[i])
            {
                return  false;
            }
        }
        return  true;
    }

    inline bool operator!=(AnyColor &op)
    {
        return (*this == op) ? false : true;
    }

    cSpace  space;
    double  axis[4];
};

static std::unordered_map<const AnyColor,int> colormap;
static int seq = -1;
const int numColors = 25;

static double quarters()
{
    return 0.25 * static_cast<double>(rand() % 5);
}

int _tmain(int argc, _TCHAR* argv[])
{
    AnyColor c;

    for(int i = 0; numColors > i; ++i)
    {
        c.axis[0] = quarters();
        c.axis[1] = quarters();
        c.axis[2] = quarters();
        if (colormap.count(c) == 0) // THIS IS WHERE THE PROBLEM SHOWS UP
        {
            colormap[c] = ++seq;
        }
    }
    return 0;
}

I've tried all combinations of passing the parameter by value vs by reference and const vs not const. I get the same error every time. I bet I'm overlooking something simple.

This program does nothing; I was just starting to write it when I encountered this error. I hope to end up with code that assigns sequence numbers to unique colors.

I have to be able to compile with VS2010 so my C++ dialect is limited to C++11.

In this little test segment, I generate random colors just to test my use of unordered_map. What do I need to do to get this to compile?

How do i call a C++ function from python? [duplicate]

I currently am working on an agriculture project and need to call some C++ functions that are usually used for manipulating pipes. However i need to call them from my Python script. Is there any way to do that ?

how to check for positive multiples of 2 using modulus operator in an if loop

I was trying to use the mod % operator in C++ but it shows the error Expression is not assignable

int i = 0;
    cin>>i;
//    for (i; i < 25; i++) {
        if (i < 25 && i % 2 = 0) {
            cout<<"test"<<i;
        } else {
            cout<<"test2"<<i;
        }
    }
    return 0;
}

vendredi 29 octobre 2021

Find the value of y according to condition:

Find the value of y according to condition: Condition

I tried to do but something is wrong or I did not right so I need some help

#include <stdio.h>

int x,y;


int main()
{
   scanf("%d",&x);
   if (x<5) y=x*x-3*x+4;
      else y= x+7;
    printf("%d",y);
    return 0;
}

How to use a child class method in an array of superclass type C++

I have a superclass bankAccount along with its multiple child classes. As my professors example shows, I created a dynamic array, bankAccount *accountList[10], then allow the user to select what type of account they want to access, which is then stored in accountList[i] =(whatever account type they chose). My problem arises when the user selects an option which isn't the superclass (bankAccount) and I need to do the corresponding methods, such as postInterest() as I get the error 'class bankAccount' has no member named 'postInterest' I've found 2 work arounds, the first being placing the methods (of the child classes) within the constructors, and while this methods gets me a correct output, if I try accessing these methods again in my main outside of the accountList[i] =savingsAccount(name, actN, bal, check) I get the same error. The second work around was using a static_cast, which has worked without fail so far. Is this the only way I can do this or am I missing something (On week 4 of C++ OOP and professor has skipped lectures for 2 weeks so concepts aren't too clear to me right now)

main.cpp

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

#include "savingsAccount.h"


int main()
{
    string choice;
    int actN;
    double iR;
    double bal;
    double with;
    double dep;
    string name;
    bankAccount *accountList[10];
    for (int i=0; i<10; i++)
    {
        
        cout<<"Would you like to access Bank or Savings: ";
        cin >> choice;
        
        if (choice == "B"){
            cout << "Please enter Name: ";
            cin>>name;
            cout << "Please enter Account #: ";
            cin>>actN;
            
            cout<< "Please enter Balance: ";
            cin>> bal;
            
            cout << "How much would you like to withdrawl: ";
            cin >> with;

            cout << "How much would you like to Deposit: ";
            cin >> dep;
        
            accountList[i] = new bankAccount(name, actN, bal);
            accountList[i] -> setWithdrawl(with);
            accountList[i] -> setDeposit(dep);
            accountList[i] -> show();
    }
        if (choice == "S"){
            double intRate;
            cout << "Please enter Name: ";
            cin >> name;
            cout << "Please enter Account #: ";
            cin>>actN;
            
            cout<< "Please enter Balance: ";
            cin>> bal;
            
            cout << "How much would you like to withdrawl: ";
            cin >> with;
        
            cout << "How much would you like to Deposit: ";
            cin >> dep;
            
            cout << "Please enter Interest rate %: ";
            cin>> intRate;
            accountList[i] = new savingsAccount(name, actN, bal, intRate);
            accountList[i] -> setWithdrawl(with);
            accountList[i] -> setDeposit(dep);
            static_cast<savingsAccount*>(accountList[i]) -> postInterest();
            accountList[i] ->show();
        }
    }
}

bankAccount.h

#ifndef bankAccount_H
#define bankAccount_H
#include <iostream>
#include <string>

using namespace std;

class bankAccount{
    protected:
        double balance;
        int acctNumber;
        string name;
    public:
    bankAccount();

    
    bankAccount(string n, int aN, double bal);
    
    void setName(string n);
    
    void setAcctNum(int actNum);

    void setBal(double bal);
        
    double getBal();
    
    void setWithdrawl(double w);
    void setDeposit(double d);
    
    virtual void show();
};
#endif

bankAccount.cpp

#include "bankAccount.h"

bankAccount::bankAccount()
{
    acctNumber=0;
    balance = 0;
    name = "N/A";
}
    
    bankAccount::bankAccount(string n, int aN, double bal)
{
    setName(n);
    setAcctNum(aN);
    setBal(bal);
        
}
    
void bankAccount::setName(string n)
{
    name = n;
}

void bankAccount::setAcctNum(int actNum)
{
    acctNumber = actNum;
}

void bankAccount::setBal(double bal)
{
    balance = bal;
}

double bankAccount::getBal() 
{
    return balance;
}

void bankAccount::setWithdrawl(double w)
{
    balance = balance - w;
}

void bankAccount::setDeposit(double d)
{
    balance = balance + d;
}

void bankAccount::show()
{
    cout <<"Holder name: "<<name<<endl<< "Account number: "<< acctNumber<<endl <<"Balance: "<<balance<<endl<<endl;
}

savingsAccount.h

#ifndef savingsAccount_H
#define savingsAccount_H
#include <string>
#include "bankAccount.h"
  
using namespace std;

class savingsAccount :public bankAccount
{
    protected:
        double interestRate;
    public:
        savingsAccount();

        savingsAccount(string n,int aN, double bal, double iR);
        void setIR(double iR);

        void postInterest();
        virtual void show();
        
};
#endif

savingsAccount.cpp

#include "savingsAccount.h"

savingsAccount::savingsAccount(){
    interestRate = 0;
}
savingsAccount::savingsAccount(string n,int aN, double bal, double iR) : bankAccount (n,aN, bal)
{
    setIR(iR);
    //postInterest(); I know this is commented out, just to give a reference to what I was talking about in my post
}

void savingsAccount:: setIR(double iR)
{
    interestRate = iR/100;
}

void savingsAccount:: postInterest()
{
    balance *=(1+interestRate/12);
}

void savingsAccount::show()
{
    cout<<"Account Number: "<<acctNumber<<endl<<"Interest Rate: "<<interestRate<<endl<<"Final Balance: "<< balance<<endl<<endl;
}

P.S. this is my first stack overflow post! So any tips on making my post easier to answer would be greatly appreciated!

why my code does not work when I put Variables inside vector with + operand

//This Code WORKS.

//Main driver

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

int main()
{
    string name, age;

    name = "Muzaib";
    age = "16";

    std::vector<std::string> B = {name + "\n" + age + "lll" + '\n'};
    B.push_back(name + '\n' + age);
    cout << B[0];
     cout << B[1];
    return 0;
}

//This Code DOES NOT WORK.

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

//Doctor class

class Doctor : public Hospital
{
    protected:
        std::vector<std::string> doctors;               //contains list of doctors.
        string Docname;
        int Docage;
        string Docgender;
        string specialty;

    public:
        Doctor();                       //Constructor
        void listDoctors();
        void addDoctor();
        void removeDoctor();
    
};

// Allows user to add doctor to the list.

void Doctor::addDoctor()
{
    cin.ignore();
    cout << "Enter Doctors name: ";
    getline(cin, Docname);
    cout << "\nEnter Soctors age: ";
    cin >> Docage;
    cin.ignore();
    cout << "\nEnter Doctors gender";
    getline(cin, Docgender);
    cout << "\nEnter Doctors specialty: ";
    getline(cin, specialty);

//This line of code is giving me the following error: [Error] no match for 'operator+' (operand types are 'std::basic_string' and 'int') I do not get any errors on the other program.

    doctors.push_back(Docname + '\n' + "Age: " + Docage + '\n' + "Gender: " + Docgender + '\n' 
    + "Specialty: " + specialty);
}

How do I replace spaces with std::regex_replace between markers using non-capture groups?

I'm trying to eliminate whitespaces in a string with a regular expression. From the following snippet:

std::string in = "abc>  <def\n"
                 "xyz>      \n";
std::regex re = R"((?:>)\s+(?:<)|\s+$)";
std::string out = std::regex_replace(in, re, "(newcontent)");

I'm expecting out to contain

abc>(newcontent)<def
xyz>(newcontent)

but, alas, I get

abc(newcontent)def
xyz>(newcontent)

instead. To me it seems that the non-capture sequence (?:...) isn't working. I've tried to modify the program with extensions as std::regex re ("....", std::regex::ECMAScript | std::regex::nosubs); and appending , std::regex_constants::format_default to regex_replace to no avail. Can this be a library implementation problem or am I at fault?

how do I solve this error while opening dev c++?

enter image description here

I cannot find any solution anywhere . Why is this showing everytime?

c++ create a global unique id that is not a UUID type

In other languages, such as Go, there are a myriad of libraries that can be used to create a globally unique ID string (using elements such as nanosecond time, machine id, process id, random bytes...)

However, in C++, the only real choice seems to be UUID (such as that from Boost)

I am looking to use a globally unique identifier in my code, but do not want something with as many chars as a UUID.

As an example of the type of things available in GoLang. Please see the below. Anything similiar in c++?

https://blog.kowalczyk.info/article/JyRZ/generating-good-unique-ids-in-go.html

How to cycle through smart pointer to a class with custom iterator

I have a smart pointer to a class with custom iterator. I need to iterate through it and couldn't find any examples.

struct SomeContrainer
{
   int a;
}

struct ListClass
{
   std::vector<SomeContrainer>::iterator begin() { return m_devs.begin(); }
   std::vector<SomeContrainer>::iterator end()   { return m_devs.end();   }                                         

   void add( const SomeContrainer& dev ) { m_devs.push_back( dev ); }

   private:
      std::vector<SomeContrainer> m_devs;
};

typedef std::unique_ptr<ListClass> ListPtr_t;


void Foo_Add( const ListPtr_t& list )
{
   SomeContrainer dev1, dev2;
   dev1.a = 10;
   dev2.a = 100;
   list->add(dev1);
   list->add(dev2);
}

void DoSomeWorkOtherList( const ListPtr_t& list )
{
   for( auto const& dev : list )    // <-- how to iterate other list ???
   {}
}

// -----------

ListPtr_t pMyList( new ListClass() );

Foo_Add( pMyList );
DoSomeWorkOtherList(pMyList );

It works fine if I don't use a smart pointer and have just an object ListClass list I'm using C++11 and can't upgrade.

Visual Studio auto tab "Move Lines Up/Down"

I normally select a portion of code and then use Alt+Up/Down to perform a "Edit.MoveSelectedLinesUp" or "Edit.MoveSelectedLinesDown". Trying to fix another auto formatting issue, I changed a substantial amount of settings. Then I didn't remember which ones I changed, So I decided to reset everything by "Tools-> Import and Export Settings -> Reset all".

Now when I perform this Move Up and Down, the code is not auto idented, so I need to manually tab it or do an auto format.

I tried reinstalling and installing everything, but for some reason Visual Studio remembers keeps doing it by default.

I don't know if this is the default behaviour or is it something I configured and I lost it by performing a reset.

Can anyone help me with this?

I use the C++ Editor and I have Visual Assist installed.

Thanks

how to solve this c++ project?

  • defines an '*' operator in his project, which he is developing. This operator comes between two numbers A, and B, and performing this operator on these numbers produces an expression that A is repeated B times and after that B is repeated A times. Following this, he alternately puts '+' and '-' before the numbers (before the first number '+' comes and then alternately '-' and '+'). In the end, the answer of A
  • B is the result of the expression. Your task is to help him calculate the answer of A * B when he gives you these two numbers. Input The only line of the input indicates two integers A and B. 1 <= A, B <= 100 Output Print a single line that indicates the result of A*B.

jeudi 28 octobre 2021

C++ Socket recv() always returns 0

1) Does work:

char blockSize[4];
int r = recv(socket, blockSize, 4, 0);


2) Does not work. It always returns zero:

size_t blockSize = 0;
int r = recv(socket, (char*)blockSize, 4, 0);

Why does the code in paragraph two instantly return 0?

It's not a major problem, I know how to convert the char array back to a size_t. But I just want to know why it's not working.

Problem compiling multithreading process regarding arguments

I'm trying to compile a program but it keeps coming up with errors; I have searched through the forum and I think it has to do with passing by reference, but I can't find where I went wrong.

Here is an extract of the code:

#include <iostream>
#include <thread>

using namespace std;

const int N = 512;
const int N_BUSC = 8;
using VectInt = int[N];

void coord (VectInt v, bool& lectura, bool acabados[N_BUSC], int resultados[N_BUSC]);

int main(int argc, char *argv[]){
    bool leido = false; 
    VectInt v;
    int acabados [N_BUSC], resultados [N_BUSC];

...

    thread coordinacion (&coord, v, std::ref(leido), acabados, resultados);

...
}

The error it keeps showing is:

/usr/include/c++/9/thread: In instantiation of ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (*)(int*, bool&, bool*, int*); _Args = {int (&)[512], std::reference_wrapper<bool>, int (&)[8], int (&)[8]}; <template-parameter-1-3> = void]’:
ej1.cpp:43:74:   required from here
/usr/include/c++/9/thread:120:44: error: static assertion failed: std::thread arguments must be invocable after conversion to rvalues
  120 |           typename decay<_Args>::type...>::value,
      |                                            ^~~~~
/usr/include/c++/9/thread: In instantiation of ‘struct std::thread::_Invoker<std::tuple<void (*)(int*, bool&, bool*, int*), int*, std::reference_wrapper<bool>, int*, int*> >’:
/usr/include/c++/9/thread:131:22:   required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (*)(int*, bool&, bool*, int*); _Args = {int (&)[512], std::reference_wrapper<bool>, int (&)[8], int (&)[8]}; <template-parameter-1-3> = void]’
ej1.cpp:43:74:   required from here
/usr/include/c++/9/thread:243:4: error: no type named ‘type’ in ‘struct std::thread::_Invoker<std::tuple<void (*)(int*, bool&, bool*, int*), int*, std::reference_wrapper<bool>, int*, int*> >::__result<std::tuple<void (*)(int*, bool&, bool*, int*), int*, std::reference_wrapper<bool>, int*, int*> >’
  243 |    _M_invoke(_Index_tuple<_Ind...>)
      |    ^~~~~~~~~
/usr/include/c++/9/thread:247:2: error: no type named ‘type’ in ‘struct std::thread::_Invoker<std::tuple<void (*)(int*, bool&, bool*, int*), int*, std::reference_wrapper<bool>, int*, int*> >::__result<std::tuple<void (*)(int*, bool&, bool*, int*), int*, std::reference_wrapper<bool>, int*, int*> >’
  247 |  operator()()
      |  ^~~~~~~~

Thank you in advance.

How to Parsing a String into Characters in C++ [closed]

Is there a way to parse strings into characters in C++? I didn't found any way for this question to solve it.

Asio UDP write from outside read handler

The asio UDP server class has an async read and write function. Everything works fine if I do a write from within the handler of read (e.g.: https://www.boost.org/doc/libs/1_37_0/doc/html/boost_asio/tutorial/tutdaytime6/src.html))

I found this link on the web, which mentions:

Send the message to the client using the endpoint as set by receive_from()

(e.g.: http://thisthread.blogspot.com/2018/03/boost-asio-synchronous-udp-clientserver.html)

I want the write to be independent of the read. Is this possible?

Any help would be appreciated.

Error keeps saying my app most have a class type not a "BankApplication bankopen1()" [closed]

I keep getting an error message for the bankopen1.

    case 1:
       bankopen1.openAccount();

        break;

What optimization technique (ex: loop piplining, urolling, merging..etc) can be applied on my code?

I am new to parallel implementation using optimization techniques. I read many documentations about this topic.

But I am not sure what optimization technique is the proper to be applied on my code to reduce execution time.

(ex: loop pipliing, loop unrolling, dataflow, loop merging ...etc )

my code:

for (int i = 0; i < 4344; i++)
    {
        for (int j = i + 1; j < 4344; j++)
        {
            if (array_dist[index_arr[i]] > array_dist[index_arr[j]])
            {
                x = index_arr[i];
                index_arr[i] = index_arr[j];
                index_arr[j] = x;
            }

        }
    }

The C++ Programming Language 4th edition A desk calculator return ct={Kind::name;} the output is wrong when i input pi

when i copy the code from the book The C++ Programming Language Fourth Edition ,Bjarne Stroustrup I found out that when i input a pi(which has been defined in the code) the output is wrong so i spent 1 day to find out the problem. i just share it

#include<iostream>
#include<map>
#include<string>
#include<sstream>
#include<cctype>

enum class Kind:char{
  name,number,end,
  plus='+',minus='-',mul='*',div='/',print=';',assign='=',lp='(',rp=')'
};

struct Token{
  Kind kind;
  std::string string_value;
  double number_value;
};

int no_of_errors;

double error(const std::string& s)
{
  no_of_errors++;
  std::cerr<<"error: "<<s<<'\n';
  return 1;
}

std::map<std::string,double> table;

double expr(bool get);
double term(bool get);
double prim(bool get);

class Token_stream{
public:
  Token_stream(std::istream& s):ip{&s},owns{false}{}
  Token_stream(std::istream* p):ip{p},owns{true}{}

  ~Token_stream(){close();}

  Token get();
  Token& current(){return ct;}

  void set_input(std::istream& s){close();ip=&s;owns=false;}
  void set_input(std::istream* p){close();ip=p;owns=true;}

private:
  void close(){if(owns) delete ip;}

  std::istream* ip;
  bool owns;
  Token ct{Kind::end};
};

Token_stream ts{std::cin};

//Token& Token_stream::current()
//{
//  return ct;
//}

Token Token_stream::get()
{
  char ch;

  do{
    if(!ip->get(ch)){
      return ct={Kind::end};
    }
  }while(ch!='\n' && std::isspace(ch));

  switch(ch){
    case ';':
    case '\n':
      return ct={Kind::print};
    case '*':
    case '/':
    case '+':
    case '-':
    case '(':
    case ')':
    case '=':
      return ct={static_cast<Kind>(ch)};
    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
    case '.':{
      ip->putback(ch);
      *ip>>ct.number_value;
      ct.kind=Kind::number;
      return ct;
    }
    default:
      if(std::isalpha(ch)){
        ct.string_value = ch;
        while(ip->get(ch) && std::isalnum(ch)){
          ct.string_value +=ch;
        }
        //test
        //std::cout<<ts.current().string_value<<'\n';
        //std::cout<<table[ct.string_value]<<'\n';
        ip->putback(ch);
        return ct={Kind::name,ct.string_value};
      }
      error("bad token");
      return ct={Kind::print};
  }
}

double expr(bool get)
{
//test  
//  std::cout<<ts.current().string_value<<'\n';
//  std::cout<<table[ts.current().string_value]<<'\n';
  double left=term(get);

  for(;;){
    switch(ts.current().kind){
      case Kind::plus:
        left += term(true);
        break;
      case Kind::minus:
        left-= term(true);
        break;
      default:
        return left;
    }
  }
}

double term(bool get)
{
  double left = prim(get);

  for(;;){
    switch(ts.current().kind){
      case Kind::mul:
        left *= prim(true);
        break;
      case Kind::div:
        if(auto d = prim(true)){
          left /= d;
          break;
        }
        return error("divide by 0");
      default:
        return left;
    }
  }
}

double prim(bool get)
{
  if(get){
    ts.get();
  }

  switch(ts.current().kind){
    case Kind::number:
    {
      double v=ts.current().number_value;
      ts.get();
      return v;
    }
    case Kind::name:
    {
      //test
      //std::cout<<ts.current().string_value<<'\n';
      double& v=table[ts.current().string_value];
      //std::cout<<table[ts.current().string_value]<<'\n';
      if(ts.get().kind == Kind::assign){
        v=expr(true);
      }
      //std::cout<<ts.current().string_value<<'\n';
      //std::cout<<v<<'\n';
      //std::cout<<table[ts.current().string_value]<<'\n';
      return v;
    }
    case Kind::lp:
    {
      auto e = expr(true);
      if(ts.current().kind!=Kind::rp){
        return error("')' expected");
      }
      void(ts.get());
      return e;
    }
    default:
      return error("primary expected");
  }
}

void calculate()
{
  for(;;){
    ts.get();
    //test
    //if(ts.current().kind != Kind::number){
    //  std::cout<<"number"<<'\n';
    //}
    if(ts.current().kind == Kind::end)break;
    if(ts.current().kind == Kind::print)continue;
    std::cout<<expr(false)<<'\n';
  }
}


int main(int arg,char* argv[])
{
  switch(arg){
    case 1:
      break;
    case 2:
      ts.set_input(new std::istringstream{argv[1]});
      break;
    default:
      error("too many arguments");
      return 1;
  }

  table["pi"] = 3.1415926535897932385;
  table["e"] = 2.7182818284590452354;

  calculate();
  return no_of_errors;

}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         233,1         Bot


the most important for correct the error is as follows:

//in member function Token Token_stream::get()
//old code:
return ct={Kind::name;}

we should change the code like this:

//in member function Token Token_stream::get()
//new code:
return ct={Kind::name,ct.string_value}

C++11 is not executing switch correctly when variable is declared in case block

Consider the snippet below. If I compile this with GCC/C++11 then I expect that if I call this with e.g. var=2 that that block is executed. Anyway I expect at least one of the 3 switch blocks are called.

However what I get is only the "start" and "end" lines. So this switch block is not working: even "default" is not called. I even did not believe GDB when I saw this!

The root cause of this is the variable declaration in case block 1 (int anotherVar). To fix this problem I need to add brackets around case 1 (own scope) or decl the variable in the constructor body at the top.

My Questions are:

  • Why is this happening? What is the technical reason? If this is not happening in all situations, then in which situations can this happen?
  • Is there a compiler error/warning flag for this?
MyClass::MyClass(int var) { 
   std::cout << "Constructor start" << std::endl;
   switch (var) {
     case 1:
       std::cout << "Case 1 executed" << std::endl;
       int anotherVar = doSomething();
     case 2:
       std::cout << "Case 2 executed" <<std::endl;
     break;
     default:
       std:cout << "Default executed" << std::endl;
   }
   std::cout << "Constructor ended" << std::endl;
}`

This outputs when called with var=2:

Constructor start
Constructor ended

Why is copy assigment possible, if a class has only a (templated) move assignment operator?

I have stumbled over code today, that I don't understand. Please consider the following example:

#include <iostream>
#include <string>

class A
{
public:
    template <class Type>
    Type& operator=(Type&& theOther)
    {
        text = std::forward<Type>(theOther).text;

        return *this;
    }

private:
    std::string text;
};

class B
{
public:
    B& operator=(B&& theOther)
    {
        text = std::forward<B>(theOther).text;

        return *this;
    }

private:
    std::string text;
};

int main()
{
    A a1;
    A a2;
    a2 = a1;

    B b1;
    B b2;
    b2 = b1;

    return 0;
}

When compiling, MinGW-w64/g++ 10.2 states:

..\src\Main.cpp: In function 'int main()':
..\src\Main.cpp:41:7: error: use of deleted function 'B& B::operator=(const B&)'
   41 |  b2 = b1;
      |       ^~
..\src\Main.cpp:19:7: note: 'B& B::operator=(const B&)' is implicitly declared as deleted because 'B' declares a move constructor or move assignment operator
   19 | class B
      |       ^
mingw32-make: *** [Makefile:419: Main.o] Error 1

I fully understand the error message. But I don't understand why I don't get the same message with class A. Isn't the templated move assignment operator also a move assignment operator? Why then is the copy assignment operator not deleted? Is this well-written code?

Is it allowed to use the name of an enum when specifying its underlying type?

In the current C++ working draft, the name of an enum becomes "visible" immediately after it ([basic.scope.pdecl] p3):

The locus of an enum-specifier or opaque-enum-declaration is immediately after the identifier (if any) in it ([dcl.enum]).

It seems that the rule has been essentially unchanged since C++11 (WG21-N3337).

However, I haven't found any compiler accepting the following usage. All of gcc, clang, msvc, and icc rejects it, saying foo is not declared or defined.

template<class> using mapped_to_int = int;
enum foo : mapped_to_int<foo> {};

Is there any rule rejecting such usage in the Standard?

mercredi 27 octobre 2021

C++ LNK2019 Unresolved External Symbol: What about my code is causing this error? [closed]

I am new to C++ and am having a hard time figuring this one out. I get the following two errors: LNK2019 "unresolved external symbol void_cdecl editExistingEntry(struct CustomerAccount * const, int) (? editExistingEntry@@YAXQUACustomerAccount@@H@Z) referenced in function_main

Followed by a LNK1120 error... My code will not even compile.

Here is my code:

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

struct CustomerAccount {
    string name;
    string address;
    string city;
    string state;
    string zip;
    string telephone;
    double acc_balance;
    string dateOfLastPayment;
};

// function prototyes
// enter new data function
void addNewEntries(CustomerAccount[], int);
// change existing data function
void editExistingEntry(CustomerAccount[], int);
// display data function
void displayEntries(const CustomerAccount[], int);

// main function
int main() {

    // variable to hold menu choice
    char choice;
    // named constant for number of customers
    const int NUM_CUSTOMERS = 10;
    // array to hold 10 CustomerAccount structures
    CustomerAccount customers[NUM_CUSTOMERS];

    // display menu
    cout << "Please choose an option from the following menu: \n";
    cout << "A) Enter new customers' data \n";
    cout << "B) Edit an existing customer's data \n";
    cout << "C) Display all customer data \n";
    cin >> choice;

    if (choice == 'a' || choice == 'A') {
        // call addNewEntries function
        addNewEntries(customers, NUM_CUSTOMERS);
    }

    if (choice == 'b' || choice == 'B') {
        // call editExistingEntry function
        editExistingEntry(customers, NUM_CUSTOMERS);
    }

    if (choice == 'c' || choice == 'C') {
        // call displayEntries function
        displayEntries(customers, NUM_CUSTOMERS);
    }
    return 0;
}

//****************************************************************************************************************
// displayEntries function: accepts array of customerAccount structures and its size as arguments, displays the 
// contents of the array.
//****************************************************************************************************************
void displayEntries(const CustomerAccount customers_array[], int size_of_array) {
    for (int index = 0; index < size_of_array; index++) {
        cout << "Customer #" << (index + 1) << endl;
        cout << "Name: " << customers_array[index].name << endl;
        cout << "Address: " << customers_array[index].address << endl;
        cout << "City: " << customers_array[index].city << endl;
        cout << "State: " << customers_array[index].state << endl;
        cout << "Zip: " << customers_array[index].zip << endl;
        cout << "Telephone: " << customers_array[index].telephone << endl;
        cout << "Account Balance: " << customers_array[index].acc_balance << endl;
        cout << "Date of Last Payment: " << customers_array[index].dateOfLastPayment << endl << endl;
    }
}

//****************************************************************************************************************
// addNewEntries function: accepts array of customerAccount structures and its size as arguments, allows the 
// user to enter data for 10 new customer accounts.
//****************************************************************************************************************
void addNewEntries(CustomerAccount customers_array[], int size_of_array) {
    // variable to temporarily hold account balance for input validation
    double temp_acc_balance;
    cout << "Enter the data for 10 customer accounts: ";
    for (int index = 0; index < size_of_array; index++) {
        cout << "Customer #" << (index + 1) << endl;
        // get name
        cout << "Enter Name: " << endl;
        getline(cin, customers_array[index].name);
        // get address
        cout << "Enter Address: " << endl;
        getline(cin, customers_array[index].address);
        // get city
        cout << "Enter City: " << endl;
        getline(cin, customers_array[index].city);
        // get state
        cout << "Enter State: " << endl;
        getline(cin, customers_array[index].state);
        // get zip
        cout << "Enter Zip: " << endl;
        getline(cin, customers_array[index].zip);
        // get telephone
        cout << "Enter Telephone: " << endl;
        getline(cin, customers_array[index].telephone);
        // get account balance
        cout << "Enter Account Balance: " << endl;
        cin >> temp_acc_balance;
        // validate input for account balance
        if (temp_acc_balance < 0) {
            cout << "You entered an invalid entry. Please run the program again and enter a positive value.\n";
        }
        else {
            customers_array[index].acc_balance = temp_acc_balance;
        }
        // get date of last payment
        cout << "Enter Date of Last Payment: " << endl;
        cin >> customers_array[index].dateOfLastPayment;
    }
}

//****************************************************************************************************************
// editExistingEntries function: accepts array of customerAccount structures as an argument, allows the 
// user to edit data for one of the 10 existing customer accounts.
//****************************************************************************************************************
void editExistingEntries(CustomerAccount customers_array[], int size_of_array) {
    // variable to hold user's choice 
    short customer_to_edit;
    // ask user which of the 10 accounts they want to edit
    cout << "Which of the 10 existing accounts would you like to edit? (Enter a value 1-10) \n";
    cin >> customer_to_edit;
    // allow user to edit the name of the chosen customer
    cout << "Edit Name: \n";
    cin >> customers_array[customer_to_edit - 1].name;
    // edit address
    cout << "Edit Address: \n";
    cin >> customers_array[customer_to_edit - 1].address;
    // edit city
    cout << "Edit City: \n";
    cin >> customers_array[customer_to_edit - 1].city;
    // edit state
    cout << "Edit State: \n";
    cin >> customers_array[customer_to_edit - 1].state;
    // edit zip
    cout << "Edit Zip: \n";
    cin >> customers_array[customer_to_edit - 1].zip;
    // edit telephone
    cout << "Edit Telephone: \n";
    cin >> customers_array[customer_to_edit - 1].telephone;
    // edit account balance
    cout << "Edit Account Balance: \n";
    cin >> customers_array[customer_to_edit - 1].acc_balance;
    // edit date of last payment
    cout << "Edit Date of Last Payment: \n";
    cin >> customers_array[customer_to_edit - 1].dateOfLastPayment;

}

explanation on Delete copy/move so extra instances can't be created/moved

I am exploring design patterns in cpp, in singleton pattern we usually saw this piece of code

// Delete copy/move so extra instances can't be created/moved.
  Singleton(const Singleton&) = delete;
  Singleton& operator=(const Singleton&) = delete;
  Singleton(Singleton&&) = delete;
  Singleton& operator=(Singleton&&) = delete;

didn't see any good explanation of what these part of code are doing? Is it possible to get a line by line explanation of what each line is doing?

How to write function to check all combinations in a given array in C++11

I have an array of pairs containing. First number in a pair describes time it takes to do a task and second is the time before it must be done. After "using" one element it's time adds to total time. The problem is to find maximum number of elements of an array that can be used. How to check all combinations of elements and keep track of sum of time? I have done it recursively but that's messy and pretty inefficient in terms of memory.

C++ CUDA using Halton Sequence for Monte Carlo Simulation

I am quite new to programming in CUDA C++ and I am struggling to get this code to work. In short, it runs a Quasi Monte Carlo Simulation of stock prices. I have mainly three parts: the halton.cpp and halton.h to generate the Quasi random number, the main.cpp to run the process and the kernel.h and kernel.cu for implementing the Quasi monte carlo using CUDA.

However I keep getting errors like:

In file included from main.cpp:9:0:
/usr/include/curand.h:70:1: error: expected initializer before ‘extern’
 extern "C" {
 ^~~~~~
In file included from /usr/include/boost/math/policies/error_handling.hpp:15:0,
                 from /usr/include/boost/math/special_functions/gamma.hpp:23,
                 from /usr/include/boost/math/special_functions/erf.hpp:15,
                 from /usr/include/boost/math/distributions/normal.hpp:19,
                 from main.cpp:11:
/usr/include/c++/6/typeinfo:39:37: error: expected declaration before end of line
 #pragma GCC visibility push(default)

when i compile using

nvcc -o test main.cpp halton.cpp kernel.cu -lcurand

My files are like this and do anyone know what has gone wrong in my code?

main.cpp

#include <chrono>
#include <iostream>
#include <string>
#include <random>
#include <vector>
#include <math.h>
#include <cuda_runtime.h>
#include "kernel.h"
#include <curand.h>

#include <boost/math/distributions/normal.hpp>

#include "halton.hpp"

using namespace std;

void quasi_random_number_1d(double* rand_nums, int size, int skip) {
    boost::math::normal norm;
    const int LIMIT = 1600;
    int dim = 1;
    int count = 0;

    double halton_num;
    float quasi_num;
    double* quasi_seq;

    while (true) {
        quasi_seq = halton(dim, LIMIT);
        for (int i=0; i<LIMIT; i=i+skip){
            halton_num = *(quasi_seq+i);
            rand_nums[count] = (quantile(complement(norm, halton_num)));
            count++;
            if (count >= size) break;
        }
        dim += 1;
    }
    // return rand_nums;
}

int main() {

    // place quasi randnums in d_normal
    double S = 100;
    double sigma = 0.2;
    double rate = 0.02;
    double T = 3;
    double K = 95;
    int n = 10; // num of step
    int m = 10; // num of path

    double Zs [n*m];
    quasi_random_number_1d(Zs, n*m, 2);
    double ST [m];

    run_mc(ST, S, sigma, rate, T, n, m, Zs);

    for (int i=0; i<m; i++) {
        cout << ST[i] << " ";
    }
    cout << endl;

    return 0;
}

kernel.h

#ifndef _KERNEL_CUH_
#define _KERNEL_CUH_


// double S, double sigma, double rate, double T, double K, int n, int m, int seed=1126


// void run_mc(float * d_s,float T, float K, float B,
//  float S0, float sigma, float mu, float r,
//  float dt, float* d_normals, unsigned N_STEPS, unsigned N_PATHS);

void run_mc(double* ST, double S, double sigma, double rate, double T, int n,
    int m, double* Zs)

#endif

kernel.cu

#include "kernel.h"
#include <stdexcept>
#include <algorithm>
#include <math.h>

__global__ void monte_carlo_sim();

void run_mc(double* ST, double S, double sigma, double rate, double T, int n,
    int m, double* Zs) {

    double deltaT = T/n;
    double drift = exp(rate - 0.5*(pow(sigma, 2.0))*deltaT);

    // arrays
    double* d_ST = nullptr
    double* d_Zs = nullptr;
    cudaMalloc((void**)&dev_Zs, size * sizeof(double));
    cudaMalloc((void**)&dev_ST, size * sizeof(double));

    // values
    double d_S, d_sigma, d_deltaT, d_drift;
    int d_n, d_m;
    cudaMalloc(&d_S, sizeof(double));
    cudaMalloc(&d_sigma, sizeof(double));
    cudaMalloc(&d_deltaT, sizeof(double));
    cudaMalloc(&d_drift, sizeof(double));
    cudaMalloc(&d_n, sizeof(int));
    cudaMalloc(&d_m, sizeof(int));

    // copy values from host to device
    cudaMemcpy(d_Zs, Zs, size, cudaMemcpyHostToDevice);
    cudaMemcpy(d_ST, ST, size, cudaMemcpyHostToDevice);
    cudaMemcpy(d_S, S, size, cudaMemcpyHostToDevice);
    cudaMemcpy(d_sigma, sigma, size, cudaMemcpyHostToDevice);
    cudaMemcpy(d_deltaT, delta, size, cudaMemcpyHostToDevice);
    cudaMemcpy(d_drift, drift, size, cudaMemcpyHostToDevice);
    cudaMemcpy(d_n, n, size, cudaMemcpyHostToDevice);
    cudaMemcpy(d_m, m, size, cudaMemcpyHostToDevice);

    //test
    int threadsPerBlock,blocksPerGrid;
    if (n_el<1024){
        threadsPerBlock = n_el;
        blocksPerGrid   = 1;
    } else {
        threadsPerBlock = 1024;
        blocksPerGrid   = ceil(double(n_el)/double(threadsPerBlock));
    }

    // invoke the kernel
    monte_carlo_sim<<<blocksPerGrid,threadsPerBlock>>>(d_ST, d_Zs,
        d_S, d_sigma, d_deltaT, d_n, d_m);

    cudaMemcpy(ST, d_ST, size, cudaMemcpyDeviceToHost);

    // free device memory
    cudaFree(d_Zs);
    cudaFree(d_ST);
    cudaFree(d_S);
    cudaFree(d_sigma);
    cudaFree(d_deltaT);
    cudaFree(d_drift);
    cudaFree(d_n);
    cudaFree(d_m);

    // free host memory
    delete[] d_Zs;

}

__global__ void monte_carlo_sim(double* d_ST, const double* d_Zs,
    const double* d_S, const double* d_sigma, const double* d_deltaT,
    const double* d_n, const double* d_m) {

    const unsigned tid = threadIdx.x;
    const unsigned bid = blockIdx.x;
    const unsigned bsz = blockDim.x;

    int s_idx = tid + bid * bsz;
    int n_idx = tid + bid * bsz;

    double S = d_S;

    if (s_idx < d_m) {
        int ni = 0;
        do {
            S = S * d_drift * exp(d_sigma * sqrt(d_deltaT) * d_Zs[n_idx]);
        }
        while (ni < d_n);
        d_ST[s_idx] = S;
    }
}

For reference, the code below is an implementation for Monte Carlo Simulation for CPU/non-GPU/non-cuda:

#include <iostream>
#include <string>
#include <random>
#include <vector>
#include <math.h>

#include <boost/math/distributions/normal.hpp>

#include "halton.hpp"

using namespace std;

/*
Random Number Generator
*/

vector<vector<double>> quasi_random_number(int n, int m, int seed) {

    boost::math::normal norm;

    double* quasi_seq = halton(seed, n*m);
    vector<vector<double>> rand_nums(m, vector<double> (n, 0));

    for (int mi=0; mi<m; mi++){
        for (int ni=0; ni<n; ni++){
            double halton_num = *(quasi_seq+mi+ni);
            rand_nums[mi][ni] = quantile(complement(norm, halton_num));
        }
    }

    return rand_nums;
}

vector<vector<double>> pseudo_random_number(int n, int m, int seed) {
    std::default_random_engine generator(seed);
    std::normal_distribution<double> distribution (0.0,1.0);

    vector<vector<double>> rand_nums(m, vector<double> (n, 0));

    for (int mi=0; mi<m; mi++){
        for (int ni=0; ni<n; ni++){
            rand_nums[mi][ni] = distribution(generator);
        }
    }

    return rand_nums;
}



/*
Monte Carlo Simulation
*/

double compute_growth_factor(const double &drift, const double &sigma, const double &deltaT, const double &Z) {
    return drift * exp(sigma * sqrt(deltaT) * Z);
}

vector<vector<double>> monte_carlo_simulate(double S, double sigma, double rate, double T, double K, int n, int m, int seed=1126) {
    /*
    S - stock price
    sigma - stock variance
    rate - discount rate
    T - time periods
    K - strike price
    n - number of simulation period
    m - number of simulations
    */

    double deltaT = T/n;
    double drift = exp(rate - 0.5*(pow(sigma, 2.0))*deltaT);

    // vector<vector<double>>  Zs = pseudo_random_number(n, m, seed);
    vector<vector<double>>  Zs = quasi_random_number(n, m, seed);

    double growth_factor;
    vector<vector<double>> S_path(m, vector<double> (n, 0));

    for (int mi=0; mi<m; mi++) {
        vector<double> Z = Zs.at(mi);
        double growth_factor = compute_growth_factor(drift, sigma, deltaT, Z.at(0));
        S_path[mi][0] = S * growth_factor;
        for (int ni=1; ni<n; ni++) {
            growth_factor = compute_growth_factor(drift, sigma, deltaT, Z.at(ni));
            S_path[mi][ni] = growth_factor * S_path[mi][ni-1];
        }
    }
    return S_path;
}

int main() {

    vector<vector<double>> stock_paths = monte_carlo_simulate(100, 0.2, 0.02, 3, 95, 10, 10);

    for (int x=0; x<stock_paths.size(); x++) {
        for (int y=0; y<stock_paths[0].size(); y++) {
            std::cout << stock_paths[x][y] << " ";
        }
        std::cout << std::endl;
    }

    return 0;
}

Assigning an array with std::fgetc() return

I am trying to store the first 4 chars of a .awv file using the std::fgetc function

This is what I have

FILE* WAVF = fopen(FName, "rb");
std::vector<std::string> ID;
ID[4];
for (int i = 0; i < 4; i++)
{
    ID[i] = fgetc(WAVF);
}

I keep getting this error:

Exception thrown at 0x00007FF696431309 in ConsoleApplication3.exe: 
0xC0000005: Access violation writing location 0x0000000000000010.

What is the change I need to make to perform reverse of upper_bound?

I feel lower_bound in c++ stl is not the opposite of the upper_bound function. By default, in a non-decreasing array, if I use upper_bound and if the element is found and it is not the last element in the sorted array, then the next element > passed element is given and if the element is then last element or not found, then end() iterator returned. The following C++ code can be used to test this.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int
main ()
{
  vector<int> arr{-973, -808, -550, 301, 414, 897};
  auto p = upper_bound (arr.begin (), arr.end (), 301);
  if (p != arr.end ())
    cout << *p << endl;
  else
    cout << "end" << endl;
  return 0;
}
// Output: 414

But now I need the opposite thing. I need the smaller element from the matched element to be returned. In the above example, if I pass 301, then, I want to get -550 in return. Currently, I am using the following code and it seems to work for the given example but I am not sure if it is the right code or I need to implement it manually using binary search.

auto p = upper_bound(arr.rbegin(), arr.rend(), 301, greater<int>());

PS. I am using if (p != arr.rend ()) for this.

std::vector and move semantics

To enable move semantics on a std::vector do I need to pass by value; so the compiler will not copy the element but just move them?

Example:

class data
{
public:
    void setMyData(vector<string> sourceData)
    {
        private_data_ = sourceData;
    }

private:
    vector<string> private_data_;
};

C++ Output array function

I am currently following Deitel's C++ How to Program 9th edition textbook and am having difficulties with a particular problem.

The problem is to take a the code written earlier on in the chapter using the vector class template and rewrite using the array class template.

In the code there are the following functions for inputting data into the vector and displaying the vector.

// output vector contents
void outputVector( const vector< int > &array )
{
    for ( int item : array )
        cout << item << " ";

    cout << endl;
} // end function outputVector

// input vector contents
void inputVector( vector< int > &array )
{
    for ( int &item : array )
        cin >> item;
} // end function inputVector

My confusion here is I do not know how to create such functions which take an array template as an argument, for example with lengths 7 and 10 as is the case in the vector template version of the code.

Is this possible or must a function be defined for a specific length array template?

Further, if this is the case, then what really is the value of using an array over a vector?

Thanks

Address of reference variable is different when function is called using std::async

In the following snippet of code, the address of v in print function is same as address of a when std::ref(a) is used in std::async, but different when a is passed

#include <iostream>
#include <future>

void print (const int& v)
{
    std::cout  << "&v = " << &v << "\n";
}


int main()
{
    int a = 10;

    auto f = std::async(print, std::ref(a));
    f.get();
    
    std::cout  << "&a = " << &a << "\n";

    return 0;
}

output

&v = 0x7ffd3b5000b4
&a = 0x7ffd3b5000b4

But when I remove std::ref then address is different

auto f = std::async(print, a);

output

&v = 0x55586497cef8
&a = 0x7ffee2e3dadc

Question:

  • Do std::async copies the data rather than reference if std::ref is not used ?
  • why addresses is changes even though my print function parameter is reference type const int &

Reference: Passing arguments to std::async by reference fails

Constructor with variable number of arguments

I want to add a constructor that could allow a variable number of arguments. caller is a function that could call other functions with their arguments(something simliar to thread but for calling functions only). I already made it with a function template

template <class C,class ... _Args >
void caller(C(*f) ( _Args ... __args ), _Args ... __args ){(*f ) ( __args ...) ;}

But I need to have a class because it also should make an object of this class. something like this.

caller()

I made a class for caller with a constractor that could call other functions with a known number of arguments.

#include <iostream>
class caller  {
public:
caller(){std::cout<<"Constructor default";  }
caller(void (*Optype)(int),int a){Optype(a);std::cout<<"Constructor 1";  }
//*** Constructor for variable number of arguments**
};

and it works correctly with following code

#include <iostream>
#include "caller"
using namespace std;
void foo(int a){
  cout<<a<<endl;
}
int main()
{
  caller c;
  caller(); 
  caller(foo,2);  
  return 1;
}

I want to know how can I add a constructor which works with different numbers of variables and is it possible it allows different types of variables too? I ask for something like the function template that I already made but in the class.

How can I translate this python function to c++?

I am trying to translate a python function to c++ without success. Can someone help me?

The python function receives as input a string S and 2 integers (fragment_size and jump). The aim of this function is to slice the string S in a number of fragments of length equal to the first integer given by the input (fragment_size) and traverse the whole string S with a step equal to the second integer given by the input (jump).

import sys
# First we read the input and asign it to 3 different variables
S = sys.stdin.readline().strip()
fragment_size = sys.stdin.readline().strip()
jump = sys.stdin.readline().strip()

def window(S, fragment_size, jump):
    for i in range(0, len(S), jump):
        word = S[i:i+fragment_size]
        if len(word)< fragment_size:
            return []
        else:
            return [word] + window(S[jump:], fragment_size, jump)

# We check that S is not an empty string and that fragment_size and jump are bigger than 0. 
if len(S) > 0 and int(fragment_size) > 0 and int(jump) > 0:
    # We print the results 
    for i in window(S, int(fragment_size), int(jump)):
        print(i)

For example: Input ACGGTAGACCT 3 1

Output ACG CGG GGT GTA TAG AGA GAC ACC CCT

Example 2: Input ACGGTAGACCT 3 3

Output ACG GTA GAC

Thanks!

only enable template function for specified types / disable for any other types

//my_utils.h
namespace A {
 namespace B {
  template <typename T, typename U>
  T encode( U value ) = delete;
  
  template <typename T, typename U>
  U decode( T value ) = delete;

  uint8_t encode( bool value );

  bool decode( uint8_t value );
  .
  .
  .
  //in this same .h file
  template <typename T>
  class X {
    public:
     void func() {
       uint8_t a = encode(bool_var);
     }
  };
 }
}

//myutils.cpp
namespace A {
 namespace B {
  
  uint8_t encode<uint8_t, bool>( bool value ) {
    //do something
  }

  bool decode<uint8_t, bool>( uint8_t value ) {
    //do something
  }

 }
}

It works this way but I was wondering... is this the right way? I was spending quite some time trying to make it work with template specialization but I just couldn't figure it out.For example it works with "const char *" but it's not what my intention was.

My goal was to disable this function for any type other than those I specialized and disable implicit type conversion at the same time.

Any toughts on this? Is there a better practice?

I'm using templates more and more and I really see some benefits there, but I still feel like I'm hopeless sometimes.

When dose move constructor and default constructor called [duplicate]

I have this code

class MyString {
    public:
        MyString();
        MyString(const char*);
        MyString(const String&);
        MyString(String&&) noexcept;
        ...
};

String::String()
{
    std::cout << "default construct!" <<std::endl;
}

String::String(const char* cb)
{
    std::cout << "construct with C-char!" <<std::endl;
    ...
}


String::String(const String& str)
{
    std::cout << "copy construct!" <<std::endl;
    ...
}

String::String(String&& str) noexcept
{
    std::cout << "move construct!" <<std::endl;
    ...
}

In main()

MyString s1(MyString("test"));

I thought result would be this:

construct with C-char! <---- called by MyString("test")
move construct! <---- called by s1(...)

But what I get was this:

construct with C-char! <---- maybe called by MyString()

The steps what I thought

  1. MyString("test") construct a rvalue by using the constructor with char*
  2. Construct s1(arg)
  3. Because of arg is a rvalue, s1 should construct by move constructor But I find move constructor won't be called without std::move.

Why is that happening?
How to use move constructor without std::move()?

Compiler:
Gnu C++ 9.3.0

mardi 26 octobre 2021

How can I eliminate garbage value in this output?

In this below program, I'm trying to marge 2 arrays into a single vector, but while returning the function I'm getting additional garbage values along with it.

Please anyone suggest me how to remove those!

#include <bits/stdc++.h>
#include <vector>
#include <string>

using namespace std;

vector <int> merge(int a[],int b[]){
  vector <int> marr1;
  marr1.clear();
  int i=0,j=0;
  while(i+j <= ((*(&a+1)-a)+(*(&b+1)-b)))
  {
    if ((i<= *(&a+1)-a)){
      marr1.push_back(a[i]);
      i++;
    }
    else{
       marr1.push_back(b[j]);
      j++;
    }
  }
  sort(marr1.begin(),marr1.end());
return marr1;
}

int main(){
  //array imlementation
  int arr1[] = {5,7,4,5},arr2[] = {8,3,7,1,9};
  vector <int> ans;
  ans.clear();
  ans = merge(arr1,arr2);
  for (auto i=ans.begin();i<ans.end();++i){
    cout<<*i<<"\t";
  }
}

output produced:

0   0   0   0   1   3   4   5   5   7   7   8   9   32614   32766   4207952 1400400592

How do I insert user input variables into same spot in vector

//Main driver

int main(){

//If I run the code below.

    vector<string> A = {"My name is Muzaib.\n Hello"};
    cout << A[0];

//It will print My name is Muzaib

// Hello

//But what I want to know is how do I do the same but with user input?

string name, age;
cout << "Enter name: ";
getline(cin,name);
cout << "\nEnter age: ";
getline(cin,age);
vector<string> B = {"name \n age"}  //remember I want it in the same spot.
cout << B[0]

​ return 0; }

std::lock_guard and std::adopt_lock behaviour without locking the mutex

I have been learning about the usage of std::lock and std::lock_guard and most examples follow the pattern below:

std::lock(m1, m2);
std::lock_guard<std::mutex> guard1(m1, std::adopt_lock);
std::lock_guard<std::mutex> guard2(m2, std::adopt_lock);
//Do something here

Then I came across an example that utilized the same pattern you would use if you were using std::unique_lock, but with lock_guard:

std::lock_guard<std::mutex> guard1(m1, std::adopt_lock);
std::lock_guard<std::mutex> guard2(m2, std::adopt_lock);
std::lock(m1, m2);
//Do something here

My question is, would this cause undefined behaviour if you use the second pattern and an exception occurs before you reach std::lock?

P.S. I am aware that C++17 introduced std::scoped_lock and that std::lock_guard is still around mainly for compatibility with older code.

Make thread library [closed]

I want to simulate thread library. I already make separate class and function template but I get error to use both of them. How can I use both of them? Are they right or I should follow another method.

class thread  {
public:
    thread() { }
};
template <class P,class ... _Args >
void thread(P(*f) ( _Args ... __args ), _Args ... __args ){(*f ) ( __args ...) ;}

I want to have following constructor and function by thread.

void add(){
  cout<<"Method add"<<endl;
}
int main()
{
  thread t1;
  thread(add);
  thread(bar,0);  
  thread();  
  return 1;
}

What is the order of destruction for static objects and global objects?

If in a program I create a meyer's singleton and an object that uses this meyer's singleton in both its constructor and destructor, things are okay as long as the object that uses meyer's singleton is destroyed before the singleton itself (like when it is in a function scope).

Now if I make the same object global, I see seg fault. The reason is that the singleton gets destroyed before the global object.

Is this a compiler defined behaviour or standard defined behaviour? Is there any way we can modify this behaviour?

Any pointers will be appreciated.

lundi 25 octobre 2021

Asio multicast read/write

I have seen the below samples: boost_asio/example/cpp11/multicast/receiver.cpp boost_asio/example/cpp11/multicast/sender.cpp

Is it possible for the receiver & sender to do a read & write operation in both the classes?

Currently the sender writes data, while the receiver reads data. I want the sender to read & write and the same applies to the receiver as well. Are any code examples available?

how to emplace in map of(string and vector)..?

I'm not sure if it is possible to have a vector inside of a map container.

If yes, can I have the map with vector and vector?

INPUT

ONE 1 11 111 1111
TWO 22 2 2222
THREE 333 3333 3
map<string, vector<int>> mp;

How to emplace the input in the above container?

map<vector<int>, vector<int>> mp;

If this is possible to implement, how will you emplace elements here, and how can you access those elements?

Debugging C++ in (Neo)vim

I just switched from windows 10 to arch linux I want to use (Neo)Vim as my code editor I've sitted up autocomplition and Fuzzy finder But I have no idea how to debug in (Neo)Vim

Any helps!

Should I use for iterators instead of for range based loop, if so, why?

I just learned about iterators. Should I use this?

for (auto& i : just_a_vec )

Or this?

for (std::vector<std::string>::iterator it = just_a_vec.begin(); it < just_a_vec.end(); it++)

And if so, why this is the case?

c++ dynamic memory allocation - matrix multiplication

I am trying to do a large matrix multiplication, e.g. 1000x1000. Unfortunately, it only works for very small matrices. For the big ones, the program just turns on and that's all - no results. Here's the code:

#include <iostream>

using namespace std;

int main() {
    int matrix_1_row;
    int matrix_1_column;
    matrix_1_row = 10;
    matrix_1_column = 10;

    int** array_1 = new int* [matrix_1_row];
    // dynamically allocate memory of size matrix_1_column for each row
    for (int i = 0; i < matrix_1_row; i++)
    {
        array_1[i] = new int[matrix_1_column];
    }
    // assign values to allocated memory
    for (int i = 0; i < matrix_1_row; i++)
    {
        for (int j = 0; j < matrix_1_column; j++)
        {
            array_1[i][j] = 3;
        }
    }

    int matrix_2_row;
    int matrix_2_column;
    matrix_2_row = 10;
    matrix_2_column = 10;
    // dynamically create array of pointers of size matrix_2_row
    int** array_2 = new int* [matrix_2_row];
    // dynamically allocate memory of size matrix_2_column for each row
    for (int i = 0; i < matrix_2_row; i++)
    {
        array_2[i] = new int[matrix_2_column];
    }
    // assign values to allocated memory
    for (int i = 0; i < matrix_2_row; i++)
    {
        for (int j = 0; j < matrix_2_column; j++)
        {
            array_2[i][j] = 2;
        }
    }

    // Result
    int result_row = matrix_1_row;
    int result_column = matrix_2_column;
    // dynamically create array of pointers of size result_row
    int** array_3 = new int* [result_row];
    // dynamically allocate memory of size result_column for each row
    for (int i = 0; i < result_row; i++)
    {
        array_3[i] = new int[result_column];
    }


    // Matrix multiplication
    for (int i = 0; i < matrix_1_row; i++)
    {
        for (int j = 0; j < matrix_2_column; j++)
        {
            array_3[i][j] = 0;
            for (int k = 0; k < matrix_1_column; k++)
            {
                array_3[i][j] += array_1[i][k] * array_2[k][j];
            }
        }
    }


    //RESULTS
    for (int i = 0; i < result_row; i++)
    {
        for (int j = 0; j < result_column; j++)
        {
            std::cout << array_3[i][j] << "\t";
        }
    }


    // deallocate memory using delete[] operator 1st matrix
    for (int i = 0; i < matrix_1_row; i++)
    {
        delete[] array_1[i];
    }
    delete[] array_1;
    // deallocate memory using delete[] operator 2nd matrix
    for (int i = 0; i < matrix_2_row; i++)
    {
        delete[] array_2[i];
    }
    delete[] array_2;
    // deallocate memory using delete[] operator result
    for (int i = 0; i < result_row; i++)
    {
        delete[] array_3[i];
    }
    delete[] array_3;

    return 0;
}

Anyone have an idea how to fix it? At what point did I go wrong? I used pointers, dynamic memory allocation.

Create json string dynamically using a function in C++

I want to create a json string using C++ function like a simple example below:

string createJson(string one, string two, string three, string four)
{
    boost::proprty_tree::ptree pt;
    std::stringstream ss;

    pt.put("one", one);
    pt.put("two", two);
    pt.put("three", three);
    pt.put("four", four);

    return ss.str();
}

int main()
{
    string jsonstr;
    //assume one below are initialised any strings
    string one, two, three, four;
    for(i = 0; i < m; i++)
    {
        tempstr = createJson(one, two, three, four);
        jsonstr.append(tempstr);
    }
    cout << jsonstr << endl;
}

The output should be in proper json format. But somewhere I am getting improper json format when all loops run. The json needs to be sent to client application from server and should be processed with json form only. Is it the right way to do it?

Please feel free to assume json values(int, string etc).

How to get integers until \n for n number of lines

My input : the first input is number of lines the input will contain

5
7 3 29 0
3 4 3 
2 3 4 55 5
2 3
1 2 33 4 5

My issue is how can I store them in vector of vector..?

My concept..

.
.
.
cin>>n;
vector<vector<int>>vec;
while(n--)
{
    vector<int>vec2;
    for(**Getting input until the line**){
    vec2.emplace_back(input);}
    vec.emplace_back(vec2)
}

I need to implement that getting input till the line. For this I thought of getting the input as string and storing the values in vector vec2 using strtok after converting it to c_string... But I need to know whether there is any efficient way I can overcome this problem..

Pointer to portions of array. Overloading [] operator to access portions of array

Following the question in Pointer to portions of array, a structure that does operations with portions of an array was proposed.

I would like to request one further question within this issue.

I would like to create a structure for blockMatrices using std::vector and would require to change the implementation of the structure for getting a 3x3 matrix out of a 4x4 matrix.

The current test case is:

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

// define matrix 4x4
typedef std::array<double, 16> matrix4;

// define matrix 3x3
typedef std::array<double, 9>  matrix3;

// get 3x3 matrix out of a 4x4 matrix
struct subMat
{
    matrix4& matrix_;

    const double& operator[](size_t index) const
    {
        static size_t mapping[] = {0, 1, 2, 4, 5, 6, 8, 9, 10};
        return matrix_[mapping[index]];
    }    
    subMat (matrix4& A): matrix_(A){}
};

template <typename T>
double sum_of_elements(const T& arr)
{
    double res = 0;
    for (int i=0;i < 9; ++i)
    {
        res += arr[i];
    } 
    return res;
}

int main(int argCount, char *args[])
{
    std::vector<matrix4> myBlockMatrix(5);

    for (int i=0; i < myBlockMatrix.size(); i++)
    {
        for (int j = 0; j<myBlockMatrix[0].size(); j++)
        {
            myBlockMatrix[i][j] = i*j;
        }
    }

    for (int i = 0; i<myBlockMatrix.size(); i++)
    {
        std::cout << sum_of_elements(subMat(myBlockMatrix[i])) << std::endl; // this works
    }

    subBlockMatrix subBlock (myBlockMatrix);
    for (int i = 0; i<myBlockMatrix.size(); i++)
    {
        std::cout << sum_of_elements(subBlock[i])) << std::endl; 
    } 

    return 0;
}

For overloading the [] operator, I have:

struct subBlockMatrix : std::vector<matrix4>
{
    std::vector<matrix4>& blockMatrix_;

    const matrix4& operator[](std::size_t index) const
    {   
        static size_t mapping[] = {0, 1, 2, 4, 5, 6, 8, 9, 10};
        return blockMatrix_[mapping[index]];
    } 
    subBlockMatrix(std::vector<matrix4>& A) : blockMatrix_(A) {}
};

But this does not work... I am having difficulty understanding how to make it work and would really appreciate the help!

Best Regards

Pointer to portions of array. Operations with filtered array

Following the question in Pointer to portions of array, a structure that does operations with portions of an array was proposed.

However, I am having a problem when calling functions that change entries in the matrices.

When defining operations for matrices it is standard to pass by reference. However, when I use the same structure for the filtered array I get:

error: cannot bind non-const lvalue reference of type ‘subMat&’ to an rvalue of type ‘subMat’

Here is the code:

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

// define matrix 4x4
typedef std::array<double, 16> matrix4;

// define matrix 3x3
typedef std::array<double, 9>  matrix3;

struct subMat{

    matrix4& matrix_;

    const double& operator[](size_t index) const
    {
        static size_t mapping[] = {0, 1, 2, 4, 5, 6, 8, 9, 10};
        return matrix_[mapping[index]];
    }
    double& operator[](size_t index)
{
    static size_t mapping[] = {0, 1, 2, 4, 5, 6, 8, 9, 10};
    return matrix_[mapping[index]];
}


    subMat (matrix4& A): matrix_(A){}
};

template <typename T>
double sum_of_elements(const T& arr)
{
    double res = 0;
    for (int i=0;i <9; ++i) res += arr[i];
    return res;
}

template <typename T>
void test(T& arr)
{
    for (int i=0;i <9; ++i)
    {
        arr[i] = 1;
    } 
}


int main(int argCount, char *args[])
{
    std::vector<matrix4> myBlockMatrix(5);

    for (int i=0; i < myBlockMatrix.size(); i++)
    {
        for (int j = 0; j<myBlockMatrix[0].size(); j++)
        {
            myBlockMatrix[i][j] = i*j;
        }
    }

    for (int i = 0; i<myBlockMatrix.size(); i++)
    {
        std::cout << sum_of_elements(subMat(myBlockMatrix[i])) << std::endl; // this owrks
    }

    test(subMat(myBlockMatrix[0])); // this does not work

    subMat a = subMat(myBlockMatrix[0]); 
    test(a); // this works and changes the values in myBlockMatrix

    return 0;
}

The question is: What can I do with this structure to re-use the previous functions for matrix3. Do I need to always create a new instance of subMat to do operations? Or is there a way to use subMat(myBlockMatrix[0]) inside the function argument?

How to reverse a std::list at a given position?

I am trying to figure out how to reverse for example,grades{1, 2, 3, 4, 5, 6} starting at the third element.

I know for lists we cannot do (grades.begin() + 2) to obtain the position, but I'm not sure how to go about it. This is what I have so far, where I'm just reversing the entire list:

reverse(firstList.begin(), firstList.end());

I want it to be reverse so that the list becomes: grades{1, 2, 6, 5, 4, 3}

dimanche 24 octobre 2021

Is there a method to increase the gap between two lines in c++ ColorText function?

enter image description here

is there a method to increase the gap between these lines in c++?

I felt that all the text are too near to each other, I want to increase the gap between those lines.

original code:

void ColorText(int color)
{
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),color);
}

int main()
{
    ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);
    system_boot();
    ColorText(1761); 
    userInput(); //ignore this, some code doing some other functional stuff

    return 0;
}

what I've tried:

int main()
{
    ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);
    system_boot();
    ColorText(1761); //1999 //1770 //1777 //1725 //1765 //1761
    cout<<endl<<endl<<endl<<endl; //I applied endl here
    userInput();

    return 0;
}

However, it hasn't got me to the solution, I guess that changes should be made at the SetConsoleTextAttribute in ColorText function , but I can't find any related documentation on that, so I seek help from here.

Best i can think of is I can directly add endl to those printed text, but it is very lengthy and inefficient, and also adding an endl will just print out another empty line only, like below enter image description here

It wasn't my initial motive, which is just increase / widen the gap and space of a particular line

How can I fix LNK2019 error with libsndfile?

Severity Code Description Project File Line Suppression State

Error   LNK2019 unresolved external symbol _sf_open referenced in function "private: unsigned int __thiscall SoundBuffer::AddSoundEffect(char const *)" (?AddSoundEffect@SoundBuffer@@AAEIPBD@Z)    Engines4    D:\xxx\xxxx\sound\PhysicsEngine\Engines4\SoundBuffer.obj

1
and three more similar LNK2019

I have done Properties >> General >> Additional Library Directories Debug >> Project Properties >> Configuration Properties >> C/C++ >> ,General >> Additional Include Directories

Installed the library libsndfile-1.0.25-w64-setup.exe file of libsndfile. I have exited, clean, and rebuild many times! And VS keeps crying...

Converting UML to code c++. Problem with inheritence. Do constructors of all classes run when object of any one of them is created?

UML code -> C++ code

//Parent class Flight

class Flight
{
    private:
        int callNumber;
        Airplane plane;
        vector<Passenger> passengers;
    
    public:

//Constructor

        Flight();

//Functions

        int getCallNum();
        void setCallNum();
        Airplane getPlane();

//What parameters are taken in these functions.

//I know they are of type Airplane and passenger but are they vectors?

        void setPlane(Airplane);            
        void addPassenger(Passenger);
        void removePassenger(Passenger);    
};

//Airplane class, child of Flight

class Airplane : public Flight
{
    private:
        int firstClassSeats;
        int economySeats;

    public:

//Constructor

        Airplane();

//Functions;

        int getFirstClassSeats();
        int getEconomySeats();
        void setFirstClassSeats();
        void setEconomySeats();
};

//Passenger class, child of FLight

class Passenger : public Flight
{
    private:
        string name;
        int age;
        string address;

    public:

//Constructor

        Passenger();

//Functions

        string getName();
        int getAge();
        string getAddress();
        void setName(string);
        void setAge(int);
        void setAddress(string);    
};

Why we return the size of the vector in the given fucntion?

This is a function that removes the duplicate values from a vector. What is the significance of returning the size of the vector here? how will it print out the vector with no duplicate values?


    int removeDuplicates(vector<int>& nums) {
         nums.resize(distance(nums.begin(), unique(nums.begin(), nums.end())));
        return nums.size();
        
    }

Speeding Up MPI When Writing to File

I'm implementing Conoway's Game of Life using MPI, everything works fine but when writing the board to a file my performance is terrible. I've commented out the write to file block of code to test it.

1000x1000Test
With Output File: 1.8653
Without Output File: 0.620289

Here's the code:

 int aBoard[sliceSize][N];
        //Write to file.
        if (rank == 0) {

            output << "Generation " << currentGen + 1 << ":" << std::endl;
            //Write current slice of board to file

            for (int i = 0; i < sliceSize; ++i) {
                for (int j = 0; j < N; ++j) {
                    char q = '.';
                    if (mySlice[i][j] == 1)
                        q = '*';
                    output << q << '\t';
                }
                output << std::endl;
            }


            //receive the other board's slices and write to file
            for (int i = 1; i < size; i++) {
                MPI_Recv(&aBoard[0][0], N * sliceSize, MPI_INT, i, 1, MPI_COMM_WORLD, &Stat);
                for (int x = 0; x < sliceSize; x++) {
                    for (int y = 0; y < N; y++) {
                        char q = '.';
                        if (aBoard[x][y] == 1)
                            q = '*';
                        output << q << '\t';

                    }
                    output << std::endl;

                }
            }
            output << std::endl << std::endl;
        } else {
            //send the slice to the first rank
            MPI_Send(&mySlice[0][0], N * sliceSize, MPI_INT, 0, 1, MPI_COMM_WORLD);
        }

Is there any changes I could make that would potentially improve performance?

Thank you

Scanning from specific variable using cin in c++

What will be the cin equivalent of scanf code written below I am only aware of cin>>a[i]>>b[i]

scanf_s("x=%d(mod %d)\n", &a[i], &b[i]);

How to push strings (char by char) into a vector of strings

This code is just a prototype, how I'm expecting my output..
My program should be able to insert char by char to particular index of vector;

This program works fine for vector<vector<int>>

#include<bits/stdc++.h>

using namespace std;

int main()
{
  
  vector<vector<string>>v;

  for(auto i=0;i<5;i++)
  v.emplace_back(vector<string>());
  
  v[0].emplace_back('z');
  v[1].emplace_back('r');
  v[0].emplace_back('x');
  v[1].emplace_back('g');
  
  for(auto i:v){
  for(auto j:i)
  cout<<j<<" ";cout<<endl;}
  
  
  return 0;
}

My Expected output:
z x
r g

Error:
no matching function for call to ‘std::__cxx11::basic_string<char>::basic_string(char)’ { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }

samedi 23 octobre 2021

Is there a guaranteed address-order inside a tuple / why is it reverse?

I just discovered that with my STL-implementaton (VS2019) the address-order of the parts of a tuple is reverse. Look at this code:

#include <iostream>
#include <tuple>

using namespace std;

int main()
{
    tuple<string, string> tss( "try", "this" );
    cout << &get<1>( tss ) - &get<0>( tss ) << endl;
}

The output is:

-1

Is there a guaranted order of addresses inside a tuple or is it implementation-defined ?

Unpacking a tuple's parts as function paramters

Imagine I have a tuple<...> with several types. And I want to expand the tuple's value-parts as parameters for a function with static paramters - i.e. not necessarily variadic so that the function-parameters should match the tuples parts. How can I do that ?

how can i display the actual input from the user even after arithmetic operations?

const int SCND_TO_HOUR = 3600, SCND_TO_MINUTE = 60; //constant declaration
int seconds,hour,minute,remainSeconds;
cout << "Input the total time in seconds : " << endl;
cin >> seconds;
hour = seconds / SCND_TO_HOUR;
seconds = seconds % SCND_TO_HOUR;
minute = seconds / SCND_TO_MINUTE;
seconds = seconds % SCND_TO_MINUTE;
remainSeconds = seconds;

//the display is suppossed to be user input seconds are equals to .... cout << seconds << " seconds are equals to " << hour << " hours " << minute << " minutes and " << remainSeconds<< "seconds" << endl;

NK2019: unresolved external symbol [duplicate]

I've been getting these two errors and I cant seem to find a solution that works.

Severity    Code    Description Project File    Line    Suppression State
Error   LNK2019 unresolved external symbol "class ResultTable __cdecl handleFollows(class std::vector<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,class std::allocator<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > > >)" (?handleFollows@@YA?AVResultTable@@V?$vector@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V?$allocator@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@2@@std@@@Z) referenced in function __catch$?evaluate@@YA?AV?$list@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V?$allocator@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@2@@std@@VQuery@@@Z$0    D:\modules\CS3203\project\Team00\Code00\build_win\x86-Debug\Code00  D:\modules\CS3203\project\Team00\Code00\build_win\x86-Debug\spa.lib(evaluator.cpp.obj)  1   

evaluator.h

#pragma once
#include "ResultTable.h"

#include "ClauseHandler.h"


#include <array>
#include <cassert>
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <unordered_map>
#include <algorithm>
#include <list>
#include <iomanip>

using namespace std;

ResultTable handleClause(string type, vector<string> argList);

evaluator.cpp

#include "evaluator.h"
ResultTable handleClause(string type, vector<string> argList) {
    ResultTable temp;
    if (type == "Follows") temp = handleFollows(argList);
    return temp;
}

ClauseHandler.h

#pragma once

#include <array>
#include <cassert>
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <list>
#include <math.h>
#include <numeric>

#include <iomanip>

#include <regex>

//#include "Query.h"
#include "ResultTable.h"
//#include "PKB/OtherStmt.h"
//#include "PKB.h"
//#include "Common.h"


using namespace::std;

ResultTable handleFollows(vector<string> argList);

ClauseHandler.cpp

#include "ClauseHandler.h"



ResultTable handleFollows(vector<string> argList) {
    return ResultTable();
}

ResultTable.h

#pragma once

#include <array>
#include <cassert>
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>


using namespace std;

class ResultTable
{
    bool hasResult;
    unordered_map<string, int> synonymMap;
    vector<vector<string>> result;
public:
    ResultTable(); //default constructor

    ResultTable(bool hasResult, unordered_map<string, int> synonymMap, vector<vector<string>> result);

    void setHasResultTrue();

    bool checkHasResult();

    unordered_map<string, int> getSynonymMap();

    vector<vector<string>> getResult();
};

ResultTable.cpp

#include "ResultTable.h"

ResultTable::ResultTable()
{
    hasResult = false;
    synonymMap = {};
    result = {};
}

ResultTable::ResultTable(bool hasResult, unordered_map<string, int> synonymMap, vector<vector<string>> result)
{
    this->hasResult = hasResult;
    this->synonymMap = synonymMap;
    this->result = result;
}

void ResultTable::setHasResultTrue()
{
    this->hasResult = true;
}

unordered_map<string, int> ResultTable::getSynonymMap()
{
    return this->synonymMap;
}

vector<vector<string>> ResultTable::getResult()
{
    return this->result;
}

bool ResultTable::checkHasResult() {
    return this->hasResult;
}

When I commented out the ClauseHandler.cpp, the same error occurred so I think maybe the ClauseHandler.cpp cannot be connected with ClauseHandler.h. How can I fix this?

How to get a confidence level with cpplint?

How do I get a confidence value from cpplint?

--verbose = 0 doesn't do anything for me

Thanks!

My functions to rotate the contents of memory to right/left not working correctly

void MoveRight()
{
    for (int i = 0; i < numbersCount; ++i)
    {
        pNumbers[i + 1] = pNumbers[i];
    }
    pNumbers[0] = pNumbers[numbersCount];
}

void MoveLeft()
{
    for (int i = numbersCount; i > 0; --i)
    {
        pNumbers[i - 1] = pNumbers[i];
    }
    pNumbers[numbersCount] = pNumbers[0];
}

In the class,

pNumbers = new int[sizeof(int) * numIntegers];

Let's say numbersCount value I have set to is 5.

So I used some test data and it seems instead of moving data right/left, it's just copying the first and last data?

What am I doing wrong?