lundi 31 janvier 2022

Making an array equal by decreasing elements adjacent to each other

I was doing this exercise in my computer science class for a warm up earlier, which was to find the minimum number of moves to make all the elements in an array equal to each other, where the only operation is to subtract one from an element in an array.

This made me curious about extensions to the problem; for example I immediately thought of an extension, how many moves will it take to make all the elements in an array equal to each other, where the only operation is to subtract one from two elements that are adjacent to each other.

For example: Given array [4, 6, 4], we can decrease elements in index 0 and 1 to get [3, 5, 4], then [3, 4, 3], then [2, 3, 3], and then decrease elements in index 1 and 2 to get [2, 2, 2]. This would take 4 moves. However, how would we extend this kind of thinking to larger arrays, where we cannot trace this out by hand like I just did above?

Cheers

Why am I getting an undefined reference to both of my functions? Ex: undefined reference to medSelectiveSort(int*, int*)

The purpose of my program is to:

  1. Collect the size that the user would like the array to be.
  2. Collect the user's integer input for each element.
  3. Use pointers to refer to the array and the array size (required as a pointer assignment).
  4. Call a function to use a selective sort to sort the array in ascending order (using pointers as parameters) while also displaying the result after each sorting iteration
  5. Call another function to find the median of the sorted array (using pointers as parameters) and to display the median.

However, despite using what I thought was the correct syntax for pointers, I keep getting undefined reference errors for both of my functions, resulting in "ID returned 1 exit status".

#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <math.h>
using namespace std;

void medSelectiveSort(int*, int*);
int medDetermination(int*, int*);

int main()
{
    int arraySize;
    int *arraySizePtr = &arraySize;
    int median;
    
    
    cout << "How large would you like the array to be?" << endl;
    cin >>  arraySize;
    
    if (arraySize <= 10)
        cout << "Processing..." << endl;
    else if (arraySize > 10)
    {
        cout << "That is too large. It will be reduced to 10." << endl;
        arraySize = 10;
    }
    
    int arrayMedian[arraySize];
    int *arrayMedianPtr = arrayMedian;
    
    int inverseLoopCounter = 0;
    for (arraySize; arraySize > 0; arraySize--)
    {
        cout << "Please enter element number " << inverseLoopCounter << "." << endl;
        cin >> arrayMedian[inverseLoopCounter];
        inverseLoopCounter++;
    }
    
    medSelectiveSort(arraySizePtr, arrayMedianPtr);
    
    median = medDetermination(arraySizePtr, arrayMedianPtr);
    
    cout << "The median is " << median << "." << endl;
    
    return 0;
}

void medSelectiveSort(int arraySizePtr, int arrayMedianPtr[])
{
    int startScan, minIndex, minValue;
    int arraySizePtrPlaceHolder = arraySizePtr;

    for (startScan = 0; startScan < (arraySizePtrPlaceHolder - 1); startScan++)
    {

        minIndex = startScan;
        minValue = arrayMedianPtr[startScan];

        for(int index = startScan + 1; index < arraySizePtrPlaceHolder; index++)
        {
            if (arrayMedianPtr[index] < minValue)
            {   

                minValue = arrayMedianPtr[index];
                minIndex = index;

            }

        }
        
        
        arrayMedianPtr[minIndex] = arrayMedianPtr[startScan];

        arrayMedianPtr[startScan] = minValue;
        cout << "" << endl;
        cout << "Sorting..." << endl;
        for(int i = 0; i < arraySizePtrPlaceHolder; i++) 
        {
            cout << arrayMedianPtr[i] << " ";
        }
        cout << endl;

    }
    cout << "" << endl;
    cout << "This array of integers has been sorted in ascending order using the selection sort." << endl;
    cout << "" << endl;

}

int medDetermination(int arraySizePtr, int arrayMedianPtr[])
{
    int finalMedian;
    
    int arraySizePtrPlaceHolder = arraySizePtr;
    
    int medCalculator1;
    int medCalculator2;
    int medCalculator3;
    
    
    if (arraySizePtrPlaceHolder % 2 == 0)
    {
        medCalculator1 = arraySizePtrPlaceHolder / 2;
        medCalculator2 = medCalculator1 + 1;
        finalMedian = arrayMedianPtr[medCalculator1] + arrayMedianPtr[medCalculator2] / 2;
    }
    else 
    {
        medCalculator1 = arraySizePtrPlaceHolder % 2;
        medCalculator2 = arraySizePtrPlaceHolder + medCalculator1;
        medCalculator3 = medCalculator2 / 2;
        finalMedian = arrayMedianPtr[medCalculator3];
    }
    
    return finalMedian;
}

How to store each user input into array?

I used a do while loop to ask user to enter integer as long as its not 0 or it will exit the program. I'm stuck on how to store every user input into the dynamically allocated array.

#include <iostream>
using namespace std;


int main() {
  int *A;
  A= new int();
  int n;
  do{
    cout<<"Enter integer: "<<endl;
    cin>>n;
    cout<< *A + n << endl;

    
  }while(n!=0);

  return 0;
}

Vector of mutex to synchronize access to vector cells

I wrote code to do some parallel operations on a vector, my goal is to protect a single cell of a vector so other cells can be accessed in parallel, so I tried to use a vector of mutex of the same size of the other vector

vector<int> myIntVec(n,0);
vector<mutex> mtxVec(n);

then the critical section, each thread executes this (goal is to mark seen cells)

 for (i of something)
        {
           mtxVec[i].lock();
           if (myIntVec == 0 ){ 
                myIntVec[i]++;
                mtxVec[i].unlock();
               }
            else
              mtxVec[i].unlock();
         }

no other operations on these 2 vectors. but doing some tests, what i got is that myIntVec cells contain numbers greater than 1, when they should contain at least 1. What am I missing?

pybind11 - Return a shared_ptr of std::vector

I have a member variable that stores a std::shared_ptr of std::vector<uint32_t>. I want to create a Python binding for test_func2() so that I can access that vector without any additional copy. Here is a skeleton code.

#include <vector>
#include <memory>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/numpy.h>

namespace py = pybind11;



class TestLoader
{
private:
    std::shared_ptr<std::vector<uint32_t>>  tileData;

public:
    TestLoader();
    ~TestLoader();
    void test_func1();
    std::shared_ptr<std::vector<uint32_t>> test_func2()  const;
};

void  TestLoader::test_func1() {
    tileData = std::make_shared<std::vector<uint32_t>>(100000000);
    for(auto &x: *tileData){ x = 1;}
}
std::shared_ptr<std::vector<uint32_t>>  TestLoader::test_func2() const{

    return tileData;
}

The interface code is like the following:

#include <pybind11/pybind11.h>
#include <pybind11/stl.h>

namespace py = pybind11;
PYBIND11_MODULE(fltest_lib, m) {
    py::class_<TestLoader,  std::shared_ptr<TestLoader>>(m, "TestLoader")
    .def(py::init<const std::string &>())
    .def("test_func1", &TestLoader::test_func1)
    .def("test_func2", &TestLoader::test_func2, py::return_value_policy::reference_internal);
}

However, this does not compile and I get a long error message. One particular line is the following:

