mardi 28 février 2023

How can I fill a vector with another smaller vector in c++?

I want to fill a std::vector with another vector . For example:

std::vector<int> src = {1, 2, 3};
std::vector<int> dst(9);

I want to fill dst to make it become: 1, 2, 3, 1, 2, 3, 1, 2, 3

Is there an efficient method to do this?

I have two methods now:

The first is two loop:

for (int i = 0; i < dst.size() / src.size(); i++) {
    for (int val : src) {
        dst.emplace_back(val);
    }
}

Or use the std::copy in one loop.

Maybe exist a more efficient method?

program crashes after converting infix to postfix. (segmentation fault ) [closed]


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



/*
* This program implements an Expression class that contains 
* a constructor and three methods. The Expression class is used to store and manipulate 
* expressions written in either infix or postfix notation. The class contains two private 
* string variables, one to store the infix expression and one to store the postfix expression.
*/ 

class Expression {

public:

    Expression(string input, int direction); // constructor

    string inToPost(); // method to transform the local infix expression to postfix

    string postToIn(); // method to transform the local postfix expression to infix

    double evaluate(); // method to evaluate the expression



private:

    string infix; // private string variable to store the infix expression

    string postfix; // private string variable to store the postfix expression

};



// constructor to initialize the infix/postfix expression and the direction

Expression::Expression(string input, int direction) {

    if (direction == 1) 

        infix = input;

    else if(direction == 2) 

        postfix = input;

}



// inToPost() method

string Expression::inToPost() {

    stack<char> s;

    string postfix = ""; // initialize postfix as empty string

    for (int i = 0; i<infix.length(); i++) {

        // If the scanned character is an operand, add it to output.

        if ((infix[i] >= 'a' && infix[i] <= 'z') || (infix[i] >= 'A' && infix[i] <= 'Z'))

            postfix+= infix[i];

 

        // If the scanned character is an '(', push it to the stack.

        else if (infix[i] == '(')

            s.push('(');

 

        //  If the scanned character is an ')', pop and output from the stack

        // until an '(' is encountered.

        else if (infix[i] == ')') {

            while (s.top() != '(') {

                postfix += s.top();

                s.pop();

            }

            s.pop();

        }

 

        //If an operator is scanned

        else {

            while (!s.empty() && s.top() != '(' && (infix[i] == '*' || infix[i] == '/' || infix[i] == '+' || infix[i] == '-')) {

                postfix += s.top();

                s.pop();

            }

            s.push(infix[i]);

        }

    }

 

    //Pop all the remaining elements from the stack

    while (!s.empty()) {

        postfix += s.top();

        s.pop();

    }

    return postfix;

}



// postToIn() method

string Expression::postToIn() {

    stack<string> s;

    for (int i = 0; i<postfix.length(); i++) {

 

        // If the scanned character is an operand (number here),

        // push it to the stack.

        if ((postfix[i] >= 'a' && postfix[i] <= 'z') || (postfix[i] >= 'A' && postfix[i] <= 'Z'))

            s.push(string(1, postfix[i]));

 

        //  If the scanned character is an operator, pop two

        // elements from stack apply the operator

        else {

            string val1 = s.top();

            s.pop();

            string val2 = s.top();

            s.pop();

            string temp = "(" + val2 + postfix[i] + val1 + ")";

            s.push(temp);

        }

    }

 

    // There must be a single element in stack now which is the result

    return s.top();

}



// evaluate() method takes the local postfix expression and returns the value of the expression.

double Expression::evaluate() {

    stack<double> s;

    for (int i = 0; i<postfix.length(); i++) {

        // If the scanned character is an operand (number here),

        // push it to the stack.

        if ((postfix[i] >= 'a' && postfix[i] <= 'z') || (postfix[i] >= 'A' && postfix[i] <= 'Z'))

            s.push(postfix[i] - '0');

        //  If the scanned character is an operator, pop two

        // elements from stack apply the operator

        else {

            double val1 = s.top();

            s.pop();

            double val2 = s.top();

            s.pop();

            switch (postfix[i]) {

            case '+':

                s.push(val2 + val1);

                break;

            case '-':

                s.push(val2 - val1);

                break;

            case '*':

                s.push(val2 * val1);

                break;

            case '/':

                s.push(val2 / val1);

                break;

            }

        }

    }

    return s.top();

}



/* The main() function of the program displays a prompt to the user,
* allowing them to enter an expression in either infix or postfix notation to be 
* transformed to the other and evaluated. */

/* The program then creates an Expression object, passing the user input and the direction
* as parameters to the constructor. The program then checks the direction and if it is 1, 
* it calls the inToPost() method to convert the infix expression to postfix. If the direction is 2, 
* the postToIn() method is called to convert the postfix expression to infix. Finally, the evaluate() 
* method is called to evaluate the expression.
*/

int main() {

    string input;

    int direction;

    cout << "Enter expression in infix or postfix notation: ";

    cin >> input;

    cout << "Enter direction (1 for infix to postfix, 2 for postfix to infix): ";

    cin >> direction;

    Expression expression(input, direction);

    if (direction == 1)

        cout << "Postfix: " << expression.inToPost() << endl;

    else if (direction == 2)

        cout << "Infix: " << expression.postToIn() << endl;

    cout << "Evaluate expression: " << expression.evaluate() << endl;

    return 0;

}


infix : a+bc+(de+f)g postfix: ab+cdef++g crash: segmentation fault

my intruition is that: it seems like the issue might be related to calling pop() on an empty stack. This can happen if you're not checking whether the stack is empty before trying to pop an element.

I cannot fix the issue, can anyone help me

call getting stuck at std::map erase function

I want to understand in which scenario the std::map erase function can gets blocked and not able return from erase.

{
    popHttpRequest(uint64_t requestId)
   {
    boost::unique_lock<boost::shared_mutex> uniqueLock{ m_HttpRequestTableMutex };
    auto itr = m_HttpRequestTable.find(requestId);
    if (itr != m_HttpRequestTable.end())
    {
     auto request = itr->second;
     m_HttpRequestTable.erase(itr);
    }
}

lundi 27 février 2023

Why the std::bind for a callback method doesn't match the declared one thus it compiles?

I've created a minimal example to illustrate my question.

class Bar {
public:
    void bind_function(std::function<void(int)> callback){
        m_callbacks.push_back(callback);
    }

    void invoke() {    
        for(auto& c : m_callbacks){
            c(12345);
        }
    }

private:
    std::vector<std::function<void(int)>> m_callbacks;
};

class Foo{
public:
    void register_foo(){ m_msg.bind_function(std::bind(&Foo::callback_foo, this));  }
    void callback_foo(/*int a*/){ std::cout << "callback foo invoked!!!!" << std::endl;  }
    void run() { m_msg.invoke(); }
private:
    Bar m_msg;
};


int main(){
    Foo foo;
    foo.register_foo();
    foo.run();
    return 0;
}

I have a Bar class where it has two methods: Bar::bind_function to pass a function pointer to be pushed into some vector. And a Bar::invoke method which will invoke the callbacks from the vector.

Then I have a Foo which has three methods: A Foo::register_foo method where I will invoke the Bar::bind_function from Bar and the actual method to be invoked Foo::callback_foo. Finally a method to Foo::run the registered functions.

The code compiles and I can see the callback/registered method being executed.

[QUESTION]

Why does the code compile if the function pointer from this vector:

std::vector<std::function<void(int)>> m_callbacks

Doesn't match the actual callback:

void callback_foo(/*int a*/){...}

One is void(int) and the other is void().

If I uncomment my void callback_foo(/*int a*/){...} to match void callback_foo(int a){...}

I get the following error:

 error: static assertion failed: Wrong number of arguments for pointer-to-member

How can I fix this error?

std::unorder_map erase function getting blocked in multithreaded setup

In my application i am preparing the unordermap of request objects and using this through the session, i suppose to erase map entry when request processing is completed and send the response to client. i am using multithreading in application, when the request is processed and application has to send response to client, the code will erase the request object from map but unfortunately the erase() is getting hanged indefinitely.

I want to understand reason behind the erase() getting blocked in multithreaded environment. I have used boost::shared_mutex around this map in critical section of the code.

dimanche 26 février 2023

implementing doubly linked list in C++

I have a trouble implementing doubly linked list especially in a function that swap the adjacent elements.

Here is my original code:

#include<iostream>
using namespace std;

struct node {
    int data; 
    node *prev;
    node *next;
};
node *head = NULL;

node* getNewNode (int i){
    node *newNode = new node; //allocate a dynamic memory in the heap
    newNode->data = i;
    newNode->prev = NULL;
    newNode->next = NULL;
    return newNode;
}


void InsertAtHead(int i){
    node *newNode = getNewNode(i);
    if (head == NULL){   //addressing inserting the first node in the list.
        head =  newNode;
        return;
    }
    
    newNode->next = head;
    head->prev = newNode;
    head = newNode;
    
    }
void swapAdjacent() {
    node *temp = head;
    while (temp != NULL ) {
        node *temp1 = temp;
        node *temp2 = temp->next;
        temp1->next = temp2->next;
        temp2->prev = temp1->prev;
        if (temp1->prev != NULL) {
            temp1->prev->next = temp2;
        }
        temp1->prev = temp2;
        temp2->next = temp1;
       
        if (temp == head) {
            head = temp2;
        }
        temp = temp->next->next;
    }
}





void display (){
    node *temp = head;
    while (temp != NULL){
        cout  <<temp->data << '\t';
        temp = temp->next;
    
    }
    cout << '\n';
}



int main (){
    InsertAtHead(8); 
    InsertAtHead(4);
    InsertAtHead(12);
    InsertAtHead(3);
    InsertAtHead(-8);
    InsertAtHead(7);
    cout << "The original list is: " << endl;
    display();
    swapAdjacent();
    cout << "The list after swapping the adjacent elements is: " << endl;
    display();
    
   
    return 0;
}

The original list is The original list is: 7 -8 3 12 4 8 The output I got after calling swapAdjacent() is : -8 7 3 4 12 8 while I am looking for: -8 7 12 3 8 4

I tried visualizing this with pen and paper, did several attempts to look it up and even I used chat GPT to no avail. I always don't get the output I am looking for.

I appreciate all of your feedback.

samedi 25 février 2023

get the size of std::array inside unique_ptr without an instance in c++

I have a type declared as:

using Buffer = std::unique_ptr<std::array<uint8_t, N>>;

I also have a template function declared as:

template<typename Buffer>
bool temp_func()
{
    // do something
}

and I'm calling temp_func with type Buffer:

temp_func<Buffer>();

now, inside temp_func I want to get the size of the type Buffer without creating an instance of this type.

what I need is something similar to std::tuple_size<Buffer>::value except I can't call std::tuple_size on unique_ptr, only directly on std::array.

I can use C++11 only. How can I do it?

How can I correct my `upp` and `low` in my Binary Search? [closed]

I am doing a problem, which states

You are given 3 integers N, TC and TM. You are also given Ai, Bi and Ti for 1 ≤ i ≤ N.
There exist 2 integers AC and AM such that Ai × AC + Bi × AM ≤ Ti for 1 ≤ i ≤ N. Find the greatest value of AC + AM. Note: You may need to use long long in C++ or BigInteger in Java.

My code

#include <iostream>
#include <algorithm>
#include <assert.h>
#include <cmath>

const int N=113;
const long long inf=1e18;

int n;
long long tc, tm;
long long c[N], m[N], t[N];

long long mfn(long long ac)
{
    long long am=inf;
    for (int a=0; a<n; a++)
    {
        am=std::min(am, (long long)(t[a]-c[a]*ac)/m[a]);
    }
    return am;
}
long long driver()
{
    std::cin>>n>>tc>>tm;
    long long ctot, mtot;
    for (int a=0; a<n; a++) 
    {
        std::cin>>c[a]>>m[a]>>t[a];
        ctot+=c[a];
        mtot+=m[a];
    }
    
    long long low=0, upp=tc;
    long long ans=-inf;
    long long ac, am;
    while (low<=upp)
    {
        //cout<<low<<' '<<upp<<' '<<ac<<' '<<am<<' '<<ans<<endl;
        ac=(low+upp)>>1, am=mfn(ac);
        if (ac>=0 && am>=0)
        {
            ac=std::min(ac, tc), am=std::min(am, tm);
            if (ans<ac+am) ans=ac+am;
            if (ctot<=mtot) upp=ac-1;
            else low=ac+1;
        }
        else upp=ac-1;
        //cout<<low<<' '<<upp<<' '<<ac<<' '<<am<<' '<<ans<<endl;
    }
    return tc+tm-ans;
}

int main()
{
    int t;
    std::cin>>t;
    while (t--) std::cout<<driver()<<std::endl;
    return 0;
}

Explanation:
N: The maximum value for n.
inf: 1e18.
n: The number of conditions.
tc, tm: TC and TM.
c[], m[], t[]: Stores A, B and T.
mfn(): Solve for the maximum AM when AC is fixed.
driver(): The function that is used to solve for AC+AM.
ctot, mtot: The total sum of Ai, Bi respectively. I use this to decide how to update low and upp since AMnew=AMold - (Ai / Bi) * x, where x is the increase in AC.
low, upp: Binary Search.
ans: Final answer.
ac, am: AC and AM. main: Main function.

My method is binary search for AC, then solve for the corresponding biggest AM and update the maximum value of AC+AM. The formula I used to find AM is AM = minimum of the floor of (t[a] - c[a] * ac) / m[a]. However, I keep getting Wrong Answer. I think there is a problem in my low and upp, but I don't know what it is. Any help is appreciated. Thanks in advance!

Different rounding between int and double type in c++?

Picture

I am curious about getting different answer just because differnt data type. If it have double precision problem, but why the double type "size2" return the right answer?

(12 000 * 60 * 2.8)/ 8000 = 252 based on ordinary calculator

Displaying steady_clcok::now() using fmt library

I'm able to display the current time using C++ fmt library using std::chrono::system_clock and std::chrono::high_resolution_clock but unable to displaying time using std::chrono::steady_clock.

Here is the minimum reproducible example:

#include <iostream>
#include <fmt/core.h>
#include <fmt/chrono.h>
#include <fmt/format.h>
#include <fmt/std.h>

int main()
{
    fmt::print("current time: {:%Y-%m-%d %H:%M:%S.%z}\n", std::chrono::system_clock::now());
    fmt::print("current time: {:%Y-%m-%d %H:%M:%S.%z}\n", std::chrono::high_resolution_clock::now());
    // fmt::print("current time: {:%Y-%m-%d %H:%M:%S.%z}\n", std::chrono::steady_clock::now());
}

output:

current time: 2023-02-25 11:08:43.+0000
current time: 2023-02-25 11:08:43.+0000

When I un-comment the last line I get following error:

In file included from <source>:12:
/opt/compiler-explorer/libs/fmt/9.1.0/include/fmt/core.h:1756:3: error: static assertion failed due to requirement 'formattable': Cannot format an argument. To make type T formattable provide a formatter<T> specialization: https://fmt.dev/latest/api.html#udt
  static_assert(
  ^
/opt/compiler-explorer/libs/fmt/9.1.0/include/fmt/core.h:1777:10: note: in instantiation of function template specialization 'fmt::detail::make_value<fmt::basic_format_context<fmt::appender, char>, std::chrono::time_point<std::chrono::steady_clock, std::chrono::duration<long, std::ratio<1, 1000000000>>> &>' requested here
  return make_value<Context>(val);
         ^
/opt/compiler-explorer/libs/fmt/9.1.0/include/fmt/core.h:1899:23: note: in instantiation of function template specialization 'fmt::detail::make_arg<true, fmt::basic_format_context<fmt::appender, char>, fmt::detail::type::custom_type, std::chrono::time_point<std::chrono::steady_clock, std::chrono::duration<long, std::ratio<1, 1000000000>>> &, 0>' requested here
        data_{detail::make_arg<
                      ^
/opt/compiler-explorer/libs/fmt/9.1.0/include/fmt/core.h:1918:10: note: in instantiation of function template specialization 'fmt::format_arg_store<fmt::basic_format_context<fmt::appender, char>, std::chrono::time_point<std::chrono::steady_clock, std::chrono::duration<long, std::ratio<1, 1000000000>>>>::format_arg_store<std::chrono::time_point<std::chrono::steady_clock, std::chrono::duration<long, std::ratio<1, 1000000000>>> &>' requested here
  return {FMT_FORWARD(args)...};
         ^
/opt/compiler-explorer/libs/fmt/9.1.0/include/fmt/core.h:3294:28: note: in instantiation of function template specialization 'fmt::make_format_args<fmt::basic_format_context<fmt::appender, char>, std::chrono::time_point<std::chrono::steady_clock, std::chrono::duration<long, std::ratio<1, 1000000000>>> &>' requested here
  const auto& vargs = fmt::make_format_args(args...);
                           ^
<source>:23:10: note: in instantiation of function template specialization 'fmt::print<std::chrono::time_point<std::chrono::steady_clock, std::chrono::duration<long, std::ratio<1, 1000000000>>>>' requested here
    fmt::print("current time: {:%Y-%m-%d %H:%M:%S.%z}\n", std::chrono::steady_clock::now());
         ^
1 error generated.

Why fmt library doesn't support displaying time using std::chrono::steady_clcok::now()?

vendredi 24 février 2023

Correct way to 'glue' two class implementation in C++

I am new to C++, now I have a problem needs to solve. I have a class in A library and the same class in B library, C function is the only connection between A and B, I need to pass the class implemented in A and run it in B, what is the best way to do it in C function? In library A

class ClassAImp : public ClassA
{
public:
    ClassAImp();
    ~ClassAImp();
    
    void Setup() override {/* do some setup */};
    void TearDown() override {/* do teardown stuff */};
    void runMethodA(void* ptr) override {/* do method A stuff */};
}

class ClassA
{
public:    
    virtual void Setup() = 0;
    virtual TearDown() = 0;
    virtual runMethodA(void* ptr) = 0;
}

In library B

class ClassB
{
public:    
    virtual void Setup() = 0;
    virtual TearDown() = 0;
    virtual runMethodA(void* ptr) = 0;
}

Currently what I am doing in C is

class ClassBImp : public ClassB
{
public:
    ClassBImp(std::shared_ptr<ClassA> _classAObj) : classAObj(_classAObj) {};
    virtual ~ClassBImp();
    
    void Setup() override { if (classAObj) classAObj->Setup(); };
    void TearDown() override { if (classAObj) classAObj->TearDown(); };
    void runMethodA(void* ptr) override { if (classAObj) classAObj->runMethodA(ptr); };
private:
    std::shared_ptr<ClassA> classAObj;
}

And pass the ClassBImpPtr (as std::shared_ptr) to the B library.

I don't have any control over library A or B, only can do things in C and pass the implemented object back to B. Is it the right way of doing things in C++ (11?) Is there a better way of doing it?

jeudi 23 février 2023

Why Heap-buffer-overflow in std::map(or std::Rb_tree)

I am writing a multithreads program. However, when I run this code, I meet heap-buffer overflow.

int lock_server_cache_rsm::acquire(lock_protocol::lockid_t lid, std::string id,
                                   lock_protocol::xid_t xid, int &) {
std::unique_lock<std::mutex> ulock(mutex_);
  std::shared_ptr<Lock> lock;
  if (lock_table_.count(lid) == 0U) {
    lock = std::make_shared<Lock> (lid, ServerLockState::FREE);
    lock_table_[lid] = lock;
  } 
  else lock = lock_table_[lid];
  bool revoke = false;
  if (!lock->findClientId(id) || lock->getClientXid(id) < xid)
    lock->setClientXid(id, xid);
}

I use asan check my program, it shows that : heap-buffer-overflow in the std::map.

=================================================================
==2048==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60c0000000c8 at pc 0x55d830fd8595 bp 0x7f102777b460 sp 0x7f102777b450
READ of size 8 at 0x60c0000000c8 thread T

SUMMARY: AddressSanitizer: heap-buffer-overflow /usr/include/c++/11/bits/stl_tree.h:735 in std::_Rb_tree

The Lock class and lock_server_cache_rsm class like this:

class lock_server_cache_rsm : public rsm_state_transfer {
 private:
  int nacquire;
  class rsm *rsm;
  std::unordered_map<lock_protocol::lockid_t, std::shared_ptr<Lock>>
      lock_table_;
  std::mutex mutex_;
 public:
  lock_server_cache_rsm(class rsm *rsm = 0);
  int acquire(lock_protocol::lockid_t, std::string id, lock_protocol::xid_t,
              int &);
};
class Lock {
 public:
  Lock(lock_protocol::lockid_t lid, ServerLockState state)
      : lid_(lid), state_(state){}
  void setClientXid(std::string id, lock_protocol::xid_t xid) {
    std::lock_guard<std::mutex> lg(lck_mutex_);
    client_max_xid_[id] = xid;
  }
 private:
  std::string owner_;
  lock_protocol::lockid_t lid_;
  ServerLockState state_;
  std::unordered_set<std::string> wait_client_set_;
  public:
  std::map<std::string, lock_protocol::xid_t> client_max_xid_;
  std::unordered_map<std::string, int> acquire_reply_;
  std::unordered_map<std::string, int> release_reply_;
  std::mutex lck_mutex_;
};

I donot know why I meet this problem,and I have use the lock_guard to protect my data structure and use unique_lock to protect my method.

mercredi 22 février 2023

why does bcc memleak lose malloc information

I'm using bcc-memleak to locate memory leak in my project. But the top command shows that the VIRT increase from 100GB to 200GB and RES from 70GB to 90GB in 10-hours, while memleak shows that only 150MB not released.

I compile project with "-O2 -fno-omit-frame-pointer" and I got almost every call-stack with outstanding allocations.

memleak command is : memleak -p {pid} -o 30000 -T 10 20

bcc & memleak project: https://github.com/iovisor/bcc/blob/master/tools/memleak.py

use std malloc and jemalloc have the same result.

Anyone know how to get more information? or other tools recommend to check memleak.

I have tried jemalloc with prof, but it needs too much cpu and memory, so it didn't solve my problem.

googlemock expectation: Copy varying array contents to out parameter

Using google test, I want to set expectations (or default behavior) for a function that provides multiple data as out parameters, including a fixed-size array, to which a pointer is passed. Using SetArgPointee to set the out parameter won't work with an array, so my guess is that defining a custom parametrized action should work. I reduced the problem (and my attempt at a solution) to this:

#include "gtest/gtest.h"
#include "gmock/gmock.h"

class MyInterface {
  virtual bool GetFixedSizeArray(unsigned char* msg) = 0;
};

class MYMock : public MyInterface {
public: 
  MOCK_METHOD1(GetFixedSizeArray, bool(unsigned char* msg));
 };

ACTION_P(MyCopyAction, src) { for (int i = 0; i < 6; i++) arg0[i] = src[i]; }

using namespace ::testing;

TEST(Case1, Test1) {
  MYMock mock;

  unsigned char dummymsg[6] = { 1,2,3,4,5,6 };

  ON_CALL(mock, GetFixedSizeArray(_)).WillByDefault(DoAll(
    WithArg<1>(MyCopyAction(dummymsg)),
    Return(true)));

  // ... expectations and 
  // code under test

}

This version looks fine in VS2019 Intellisense, but it fails to compile with the message:

 error C2504: 'std::tr1::_Not_nil<std::tr1::_Nil>' : base class undefined

The ON_CALL should be able to take an argument for the array contents, so that it can change over multiple calls to GetFixedSizeArray. I am working on a legacy project with MSVC 2010, hence the googletest 1.1.8 syntax.

Any suggestions on how to do this?

mardi 21 février 2023

Parsing Custom String in C++

I have string like:


"../blabla/here_is_same0000:00/0000:00:1A.0/blabla/blabla/blabla"

I want to get 1A.0 part from the string and returning as decimal. These place always comes after the here_is_same0000:00 pattern. Also these places (0000:00:1A.0) not always third place in the given string.

I wrote a code like :

static const std::string test_str1{"../blabla/here_is_same0000:00/0000:00:1A.0/blabla/blabla/blabla"};

std::tuple<int, int> values(const std::string& in)
{
  static const std::string constant_pattern{"here_is_same0000:00"};
  std::size_t found_idx = in.find(constant_pattern);
  if(found_idx == std::string::npos)
  {
    return std::make_tuple(0,0);
  }

  std::string remaining = in.substr(found_idx + constant_pattern.length() + 1, in.length());
  
  found_idx = remaining.find("/");
  if(found_idx == std::string::npos)
  {
    return std::make_tuple(0,0);
  }

  remaining = remaining.substr(0, found_idx);
  found_idx = remaining.find_last_of(":");
  remaining = remaining.substr(found_idx + 1, remaining.length());

  std::stringstream ss(remaining);
  std::string items;
  std::vector<std::string> elements;
  while(std::getline(ss, items, '.'))
  {
    elements.push_back(std::move(items));
  }

  int x;
  std::stringstream ss_convert_x;
  ss_convert_x << std::hex << elements[0];
  ss_convert_x >> x;
  
  int y;
  std::stringstream ss_convert_y;
  ss_convert_y << std::hex << elements[1];
  ss_convert_y >> y;

  std::cout << x <<" "<< y;
  
  return std::make_tuple(x,y);
}

But it looks like bad to me, is there any better way ?

How do I replace specific characters in a string read from input with another character if they are digits? [closed]

I am trying to replace the first and third characters in a string read from input with the character '=' (using <cctype> library). This is what I have so far:

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

int main() {
   string userCode;

   getline(cin, userCode);
   
   char firstChar = userCode.at(0);
   char thirdChar = userCode.at(2);
   if (isdigit(firstChar) && isdigit(thirdChar)) {
      firstChar = '=';
      thirdChar = '=';
      userCode.at(0) = firstChar;
      userCode.at(2) = thirdChar;
   }
   else {
      userCode;
   }
      
   cout << userCode << endl;

   return 0;
}

But I keep getting inconsistent results? In some test cases, like

Input
465
Output
=6=

It seems to work, but then in others like

Input
11c
Output
11c
Expected output
=1c

It just doesn't for some reason? It also seems as if the test cases where it doesn't work, the digit that goes unreplaced is 1 or 3. Could this have to do with the fact that I am only trying to replace the first and third characters of the string? What is the issue here??? As you can see I've already tried to remedy the issue by making the first and third characters their own char variables in advance, rather than calling them directly using .at within the if statement, as I thought maybe the issue had to do with memory allocation or something at first, but I got the same result.

Apologies in advance if I broke any conventions or rules in asking this question, I am new to this website. Just a noob to C++ trying to give it my all. Thanks guys.

lundi 20 février 2023

Core dump while spawning/joining threads inside Google benchmark test

I am getting core dump while trying to spawn and then join the threads inside google benchmark. This is irrespective of the number of threads I try to create.

Code to reproduce the issue:

void BM_ThreadsTest(benchmark::State &state)
{
  std::atomic<size_t> curr_processed {0};
  constexpr size_t max_processed = 100;
  constexpr size_t NUM_CORES = 24; //get programmatically
  std::vector<std::thread> threads;
  while (state.KeepRunning())
  {
    for (int i = 0; i < NUM_CORES; i++){
      threads.push_back(std::thread( [&curr_processed, &max_processed]() {
        while (curr_processed <= max_processed)
        {
          curr_processed++;
        }
      }));
    }
    for (auto &th: threads){
      th.join();
    }
   }
  }
  BENCHMARK(BM_ThreadsTest);
  BENCHMARK_MAIN();

Error:

terminate called after throwing an instance of 'std::system_error'
  what():  Invalid argument
Aborted (core dumped)

Stacktrace:

(gdb) bt
#0  __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:50
#1  0x00007fc21548b859 in __GI_abort () at abort.c:79
#2  0x00007fc215714a31 in ?? () from /lib/x86_64-linux-gnu/libstdc++.so.6
#3  0x00007fc2157205dc in ?? () from /lib/x86_64-linux-gnu/libstdc++.so.6
#4  0x00007fc215720647 in std::terminate() () from /lib/x86_64-linux-gnu/libstdc++.so.6
#5  0x00007fc2157208e9 in __cxa_throw () from /lib/x86_64-linux-gnu/libstdc++.so.6
#6  0x00007fc2157177e5 in std::__throw_system_error(int) () from /lib/x86_64-linux-gnu/libstdc++.so.6
#7  0x00007fc21574d930 in std::thread::join() () from /lib/x86_64-linux-gnu/libstdc++.so.6
#8  0x000055e40166b6a2 in (anonymous namespace)::BM_MeasurementsTest(benchmark::State&) ()
#9  0x00007fc2158e972f in benchmark::internal::BenchmarkInstance::Run(unsigned long, int, benchmark::internal::ThreadTimer*, benchmark::internal::ThreadManager*) const () from /lib/x86_64-linux-gnu/libbenchmark.so.1
#10 0x00007fc2158d5f59 in ?? () from /lib/x86_64-linux-gnu/libbenchmark.so.1
#11 0x00007fc2158d681e in benchmark::internal::RunBenchmark(benchmark::internal::BenchmarkInstance const&, std::vector<benchmark::BenchmarkReporter::Run, std::allocator<benchmark::BenchmarkReporter::Run> >*) ()
   from /lib/x86_64-linux-gnu/libbenchmark.so.1
#12 0x00007fc2158ee7cc in benchmark::RunSpecifiedBenchmarks(benchmark::BenchmarkReporter*, benchmark::BenchmarkReporter*) () from /lib/x86_64-linux-gnu/libbenchmark.so.1
#13 0x000055e40166b757 in main ()

Will the same lambda be created multiple times in C++?

  void do_something(std::function<void(void)> callback){
    callback();
  }

  int main() {
    int counter = 0;
    while(counter < 10000000) {
      do_something([&](){  std::cout << "by reference:" << counter << endl;  })
      do_something([=](){  std::cout << "by value:" << counter << endl;  })
      ++counter;
    }
  }

As shown in the above code, will a new lambda be created in each loop? Will there be a difference with capturing a value or a reference?

I've been searching for some articles, but still not quite sure. I believe value-capturing lambdas need to be created multiple times, while reference-capturing ones probably don't.

If a lambda captured by reference can be reused, will the copying of the lambda still happen? For example, will the following two functions still make a difference?

  void do_something2(std::function<void(void)> callback){
    callback();
  }
  void do_something2(std::function<void(void)> & callback){
    callback();
  }

How to place selected text from any windows OS application. Analog ctrl+c

The program runs in the background, minimized to the tray. When you press the global hotkey, a function is called that should output selected text to the console (from any windows OS application).

I use QClipboard. I understand how to output to the console what is already in the buffer clipboard->text();, I understand how to write from my application to the clipboard clipboard->setText(); But I don't know how to write selected text from any windows OS application to the buffer Thanks

samedi 18 février 2023

how can I identify the cause of an expontential increase in time of iteration? [closed]

I am running a loop in C++ (with the template library) and print the amount it took from the beginning of the loop to go through another 10% of the data.

I see the following behavior:

plot

in row 1 you see the time that passed between the beginning and each 10% of the loop.

in row 2 you see the differences between each adjacent cells in row 1 (which gives the amount of time it took to just go through the extra 10%).

in row 3 you see the division of each adjacent cell from row 2 (so it is the factor by which the amount of taking more 10% of the loop takes at each 10% that goes by).

I was expecting given my knowledge of the code that I would see row 3 to be close to 1.0.

oddly enough, there is an exponential increase between each 10%, and in the beginning it is even worse. later on it stabilizes, but still exponential ~ 1.4.

I do manage a lot of data structures (mostly unordered_map and sets, etc. all from the standard C++ library), and I am wondering what's the best way to identify why this happens, perhaps with valgrind or otherwise? are there anything to be wary of when using such data structures (the only thing I can think of at the moment is that I have a map where the value is a map too, and I am wondering if it is copying the whole map each time I find one with a key? it looks like this: I define an object of type unordered_map<T, unordered_map<T, my_set> > where I have typedef unordered_set<some_obj<T> > my_set;)

also, I do not want to wait again that long (the numbers in the first row are in seconds!), is there a quicker way to test it, even with valgrind? I just need to identify a (set of) function(s) where there is such increase.

How to read, write parent class & Inherited class's data to a binary file in C++ altogether?

I am working on a routine management system. I just thought like this, the binary file will have 8 lines, 1st line for password matching (8 characters fixed, drama for college), rest of the lines will have the timetable for each day and each line no corresponds to the day no.

Now I made 1 TimeTable Class and a Inherited class Period. Timetable holds day no and Period holds all the details of a period like faculty id, time, sub code, etc.

Now, problem is, how can I write & read the whole data to & from the binary file?
Also, how can I display the whole routine like spreadsheet?

table_manage.h

#define pause()                               \
    do                                        \
    {                                         \
        cout << "\n";                         \
    } while (cin.get() != '\n');              \
    do                                        \
    {                                         \
        cout << "Press a key to continue..."; \
    } while (cin.get() != '\n')

class TimeTable
{
public:
    int getDay();
    void setDay(int day);
    void displayRoutine(std::string uname);

private:
    int day = 0;
};

class Period : public TimeTable
{
public:
    void periodConstructor(int periodNo, int startTime, int endTime, std::string facultyId, std::string subId, int day, int totalPeriods)
    {
        this->periodNo = periodNo;
        this->startTime = startTime;
        this->endTime = endTime;
        this->facultyId = facultyId;
        this->subId = subId;
    }
    void openFileChk(std::string uname);

private:
    int periodNo;
    int startTime;
    int endTime;
    std::string facultyId;
    std::string subId;
};

table_manage.cpp

#include <iostream>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <cmath>
#include <array>
#include <set>
#include <map>
#include <cstring>
#include <queue>
#include <stack>
#include <chrono>
#include <random>
#include <functional>
#include <limits>
#include <fstream>
#include <sstream>
#include <filesystem>

#include "login.h"
#include "signup.h"
#include "table_manage.h"

using namespace std;

int TimeTable::getDay()
{
    return day;
}

void TimeTable::setDay(int day)
{
    this->day = day;
}

void Period::openFileChk(string uname)
{
    string funame = uname + ".dat";
    if (std::filesystem::exists(funame))
    {
        ifstream file(funame, ios::out | ios::binary);
        file.close();
    }
}

void TimeTable::displayRoutine(std::string uname)
{
    string funame = uname + ".dat";
    if (std::filesystem::exists(funame))
    {
        TimeTable period[7];
        ifstream file(funame, ios::out | ios::binary);
        file.seekg(9, ios::beg);
        for (int i = 0; i < 8; i++)
        {
            if (!file.eof())
            {
                file.read((char *)&period[i], sizeof(Period));
                setDay(i + 1);
            }
        }

        file.close();
    }
}

I separated the modules as I have also made login & signup features (module) in my code.

To view the full project you can check my GitHub Repo: https://github.com/ArchismanKarmakar/TimeTable-AK

I am working on a routine management system. I just thought like this, the binary file will have 8 lines, 1st line for password matching (8 characters fixed, drama for college), rest of the lines will have the timetable for each day and each line no corresponds to the day no.

Now I made 1 TimeTable Class and a Inherited class Period. Timetable holds day no and Period holds all the details of a period like faculty id, time, sub code, etc.

Now, problem is, how can I write & read the whole data to & from the binary file?
Also, how can I display the whole routine like spreadsheet?

vendredi 17 février 2023

why is this not running, multiple errors

i have copied and pasted the solution of this leetcode problem, yet it doesn't run successful when I go to terminal and select run task. Any help is greatly appreciatedattached photo

i think my problem is either #include something or maybe std::, but if i do std:: then i would have to do alot of std::

Change with taking pointers-to-members as template arguments in C++17 [duplicate]

I know that C++17 introduced template< auto >, but the following example doesn't use it, yet still only compiles in C++17:

struct Foo
{
  int bar;
};

template< int Foo::* >
void takePtrToMember() {}

int main()
{
  takePtrToMember< &Foo::bar >(); // This works everywhere

  constexpr auto x = &Foo::bar;

  takePtrToMember< x >(); // This only works in C++17

  return 0;
}

Why doesn't it work in C++11? What has changed in C++17 so it's now allowed there?

c++: condition variable ownership

I am facing an issue while performing thread synchronisation.

I have a class very similar to the ThreadQueue implementation proposed in this answer, which I'll briefly report here for completeness:

#include <mutex>
#include <queue>
#include <condition_variable>

template <typename T>
class ThreadQueue {
  std::queue<T> q_;
  std::mutex mtx;
  std::condition_variable cv;

public:
  void enqueue (const T& t) {
    {
      std::lock_guard<std::mutex> lck(mtx);
      q_.push(t);
    }
    cv.notify_one();
  }

  T dequeue () {
    std::unique_lock<std::mutex> lck(mtx);
    cv.wait(lck, [this] { return !q_.empty(); });
    T t = q_.front();
    q_.pop();
    return t;
  }
};

I have a consumer that continuously extracts the first available item of a shared instance of that class, say ThreadQueue<int> my_queue;, until it receives a signal to quit, for instance:

std::atomic_bool quit(false);

void worker(){
  std::cout << "[worker] starting..." << std::endl;
  while(!quit.load()) {
      std::cout << "[worker] extract element from the queue" << std::endl;
      auto el = my_queue.dequeue();
       
      std::cout << "[worker] consume extracted element" << std::endl;
      std::cout << el << std::endl;
  }
    
  std::cout << "[worker] exiting" << std::endl;
}

Suppose the program has to terminate (for any reason) before any producer can insert elements in the queue; in this case the worker would be stuck on the line auto el = my_queue.dequeue(); and cannot terminate. An exemple of this case is the following:

int main() {
  std::thread t(worker);
  std::this_thread::sleep_for(std::chrono::seconds(1));
  
  std::cout << "[main] terminating..." << std::endl;
  quit.store(true);
  t.join();
  std::cout << "[main] terminated!" << std::endl;
  return 0;
}

Clearly, the worker can be "unlocked" by pushing a dummy element in the queue, but it does not seem an elegant solution.

I am thus wondering whether the thread syncronisation on the empty queue should be taken out of the ThreadQueue class and done inside the worker instead, i.e. moving the "ownership" of the condition variable outside the ThreadQueue container.

In general, is a class such as ThreadQueue always a bad design?

In case it's not, is there any solution that allows to keep the condition variable encapsulated in ThreadQueue, hence removing the responsibility of thread syncronisation from the users of that class (bearing in mind I am limited to usage of C++11)?

Full MWE here

jeudi 16 février 2023

how to switch the page of stackwidget by mouse's hover event?

how to switch the page of stackwidget by mouse's hover event?

I try to use mouse'events and eventfilter on button, and successfully,but fail in this widget

Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x0 in tid 10852 (DefaultDispatch), pid 10677 (com.example.chat)

2023-01-31 18:28:08.895 17883-17883/? A/DEBUG: *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** 2023-01-31 18:28:08.895 17883-17883/? A/DEBUG: Revision: '0' 2023-01-31 18:28:08.895 17883-17883/? A/DEBUG: ABI: 'arm64' 2023-01-31 18:28:08.895 17883-17883/? A/DEBUG: Timestamp: 2023-01-31 18:28:06.834273628+0530 2023-01-31 18:28:08.895 17883-17883/? A/DEBUG: Process uptime: 0s 2023-01-31 18:28:08.895 17883-17883/? A/DEBUG: Cmdline: com.example.chat 2023-01-31 18:28:08.895 17883-17883/? A/DEBUG: pid: 17027, tid: 17067, name: DefaultDispatch >>> com.example.chat <<< 2023-01-31 18:28:08.895 17883-17883/? A/DEBUG: uid: 10427 2023-01-31 18:28:08.895 17883-17883/? A/DEBUG: signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x0 2023-01-31 18:28:08.895 17883-17883/? A/DEBUG: Cause: null pointer dereference 2023-01-31 18:28:08.895 17883-17883/? A/DEBUG: x0 0000000000000000 x1 0000007266c00000 x2 0000007332777400 x3 0000000000000000 2023-01-31 18:28:08.895 17883-17883/? A/DEBUG: x4 0000000000000025 x5 00000072cdae71a0 x6 00000072a24c3588 x7 00000072a24c3588 2023-01-31 18:28:08.895 17883-17883/? A/DEBUG: x8 0000000000000336 x9 0000000000039336 x10 00000073562936c0 x11 ffffffffffffffff 2023-01-31 18:28:08.895 17883-17883/? A/DEBUG: x12 0000000000000072 x13 ffffffffffffffff x14 0000000000000012 x15 0000000000000000 2023-01-31 18:28:08.895 17883-17883/? A/DEBUG: x16 00000073ec129bd8 x17 00000073ec11ac88 x18 00000072cd46e000 x19 0000007332798488 2023-01-31 18:28:08.895 17883-17883/? A/DEBUG: x20 0000007332777400 x21 0000007266c00000 x22 0000000000000000 x23 00000073ec12d808 2023-01-31 18:28:08.895 17883-17883/? A/DEBUG: x24 00000073ec12d7e8 x25 b4000072a929e1c8 x26 0000000000000000 x27 00000072cdae8200 2023-01-31 18:28:08.895 17883-17883/? A/DEBUG: x28 00000072cdae8518 x29 00000072cdae7f90 2023-01-31 18:28:08.895 17883-17883/? A/DEBUG: lr 00000073ec09bf9c sp 00000072cdae7f90 pc 00000073ec09bf9c pst 0000000060000000 2023-01-31 18:28:08.895 17883-17883/? A/DEBUG: backtrace: 2023-01-31 18:28:08.895 17883-17883/? A/DEBUG: #00 pc 000000000005df9c /apex/com.android.runtime/lib64/bionic/libc.so (je_huge_salloc+20) (BuildId: f24f65acf653c409ca4332aced817a71) 2023-01-31 18:28:08.895 17883-17883/? A/DEBUG: #01 pc 0000000000061b54 /apex/com.android.runtime/lib64/bionic/libc.so (ifree+308) (BuildId: f24f65acf653c409ca4332aced817a71) 2023-01-31 18:28:08.895 17883-17883/? A/DEBUG: #02 pc 0000000000061eb4 /apex/com.android.runtime/lib64/bionic/libc.so (je_free+116) (BuildId: f24f65acf653c409ca4332aced817a71) 2023-01-31 18:28:08.895 17883-17883/? A/DEBUG: #03 pc 00000000005bf31c /data/app/~~rMr4QLvchrg_MGXR6psmpQ==/com.example.chat-yvtcWqmjtQLgIj6SsDy-bQ==/base.apk!libapp.so (cpr::Response::~Response()+124) (BuildId: ce052f57203862ee6096f5475361cb76e654ded6) 2023-01-31 18:28:08.895 17883-17883/? A/DEBUG: #04 pc 00000000006bc950 /data/app/~~rMr4QLvchrg_MGXR6psmpQ==/com.example.chat-yvtcWqmjtQLgIj6SsDy-

I try to get the data from c++ file while background thread running time for purposes of display the value in Android native code, Sometimes its shows error like above I mentioned.

mercredi 15 février 2023

C++ std::condition_variable usage to synchronize two threads

I'm trying to understand how the std::condition_variable works and fail to understand.

I have composed the below program, that its objective is to "guarentee" that thread1 will print "foo", followed by thread2 that will print "bar" and then again thread1 "foo" and eventually thread2 will print "bar". When I run the program, sometimes the objective is achived, i.e. - it prints "foobarfoobar" but sometimes it does not - and it prints "foobarbarfoo".

I struggelling to understand what am I missing in my implementation here. Note, if I run the program with n=1 it always outputs the required output.

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

using namespace std;

mutex m;
condition_variable cv;
bool ready = false;
bool processed = false;
int numOfIterations = 2;

void worker_thread2()
{
    cout << "worker_thread2 - start" << endl;
    for (int i = 0; i < numOfIterations; ++i)
    {
        cout << "worker_thread2 - iteration:" << i << endl;
        // Wait until thread1 sends data
        unique_lock lk(m);
        cv.wait(lk, []{return ready;});
        // after the wait, we own the lock.
        cout << "bar" << endl;
 
        // Send data back to thread1
        processed = true;

        // Manual unlocking is done before notifying, to avoid waking up
        // the waiting thread only to block again (see notify_one for details)
        lk.unlock();
        cv.notify_one();
    }
    cout << "worker_thread2 - end" << endl;
}

void worker_thread1()
{
    cout << "worker_thread1 - start" << endl;
    for (int i = 0; i < numOfIterations; ++i)
    {
        cout << "worker_thread1 - iteration:" << i << endl;
        {
            lock_guard lk(m);
            cout << "foo" << endl;
            ready = true;
        }
        cv.notify_one();
        // wait for the worker2 to finish
        {
            cout << "worker_thread1 BEFORE unique_lock lk(m)" << endl;
            unique_lock lk(m);
            cv.wait(lk, []{return processed;});
        }
    }
    cout << "worker_thread1 - end" << endl;
}

int main()
{
    cout << "main - about to start the two worker threads" << endl;
    thread worker1(worker_thread1);
    thread worker2(worker_thread2);
    cout << "main - joining the two worker threads" << endl;
    worker1.join();
    worker2.join();
    cout << "main - end" << endl;
    return 0;
}

I guess that I'm not using the ready & processed properly, but whenever I try to change it I get to a deadlock.

mardi 14 février 2023

Return variable declared in for loop [duplicate]

int square(int i) // function which calculates the square of any number
{
    for(int t = 0; t <= i; t += i); // t=0 at first, then as long as t is less than or equal to i, increase t by i
    return t;
}

I expected this function to work. However, the compiler said "t is not defined". However, I said int t = 0, so not sure what to do. Thanks

How To get size of varying cols in rows of a 2d vector?

How do you find the size of an individual row in a 2d matrice in which all the rows vary in size. So its not a NxM matrice rather they're all a little different in length.

vector<vector<int>> &someVector;
vector<int> v;
resV.resize(10);

for(int i = 0; i < 10; i++)
{
    for(int j = 0; j < (int)someVector.size(); j++) //iterates through all the rows
        if(!(someVector[i][j] <= 0) ) // i represents the row and j the col it is at
            .push_back(someVector[i][j]); // adds value into 1d vector
}

I used this code here because i know the columns length of 1 row wont exceed 10. It psuhes it into another vector which is of 1 row so it will be easier to print out and find its mid value which is something different that will be easy once i can get the values of this 2d vector into the 1d vector.

This code here results in an error on the 2nd for loop line.

How to store multi-dimensional key-value pair?

I have the below sequence of data to be stored into C++ container.

`Type1 -> Channel 0 -> Data1 -> Value
                   -> Data2 -> Value
                   -> Data3 -> Value
         Channel 1 -> Data1 -> Value
                   -> Data2 -> Value
                   -> Data3 -> Value
         Channel 2 -> Data1 -> Value
                   -> Data2 -> Value
                   -> Data3 -> Value
Type2 -> Channel 0 -> Data1 -> Value
                   -> Data2 -> Value
Type3 -> Channel 0 -> Data1 -> Value
                   -> Data2 -> Value
         Channel 1 -> Data1 -> Value
                   -> Data2 -> Value`

What is the best way to store in a container. We use C++14.

Thanks in advance !!

I have tried the below map:

std::map<std::string,std::map<int,std::map<std::string, int>>> DataMap;

Is there any optimized way to do this?

lundi 13 février 2023

Iterating over vector in one thread while other may potentially change reference

I have a vector allow_list that is periodically updated in a thread while another serves a function that checks if a certain string is in that allow_list via:

if (std::find(allow_list->begin(), allow_list->end(), target_string) != allow_list->end()){
    allow = true;
}

Now, the other thread may do something like this

// Some operation to a vector called allow_list_updated
allow_list = allow_list_updated;

Should I add a mutex here to lock and unlock before and after these operations? My intuition tells me it's "ok" and shouldn't crash and burn but this seems like undefined behavior to me.

How to use braced integer list initialization for constructor in c++?

I am trying but unable to create a constructor for my class which takes in integer arguments (which may change to some custom data type later) through braced list initialization like the classic old int a{0,1,2}. Here is my code

#include<iostream>
using namespace std;

class class_a {
    private:
        int ptr;
    public:
        class_a() {};
        template<typename ... Args>
        class_a(Args&& ... args) : ptr((args)...) {}
};

int main()
{
    class_a c1{0}; //works
    class_a c2{0,1,2}; //doesnt works
}

I want an output where the variable ptr can be initialized as the array of integers {0,1,2} (again, just for now - it may change to any complex data type later)

dimanche 12 février 2023

Why the below program aborts when a std::vector<:future>> is used.?

I wanted to perform hashing of a stream of input messages in multithreading, so was trying to implement

std::vector<std::future<HashData>> futures;

but the program aborts from abort.h when debugging in Visual Studio 2019.

Code Snippet:

std::vector<std::future<HashData>> futures;
std::vector<std::string> messages;

for (int i = 0; i < messages.size(); i++)
{
  std::promise<HashData> promiseHashData;
  std::future<HashData> futureHashData = promiseHashData.get_future();
  futures.emplace_back(std::move(futureHashData));
  std::async(std::launch::async, [&]() {PerformHash(std::move(promiseHashData), messages[i]);});
}

std::vector<HashData> vectorOfHashData;
// wait for  all async tasks to complete
for (auto& futureObj : futures)
{
  vectorOfHashData.push_back(futureObj.get());
}

void PerformHash(std::promise<HashData>&& promObject, std::string& message)
{
    ComputeHashUsingSHA256(message);
        HashData data;

    // set data for HashData object
    data.i = i;
    data.blocks = blocks;
    data.blocksize = blocksize;
    data.blockbufs = blockbufs;
    data.secs = secs;
    memcpy(data.digest, digest, SHA256_DIGEST_SIZE);

    data.has_hashdata = has_hashdata;
    memcpy(data.hashdata_buf, hashdata_buf, c_hashsize);

    promObject.set_value(data);

}

while debugging the code, observed as only few threads were created using async and post that, the program aborts from abort.h as shown in this image

Does the conversions between SQLWCHAR and char16_t are safe?

I'm using the same code, using ODBC, on both Windows and Linux (linuxODBC).

On windows moving from SQLWCHAR and std::wstring is natural. bot on Linux I must convert encoding from std::wstring (UTF-32) to SQLWCHAR (UTF-16) and vice versa, and store results in std::u16string.

Whenever I give SQLWCHAR to char16_t and vice versa, I get a compilation error, which I can easily resolve with casting. using macros like this:

#ifdef WIN32
#define SQL(X) (X)
#define CHAR16(X) (X)
#else
#define SQL(X) ((const SQLWCHAR*)X)
#define CHAR16(X) ((const char16_t*)X)
#endif

both appear to have the same size, but see this in cppreference:

int_least8_t int_least16_t int_least32_t int_least64_t smallest signed integer type with width of at least 8, 16, 32 and 64 bits respectively (typedef)

the "at least" made me start to be worried...

So I would like to ask, is this casting safe?

The smart pointer from cracking the code interview

struct Data
{
    ~Data()
    {
        std::cout << "dtor" << std::endl;
    }
};

template <typename T> class SmartPointer
{

public:
    SmartPointer(T* ptr)
    {
        ref = ptr;
        ref_count = (unsigned int*)malloc(sizeof(unsigned));
        *ref_count = 1;
    }

    SmartPointer(SmartPointer<T>& sptr)
    {
        ref = sptr.ref;
        ref_count = sptr.ref_count;
        ++(*ref_count);
    }

    SmartPointer<T>& operator=(SmartPointer<T>& sptr)
    {
        if (this == &sptr)
            return *this;

        if (*ref_count > 0)
            remove();

        ref = sptr.ref;
        ref_count = sptr.ref_count;
        ++(*ref_count);
        return *this;
    }

    ~SmartPointer()
    {
        remove();
    }

    T getValue()
    {
        return *ref;
    }

private: // protected:
    T* ref = nullptr;
    unsigned* ref_count = nullptr;

    void remove()
    {
        --(*ref_count);
        if (!*ref_count)
        {
            delete ref;
            free (ref_count);
            ref = nullptr;
            ref_count = nullptr;
        }
    }
};

int main()
{
//    Data data;

//    auto data = new Data;
//    delete data;

    auto data = SmartPointer<Data>(new Data);
}

Saw the above implementation of a smart pointer on cracking the code interview 6th ed.

I changed protected members to be private and it still seem to work. Do we really need them do be protected?

Force kill a C++ thread which is stuck on some blocking function

I have std::thread which listens for netlink events from the Linux kernel, It has an infinite while loop and a blocking function which blocks until the next event. I want to stop the thread forcefully in the program workflow when I don't need that anymore.

Here is my current solution:

#include <pthread.h>
#include <signal.h>
#include <unistd.h>
#include <iostream>
#include <thread>
#include <signal.h>

void thread_func() {
    while(true) {
        std::cout << "Processing events.." << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(10)); // simulating a blocking function that blocks until next events
        std::cout << "Events received.." << std::endl;
    }
}

int main() {
    std::thread eventListener(thread_func);
    std::this_thread::sleep_for(std::chrono::seconds(3)); // doing some work in main thread
    pthread_cancel(eventListener.native_handle()); // I don't want the eventListener anymore
    eventListener.join();
    std::cout << "eventListener killed" << std::endl;
    return 0;
}

My program only compiles to the Linux platform.

Questions:

  1. Is it the correct way of doing it in C++? or I'm missing some minor details here?
  2. Is there any other better way of achieving this?
  3. if I change the above code to kill the thread by pthread_kill instead of pthread_cancel then I don't see the print "eventListener killed" in output, I don't know why?

samedi 11 février 2023

How to take user input and write it to a pipe?

I just want to take a user input from cin and write it to a pipe but unable to do so.

if(id==0)  
{  
    close(fd[0]);  
    int x;  
    cout<<"Enter a number : ";  
    cin>>x;  
    write(fd[1],&x,sizeof(int));  
    close(fd[1]);  
}  
else  
{  
    close(fd[1]);  
    int y;  
    read(fd[0],&y,sizeof(int));  
    close(fd[0]);  
    cout<<"X is same as Y i.e : "<<y;  
    wait(NULL);     
}

Getting output as:- "Enter a number : X is same as Y i.e ".

But if I remove the close() then it works fine.

how to initialise a static member variable container with elements that are instances of structs?

Hello so I have a class that uses 5 instances of a struct and I would like a static vector to hold those instances but I do not want the elements themselves to be static.

the header file looks like this

#pragma once
#include <string>
#include<vector>

using namespace std;


struct table {
    unsigned int tableNumber;
    unsigned int numChairs;
    unsigned int numberOfPeople;
    bool occupied;

    //table();

    void toggleOccupied() {
        if (occupied == true) {
            occupied = false;
        }
        else
        {
            occupied = true;
        }
    }

    bool getTableOccupied() {
        return occupied;
    }

    void setNumChairs(int newChairNum) {
        numChairs = newChairNum;
    }

    void setTableNumber(int assignTableNum) {
        tableNumber = assignTableNum;
    }

     int getTablenumber() {
        return tableNumber;
    }

     int getNumberOfChairs() {
        return numChairs;
    }

    void setNumberOfPeople(int addNumPeople) {
        numberOfPeople = addNumPeople;
    }


};





class tableOrder {
public:

    tableOrder();
    
    int getSP() {
        return SP;
    }

    enum ServingProgress {
        seated,
        drinksOrder,
        starters,
        main,
        dessert,
        bill
    };

    ServingProgress SP = seated;

    std::string progress;

    void getCurrentProgress() {
        switch (SP) {
        case 0:
            progress = "seated";
            break;
        case 1:
            progress = "drinksOrder";
            break;
        case 2:
            progress = "starters";
            break;
        case 3:
            progress = "main";
            break;
        case 4:
            progress = "dessert";
            break;
        case 5:
            progress = "bill";
            break;
        }
    }

    void ProgressOrder() {
        switch (SP) {
        case 0:
            SP = drinksOrder;
            break;
        case 1:
            SP = starters;
            break;
        case 2:
            SP = main;
            break;
        case 3:
            SP = dessert;
            break;
        case 4:
            SP = dessert;
            break;
        case 5:
            SP = bill;
            progress = "finished";
            break;
        }
    }

    void checkForTablesInUse() {
        for (int i(0); i < allTables.size(); i++) {
            if (allTables[i].occupied) {
                TablesInUse.push_back(allTables[i]);
            }
        }
    }

    void checkForTablesNotInUse() {
        for (int i(0); i < TablesInUse.size(); i++) {
            if (TablesInUse[i].occupied == false) {
                TablesInUse.erase(TablesInUse.begin() + i);
            }
        }
    }

    void updateTablesInUse() {
        checkForTablesInUse();
        checkForTablesNotInUse();
    }

    table& getTable(unsigned int tableIndex) {
        return allTables[tableIndex - 1];
    }

    //instantiate tables
    table table_1 = { 1,6,0,false };
    table table_2 = { 2,5,0,false };
    table table_3 = { 3,4,0,false };
    table table_4 = { 4,8,0,false };
    table table_5 = { 5,4,0,false };


//protected:

    unsigned int assignedTableNumber;

    table assignedTable;

    static vector<table> availableTables;
    static vector<table> TablesInUse;
    static vector<table> TablesToSelect;
    static vector<table>  allTables;
    static tableOrder passTable;

};
    

I have made 5 instance of table and want to store them in the static allTables. Here is the cpp file

#include "TableOrder.h"

vector<table> tableOrder::availableTables = {};
vector<table> tableOrder::TablesInUse = {};
vector<table> tableOrder::TablesToSelect = {};
vector<table>tableOrder::allTables = {table_1,table_2,table_3,table_4,table_5 };

tableOrder::tableOrder() {
     assignedTableNumber = 0;

     assignedTable = table_1;
    
     
     
}

I understand why I can't initialise allTables like this as I am putting unique variables inside a shared variable. Is there any decent way around this? thanks for the help!

vendredi 10 février 2023

Implementing /usr/bin/g++ -DEVAL -std=gnu++11 -O2 -pipe -static -s -o A A.cpp into Visual Studio for task upload

I need to upload a .cpp file for a course application. The code works, i tried their test inputs, but when i upload my file it throws this error

</usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/crt1.o: In function _start': (.text+0x20): undefined reference to main' collect2: error: ld returned 1 exit status>

On the website it has a list of compilation commands that I assume have to somehow put into my code so the website can process my code? Maybe that isnt even it, this is my first time dealing with this sort of thing, so any help is appreciated.

Tried just putting it into the code outside of main, didnt work.

Why unique_ptr requires complete type in constructor?

From Is std::unique_ptr required to know the full definition of T?, I know that if a class A has a member unique_ptr<T>, then T shall be a complete type in destructor ~A(). However, I came across a situation that the constructor A() also requires complete type of T, see code below:

// a.h -------------------------------
#pragma once
#include <memory>
struct B;
struct A {
  A(); // <---
  ~A();
  std::unique_ptr<B> ptr;
};

// a.cpp -------------------------------
#include "a.h"
struct B {};
A::A() = default; // <---
A::~A() = default;

// main.cpp -------------------------------
#include "a.h"
int main() {A a;}

If the definition of constructor A::A() is moved to the header a.h, the compiler will complain error: invalid application of ‘sizeof’ to incomplete type ‘B’. Why is this happening? Is there any reference material about this?

BTW, I'm using gcc-7.5.0 on Ubuntu 18.04, with c++17 enabled.

jeudi 9 février 2023

auto open_flags = std::ios::binary; seems to produce the wrong type in MSVC. Is it a bug?

This c++ code compiles fine with gcc, icc, and clang, but fails with MSVC:

#include <ios>

int main()
{
    auto open_flags = std::ios::binary;
    open_flags |= std::ios::app;

    return 0;
}
(6): error C2678: binary '|=': no operator found which takes a left-hand operand of type 'std::_Iosb::_Openmode' (or there is no acceptable conversion)

https://godbolt.org/z/999fffPEx

Changing the code to this gives a more helpful error message:

#include <ios>

int main()
{
    auto open_flags = std::ios::binary;
    open_flags = open_flags | std::ios::app;

    return 0;
}
(6): error C2440: '=': cannot convert from 'int' to 'std::_Iosb::_Openmode'

And this compiles fine:

#include <ios>

int main()
{
    auto open_flags = std::ios::binary | std::ios::out;
    open_flags = open_flags | std::ios::app;

    return 0;
}

This looks like incorrect behaviour to me. Like MSVC has implemented the | operator with return type int instead of ios::openmode.

It's also worth noting that the original code compiles if I use std::ios::openmode instead of auto, presumably through implicit conversion.

Is this an MSVC bug, or am I missing something? Standards references welcome!

How can I determine functions' parameter and return value for std::unique_ptr? [closed]

These three pieces of code below seem to convey almost the same thing(i.e. change the outside resource in the function), and how can I determine the exact way?

std::unique_ptr<int> test(std::unique_ptr<int> ptr)
{
   // some op
   return ptr;
}
std::unique_ptr<int>&& test(std::unique_ptr<int>&& ptr)
{
   // some op
   return std::move(ptr);
}
void test(std::unique_ptr<int>& ptr)
{
   // some op
   return;
}

Besides, this seems to be a common problem for moveable classes.

How fix it. Unhandled exception at 0x0099B514 in ConsoleApplication15.exe: 0xC0000094: Integer division by zero

I am trying to solve problem with c++: Find all unique elements of a two-dimensional array of integers using MPI_Scatter and MPI_Comm_split to distribute the array's rows among a set of processes, so that the set of processes is split into three groups. Got the code

#include <iostream>
#include <unordered_set>
#include <mpi.h>

using namespace std;

int main(int argc, char* argv[])
{
    int rank, size;
    int rows = 0, columns = 0;

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);

    int* matrix = nullptr;
    if (rank == 0)
    {
        cout << "Enter the number of rows: ";
        cin >> rows;
        cout << "Enter the number of columns: ";
        cin >> columns;

        matrix = new int[rows * columns];

        cout << "Enter the elements of the matrix: " << endl;
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < columns; j++)
            {
                cin >> matrix[i * columns + j];
            }
        }
    }

    MPI_Bcast(&rows, 1, MPI_INT, 0, MPI_COMM_WORLD);
    MPI_Bcast(&columns, 1, MPI_INT, 0, MPI_COMM_WORLD);

    int sub_size = rows / size;
    int* local_matrix = new int[sub_size * columns];

    MPI_Scatter(matrix, sub_size * columns, MPI_INT, local_matrix, sub_size * columns, MPI_INT, 0, MPI_COMM_WORLD);

    unordered_set<int> local_set;
    for (int i = 0; i < sub_size; i++)
    {
        for (int j = 0; j < columns; j++)
        {
            local_set.insert(local_matrix[i * columns + j]);
        }
    }

    MPI_Comm sub_comm;
    MPI_Comm_split(MPI_COMM_WORLD, rank / (size / 3), rank, &sub_comm);

    int sub_rank, new_sub_size;
    MPI_Comm_rank(sub_comm, &sub_rank);
    MPI_Comm_size(sub_comm, &new_sub_size);

    unordered_set<int>* global_set = nullptr;
    if (sub_rank == 0)
    {
        global_set = new unordered_set<int>[new_sub_size];
    }

    MPI_Gather(&local_set, sizeof(unordered_set<int>), MPI_BYTE, global_set, sizeof(unordered_set<int>), MPI_BYTE, 0, sub_comm);

    if (sub_rank == 0)
    {
        unordered_set<int> final_set;
        for (int i = 0; i < new_sub_size; i++)
        {
            for (auto it = global_set[i].begin(); it != global_set[i].end(); it++) {
                final_set.insert(*it);
            }
        }
        cout << "The unique elements in the matrix are: ";
        for (auto it = final_set.begin(); it != final_set.end(); it++) {
            cout << *it << " ";
        }
        cout << endl;
        delete[] global_set;
    }

    delete[] local_matrix;
    if (rank == 0) {
        delete[] matrix;
    }

    MPI_Finalize();
    return 0;
}