/home/samee/fl_test/lib/pybind11/include/pybind11/cast.h:653:61: error: static assertion failed: Holder classes are only supported for custom types
  653 |     static_assert(std::is_base_of<base, type_caster<type>>::value,
      |                                                             ^~~~~

Any help to circumvent this will be really helpful.

make std::ostream automatically ident when encountering special characters

I would like to have some facility which makes a std::ostream automatically ident on encountering special characters (or special objects). Let's assume that the special characters are < and >. In this case the following input test0<test1<test2> > should produce the following output:

test0<
    test1<
        test2
    >
>

How would one go to implement this?

vector variable scope in C++ [duplicate]

I am writing a program in C++ that is reading some files with fstream then writes with a simple function and after that closes them.

I created a struct and I keep here filetag, filepointer and lines. The problem is that from main I can't write or close the file ... but I can access filetag and lines variables. Here is my code:

struct Fileoutput
{
    string filetag;
    std::fstream* filepointer;
    int lines = 0;
};

static std::vector<Fileoutput> vect_fileoutputs;

static void open_files()
{
    // open all
    struct Fileoutput fo_all;
    fo_all.filetag = "all";
    fo_all.lines = 0;
    std::fstream fs_all;
    fs_all.open("all.log",std::fstream::out | std::fstream::app);
    fo_all.filepointer = &fs_all;
    //*fo_all.filepointer << "something from struct" << endl; // here it is working, in other scope ... no
    vect_fileoutputs.push_back(fo_all);
    /*
    for(const struct Fileoutput fo : vect_fileoutputs)
    {
        *fo.filepointer << "something from vect" << endl; // here is working
    }
    */

    // open error
    struct Fileoutput fo_error;
    fo_error.filetag = "error";
    fo_error.lines = 0;
    std::fstream fs_error;
    fs_error.open("error.log",std::fstream::out | std::fstream::app);
    fo_error.filepointer = &fs_error;
    vect_fileoutputs.push_back(fo_error);
}

static bool write_to_outputfile(char* outputfile,char* content)
{
bool write = false;
for(const struct Fileoutput fo : vect_fileoutputs)
{
    if(strcmp(fo.filetag.c_str(),outputfile) == 0)
    {
        printf("Writing [%s] to [%s]\n",content,outputfile);
        std::fstream* fs_write;
        fs_write = fo.filepointer;
        *fo.filepointer << content; // NOT WORKING ... seg fault
        write = true;
        break;
    }
}

return write;
}

static void close_files()
{
    for(const struct Fileoutput file_output: vect_fileoutputs)
    {
        printf("Closing file [%s]\n",file_output.filetag.c_str());
        std::fstream* fs_temp;
        fs_temp = file_output.filepointer;
        fs_temp->close(); // NOT WORKING ... seg fault
        printf("Closed [%s]\n",file_output.filetag.c_str());
    }
}

int main(int argc, char* argv[])
{
    open_files();

    write_to_outputfile((char*)"all",(char*)"something1\n");
    write_to_outputfile((char*)"all",(char*)"something2\n");
    write_to_outputfile((char*)"all",(char*)"something3\n");

    write_to_outputfile((char*)"error",(char*)"error\n");
    close_files();

    return 1;
}

The gdb error looks like :

gdb error :

Program received signal SIGSEGV, Segmentation fault.
0x0000000000405de9 in ?? ()
(gdb) x 0x0000000000405de9
0x405de9:   0xe8420348
(gdb) x 0x405de9
0x405de9:   0xe8420348
(gdb) x 0xe8420348
0xe8420348: Cannot access memory at address 0xe8420348
(gdb)

What is wrong with the code?

Gtest on new keyword

new keyword in C++ will throw an exception if insufficient memory but below code trying to return "NO_MEMORY" when new failed. This is bad because it will raise std::bad_alloc exception .

I am writing a unit test(gtest). How to create a scenario to catch this problem.

class base{


    public: base(){
        std::cout<<"base\n";
    }
};
 

std::string getInstance(base** obj){

    base *bObject = new base();
    *obj = bObject; //updated
     return (NULL == bObject) ? "NO_MEMORY" : "SUCCESS"; // here is problem if new fail it raise an exception. How to write unit test to catch this?
}

int main()
{
 
 base *base_obj;
 getInstance(&base_obj);
}
 

Can someone please explain this output?

cout<<"ccccc"+2;

Output:- ccc

I tried searching for it online and I know it is a very dumb question but couldn't find anything anywhere. Please if someone could help me out.

dimanche 30 janvier 2022

With C++ openCV, split video frames into blocks, join back together & output new video

As a very simple test (prior to ultimately performing various transformations on the blocks), I'm trying to split up frames of a video file - initially just into 4 blocks, then stitch back together, before outputting to a new file.

I've written the following code (running on Google Colab). However, it keeps failing, due to errors posted below the code.

I'm new to C++ and OpenCV, so likely a clear & obvious mistake. But, I've been scratching my head over this for hours, with no luck. Any pointers appreciated (pardon the pun).

%%writefile test.cpp

#include<opencv2/opencv.hpp>
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/videoio.hpp"
#include <vector>

using namespace std;
using namespace cv;

int main(){

VideoCapture cap;
cap.open("/content/drive/MyDrive/test.mp4");
  int frame_width = static_cast<int>(cap.get(CAP_PROP_FRAME_WIDTH));
  int frame_height = static_cast<int>(cap.get(CAP_PROP_FRAME_HEIGHT));
  Size frame_size(frame_width, frame_height);
  Size sb_size(frame_width/2,frame_height/2);
  int blocks_wide = 2;
  int blocks_high = 2;
  int fps = 20;
  VideoWriter output("/content/drive/MyDrive/output.avi", VideoWriter::fourcc('M', 'J', 'P', 'G'),fps, frame_size);
  Mat frame;
  vector<Mat> small_blocks;
  
for(;;) {
        cap >> frame;
        if (frame.empty()) break;
        for (int y = 0; y < blocks_high; y++) {
          for (int x = 0; x < blocks_wide; x++) {
            small_blocks.push_back(Mat(frame, Rect(x,y,sb_size.width,sb_size.height)).clone());   
      }
    }

  Mat combined(frame_width, frame_height, small_blocks[0].type());
  for(int i = 0; i < small_blocks.size(); i++) {
    for  (int y = 0; y < frame_height; y += sb_size.height)
      {
        for  (int  x = 0; x < frame_width; x += sb_size.width)
        {
          Mat roi = combined(Rect(x,y,sb_size.width,sb_size.height));
          small_blocks[i].copyTo(roi);
        }
      }
  }
    output.write(combined);
}
  cap.release();
    return 0;
}

Here is an example of the errors I've been getting:

    OpenCV Error: Assertion failed (0 <= roi.x && 0 <= roi.width && roi.x + roi.width <= m.cols && 0 <= roi.y && 0 <= roi.height && roi.y + roi.height <= m.rows) in Mat, file /build/opencv-L2vuMj/opencv-3.2.0+dfsg/modules/core/src/matrix.cpp, line 522
terminate called after throwing an instance of 'cv::Exception'
  what():  /build/opencv-L2vuMj/opencv-3.2.0+dfsg/modules/core/src/matrix.cpp:522: error: (-215) 0 <= roi.x && 0 <= roi.width && roi.x + roi.width <= m.cols && 0 <= roi.y && 0 <= roi.height && roi.y + roi.height <= m.rows in function Mat

the return type of lower_bound and upper_bound if key value not found

I have a confusion about the returned value from the lower_bound and upp_bound member function from C++ STL containers. According to chapter 11.3.5 of "C++ Primer 5th Edition":

"if the element is not in the multimap, then lower_bound and upper_bound will rerturn equal iterators; both will refer to the point at which the key can be inserted without disrupting the order...If the element we're looking for has the largest key in the container, then upper_bound on that key returns the off-the-end iterator."

So if we have a multimap<int, int> with keys {1, 2, 3}, and we want to look for the element with key value 4, then the returned value of both lower_bound and upper_bound are iterators pointing to the position after 3, because 4 is larger than any existing key values in the multimap.

For the same reason, if we're looking for the element with the key value 0, then both the first element with the key value 1, because we can insert this element there in front of the one with the key value 1 "without disrupting the book" according to the book.

However, I found another file about the lower_bound:https://en.cppreference.com/w/cpp/algorithm/lower_bound, in which the returned value of it will point to the "last if no such element is found", same as for the upper_bound. From here, it seems like that no matter what the key value is, the returned iterator will always point to the last (off-the-end) in the container.

So my problem is, which one is correct, or did I make it wrong somewhere?

Call function pointers and member functions

I want to create a class which can take both normal function pointers but also member functions. Adding ot that it should take any return type and any type and amount of parameters. I've successfully created what i want by using std::async like this:

    template<class... _Args>
    std::result_of_t<_Fn&&(_Args&&...)> operator()(_Args&&... _Ax) {
        mutex.lock();

        //some extra stuff here

        auto task = std::async(std::launch::deferred, _function_data, std::forward<_Args>(_Ax)...);
        task.wait();

        //some more extra stuff here

        mutex.unlock();
        return task.get();
    }

usage:

    Wrapper<decltype(&TestFunction)> function(&TestFunction); //int TestFunction(int test_parameter)
    Wrapper<decltype(&MyClass::Test)> class_function(&MyClass::Test); //void MyClass::Test()
    class_function(&myClass);
    int test = function(10);

However this solution is obviously not optimal. How would i go about calling any type of function without having to use std::async?

Can I Create a class inside a function in C++ ? Is the same possible with a structure? [duplicate]

    int main(){
    class first
    {
    int hi;
    };
    return 0; }

Is this class inside a function possible ?

does two recursive calls work simultaneously or one after the other?

so I was testing the recursive function , that is , will the function at first recursion , let the recursion complete and then proceed or will it simply initialize the recursion and proceed on , that is will both the recursive calls print numbers simultaneously or first it will print num to 1 and then it will print num to 100 ; anyway , my compiler is just outputing 32 infinitely when i give num as 23 ;

void print(int num){
   if(num == 1 || num == 100){
        return;
    }
    std::cout << num ;
    print(num-1);
    std::cout << std::endl;
    print(num+1);

    return;
}

samedi 29 janvier 2022

Unable to display multiple progress bars (from my class) on the terminal using threads, why?

I am trying to implement a feature to print multiple progress bars on the screen using threads. I have a ProgressBar class which produces progress bars (in case you need more info about it you can look here, the mutex locks have been removed from that), you need to know the definition of its update method (again, more info about the meanings of all the variables are in the link above):

  template <typename bar_type>
  void ProgressBar <bar_type>::update_output( bar_type iterating_var, std::string output )
   {
    std::cout << check_condition( [ = ]{ return iterating_var == min_; }, feat( tcs, "hcrs" ), null_str )
              << output
              << getColor()
              << empty_space + message_
              << reset( "color" )
              << std::flush
              << check_condition( [ = ]{ return iterating_var == max_ - 1; }, feat( tcs, "scrs" ), null_str );
   }
 
  template <typename bar_type>
  void ProgressBar <bar_type>::update( bar_type iterating_var )
   {
    iterating_var_ = 100 * ( iterating_var - min_ ) / ( max_ - min_ - one( iterating_var ) );
    width_ = ( iterating_var_ + 1 ) / 4;

    if( styles_map_.at( "indicator" ).find( style_ ) != styles_map_.at( "indicator" ).end() )
     {
      output_ = feat( crs, "left", 100 ) + 
                getColor() +
                std::to_string( static_cast <int> ( round( iterating_var_ ++ ) ) ) +
                reset( "color" ) + 
                getStyle();

      update_output( iterating_var, output_ );
     }

    else if( styles_map_.at( "loader" ).find( style_ ) != styles_map_.at( "loader" ).end() )
     {
      output_ = feat( crs, "left", 100 ) + 
                getBrackets_open() + 
                getColor() + 
                getStyle() * width_ + 
                empty_space * ( 25 - width_ ) + 
                reset( "color" ) + 
                getBrackets_close();  
                     
      update_output( iterating_var, output_ );
     }

    else if ( style_.find( style_p_ ) != std::string::npos && style_.find( style_l_ ) != std::string::npos &&
              type_ == "complete"  )
     {
      output_= feat( crs, "left", 100 ) + 
               getBrackets_open() + 
               getColor() + 
               style_l_ * width_ + 
               empty_space * ( 25 - width_ ) + 
               reset( "color" ) +
               getBrackets_close() + 
               getColor() + 
               empty_space + 
               std::to_string( iterating_var_ ++ ) + 
               reset( "color" ) + 
               style_p_; 

      update_output( iterating_var, output_ );
     }
     
    else
     {
      throw std::runtime_error( "ProgressBar style has not been set!" );
     }
   }

The function feat( crs, "left", 100 ) is used to move cursor left and so on. This ProgressBar is used in main in this way for example:

  ProgressBar <int> percentage_bar;
  percentage_bar.setMin( 5 );
  percentage_bar.setMax ( 46 );
  percentage_bar.setStyle( "indicator", "%" );

  cout << "This is a normal percentage bar: " << endl;
  for ( int i = percentage_bar.getMin(); i < percentage_bar.getMax(); i++ )
   {
    sleep_for( milliseconds( 100 ) );
    percentage_bar.update( i );
    //Do some operations...
   }
  cout << endl << endl;

Then, I am creating a new MultiProgressBar class to manage multiple progress bars with threads and display them at the same time in the terminal.

#ifndef MULTIPROGRESSBAR_H
#define MULTIPROGRESSBAR_h

#include <iostream>
#include <type_traits>
#include <tuple>
#include <functional>
#include <mutex>
#include <atomic>
#include <utility>
//#include <progress_bar.h>

namespace osm
 {
  //====================================================
  //     TYPE TO GENERATE INDICES FOR PARAMETER PACKS
  //====================================================
  template <size_t... Is>
  struct indices {};
  
  template <size_t N, size_t... Is>
  struct gen_indices: gen_indices <N - 1, N - 1, Is...> {};
  
  template <size_t... Is>
  struct gen_indices <0, Is...>: indices<Is...> {};
  
  //====================================================
  //     MAKE_MULTIPROGRESSBAR TEMPLATE CLASS
  //====================================================
  template <class... Indicators>
  class make_MultiProgressBar 
   {
    public:
  
     //====================================================
     //     CONSTRUCTORS
     //====================================================
     template <class... Inds>
     make_MultiProgressBar( Inds&&... bars ): bars_{ std::forward <Inds> ( bars )... } {}
  
     //====================================================
     //     OTHER PUBLIC METHODS
     //====================================================
     static size_t size() { return sizeof...( Indicators ); }
  
     template <class Func, class... Args>
     void for_one( size_t idx, Func&& func, Args&&... args )
      {
       //std::lock_guard<std::mutex> lock{mutex_};
       call_one( idx, gen_indices <sizeof...( Indicators )> (), std::forward <Func> ( func ), std::forward <Args> ( args )... );
      }
  
     template <class Func, class... Args>
     void for_each( Func&& func, Args&&... args ) 
      {
       //std::lock_guard<std::mutex> lock{mutex_};
       call_all( gen_indices <sizeof...( Indicators )> (), std::forward <Func> ( func ), std::forward <Args> ( args )... );
      }
  
    private:
  
     //====================================================
     //     OTHER PRIVATE METHODS
     //====================================================
     template <size_t... Ids, class Func, class... Args>
     void call_one( size_t idx, indices <Ids...>, Func func, Args&&... args )
      {
       std::lock_guard<std::mutex> lock{mutex_};
       [](...) {} 
        (
         (idx == Ids &&
          ( ( void ) std::forward <Func> ( func )( std::get <Ids> ( bars_ ), 
              std::forward <Args> ( args )... ), false ) )...
        );   
      }
  
     template <size_t... Ids, class Func, class... Args>
     void call_all( indices <Ids...>, Func func, Args&&... args )
      {
       //std::lock_guard<std::mutex> lock{mutex_};
       auto dummy = { ( func( std::get <Ids>( bars_ ), args...), 0 )... };
       ( void )dummy;
      } 
  
     //====================================================
     //     PRIVATE ATTRIBUTES
     //====================================================
     std::tuple <Indicators&...> bars_;
     std::mutex mutex_;
     std::atomic <bool> started_{ false };
   };
  
  //====================================================
  //     HELPER FUNCTION FOR DEDUCTION GUIDES
  //====================================================
  template <class... Indicators>
  make_MultiProgressBar <typename std::remove_reference <Indicators>::type...>
  MultiProgressBar( Indicators&&... inds ) 
   {
    return { std::forward <Indicators> ( inds )... };
   }
  
  //====================================================
  //     FUNCTOR
  //====================================================
  template <class T> 
  struct type_identity 
   {
    using type = T;
   };
  
  struct updater 
   { 
    template <template <class> class PB, class bar_type>
    auto operator()( PB <bar_type>& pb, typename type_identity <bar_type>::type v ) const
        -> decltype( pb.update( bar_type{} ) ) 
     {
      return pb.update( v );
     }
   };
 }

#endif

and in a main should work as:

#include <iostream>
#include <thread>
#include <chrono>
#include <cmath>
#include <iomanip>
#include "../include/osmanip.h"

using namespace osm;
using namespace std;
using namespace std::this_thread;
using namespace std::chrono;
  ProgressBar<int> prog_int;
  prog_int.setMin( 0 );
  prog_int.setMax ( 100 );
  prog_int.setStyle( "complete", "%", "#" );
  prog_int.setBrackets( "[", "]" );

  ProgressBar<int> prog_int_2;
  prog_int_2.setMin( 5 );
  prog_int_2.setMax ( 25 );
  prog_int_2.setStyle( "complete", "%", "#" );
  prog_int_2.setBrackets( "[", "]" );

  ProgressBar<float> prog_float;
  prog_float.setMin( 0.1f );
  prog_float.setMax ( 12.1f );
  prog_float.setStyle( "complete", "%", "#" );
  prog_float.setBrackets( "[", "]" );

  auto bars = MultiProgressBar( prog_int, prog_int_2, prog_float );

  // Job for the first bar
  auto job1 = [&bars]() {
    for (int i = 0; i <= 100; i++) {
      bars.for_one(0, updater{}, i);
      sleep_for( milliseconds( 100 ) );
    }
    cout << endl;
  };

  // Job for the second bar
  auto job2 = [&bars]() {
    for (int i = 5; i <= 25; i++) {
      bars.for_one(1, updater{}, i);
      sleep_for(std::chrono::milliseconds(200));
    }
    cout << endl;
  };

  // Job for the third bar
  auto job3 = [&bars]() {
    for (float i = 0.1f; i <= 12.1f; i += 0.1f) {
      bars.for_one(2, updater{}, i);
      sleep_for(std::chrono::milliseconds(60));
    }
    cout << endl;
  };

  thread first_job(job1);
  thread second_job(job2);
  thread third_job(job3);

  first_job.join();
  second_job.join();
  third_job.join();

The problem is that when I run the code, progress bars are printed overlapped, like this:

0 [00:53] gianluca@ubuntu:~/osmanip (main)$ ./bin/main.exe 
[##                      ] 9.166668%

Instead I want something like:

0 [00:53] gianluca@ubuntu:~/osmanip (main)$ ./bin/main.exe 
[############            ] 45%
[#########               ] 39%
[##################      ] 72%

Do you know how to solve this?

Problem displaying more of my progress bar class indicators simultaneously using threads, why?

I am trying to implement a feature to print multiple progress bars on the screen using threads. I have a ProgressBar class which produces progress bars (in case you need more info about it you can look here), you need to know the definition of its update method (again, more info about the meanings of all the variables are in the link above):

  template <typename bar_type>
  void ProgressBar <bar_type>::update_output( bar_type iterating_var, std::string output )
   {
    std::unique_lock <std::mutex> lock{mutex_};
    std::cout << check_condition( [ = ]{ return iterating_var == min_; }, feat( tcs, "hcrs" ), null_str )
              << output
              << getColor()
              << empty_space + message_
              << reset( "color" )
              << std::flush
              << check_condition( [ = ]{ return iterating_var == max_ - 1; }, feat( tcs, "scrs" ), null_str );
   }
 
  template <typename bar_type>
  void ProgressBar <bar_type>::update( bar_type iterating_var )
   {
    std::unique_lock <std::mutex> lock{mutex_};
    iterating_var_ = 100 * ( iterating_var - min_ ) / ( max_ - min_ - one( iterating_var ) );
    width_ = ( iterating_var_ + 1 ) / 4;

    if( styles_map_.at( "indicator" ).find( style_ ) != styles_map_.at( "indicator" ).end() )
     {
      output_ = feat( crs, "left", 100 ) + 
                getColor() +
                std::to_string( static_cast <int> ( round( iterating_var_ ++ ) ) ) +
                reset( "color" ) + 
                getStyle();

      update_output( iterating_var, output_ );
     }

    else if( styles_map_.at( "loader" ).find( style_ ) != styles_map_.at( "loader" ).end() )
     {
      output_ = feat( crs, "left", 100 ) + 
                getBrackets_open() + 
                getColor() + 
                getStyle() * width_ + 
                empty_space * ( 25 - width_ ) + 
                reset( "color" ) + 
                getBrackets_close();  
                     
      update_output( iterating_var, output_ );
     }

    else if ( style_.find( style_p_ ) != std::string::npos && style_.find( style_l_ ) != std::string::npos &&
              type_ == "complete"  )
     {
      output_= feat( crs, "left", 100 ) + 
               getBrackets_open() + 
               getColor() + 
               style_l_ * width_ + 
               empty_space * ( 25 - width_ ) + 
               reset( "color" ) +
               getBrackets_close() + 
               getColor() + 
               empty_space + 
               std::to_string( iterating_var_ ++ ) + 
               reset( "color" ) + 
               style_p_; 

      update_output( iterating_var, output_ );
     }
     
    else
     {
      throw std::runtime_error( "ProgressBar style has not been set!" );
     }
   }

The function feat( crs, "left", 100 ) is used to move cursor left and so on. This ProgressBar is used in main in this way for example:

  ProgressBar <int> percentage_bar;
  percentage_bar.setMin( 5 );
  percentage_bar.setMax ( 46 );
  percentage_bar.setStyle( "indicator", "%" );

  cout << "This is a normal percentage bar: " << endl;
  for ( int i = percentage_bar.getMin(); i < percentage_bar.getMax(); i++ )
   {
    sleep_for( milliseconds( 100 ) );
    percentage_bar.update( i );
    //Do some operations...
   }
  cout << endl << endl;

Then, I am creating a new MultiProgressBar class to manage multiple progress bars with threads and display them at the same time in the terminal.

#ifndef MULTIPROGRESSBAR_H
#define MULTIPROGRESSBAR_h

#include <iostream>
#include <type_traits>
#include <tuple>
#include <functional>
#include <mutex>
#include <atomic>
#include <utility>

namespace osm
 {
  template <size_t... Is>
  struct indices {};
  
  template <size_t N, size_t... Is>
  struct gen_indices: gen_indices <N - 1, N - 1, Is...> {};
  
  template <size_t... Is>
  struct gen_indices <0, Is...>: indices<Is...> {};
  
  template <class... Indicators>
  class make_MultiProgressBar 
   {
    public:
  
     template <class... Inds>
     make_MultiProgressBar( Inds&&... bars ): bars_{ std::forward <Inds> ( bars )... } {}
  
     static size_t size() { return sizeof...( Indicators ); }
  
     template <class Func, class... Args>
     void for_one( size_t idx, Func&& func, Args&&... args )
      {
       std::lock_guard<std::mutex> lock{mutex_};
       call_one( idx, gen_indices <sizeof...( Indicators )> (), std::forward <Func> ( func ), std::forward <Args> ( args )... );
      }
  
     template <class Func, class... Args>
     void for_each( Func&& func, Args&&... args ) 
      {
       std::lock_guard<std::mutex> lock{mutex_};
       call_all( gen_indices <sizeof...( Indicators )> (), std::forward <Func> ( func ), std::forward <Args> ( args )... );
      }
  
    private:
  
     template <size_t... Ids, class Func, class... Args>
     void call_one( size_t idx, indices <Ids...>, Func func, Args&&... args )
      {
       std::lock_guard<std::mutex> lock{mutex_};
       [](...) {} 
        (
         (idx == Ids &&
          ( ( void ) std::forward <Func> ( func )( std::get <Ids> ( bars_ ), 
              std::forward <Args> ( args )... ), false ) )...
        );   
      }
  
     template <size_t... Ids, class Func, class... Args>
     void call_all( indices <Ids...>, Func func, Args&&... args )
      {
       std::lock_guard<std::mutex> lock{mutex_};
       auto dummy = { ( func( std::get <Ids>( bars_ ), args...), 0 )... };
       ( void )dummy;
      } 
  
     std::tuple <Indicators&...> bars_;
     std::mutex mutex_;
     std::atomic <bool> started_{ false };
   };
  
  template <class... Indicators>
  make_MultiProgressBar <typename std::remove_reference <Indicators>::type...>
  MultiProgressBar( Indicators&&... inds ) 
   {
    return { std::forward <Indicators> ( inds )... };
   }
  
  template <class T> 
  struct type_identity 
   {
    using type = T;
   };
  
  struct updater 
   { 
    template <template <class> class PB, class bar_type>
    auto operator()( PB <bar_type>& pb, typename type_identity <bar_type>::type v ) const
        -> decltype( pb.update( bar_type{} ) ) 
     {
      return pb.update( v );
     }
   };
 }

#endif

and in a main should work as:

#include <iostream>
#include <thread>
#include <chrono>
#include <cmath>
#include <iomanip>
#include "../include/osmanip.h"

using namespace osm;
using namespace std;
using namespace std::this_thread;
using namespace std::chrono;
  ProgressBar<int> prog_int;
  prog_int.setMin( 0 );
  prog_int.setMax ( 100 );
  prog_int.setStyle( "complete", "%", "#" );
  prog_int.setBrackets( "[", "]" );

  ProgressBar<int> prog_int_2;
  prog_int_2.setMin( 5 );
  prog_int_2.setMax ( 25 );
  prog_int_2.setStyle( "complete", "%", "#" );
  prog_int_2.setBrackets( "[", "]" );

  ProgressBar<float> prog_float;
  prog_float.setMin( 0.1f );
  prog_float.setMax ( 12.1f );
  prog_float.setStyle( "complete", "%", "#" );
  prog_float.setBrackets( "[", "]" );

  auto bars = MultiProgressBar( prog_int, prog_int_2, prog_float );

  // Job for the first bar
  auto job1 = [&bars]() {
    for (int i = 0; i <= 100; i++) {
      bars.for_one(0, updater{}, i);
      sleep_for( milliseconds( 100 ) );
    }
    cout << endl;
  };

  // Job for the second bar
  auto job2 = [&bars]() {
    for (int i = 5; i <= 25; i++) {
      bars.for_one(1, updater{}, i);
      sleep_for(std::chrono::milliseconds(200));
    }
    cout << endl;
  };

  // Job for the third bar
  auto job3 = [&bars]() {
    for (float i = 0.1f; i <= 12.1f; i += 0.1f) {
      bars.for_one(2, updater{}, i);
      sleep_for(std::chrono::milliseconds(60));
    }
    cout << endl;
  };

  thread first_job(job1);
  thread second_job(job2);
  thread third_job(job3);

  first_job.join();
  second_job.join();
  third_job.join();

The problem is that when I compile with -pthread option (I am using c++17) all is fine, but when I run the code anything is displayed and the prompt continue waiting, like this:

130 [23:03] gianluca@ubuntu:~/osmanip (main)$ ./bin/main.exe 

doing anything. The makefile I use for compilation is:

TARGET_EXEC := main.exe
TEST_EXEC := tests.exe
LIB := libosmanip.a
CC := g++

BUILD_DIR := bin
SRC_DIR := src
OBJ_DIR := obj
TEST_DIR := test
LIB_DIR := lib

SRC := $(shell find $(SRC_DIR) -name '*.cpp')
SRC_LIB := $(shell find $(SRC_DIR) -type f | grep -v 'main.cpp')
TEST := $(shell find $(SRC_DIR) -type f | grep -v 'main.cpp') $(shell find $(TEST_DIR) -name '*.cpp')

OBJ := $(SRC:%=$(OBJ_DIR)/%.o)
OBJ_LIB := $(SRC_LIB:%=$(OBJ_DIR)/%.o)
TEST_OBJ := $(TEST:%=$(OBJ_DIR)/%.o)

DEPS := $(OBJ:.o=.d)
INC_DIR := $(shell find $(SRC_DIR) -type d)
INC_FLAGS := $(addprefix -I,$(INC_DIR))
CPPFLAGS := -std=c++17 -g $(INC_FLAGS) -MMD -MP
LDFLAGS := -pthread

.PHONY: clean all

#Building all:
all: $(BUILD_DIR)/$(TARGET_EXEC) $(BUILD_DIR)/$(TEST_EXEC) $(LIB_DIR)/$(LIB)

#Building main executable:
$(BUILD_DIR)/$(TARGET_EXEC): $(OBJ)
    @ mkdir -p $(dir $@)
    $(CC) $(OBJ) -o $@ $(LDFLAGS)

#Building test executable:
$(BUILD_DIR)/$(TEST_EXEC): $(TEST_OBJ)
    @ mkdir -p $(dir $@)
    $(CC) $(TEST_OBJ) -o $@ $(LDFLAGS)

#Put object files into the object dir:
$(OBJ_DIR)/%.cpp.o: %.cpp
    @ mkdir -p $(dir $@)
    $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $< -o $@

#Create a static library from object files and put it in the library dir:
$(LIB_DIR)/$(LIB): $(OBJ_LIB)
    @ mkdir -p $(dir $@)
    ar rcs $(LIB_DIR)/$(LIB) $(OBJ_LIB)

clean:
    rm -r $(OBJ_DIR) $(BUILD_DIR) $(LIB_DIR)

-include $(DEPS)

What could be the problem?

std::mutex in C++ versus std::sync::Mutex in rust

I've always found std::mutex is C++ to be manual and error-prone. I need to manually attribute a certain std::mutex to specific variables and I need to remember to always lock the std::mutex before I access those specific variables.

Then I started learning Rust and I see that in Rust, std::sync::Mutex is a wrapper for objects, similar to how std::tuple in C++ is a wrapper for objects. std::sync::Mutex can be locked, and then it returns an object to access the members. As long as that handle object exists, the std::sync::Mutex stays locked, and it gets unlocked in the destructor (or something, not sure how it works in Rust). My first impression is that that's such a better way to tie a mutex to the data it's supposed to protect!

So my thought was: how can I get this feature into C++? I know that C++ is a powerful choice for creating custom features (e.g. boost) so here's the question:

Are there issues with the way Rust does things? (deadlocking concerns etc.)

Is there a reason that Rust can get away with what it does, that C++ cannot match? (preventing deadlock, borrow checker to keep the mutex locked etc.)

Is there an existing implementation of Rust-style std::mutex wrapper for C++?

Is Rust's implementation broken? (because of deadlock or something)

Or, am I doomed? Is C++ so fundamentally broken?

Can someone explain the use of last two things in given code

struct Interval {
     int start;
     int end;
     Interval() : start(0), end(0) {}
     Interval(int s, int e) : start(s), end(e) {}
};

I understood int start and int end but can anyone please describe what other two things represent.

C++ const_cast over a dynamic_cast and vice versa

I have a doubt about about a line of the code wrote from my professor.

This is the full code.

The class Gui has a std::list<const AbstractButton*> Buttons and the function std::vector<AbstractButton*> removeUnchecked(){} wants a vector as return type and we had to remove from the Gui every checkable buttons with the attribute checked == false and put in the returned vector.

The professor wrote CheckBox* p = const_cast<CheckBox*>(dynamic_cast<const CheckBox*>(*it)); performing a dynamic_cast first and then a const_cast

If I had written CheckBox* p = dynamic_cast<CheckBox*>(const_cast<AbstractButton*>(*it)) would it be the same thing? (const_cast first and then dynamic_cast)

vendredi 28 janvier 2022

C++ I cant get my function to run in my program

The Function won't initiate can someone help? When I run it in the debugger program skips over function and I don't know why?

#include <iostream>

 using namespace std;

int size_array= 0;
int *data_array;
void sorting(int *[], int);


int main()
{
cout<<"enter in array size \n";
 cin>>size_array;
int *data_array=new int(size_array);

 for(int i=0;i<size_array;i++)
  {
   cout<<"enter number "<<i+1<<endl;
   cin>>data_array[i];
  }
 **int sorting(int data_array, int size_array);**

for (int i=0; i<size_array;i++)
  {
    cout<<data_array[i]<<endl;
  }

return 0;
}

Why comparison of 40 is less than or equal to -2147483648 true?

I am running this code on my IDE which mathematically should return false as 40 is larger than -2147483648 but for some reason, it returns true.

    cout << (40 <= -2147483648) << endl;

Why the given code(Program to remove duplicates from a linked list using hashing) is not displaying any output?

#include <iostream>
#include <unordered_map>

using namespace std;

struct Node{
int data;
Node* next;
};

unordered_map<int,int> hashmap;

Node* head = NULL;



void deldups()
{
    Node* h = head;
    Node* prev = NULL;
    Node* curr;
    curr = h;
    
    while(curr != NULL)
    {
        int val = curr -> data;
        if (hashmap.find(val) != hashmap.end())
        {
            if(hashmap[val] > 1)
            {
            prev -> next = curr -> next -> next;
            delete(curr);
            }
        }
        else{
            ++hashmap[val];
            prev = curr;
        }
        curr = prev->next;
    }
}

void print()
{
    Node* temp = head;
    while(temp != NULL)
    {
        cout << temp -> data << " ";
        temp = temp->next;
    }
}

int main() 
{
    Node* firstnode = new Node();
    head = firstnode;
    firstnode -> data = 5;
    Node* secondnode = new Node();
    firstnode -> next = secondnode;
    secondnode -> data = 6;
    Node* thirdnode = new Node();
    secondnode -> next = thirdnode;
    thirdnode -> data = 7;
    Node* forthnode = new Node();
    thirdnode -> next = forthnode;
    forthnode -> data = 5;
    Node* fifthnode = new Node();
    forthnode -> next = fifthnode;
    fifthnode -> data = 9;
    fifthnode -> next = NULL;
    

    deldups();
    print();
    return 0;
}

I want to write a program that will remove duplicates from the linked list and print the linked list. I have used the hashing method to achieve this,

Code Explanation:

  1. Traverse the linked list while ptr is not NULL

check if the given element (h -> data) is present in the map 'key' (unordered<int,int>) NOTE I am using the element as a key in the map and not its value, value will be used to count its duplicates.

again,


  1. if the key is present then we will check its value and if the value is greater than '1' i.e the element is present more than one time then remove the node from the linked list
  2. else, add the element key into the hashmap and increment its value by one.

After running the code there is no output. why?

Kth Smallest Element in a BST: Wrong output

Given a binary search tree, I am required to find the Kth smallest element in the bst.

I think I have understood the logic that I need to implement, but my code it is not giving the desired output.

Example: Input: root = [5,3,6,2,4,null,null,1], k = 3

      5
     / \
    3   6
   / \
  2   4
 /
1

The expected output is: 3

but my code outputs this:0

My C++ Code below:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */

class Solution {

public:

    int ans;
    int key;
    void inorder(TreeNode* root)
    {
        if(root==NULL)
            return;
        inorder(root->left);
        if(--key==0)
            ans=root->val;
        inorder(root->right);
    }
    int kthSmallest(TreeNode* root, int k) {
        if(root==NULL)
            return 0;
        int key=k;
        inorder(root);
        return ans;
    }
};

Where is the mistake?

jeudi 27 janvier 2022

Getting compilation errors when trying to use pointers for dynamically allocated 2D array

I've recently started learning coding in the C++ language, and am having issues grasping the concept of pointers in C++.

I'm trying to practice dynamic memory allocation but keep running into errors when trying to compile my program.

Here are some struct objects I've created along with some global variables outside of my main function:

// Storing x and y values from file
struct gridSize {
    int gridXValue;
    int gridYValue;
    
    string toString();
};

string gridSize::toString ()
{
    ostringstream oss;

    oss << "gridXValue : " << gridXValue << endl;
    oss << "gridYValue : " << gridYValue << endl;

    return (oss.str());
}

// Storing details for each grid area within
// 2D array struct
struct grid_area {
    int x, y;
    bool is_occupied;
    int city_id;
    string city_name;
    int cloud, cloud_index, pressure, pressure_index;
    char cloudcover_LMH, pressure_LMH;
};

gridSize gridSize; //Global struct object
grid_area *ga = nullptr; //Global pointer variable

Here is what my main function looks like:

int main ()
{
    int userChoice;

    // Main menu to run constantly until user enters 8
    while (userChoice != 8) {
        cout << "Welcome to Weather Information Processing System!" << endl;
        cout << "-------------------------------------------------" << endl;

        cout << endl;

        cout << "1)\tRead in and process a configuration file" << endl;
        cout << "2)\tDisplay city map" << endl;
        cout << "3)\tDisplay cloud coverage map (cloudiness index)" << endl;
        cout << "4)\tDisplay cloud coverage map (LMH symbols)" << endl;
        cout << "5)\tDisplay atmospheric pressure map (pressure index)" << endl;
        cout << "6)\tDisplay atmospheric pressure map (LMH symbols)" << endl;
        cout << "7)\tShow weather forecast summary report" << endl;
        cout << "8)\tQuit" << endl;

        cout << endl;

        cout << "Please enter your choice: ";
        cin >> userChoice;

        cout << endl;

        if (userChoice == 1) {
            // Process all files
            readAFile();
        }
    }
        
        // Deallocate memory for 2D array
        for (int i = 0; i < gridSize.gridXValue + 1; i++) 
        {
            delete[] ga[i];
        }
        delete[] ga;
        
    
    return (0);
}

I highly suspect the issue lies in the last few portions of my readAFile function, but am unable to identify the problem. Here's the portion where I suspect the problem lies in readAFile:

    // Allocate array memory
    ga = new grid_area [gridSize.gridXValue + 1];
    for (int i = 0; i < gridSize.gridYValue + 1; i++)
        ga[i] = new grid_area[gridSize.gridYValue + 1];

    // Putting x and y values into  array
    for (int x_array = 0; x_array < gridSize.gridXValue + 1; x_array++) {
        for (int y_array = 0; y_array < gridSize.gridYValue + 1; y_array++) {
            ga[x_array][y_array].x = x_array;
            ga[x_array][y_array].y = y_array;
        }
    }

This is error I'm getting:

csci251_a1.cpp: In function ‘int main()’:
csci251_a1.cpp:110:20: error: type ‘struct grid_area’ argument given to ‘delete’, expected pointer
       delete[] ga[i];
                    ^
csci251_a1.cpp: In function ‘void readAFile()’:
csci251_a1.cpp:172:54: error: no match for ‘operator=’ (operand types are ‘grid_area’ and ‘grid_area*’)
         ga[i] = new grid_area[gridSize.gridYValue + 1];
                                                      ^
csci251_a1.cpp:32:8: note: candidate: ‘grid_area& grid_area::operator=(const grid_area&)’
 struct grid_area {
        ^~~~~~~~~
csci251_a1.cpp:32:8: note:   no known conversion for argument 1 from ‘grid_area*’ to ‘const grid_area&’
csci251_a1.cpp:32:8: note: candidate: ‘grid_area& grid_area::operator=(grid_area&&)’
csci251_a1.cpp:32:8: note:   no known conversion for argument 1 from ‘grid_area*’ to ‘grid_area&&’
csci251_a1.cpp:177:24: error: no match for ‘operator[]’ (operand types are ‘grid_area’ and ‘int’)
             ga[x_array][y_array].x = x_array;
                        ^
csci251_a1.cpp:178:24: error: no match for ‘operator[]’ (operand types are ‘grid_area’ and ‘int’)
             ga[x_array][y_array].y = y_array;

I really don't understand what I'm doing wrong here... If needed, I can provide the rest of the readAFile function as well. Any help would be greatly appreciated.

Using Enum to represent days

I want to represent a Weekday (Monday to Friday) as an enum but am not sure how to represent the data in c++. I have done some reading and have my enum class:

enum Day{MONDAY=0, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY};

But I also need some sort of to_string method in order to print the days out when required.

Currently I represent a Weekday in its own separate class as shown below:

Weekday::Weekday(char day){
    switch(day){
        case 'M' :
            weekday = "Monday";
            day_value = 0;
            break;
        case 'T':
            weekday = "Tuesday";
            day_value = 1;
            break;
        case 'W':
            weekday = "Wednesday";
            day_value = 2;
            break;
        case 'R':
            weekday = "Thursday";
            day_value = 3;
            break;
        case 'F':
            weekday = "Friday";
            day_value = 4;
    }

}

But I got a few looks when presenting my code to others so I was wondering if this is really the best way to do it.

Someone suggested to just use a switch to compare days and avoid making a new class at all but I thought this is more organized and on the plus side if I ever need to add more functionality to a weekday its all already set up.

I do have quite a few classes already for representing time in my program as well so maybe I am going a little crazy with the classes so I suppose I just need some guidance.

Their reasons for not using classes were something about memory and efficiency so thus I have three questions:

1.) Is a whole new class for a weekday the best way to represent this data?

2.)If a class of some sort is the best way what about an enum?

3.) Using an enum, how can I represent the enum data as a readable string I can print to an output later?

Sorry its a lot to unpack but I can't help but wonder if my way of making a class is truly the best way if there is a best way at all.

Regardless, thanks for the help in advance!

EDIT: the end goal here is to compare weekdays for example Monday comes before Tuesday so I assigned a value to the weekday and I would prefer not to use any imports

mardi 25 janvier 2022

Why does getline function discard the middle string?

I'm pretty new to C++ and StackOverflow. I'm trying to get only the marks from the string which is read from the file. Whenever I tried doing it, it outputs 50 and 75 only. Can someone explain to me why does it print only print these 2 lines only, please?

Expected output: 50,80,75

int main()
{
    string storeContents;
    string temp;
    string fileName("input.txt");
    ifstream inFile(fileName);

    while(!inFile.eof())
    {
        getline(inFile,storeContents);
        getline(inFile,storeContents, ' ');
        getline(inFile,storeContents, ' ');
        getline(inFile,storeContents, ' ');
        getline(inFile,storeContents, '\n');
        cout << storeContents << endl;
    }

    return 0;
}

Actual output: 50 75

File contents:

102234 962 4

Data_Structures ICT283 3 50

Security_Policy ICT380 1 80

Programming ICT159 4 75

Finding the max lengths of strings to format a table output

I want to find the max length of specific attributes from a vector of Person objects.

Below is an example of a Person object:

Person::Person(string first_name, string last_name, int the_age){
     first = first_name;
     last = last_name;
     age = the_age;
} 

I have a vector that stores Person objects, and I must print all the people out in a table, like so:

First Name  Last Name     Age
----------  ------------  ----
John        Cool-Johnson  15
Paul        Bob           1000
2 people

I need to find the max length of each attribute of a Person in order to grow each column according to the maximum length of name or age. How can I do this?

So far, I have tried lambdas using this code:

unsigned int max_name = *max_element(generate(people.begin(),people.end(), [](Person a){return a.getFirstName()})).size();

But I am not sure if this even works at all.

I must use <iomanip>, but I have no clue how it works.

Is there a better way?

Is there a way to use input variable as size of an array in C++? [duplicate]

I want the user to decide the array length by using cin. I have tried changing the scope but as expected it doesn't work. I would be grateful if you suggest me some changes in the code or the approach. Thank you.

#include <iostream>
using namespace std;

//declaring functions
void choose();
void add();
void average();
void product();
//declaring global variables
int choice;
double price[size], sum, avg, pro;

int main(){
    cout<<"Enter the number of items: ";
    cin>>size;
    choose();
    return 0;
}
.
.
.

Why use time_t to convert between C++ and Python dates in pybind

pybind provides conversions between standard Python and C++ date types. These are implemented in the optional header file chrono.h. The second class, the template specialization of type_caster, converts between Python datetime.datetime and C++ std::chrono::time_point<std::chrono::system_clock, Duration>, representing time since UTC for an arbitrary measure (Duration can be days, microseconds, etc).

When converting to C++, a std::tm is created, then system_clock::from_time_t(std::mktime(...)) is used. Conversely when converting from C++, localtime(system_clock::to_time_t(...)) is used.

If I were writing this function, I would use the C++ dates library directly:

  • to convert to C++, I would do something like: return a timepoint by adding the appropriate number of days, hours, ..., microseconds to the default.
  • Conversely, to convert from C++, I would do something like: convert the given time_point to year_month_day and then use arithmetic / truncation operations to get the hours ... microseconds.

However, out of all the open source libraries I use, pybind is probably the one I admire the most, so I'm wondering what I'm missing? Why go via time_t?

More context:

  • For high precision time points, I'm most interested in the datetime.datetime <=> std::chrono::time_point<std::chrono::system_clock, std::chrono::microseconds> conversion, as I use this C++ type throughout my library.
  • For time points measured in days, I also intend to add a date.date <=> naive / local std::chrono::time_point<std::chrono::local_t, std::chrono::days> conversion, where I'm assuming that if the time_t based conversion is required for a date-time, it won't be required in this, simpler, case.

How to deduce order of two variables store/load with acq/rel order?

I am trying to learn about execution order involving atomic variables in C++, and I have the following code.

According to cppreference, I have the following reasoning:

  1. C++ enforce 1->2 order when executing Because no load/store can be moved before an acquire-load within the same thread.

  2. C++ enforce 3->4 order when executing The same reason as 1

  3. C++ enforce 2->3 order when executing

    Because 2 is a release-store to y, and 3 is an acquire-load from y. So 2 should be visible to 3. Thus, 2 should be executed before 3, and 3 will read the result of 2's write.

  4. C++ enforce 4->1 order when executing The same reason as 3

From reasoning 1/2/3, we can deduce a execution order of 1 -> 2 -> 3 -> 4, and it will break reasoning 4. From reasoning 1/2/4, we can deduce a execution order of 3 -> 4 -> 1 -> 2, and it will break reasoning 3.

Seems there are conflicts here.

int main() {
    while(true) {
        std::atomic<int> x, y;
        x.store(10);
        y.store(20);
        auto f1 = [&]() {
            int r1 = x.load(std::memory_order_acquire); // 1
            y.store(r1, std::memory_order_release); // 2
        };
        auto f2 = [&]() {
            int r2 = y.load(std::memory_order_acquire); // 3
            x.store(r2, std::memory_order_release); // 4
        };
        std::thread t1(f1);
        std::thread t2(f2);
        t1.join();
        t2.join();
        printf("%d %d\n", x.load(), y.load());
    }
}

-- EDIT --

My reasoning about why 2 must happens before 3:

  1. From preshing, y.store(rel) syncs-with y.load(acq).
  2. Then according to cppreference, we can have y.store(rel) Inter-thread happens-before y.load(acq).
  3. Then y.store(rel) happens-before y.load(acq).
  4. So y.store(rel) must happens before y.load(acq)

Detecting last column and last row with Xlnt library in a xlsx file

I am trying to use the Xlnt library to create and manipulate some xlsx files.
There are functions in this library that let you know which one it is the last not empty column and the last not empty row?
Here is a code example:

#include <xlnt/xlnt.hpp>
#include <string>
#include <iostream>

int main ()
{
     xlnt::workbook wb;
     xlnt::worksheet ws = wb.active_sheet();
     ws.cell("AB1").value(5);
     ws.cell("B12").value("string data");
     ws.cell("C3").formula("= AB1 + B12");
     wb.save("example.xlsx");
     std::string lastColumn = ws.last_column();     // exists similar function?
     size_t lastRow = ws.last_row();                // exists similar function?
     std::cout << lastColumn << ' ' << lastRow << std::endl;

     return 0;
}

Reading the code it is clear that the last column is "AB" and the last row is 12, but obviously the program does not know which cells have contents of any type.

lundi 24 janvier 2022

Line 171: Char 16: runtime error: reference binding to misaligned address 0xbebebebebebec0ba for type 'int', which requires 4 byte alignment

For this LeetCode problem why I'm getting this error

vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
        stack<int>s;
        map<int,int>nge;
        
        for (int i=nums2.size()-1;i>=0;i--) {
            if(s.top()>nums2[i]) {
                nge[nums2[i]]=s.top();
            }
            else {
                while(!s.empty() && s.top()<=nums2[i]) s.pop();
                if(!s.empty()) nge[nums2[i]]=s.top();
                else nge[nums2[i]]=-1;
            }
            s.push(nums2[i]);            
        }
        
        vector<int>ans;
        for (int i=0;i<nums1.size();i++) {            
            int temp=nge[nums1[i]];
            ans.push_back(temp);
        }
        return ans;
    }

Thanks for advance in solution!, Thank you very much for advance in solution!, Tysm for advance in solution!

dimanche 23 janvier 2022

given list of grades

This is the code I have made, however, what is being displayed is incorrect. Kindly teach me what do I need to fix.

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

bool check(int passing){
    int g;
    if(g<=passing){
        return false;
    }else{
        return true;
    }
}

int main()
{
    int pg;

    cout<<"What is the passing grade?"<<endl;
    cin>>pg;

    list<int> grades = {100,90,93,95,92,98,97,99,96,94};
    grades.remove_if(check);
    for(int x : grades){
        cout<<x<<'\t';
    }
    return 0;
}

How can I put an object in a vector by its adress and access it?

That code allow us to make labrary (Bibliotheque) that it has copy (Exemplaire) of books (oeuvre) when a call stocker(oeuvre , n) it has to stock a copy n time in put in a list "vector"

class Bibliotheque
{
    private:
        string nom;
        Exemplaire exemplaire; // One "Exemplaire" has declared
        vector<Exemplaire*> exemplaires { &exemplaire }; //list of pointers of "exemplaire" 
    public:
        Bibliotheque(string nom)
        :nom(nom)
        {
            cout << "La Bibliothèque " << nom << " est ouverte !" << endl;
        }

        string getNom()
        {
            return nom;
        }

        void stocker(Oeuvre &oeuvre, int n = 1)
        {
            for(int i = 0; i < n; i++)
            {
                  exemplaires.push_back(&exemplaire); //It has to be list of the same object that have the same argument "oeuvre"
                                                  //making n time that object and put it in the list
            }
        }
};

create a program wherein there is an initialized list of grades, and it will display the grades passed depending on the user input

This is the code I have made, however, what is being displayed is incorrect. Kindly teach me what do I need to fix.

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

bool check(int passing){
    int g;
    if(g<=passing){
        return false;
    }else{
        return true;
    }
}

int main()
{
    int pg;

    cout<<"What is the passing grade?"<<endl;
    cin>>pg;

    list<int> grades = {100,90,93,95,92,98,97,99,96,94};
    grades.remove_if(check);
    for(int x : grades){
        cout<<x<<'\t';
    }
    return 0;
}

samedi 22 janvier 2022

How does one use FLTK library using Bjarne's GUI's header file in his book Programming principles and practices?

#include "Simple_window.h"
#include "Graph.h"

int main()
{
    using namespace Graph_lib;

    Point tl(100, 100);

    Simple_window win(tl, 600, 400, "Canvas");

    Polygon poly;

    poly.add(Point(300, 200));
    poly.add(Point(350, 100));
    poly.add(Point(400, 200));

    poly.set_color(Color::red);

    win.attach(poly);

    win.wait_for_button();
}

The above code has to create a GUI window with a shape rendered on its canvas but it does not run the way it should throwing errors like ambiguous windows specified, no Point type found even though all the libraries and header files are properly placed as specified in the book. I also tried commenting and uncommenting certain parts of the supporting GUI library from Bjarne's site as done by others and also reading some of the error messages but of no use. It keeps throwing ambiguous windows specified error!

Right now my only aim is to run the code above on my machine.

Segmentation fault Binary search Tree

I know there is few questions with a similar title, however I went over them and still couldn't solve my error.

This is the BST implementation:

struct node {
    int val;
    node* left;
    node* right;
};

node* createNewNode(int x)
{
    node* nn = new node;
    nn->val = x;
    nn->left  = nullptr;
    nn->right = nullptr;

    return nn;
}

void bstInsert(node* &root, int x)
{
    if(root == nullptr) {
        root = createNewNode(x);
        return;
    }

    if(x < root->val)
    {
        if(root->left == nullptr) {
            root->left = createNewNode(x);
            return;
        } else {
            bstInsert(root->left, x);
        }
    }

    if( x > root->val )
    {
        if(root->right == nullptr) {
            root->right = createNewNode(x);
            return;
        } else {
            bstInsert(root->right, x);
        }
    }
}

Here is my main:


int main() {
    node *root = nullptr;
    for (int i = 0; i < 100000; i++) {
        bstInsert(root, i);
    }
}

If I try to insert 10000 elements then it works alright. however when I try to insert 100000 elements I get in the debugger:

Signal = SIGSEGV (Segmentation fault)

It happens when the value of I in the loop reaches 32469, what am I missing ?

vendredi 21 janvier 2022

Can you help me with oop?

This is my code:

Extractor.hpp
template <class O, class D> class Extractor{
  public:
    Extractor(
        std::vector<O>& input_data,
        Filtro<O>& filtro,
        Mapeador<O, D>& mapeador
    ): _input_data(input_data), _filtro(filtro), _mapeador(mapeador) {}

    unsigned int getData(std::vector<D>& output) {
      unsigned total = 0;
      for (O& data: _input_data) {
        if (_filtro.dadoValido(data)) {
          output.push_back(_mapeador.transformaDado(data));
          total++;
        }
      }
      return total;
    }

  private:

    std::vector<O>& _input_data;

    Filtro<O>& _filtro;

    Mapeador<O, D>& _mapeador;
};
Extractor.cpp
template <class NUM_TYPE>
class Num2Sqrt: public Mapeador<NUM_TYPE, NUM_TYPE> {
  NUM_TYPE transformaDado(NUM_TYPE& d) const override {
    // TODO: Implemente este metodo.
    d = d / d;
    return d;
  }
};

class FiltroNumPositivo: public Filtro<NUM_TYPE> {
  bool dadoValido(NUM_TYPE& d) const override {
    // TODO: Implemente este metodo.
    if (d > 0){
        return true;
    }else{
        return false;   
    }
  }
};

template <class NUM_TYPE> void test_filter_square_roots() {
    std::vector<unsigned> entrada;
    std::vector<Mapeador<std::string, int>> saida;

    read_input(entrada);  
    Filtro<int>* new_filtro;
    new_filtro = new FiltroNumPositivo<int>;

    Mapeador<int, int>* new_mapeador;
    new_mapeador = new Num2Sqrt<int>;

    Extractor<Filtro<int>,Mapeador<std::string, int>> new_extrator(new_filtro, new_mapeador, saida);

I just cut a little part of the code just to you all be capable to understand, but my problem is declaring the class of the template named Extractor, look at the extense error report(I cutted a little piece of the error):

ExtratorDeDados.cpp: In instantiation of ‘void test_filter_square_roots() [with NUM_TYPE = int]’: ExtratorDeDados.cpp:329:37: required from here ExtratorDeDados.cpp:243:61: error: no matching function for call to ‘ExtratorDeDados<Filtro, >Mapeadorstd::__cxx11::basic_string<char, int> >::ExtratorDeDados(Filtro&, Mapeador<int, >int>&, std::vector<Mapeadorstd::__cxx11::basic_string<char, int> >&)’ ExtratorDeDados<Filtro,Mapeador<std::string, int>> new_extrator(new_filtro, new_mapeador, >saida); ^~~~~~~~~~~~ In file included from ExtratorDeDados.cpp:3:0: ExtratorDeDados.hpp:124:5: note: candidate: ExtratorDeDados<O, D>::ExtratorDeDados(std::vector&, >Filtro&, Mapeador<O, D>&) [with O = Filtro; D = Mapeadorstd::__cxx11::basic_string<char, >int>] ExtratorDeDados( ^~~~~~~~~~~~~~~ ExtratorDeDados.hpp:124:5: note: no known conversion for argument 1 from ‘Filtro’ to >‘std::vector<Filtro, std::allocator<Filtro > >&’ ExtratorDeDados.hpp:113:35: note: candidate: constexpr ExtratorDeDados<Filtro, >Mapeadorstd::__cxx11::basic_string<char, int> >::ExtratorDeDados(const >ExtratorDeDados<Filtro, Mapeadorstd::__cxx11::basic_string<char, int> >&) template <class O, class D> class ExtratorDeDados { ^~~~~~~~~~~~~~~ ExtratorDeDados.hpp:113:35: note: candidate expects 1 argument, 3 provided ExtratorDeDados.hpp:113:35: note: candidate: constexpr ExtratorDeDados<Filtro, >Mapeadorstd::__cxx11::basic_string<char, int> >::ExtratorDeDados(ExtratorDeDados<Filtro, >Mapeadorstd::__cxx11::basic_string<char, int> >&&) ExtratorDeDados.hpp:113:35: note: candidate expects 1 argument, 3 provided ExtratorDeDados.cpp: In instantiation of ‘void test_filter_square_roots() [with NUM_TYPE = double]’: ExtratorDeDados.cpp:332:40: required from here ExtratorDeDados.cpp:243:61: error: no matching function for call to ‘ExtratorDeDados<Filtro, >Mapeadorstd::__cxx11::basic_string<char, int> >::ExtratorDeDados(Filtro&, Mapeador<int, >int>&, std::vector<Mapeadorstd::__cxx11::basic_string<char, int> >&)’ ExtratorDeDados<Filtro,Mapeador<std::string, int>> new_extrator(new_filtro, new_mapeador, >saida); ^~~~~~~~~~~~ In file included from ExtratorDeDados.cpp:3:0: ExtratorDeDados.hpp:124:5: note: candidate: ExtratorDeDados<O, D>::ExtratorDeDados(std::vector&, >Filtro&, Mapeador<O, D>&) [with O = Filtro; D = Mapeadorstd::__cxx11::basic_string<char, >int>] ExtratorDeDados( ^~~~~~~~~~~~~~~ ExtratorDeDados.hpp:124:5: note: no known conversion for argument 1 from ‘Filtro’ to >‘std::vector<Filtro, std::allocator<Filtro > >&’ ExtratorDeDados.hpp:113:35: note: candidate: constexpr ExtratorDeDados<Filtro, I would be really thankful if anyone can help me!

jeudi 20 janvier 2022

Cppcheck incorrect uninitialized member variable warning

I am running cppcheck on a project, and when I do, I have been getting a warning stating there is an "uninitialized member variable" (with error code [uninitMemberVar]). If I go and check the variable it is yelling about, it is always a pointer, which is correctly initialized to nullptr, albeit in the header file. I am doing all of my (pointer) initialization in the header file, rather than in the constructor.

I have found that I can suppress this warning by adding //cppcheck-suppress uninitMemberVar comment, although it only works if I add it before the default constructor in the header file, rather than before the variable itself.

I am wondering if anyone has experienced a similar issue with cppcheck before, where you have initialized a pointer but cppcheck still throws a "uninitialized member variable warning"? I am not sure what is causing this, and I would like to find a solution that is better than adding cppcheck-suppress comments. Thanks in advance for any help.

C++11 Template Method to Stream std::map to std::cout

Objective: Implement a template method that generically allows streaming std::map instances to std::cout

Problem: I'm getting undefined behavior, where my code executes without errors and other times a segfault. Either way the std::map content do print to the command window in entirety.

What I've tried:

    /* Import dependencies */
    #include <iostream>
    #include <string>
    #include <vector>
    #include <map>

    /* Declare a recursive template overload of the ostream << operator for printing std::vector types */
    template<typename T>
    std::ostream& operator<<(std::ostream& stream, std::vector<T> vec)
    {
        //Save repetitive calls to check .size()
            int container_size = vec.size();
            
        //Pre-allocate loop iterator
            int indx = 0;
            
        //Check if the input vector is empty
            if( container_size > 0 )
            {
                //Stream character for the start of a container
                    stream << "\n\t{ ";               
                    
                //For each element of the input container, could be a value or nested container
                    for(indx; indx < container_size; indx++)
                    {
                        //Execute based on iterator position within container
                            if( indx < ( container_size - 1 ) )
                            {
                                //Print value, or recurse nested container to << template
                                    stream << vec[ indx ] << ", ";
                            }
                            else
                            {
                                //Stream last value and terminate with character
                                    stream << vec[ indx ] << " }";
                            }
                    }
            }
            
        //Default & final execution
            return stream;
            
    };

    /* Template method to stream std::map instances to std::cout */
    template<typename KeyT, typename ValueT>
    std::ostream& operator<<(std::ostream& os, std::map<KeyT,ValueT> mapInst)
    {
        for(auto& item : mapInst)
        {
            std::cout << item.first << ":" << item.second << "\n";    
        }
    }

    /* Main routine */
    int main()
    {
        //Declare a map
            std::map< std::string, std::vector< std::vector<double> > > tmp;
            
        //Make some stuff to insert into the map
            std::vector< std::vector<double> > v1 = { { 3000.28, 3000.11, 1e+006, 3000.02, 1e+006, 3000.28, 3016.76, 3014.47, 3014.39, 1e+006, 1e+006, 1e+006 },
                                                      { 3000.28, 3000.11, 3000.02, 3000.02, 1e+006, 3000.28, 3016.76, 1e+006, 3014.39, 3012.26, 3012.35, 3010.39 },
                                                      { 3000.28, 1e+006, 3000.02, 3000.02, 3000.11, 3000.28, 1e+006, 3014.47, 3014.39, 3012.26, 3012.35, 1e+006 },
                                                      { 3000.28, 1e+006, 3000.02, 3000.02, 3000.11, 3000.28, 3016.76, 3014.47, 3014.39, 1e+006, 3012.35, 3010.39 },
                                                      { 3000.28, 1e+006, 1e+006, 1e+006, 1e+006, 1e+006, 3016.76, 3014.47, 3014.39, 3012.26, 1e+006, 3010.39 },
                                                      { 3000.28, 3000.11, 1e+006, 3000.02, 3000.11, 1e+006, 3016.76, 1e+006, 3014.39, 3012.26, 3012.35, 3010.39 },
                                                      { 3000.28, 3000.11, 3000.02, 3000.02, 3000.11, 1e+006, 1e+006, 3014.47, 3014.39, 3012.26, 3012.35, 3010.39 } };
            
            std::vector< std::vector<double> > v2 = { {10.0,11.0,12.0}, {-100.0,-200.0,-300.0}, {0.123,0.456,0.789} };
                                         
        //Put the data into the map
            tmp.insert( std::make_pair( "SomeKey", v1 ) );
            tmp.insert( std::make_pair( "SomeOtherKey", v2 ) );
        
        //Stream the map to cout
            std::cout<<"My MAP = \n"<<tmp<<"\n\n";
        
        //Exit the main program
            return 0;
            
    }

Can't run C++ .exe created by VSCode

I use VSCode to create the .exe file of the simple following C++ code:

#include <iostream>
using namespace std;

int main()
{
    int x = 25;
    cout << x << endl;
    return 0;
}

When I open the .exe program created, the window appears and shuts down immediately. If I put getchar() before return 0, I can make the program wait for user input to fix it. However, if I use Dev-C or Codeblocks, this problem does not happen. In other word, I do not need to add getchar() to hold the window. Hope that someone can explain what problem occurs and how can I fix it to make the .exe created by VSCode run normally? Thank you so much.

mardi 18 janvier 2022

How to compile using C++11 in VS Code

I am trying to use VS Code on Mac to run C++ code. I've used XCode before with no issue but am running into errors while trying to run this code. I am using the Microsoft C++ and CodeRunner extensions

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

using namespace std; 

int main () {
vector<string> names = {"Dan", "Sam", "Man"};  
vector<string> *name_ptr = &names;

cout << (*name_ptr).at(0);
 return 0;
}

I used Command+Shift+P to edit the Microsoft C/C++ Extension configurations and changed the C++ standard to "C+11." Doing this removed the error squiggles from the vector list but when I ran the code I still received the error:

"error: non-aggregate type 'vectorstd::__1::string' (aka 'vector<basic_string >') cannot be initialized with an initializer list"

I've tried using the advice from Error: non-aggregate type 'vector<int>' cannot be initialized with an initializer list but I am unsure how to pass the "g++ -std=c++11 myfile.cpp" argument to the compiler. I've tried putting that argument under compiler arguments in the C/C++ Extension configurations settings to no avail. I am not too familiar with how compilers so I am stuck here.

Running C++ based Rivet Monte Carlo routine in a Cluster

I am running a C++ routine which outputs a text file including the four momentum of physics partile.On local machine,it works perfectly and output a text file on the current directory.When I run the routine on cluster,I dont get a text file as an output.When the routine is run,I get files in two directories yoda(contains the information to plot histogram) and logs(for sumbit.err and submit.out files). I am mentioning these two directories in a submit.sh file as

#! /bin/bash

export JO=$1
export DATASET=$2
export WORKDIR=/beegfs/user/standalone/

if [ -z $3 ]; then
export RUN=`echo $DATASET | awk -F. '{print $2}'`
else
export RUN=`echo $DATASET | awk -F. '{print $1}'`
fi

sbatch -o ${WORKDIR}/logs/submit_${RUN}.out -e ${WORKDIR}/logs/submit_${RUN}.err  -p normal --job-name Rivet_${RUN} --export 
WORKDIR,RUN,JO,DATASET run_rivet_onnode.sh

My question is how can I confgiure this submit.sh so that the file that I create and write on the runtime using ofstream could appear in the logs directory after the run.

Atomic variable vs Normal variable with locks in C++

Recently I gave an interview to a tech company and the interviewer asked me to tell which of the operation is faster among a normal increment operation on atomic variable and increment operation on a normal variable with locks. (This came as a sub question of an original question which goes out of context)

As I don't know what's going under the hood, I gave the reason as one hardware instruction for one increment instead of three and I claimed atomic to be faster.

Now after the interview, while I though of extracting the solution, I found this happening.

Code I've written to test:

#include <iostream>
#include <chrono>
#include <thread>
#include <mutex>
#include <atomic>
#include <cmath>
using namespace std;

int iters = 1;

class Timer{
private:
    std::chrono::time_point<std::chrono::high_resolution_clock> startTime,stopTime;
    string method_name;
    // stop function
    void stop(){
        stopTime = std::chrono::high_resolution_clock::now();
        auto start = std::chrono::time_point_cast<std::chrono::microseconds>(startTime).time_since_epoch().count();
        auto stop = std::chrono::time_point_cast<std::chrono::microseconds>(stopTime).time_since_epoch().count();
        auto duration = stop-start;
        cout<<"Time taken : "<<duration<<" μs"<<endl;
    }
public:
    // constructor
    Timer(){
        startTime = std::chrono::high_resolution_clock::now();
    }
    // destructor
    ~Timer(){
        stop();
    }
};

std::mutex Lock;
long n_variable = 0;
std::atomic<long> a_variable(0);

void updateAtomicVariable(){
    for(int i = 0 ; i < iters ; i++){
        a_variable++;
    }
}

void updateNormalVariableWithLocks(){
    for(int i = 0 ; i < iters ; i++){
        Lock.lock();
        n_variable++;
        Lock.unlock();
    }
}

int main(){

    int no_th = 1;
    std::thread atomic_threads[10];
    std::thread normal_threads[10];

    // updating once
    cout<<"Updating atomic variable once"<<endl;
    {
        Timer timer;
        for(int i = 0 ; i < no_th ; i++){
            atomic_threads[i] = std::thread(updateAtomicVariable);
        }

        for(int i = 0 ; i < no_th ; i++){
            atomic_threads[i].join();
        }
    }
    cout<<"Updating normal variable once with locks"<<endl;
    {
        Timer timer;
        for(int i = 0 ; i < no_th ; i++){
            normal_threads[i] = std::thread(updateNormalVariableWithLocks);
        }

        for(int i = 0 ; i < no_th ; i++){
            normal_threads[i].join();
        }
    }

    no_th = 10;
    iters = 1e7;
    //updating multiple times
    cout<<"Updating atomic variable 1e8 times with 10 threads"<<endl;
    {
        Timer timer;
        for(int i = 0 ; i < no_th ; i++){
            atomic_threads[i] = std::thread(updateAtomicVariable);
        }

        for(int i = 0 ; i < no_th ; i++){
            atomic_threads[i].join();
        }
    }
    cout<<"Updating normal variable 1e8 times with 10 threads and with locks"<<endl;
    {
        Timer timer;
        for(int i = 0 ; i < no_th ; i++){
            normal_threads[i] = std::thread(updateNormalVariableWithLocks);
        }

        for(int i = 0 ; i < no_th ; i++){
            normal_threads[i].join();
        }
    }
}

Interestingly I got the output as :

Updating atomic variable once
Time taken : 747 μs
Updating normal variable once with locks
Time taken : 255 μs
Updating atomic variable 1e8 times with 10 threads
Time taken : 1806461 μs
Updating normal variable 1e8 times with 10 threads and with locks
Time taken : 12974378 μs

Although the numbers are varying each and every time, the relative magnitude remained same.

This is showing that for one increment operation atomic increment is slower and on the other hand while incrementing the same for multiple times it is showing atomic increment is much faster which is the contrary to first recorded observation of one increment.

I ran this on multiple machines and multiple times and found the same.

Could some one help me to understand what's going on here. Thanks in advance.

GCC infers pass-by-value copy assignment with jsoncpp

const Descriptor* descriptor_ptr = msg.GetDescriptor();
const Reflection* reflection_ptr = msg.GetReflection();
const FieldDescriptor* field_ptr = descriptor_ptr->field(i);
Json::Value value;

if (field_ptr->cpp_type() == FieldDescriptor::CPPTYPE_UINT32)
{
    value[field_ptr->name()] = reflection_ptr->GetUInt32(msg, field_ptr);
}

In our case, we tried to build a shared lib with a proto to json function The linked app would crash with no core dump and we got output in gdb as

Inferior 1 (process xxx) exited with code 0177

and _dl_signal_error frame.

Code line resulted in the error was

value[field_ptr->name()] = reflection_ptr->GetUInt32(msg, field_ptr);

and we found that ldd -r shows the shared lib has undefined symbol pointing to _ZN4Json5ValueaSES0_, demangled as Json::Value::operator=(Json::Value) by c++filt

It surprised us a lot because there was no pass-by-value copy assignment function in jsoncpp's headers or source code. We tried recompile it with latest release of jsoncpp and the problem remains

However, when we make a stand alone jsoncpp demo, it works fine and ldd -r no longer shows the undefined symbol output

We guess it's gcc which interprets and chooses a non-existent copy assignment operator. It may be relevant to copy emision or other optimization, how can we fix it? or how to explicitly use a valid copy assignment operator?

Linux version we use is Linux version 2.6.32-696.el6.x86_64 CentOS release 6.9 (Final), gcc version is gcc (GCC) 9.1.0

compiling options are

C_FLAGS          = -Wall -D_GNU_SOURCE  -Wno-deprecated -fPIC -g -pipe -D_DEBUG -Woverloaded-virtual -Wpointer-arith -fno-strict-aliasing -std=c++17

and link with jsoncpp static lib

lundi 17 janvier 2022

C++ trim string with multiple delimiters

I have the following string: ( myFirstEntry ( one 1;) mySecondEntry ( two 2; mySubSecondEntry (subTwo 22;)) myThirdEntry (three 3;)

I would like to retrieve the keyword and the value as a string:

The end result is expected to be:

myFirstEntry , one 1;

mySecondEntry, two 2; mySubSecondEntry (subTwo 22;)

myThirdEntry, three 3;

How can I achieve this?

Build argv with unique_ptr or RAII?

I have a library function that has the following signature func(int argc,char** argv), where argv is an array of c-strings, and crafted manually according to the enclosing environment of the application.

Can I use unique_ptr to manage the memory of argv instead of allocating/deallocating them via new/delete operators ?

How to take input after string variable? [duplicate]

struct book {
  int bookid;
  string bookname;
  float prize;
};
     

int main(){
        book b1;
        cout<<"Enter bookid"<<" "<<"Enter bookname"<<" "<<"enter prize"<<endl;
        cin>>b1.bookid;
        getline(cin,b1.bookname);
        cin>>b1.prize;
        cout<<b1.bookid<< " "<<b1.bookname<<" "<<b1.prize<<endl;
        return 0;
}

But after taking book name, it skips taking prize and direct show output.

How traverse an xml file and make a composite object at the end?

I have a simple xml file:

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<Menu name="First Menu" caption="FirstMenu">
    <Menu name="Do Fancy Stuff" caption="DoFancyStuff">
        <Menu name="Exit" caption="Exit">
            <Menu name="Run away" caption="RunAway"/>
            <Menu name="Foo" caption="Foo"/>
        </Menu>
    </Menu>
    <Menu name="Bar" caption="Bar"/>
    <Menu name="Tar" caption="Tar"/>
    <Menu name="Zar" caption="Zar">
        <Menu name="Ghar" caption="Ghar"/>
        <Menu name="Ghar" caption="Ghar"/>
    </Menu>
    <Menu name="Kar" caption="Kar"/>
    <Menu name="Far" caption="Far"/>
</Menu>

And i want parse it and make a composite object at the end. this is my attempt so far: https://gist.github.com/LinArcX/37eea86b43a9b2d1e6302ed2219a12fb

All the code works. The only part that remained unsolved for me is: traverseXmlReturnCompsiteObject function. Because i don't know how can i create objects on the fly for each Leaf/Composite object. Another concern is that i don't know how can i keep the fathers(for the next recursion) to add their children to it.

The output of traverseXmlReturnCompsiteObject should be a composite object that contains all the internal objects.

Any idea?

Thanks in advance.

Edit: If there was no xml parsing and recursion, creating composite object was as simple as below code:

std::shared_ptr<Component> TREE;
TREE = std::shared_ptr<Component>(new Composite("TREE"));

std::shared_ptr<Component> B1(new Composite("B1"));
std::shared_ptr<Component> L1(new Composite("L1"));
std::shared_ptr<Component> L2(new Composite("L2"));
std::shared_ptr<Component> L3(new Composite("L3"));

B1->add(L1);
B1->add(L2);
B1->add(L3);

std::shared_ptr<Component> B2(new Composite("B2"));
std::shared_ptr<Component> L4(new Composite("L4"));
std::shared_ptr<Component> L5(new Composite("L5"));

B2->add(L4);
B2->add(L5);

TREE->add(B1);
TREE->add(B2);

What is a proper way to make my Singleton thread safe

I'm working with C++11 and I'm trying to implement a singleton which works at multi-threading project.

template <typename T>
class Singleton
{
    public:
        Singleton(const Singleton&&) = delete;
        Singleton(Singleton&&) = delete;
        Singleton& operator=(const Singleton&) = delete;
        Singleton& operator=(Singleton&&) = delete;

        static T* getInstance()
        {
            static Protector protector {instance};
            return instance;
        }

        template<typename... Args>
        static void createInstance(Args&&... args) {
            static T t(std::forward<Args>(args)...);
            instance = &t;
        }

    private:
        Singleton() = default;
        ~Singleton() = default;

        static T* instance;

        struct Protector {
            Protector(T* p) {
                if (p == nullptr) {
                    assert("not-init");
                }
            }
        };
};

template<typename T>
T* Singleton<T>::instance = nullptr;

class Test
{
    friend class Singleton<Test>;
    private:
        Test(int aa): a{aa} {};
        ~Test(){};                    
        int a;      
    public:
        void print(void) {std::cout << "hello " << a << std::endl;}
};

int main(void)
{
    Singleton<Test>::createInstance(1);
    Singleton<Test>::getInstance()->print();

    return 0;
}

I've known that the initialization of static variable is thread safe in C++11 so I think this shouldn't cause any problem (https://stackoverflow.com/a/1661564/3305546).

The inner class named Protector is used to make sure that createInstance() has been called before calling getInstance(). I think this should be OK too.

But after reading this link, it seems that instance = &t; in the funciton createInstance() could cause race condition if the function is called in multi threads? If so, what is the proper way to solve this issue? Replace static T* instance with std::atomic<T*> instance?

dimanche 16 janvier 2022

/ and * in C++ money class implementation

Money.h

#pragma once
#include <string>

class Money {
private:
    long pounds;
    int pence;

public:
    Money();
    // Overloaded constructors
    explicit Money(long pounds);
    Money(long pounds, int pence);

    /* Overload operators to allow easier arithmetic of money objects, we will
     not overload * or / as it does not make logical sense for money to be multiplied
     or divided.
    */
    Money operator+(const Money& moneyRhs) const;
    Money operator-(const Money& moneyRhs) const;

    friend std::ostream& operator<<(std::ostream& os, const Money& money);

    // toString method to print out money object
    std::string toString() const;

    // Getters
    long getPounds() const;
    int getPence() const;
};

Money.cpp

#include "Money.h"
#include <iomanip>

Money::Money(): pounds(0), pence(0) {}

Money::Money(const long pounds): pounds(pounds), pence(0) {}

Money::Money(const long pounds, const int pence): pounds(pounds), pence(pence) {}

Money Money::operator+(const Money& moneyRhs) const {
    // Convert all money to pence then do addition
    const long poundsInPence = (pounds + moneyRhs.pounds) * 100;
    const int totalPence = pence + moneyRhs.pence;
    const long allPence = poundsInPence + totalPence;

    const Money m3 = Money(allPence / 100, allPence % 100);
    return m3;
}

Money Money::operator-(const Money& moneyRhs) const {
    // Convert all money to pence then do subtraction
    const long poundsInPence = (pounds - moneyRhs.pounds) * 100;
    const int totalPence = pence - moneyRhs.pence;
    const long allPence = poundsInPence + totalPence;

    const Money m3 = Money(allPence / 100, allPence % 100);
    return m3;
}

std::string Money::toString() const {
    std::string strMoneyFormat;

    // Check so see if the pence value is 1 digit, if so we need to add a trailing 0 for output
    // e.g £150.5 becomes £150.05
    if((getPence() > 0 ? static_cast<int>(log10(static_cast<double>(getPence()))) + 1 : 1) < 2) {
        strMoneyFormat = std::to_string(getPounds()) + "." + "0" + std::to_string(getPence());
    }
    else {
        strMoneyFormat = std::to_string(getPounds()) + "." + std::to_string(getPence());
    }

    return strMoneyFormat;
}

std::ostream& operator<<(std::ostream& os, const Money& money) {
    os << money.toString();
    return os;
}

long Money::getPounds() const {
    return pounds;
}

int Money::getPence() const {
    return pence;
}

I have the above money class implementation for a basic UK banking app, however, I know in coding, in general, it's best practice if you overload one type of operator e.g arithmetic you should overload its others as well, so here I have overloaded the + and -, so I need to overload / and *. However, it doesn't make much sense to multiply or divide the money, is there a way i can go about overloading these to operators that anyone knows, that would make sense?

Update:

template <class T>
    Money operator*(T number) const {
        const int penceMult = pence * number;
        const int newPence = penceMult % 100;

        const long newPounds = pounds * number + (penceMult / 100);
        Money tmp(newPounds, newPence);
        return tmp;
    }

    template <class T>
    Money operator/(T number) const {
        if (number == 0) {
            throw std::invalid_argument("Division by zero");
        }

        long total = (100 * pounds) + pence;
        const long result = total / number;

        const int newPence = result % 100;
        const long newPounds = result / 100;
        Money tmp(newPounds, newPence);
        return tmp;
    }

Binary Division using Templated Big Integers

I am trying to implement a Division Binary Algorithm.

The code has some Logical Errors which I am still trying to figure out how to fix them.

myuint operator/(const myuint<T>& x)
    {
        myuint<T> temp;
        myuint<T> result;

        int count = 0;

        for(int i = bits.size() - 1 ; i >= 0; --i)
        {
            temp.bits.push_back(bits[i]);

            if(temp >= x)
            {
                count++;
                *this = *this - x;
                temp = 0;
            }    
        }

        result = count;

        return result;
   }

I am also overloading the >=, >, and == operators for the division.

The logical problem most probably is in the for loop . What should I do? Thanks

Full code can be accessible from here

== EDIT

What I am trying to achieve is this. *this is 10100 (20 in decimal) x is 100 (4 in decimal)

  1. Get the first Bit (1).
  2. Compare it to x
  3. If the bit is greater than the value of x, count++, subtract x from *this. And then Start the loop again which a different *this size.
  4. If the bit is small, then we move to the bit next to it so, now we have 2 bits (10) and we compare it to x.
  5. Then I return the value of count which represents this number of divisions to reach 0.

Printing variable value using Reference to const gives different result

I am learning about references in C++. So i am trying out different examples to better understand the concept. One example that i could not understand is given below:

double val = 4.55;
const int &ref = val;
    
std::cout << ref <<std::endl; //prints 4 instead of 4.55

I want to know what is the problem and how can i solve it?