After compile and input data microsoft visual studio 2019 gives an error message

Unhandled exception at 0x0099B514 in ConsoleApplication15.exe: 0xC0000094: Integer division by zero.

to this line

MPI_Comm_split(MPI_COMM_WORLD, rank / (size / 3), rank, &sub_comm);

How fix it?

mercredi 8 février 2023

C++ new operator with std::move to "copy" pointer

I recently find a code snippet as follows:

  // To be specific: the "Item" can be viewed as "std::pair<xxx, xxx>*" here
  void moveItemDuringRehash(Item* itemAddr, Item& src) {
    // This is basically *itemAddr = src; src = nullptr, but allowing
    // for fancy pointers.
    // TODO(T31574848): clean up assume-s used to optimize placement new
    assume(itemAddr != nullptr);
    new (itemAddr) Item{std::move(src)};
    src = nullptr;
    src.~Item();
  }

The code is originated from the Folly Lib of Facebook. The functionality of this code is simple: copy std::pair* referenced by src to the memory pointed by itemAddr.

The implementation should be very simple, as mentioned in the comment. But actually, the code does not. The new operator with std::move is confusing, and I am not sure what is happening under the hood. I guess. Item{std::move(src)} construct a temp object with move ctor of std::pair*. And the temp object is copy to the object pointed by itemAddr by copy ctor of std::pair*. I am not sure if my guess is correct. Thank you for sharing your opinion. By the way, I was wondering if there is any performance benefit from this new operator with std::move.

Another question is why src.~Item() is needed? For safety, I need to set src (std::pair*) to nullptr. But why I need to use src.~Item() to dtor a nullptr?

How can I access a protected variable in child class through an abstract class pointer?

I have an abstract class that I have derived from two child classes. One of them has a protected variable that the other one does not. To make the code more general, I have to use an smart pointer of the abstract class. Is there any way to access the protected variable through the pointer? As an example, Consider the following code (the real code is huge and I had to write this sample code):

class Pen{
    public:
        pen(string _color): color(_color){};
        getColor(){return color;};
    protected:
        string color;
};
// base abstract class
class writer{
    public: 
        writer() {}
        virtual changeColor(string color) = 0;
    };

class oldWriter: public writer{
    protected:
        Pen *pen;
    public:
        oldWriter(string _pen):
          pen(_pen){}
        virtual changeColor(string color){ pen->color = color;};
};

class youngWriter: public writer{
    protected:
        Pen *pen;
        Pencile pencil; //we need to have access to pencil
    public:
        youngWriter(string _pen):
          pen(_pen){}
        virtual changeColor(string color){ pen->color = color;};
        Pencil getPencil(){return pencil;};
};

int main(){
    unique_ptr<Writer> artist;
    Pencil pencil = artist->getPencil(); //how?
}

How can we access "pencil" in "youngWriter" class through "artist"?

Proper way to assign lambda as a function argument [duplicate]

I've been writing a program that takes an array and returns a summary of elements that fit the condition. What am I doing wrong?

#include <iostream>
#include <array>
using namespace std;
template<typename arg>
float sum(float *arr, arg&& condition){
    int res=0;
    for(int i=0;i<sizeof(arr);i++) if(condition(arr[i])) res+=arr[i];
    return res;
}
int main(){

    // just array initialization
    int size;
    cout << "enter size: ";
    cin>>size;
    cout<< endl;
    float arr[size];
    for (int i=0;i<size;i++){
        arr[i]= float((rand() % 100))/100;
        cout << arr[i] << " ";
    }
    cout << sum(arr, [](auto&& val){ return val < 0.25 ;}) << endl; // i'm getting an error here
    
    return 0;
}

I've tried modifying Code Runner settings.json to work with c++11 but it didn't seem to fix the warning. I'm using VSCode and Code Runner. Error output:

warning: rvalue references are a C++11 extension [-Wc++11-extensions]
float sum(float *arr, arg&& condition){
                         ^
*.cpp:22:22: error: expected expression
    cout << sum(arr, [](auto&& val){ return val < 0.25 ;}) << endl;
                     ^
1 warning and 1 error generated.

mardi 7 février 2023

Initializer list issue in constructor

I have a hard time understanding how std::initializer_list works. I checked other questions, but found nothing relevant (or maybe I didn't see it?).

Say I have this:

template<typename T> 
struct Point
{
    T x,y;
};

template<typename T> 
struct A
{
    std::vector<Point<T>> v;
};

Then I can build with:

int main()
{
   A<int> a{ std::vector<Point<int>> { {4,4}, {5,5},{6,6} } };
}

But I'd like to make thing simpler, so I can write:

int main()
{
   A<int> a( { {4,4}, {5,5},{6,6} } );
}

I tried:

template<typename T> 
struct A
{
    std::vector<Point<T>> v;
    template<typename U>
    A( const std::initializer_list<Point<U>>& il ) : v{il}
    {}
};

But this fails, see live demo.

How can I write a constructor allowing this? Is this even possible?

lundi 6 février 2023

Program demonstrating the input/output control for an LRT system. Any ideas on what may be wrong?

Brief Description: This program demonstrates input/output control for an LRT system

#include <iostream>
#include <cmath>

using namespace std;

int main ()
{

    // Prompt user to enter the number of trains on each track
        double t1, t2, t3, t4; 

        cout << "Enter the number of trains on Track 1. " ;
        cin >> t1;

        cout << "Enter the number of trains on Track 2. " ;
        cin >> t2;

        cout << "Enter the number of trains on Track 3. " ;
        cin >> t3;

        cout << "Enter the number of trains on Track 4. " ;
        cin >> t4;


    // Comparison for t4
    
        if ((t4>=t1) && (t4>=t2) && (t4>=t3));
        {
            cout << "Track 1 has " << t1 << " train(s) stopped." << endl ;
            cout << "Track 2 has " << t2 << " train(s) stopped." << endl ;
            cout << "Track 3 has " << t3 << " train(s) stopped." << endl ;
            cout << "Track 4 has 1 train cleared and " << t4-1 << " train(s) stopped. " ;
            
            if ((t4-1) > 4);
            {
                cout << "Track 4 alert!" << endl ;
            }
            
            cout << endl;
        }
            

    // Comparison for t3

        else if ((t3>=t1) && (t3>=t2) && (t3>t4));
        {
            cout << "Track 1 has " << t1 << " train(s) stopped." << endl ;
            cout << "Track 2 has " << t2 << " train(s) stopped." << endl ;
            cout << "Track 3 has 1 train cleared and " << t3-1 << " train(s) stopped." ;

            if ((t3-1) > 4);
            {
                cout << "Track 3 alert!" << endl ;
            }

            cout << "Track 4 has " << t4 << " train(s) stopped. " << endl ;
            cout << endl;
        }

    // Comparison for t2   

        else if ((t2>=t1) && (t2>t3) && (t2>t4));
            {
            cout << "Track 1 has " << t1 << " train(s) stopped." << endl ;
            cout << "Track 2 has 1 train cleared and " << t2-1 << " train(s) stopped." ;

            if ((t2-1) > 4);
            {
                cout << "Track 2 alert!" << endl ;
            }

            cout << "Track 3 has " << t3 << " train(s) stopped." << endl ;
            cout << "Track 4 has " << t4 << " train(s) stopped. " << endl ;
            cout << endl;
            }

    // Comparison for t1

            else if ((t1>t2) && (t1>t3) && (t1>t4));
            {
                cout << "Track 1 has 1 train cleared and " << t1-1 << " train(s) stopped. " ;

                if ((t1-1) > 4);
                {
                    cout << "Track 1 alert!" << endl ;
                }

                cout << "Track 2 has " << t2 << " train(s) stopped." << endl ;
                cout << "Track 3 has " << t3 << " train(s) stopped." << endl ;
                cout << "Track 4 has " << t4 << " train(s) stopped. " << endl ;
                cout << endl;
            }
    
    return (0);           
}

I'm writing a program to sequentially look through four train tracks, select the track with the most trains, clear one train on the selected track and stop the rest of the trains.

Should the number of trains stopped on the track with the most trains be greater than 4, an alert is displayed.

Should there be any equivalency between the number of trains on the tracks, there is a priority list: Track 4 has priority over Track 3 which has priority over Track 2 which has priority over Track 1. answers ned to be displayed in the folowing format:

Enter the number of trains on Track 1. 1 Enter the number of trains on Track 2. 5 Enter the number of trains on Track 3. 3 Enter the number of trains on Track 4. 5 Track 1 has 1 train(s) stopped. Track 2 has 5 train(s) stopped. Track 3 has 3 train(s) stopped. Track 4 has 1 train cleared and 4 train(s) stopped. Track 4 alert!

Any help would be greatly apreciated.

how to do this exercise (Binary tree)

You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure.

Example 1:

Input: root = [1,3,null,null,2]
Output: [3,1,null,null,2]

Explanation: 3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes the BST valid. Example 2:

Input: root = [3,1,4,null,null,2]
Output: [2,1,4,null,null,3]

Explanation: 2 cannot be in the right subtree of 3 because 2 < 3. Swapping 2 and 3 makes the BST valid.

I am a new coder so i want a help from everyone

conversion from void pointer to pointer to struct or class

what is the correct approach for converting void * to pointer to struct or class.

sometime mistakes can happen like pointer to different class or struct was assigned.how to catch these types of mistakes over compile or run time.

following program tried, surprisingly it compiled and no crash even after execution.

what is right way for type casting from void * to pointer to struct or class in cpp

Description: how to avoid type casting related issues from void * to pointer to class or struct at compile time or runtime. if static_cast is used for conversion from void * then code is compiled, even it is invalid conversion.

#include <iostream> using namespace std;

struct stu { int x; int y; int z; };

struct clg { int x; float y; char z; };

void fun(void *msg) { clg myclg = static_cast<clg>(msg);

cout<<"casting is done."<<endl;

}

int main() { stu* st = new stu(); clg* cl = new clg();

void *ptr = st;
fun(ptr);

return 0;

}

dimanche 5 février 2023

Runtime Error: reference binding to null pointer of type 'int' (stl_vector.h), product of array except self

While solving a Product of array except self on leetcode , I encountered an error:

runtime error: reference binding to null pointer of type 'int' (stl_vector.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:9

Here is my code to the problem:

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        int leftarr[nums.size()];
        int rightarr[nums.size()];
        int n = nums.size();
        int prod=1;
        for(int i=0;i<n;++i){
            prod *= nums[i];
            leftarr[i]= prod;
        }
        prod=1;
        for(int j=n-1;j>=0;--j){
            prod *= nums[j];
            rightarr[j]= prod;
        }
        vector<int> output;
        output[0]= rightarr[n-1];
        output[n-1]= leftarr[n-2];
        for(int i=1;i<n-1;++i){
          output.push_back(leftarr[i-1]*rightarr[i+1]);
        }

        return output;
    }
};

My approach to solve this problem: Take two arrays, leftarr and rightarr and store the cumulative left and right multiplication at respective index, then take output vector and multiply left and right multiplication and get the output.

So, could any one of you pls tell me why this error occurs and what is wrong with my code?

C++ standard for member offsets of standard layout struct

Does the C++11 standard guarantee that all compilers will choose the same memory offsets for all members in a given standard layout struct, assuming all members have guaranteed sizes (e.g. int32_t instead of int)?

That is, for a given member in a standard layout struct, does C++11 guarantee that offsetof will give the same value across all compilers?

If so, is there any specification of what that value would be, e.g. as a function of size, alignment, and order of the struct members?

samedi 4 février 2023

When to use pointers or actual objects when going through member variables in c++ [closed]

so if I have 2 classes where class 1 has an instance of class two such as

class MyClass_1 {
public:

    

    

    void incrementNum() {
        secondClass.addOne();
    }

    void getTotalBannanas() {
        secondClass.getNumber();
    }



protected:
     
    myClass_2 secondClass;
    
};

class 2

class myClass_2 {
public:
    void addOne() {
        number += 1;
    }

    unsigned int getNumber() {
        return number;
    }

protected:
    unsigned int number = 0;

};

Now if I use the functions in class one to increment "number" then I print out the number I get what I would expect number goes up by the amount I incremented it by. But If I do the whole think through a middle class where I go through an object of class_C then go to myClass_2 then the whole the incremented amounts are no longer remembered.

By going through a middle class I mean by making changes like this

class MyClass_1 {
public:

    

    

    void incrementNum() {
        middle.getClass2().addOne();
    }

    void getTotalBannanas() {
        middle.getClass2().getNumber();
    }

protected 
middleClass middle;

middle class

class middleClass{
public:

myClass_2 getMyclass_2(){
return secondClass;
}

protected:

myClass_2 secondClass;

when I run the following code in main

int main() {
    myClass_1 woody;
    woody.incrementNum();
    woody.incrementNum();
    woody.getTotalBannanas();
    woody.incrementNum();
    woody.getTotalBannanas();

    return 0;
}

the first time I run this before the changes I get 2 and 3 After the changes I get 0,0

Could someone explain the reason why this extra step causes this. I know you can do this by using pointers such that the values are remembered but I am trying to understand the difference of using pointers and an actual instance of a class. Thanks a lot!

Why does this example use `2.` instead of `2.0` (decimal point with no decimals)?

I came across this tutorial, and I've never encountered this syntax: gp_Pnt aPnt1(-myWidth / 2., 0, 0);. I'm likely looking in the wrong places, but why does G++ accept all 3 of these variable initializations?

double a = 2;
double b = 2.;
double c = 2.0;

I don't remember coming across 2. - is this shorthand for 2.0, or are they different?

Sending text to Notepad C++

I can't figure out how to send a certain text to notepad and press Enter. I saw what they do somehow through Sendmessage, but how many times I tried, it doesn't work.

tuple with get but U is a derived class of a tuple type

Suppose we have std::tuple<Ts*...> tuple;. One of the types is T* and a class U derives from T (polymorphically). How do we define

template <typename U> T* get(const std::tuple<Ts*...>&);

so that get<U>(tuple) returns std::get<T*>(tuple)? Of course, we want get<T>(tuple) to return std::get<T*>(tuple).

vendredi 3 février 2023

color changing happens all at once in c++

i am making a program that is supposed to show you the stations to the sofia metro and i tried making it colorized, but then it turns out that it just shows the color of the last thing printed. i tried it on cxxdroid and it worked fine but on codeblox and several online compilers the issue seems to persist. what i

imagined happening is like the image attatched here: (https://i.stack.imgur.com/u03Fj.png) vs what actually ended up happening: (https://i.stack.imgur.com/q1EqZ.png)

so my (simplified ofc) code looks like this:

#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
    cout<<"chose on of the following lines to show their stations: "<<endl<<flush;
    system("color 40");
    cout<<"line one: Liulin  - Mladost (Business Park - Slivnitsa)"<<endl<<flush;
    system("color 90");
    cout<<"line 2: Nadejda - Lozenets (Obelia - Vitosha)"<<endl<<flush;
    system("color A0");
    cout<<"line 3: Ovcha Kupel - Hadji Dimitar (Gorna Bania - Hadji Dimitar)"<<endl<<flush;
    system("color 60");
    cout<<"line 4: Obelia - Sofia Airport"<<endl<<flush;
    system("color 00");
    cout<<"enter 5 for all 5 lines to be shown at once"<<endl;
    return 0;
}

Virtual method in C++ fails to get mocked. What am I missing here?

I have following setup:

Class DataFetcher {
  public:
    virtual ~DataFetcher() = default;
    explicit DataFetcher(const Backends& backends);

    virtual vector<Data> GetData(const vector<string>& q) const;

  private:
    Backends backends_;
};

Implementation:

vector<Data> DataFetcher::GetData(const vector<string>& q) {
  cout << "Yikes! This was called";
  ...
}

Then a piece of function in another place which uses it as:

void Process(const Backends& backends) {
  DataFetcher data_fetcher(backends);
  ...
  const auto& data = data_fetcher.GetData(q);
  ...
}

Now I am trying to test Process with any call to GetData being mocked, as following:

class MockDataFetcher : public DataFetcher {
  public:
    using DataFetcher::DataFetcher;
    MOCK_METHOD(vector<Data>, GetData, (const vector<string>& q), (const, override));
}

class ActualLogicTest : public ... {
  protected:
    Backends backends_;
}

TEST_F(ActualLogicTest, BasicOne) {
  MockDataFetcher mock_data_fetcher(backends_);
  vector<Data> data;
  ON_CALL(mock_data_fetcher, GetData).WillByDefault(Return(data));
  ...
  Process(backends_);
}

What is wrong in this? I am seeing that actual implementation of GetData is getting called and I am seeing that message Yikes! This was called too. Since GetData is a virtual function, it should get the empty vector of Data back as result from the mocked one. Why is that not happening?

Finally the test crashes because backend doesn't have initialization of its members.

jeudi 2 février 2023

How to iterate over a template-less variadic in C++

I was under the impression that I don't need a template in order to use variadics in C++. So in the following class, I have a method that accepts a variadic as its second variable. Now my question is: how do I iterate over the variadic?

class CoolClass{
    /** Other stuff go here */
    
    // my question is about this
    void variadic(X d, X others...){
        cout<<"Main is "<<d.value()<<endl;
        cout<<"Others are: "<<endl;
        for(const auto& o: { others... }){ // doesn't have to be const
            cout<<o.value()<<endl;
        }
    }
};

I tried running the code above and it doesn't work. I changed from { others...} to simply others`, but that doesn't work either.

mercredi 1 février 2023

I was doing a code for , "Count Digits " , Evenly divides means whether N is divisible by a digit i.e. leaves a remainder 0 when divided

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

int main() {


int n,m,z;
   cout<<"enter n: ";
   cin>>n;
     z=n;

    int count=0;
while(n>0){
    m = n % 10;
    if(z%m == 0){
        count++;
    }
    n=n/10;
}
cout<<count;

}

Code should work like that ex - for n = 12, it is divisible by both 1 , 2 so, the output will be 2 if i am taking any value which have '0' in their last then it is not working ..and i am getting an error "Floating-point exception (SIGFPE)". Could anyone help me to get rid out of this.

Are Reference iterators faster than Normal iterators in C++? [closed]

Recently I was solving a question on leetcode using for-each loop (or range-based for loop). Initially, I have used a normal iterator as follows:

for(Node* node: tree){
    vec.push_back(node->val);
}

But then I changed the reference iterator as follows:

for(Node* &node: tree){
    vec.push_back(node->val);
}

Doing so there was a significant change in the runtime of the program. I am curious whether reference iterators are faster and/or space efficient than normal iterators or if they are similar.

EDIT:
As my question was closed I want to add more clarity. I was solving a question of level-order traversal of N-ary tree. Since level order traversal of a question requires breadth-first-search, I was using a queue to solve this problem. In my code there is a for loop that stores the children of a node in a temporary vector which is as follows:

for(Node* &node: curr->children){
   temp.push_back(node->val);
   q.push(node);
}

This is where I have used a range-based for loop (to iterate through children of a node).
However, I have a general query about whether or not there is any difference in terms of runtime and space between both of these iterators (normal and referenced one).

Generate C++ string with space behind such that space is automatically adjusted

I am trying to create a text generator which shall generate following output:

localparam  OR_CHANNEL_DATA_WIDTH               = 2;
localparam  RQ_CHANNEL_DATA_WIDTH               = 18;
localparam  RSP_CHANNEL_DATA_WIDTH              = 8;
localparam  VIN_CHANNEL_DATA_WIDTH              = 43;
localparam  VOUT_CHANNEL_DATA_WIDTH             = 123;

I used std::stringstream to build the stream:

std::stringstream ss;
ss << "localparam OR_CHANNEL_DATA_WIDTH" std::right << std::setw(80) << " = " << Sth::get() << ";\n";
ss << "localparam RQ_CHANNEL_DATA_WIDTH" std::right << std::setw(80) << " = " << Sth::get() << ";\n";
ss << "localparam RSP_CHANNEL_DATA_WIDTH" std::right << std::setw(80) << " = " << Sth::get() << ";\n";

Sth::get() will return number. There are many such lines that needs to be generated. But the text in the middle is not fixed. How can I achieve the above output