mercredi 30 juin 2021

VSCode visualize dynamic arrays in debugger

I am using VSCode for some C++ code.

With the following code:

int array [10] = {1};

I can visualize the entries of the array in the debugger:

enter image description here

However, when I dynamically allocate the array, with:

int* array = new int[10];

I get:

enter image description here

Is it possible to visualize the dynamic array as the one allocated with:

int array [10] = {1};

Boost::spirit::qi parse alternative variant

I need to parse string with parameters A and B. Order of the parameters not defined. I.e. string can be present as one of the next formats

A="value1",B="value2"
B="value1",A="value2"

Part of my code you can see below. But in that code I can parse only A="value1",B="value2" variant. Could I modify this code to parse the first and second variants together? Yes, I can add alternative condition ("|"). But what if I need to parse new C and D parameters.

using Iterator = std::string::const_iterator;
qi::rule<Iterator, std::string()> quotedStringParser;
quotedStringParser %= ('"' >> +(qi::char_ - '"') >> '"');

std::string A;
std::string B;
bool isImport = false;

if (!qi::parse(begin(line), end(line),
    ("A=" >> quotedStringParser[px::ref(A) = qi::_1] >> ',' >> "B=" >> quotedStringParser[px::ref(B) = qi::_1]) >> qi::eoi
)) {
    return false;
}

what is the complexity of iterating an unordered_map in C++

What is the complexity of iterating through an unordered_map implemented using hashing with chaining? Specifically does this involve traversing all the buckets, in which case complexity is O(Buckets + NElements) vs. ideal, e.g. O(NElements)

introducing a function over a vector +sycle + dpcpp + tbb

I try to wrote a program which provide a kind of "map" skeleton that wraps OneAPI calls hiding hardware targeting issues through some parameter specifying the kind of target (CPU or GPU/Accelerator). In the former case (CPU targeting) the map can be implemented using TBB parallel for and the alike. In the latter (GPU or accelerator) the map should be wrapped on top of SyCL kernels. The Idea is to execute a complex function over each elements of a vector or a set, to understand with increasing of vector size and more complex function it is better to execute my code on GPU or on CPU. I thought also about mandelbrot, Julia set, and Sierpinski Carpets. could you introduce me a famous function for example like Mandelbrot?

Orient point normals using Cgals's mst_orient_normals() while maintaining original point order

Cgals's mst_orient_normals() method modifies the order of input points so as to pack all successfully oriented points first, and returns an iterator over the first point with an unoriented normal. I would like to maintain the order of my input points. To achieve this I currently need to use a dedicated index as shown below (note that this code is indicative only). Is there a more efficient way to achieve this that does not involve adding an index to the tuple and then sorting by this index?

#include <CGAL/pca_estimate_normals.h>
#include <CGAL/mst_orient_normals.h>
#include <CGAL/property_map.h>
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/tags.h>
typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
typedef Kernel::Point_3 Point3;
typedef Kernel::Vector_3 Vector;
typedef std::tuple<int, Point3, Vector> PointVectorTuple;
typedef std::vector<PointVectorTuple> PointListwithindex;
typedef CGAL::Parallel_if_available_tag Concurrency_tag;

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

  unsigned int nb_neighbors_pca_normals = 18; // K-nearest neighbors = 3 rings (estimate normals by PCA)
  unsigned int nb_neighbors_mst = 18; // K-nearest neighbors (orient normals by MST)

  PointListwithindex pointswithindex;

  /**
  Load indices, coordinates, and zero vector (normal in this case) into pointswithindex
  **/

  // Estimates normals direction.
  CGAL::pca_estimate_normals<Concurrency_tag>(pointswithindex,
                                              nb_neighbors_pca_normals,
                                              CGAL::parameters::point_map (CGAL::Nth_of_tuple_property_map<1,PointVectorTuple>()).
                                                      normal_map (CGAL::Nth_of_tuple_property_map<2,PointVectorTuple>()));

  // Orients normals.
  PointListwithindex::iterator unoriented_points_begin =
          CGAL::mst_orient_normals(pointswithindex,
                                   nb_neighbors_mst,
                                   CGAL::parameters::point_map (CGAL::Nth_of_tuple_property_map<1,PointVectorTuple>()).
                                           normal_map(CGAL::Nth_of_tuple_property_map<2,PointVectorTuple>()));

  // Sort list back by into original order using the index
  std::sort(pointswithindex.begin(), pointswithindex.end(),
            [](const PointVectorTuple & a,
               const PointVectorTuple & b) {
                return (std::get<0>(a) < std::get<0>(b));
            });

}

How to sum up elements of a C++ vector "atomically"?

There are kinds of ways of summing up elements of a C++ vector sum up elements of vector, but how to guarantee the "atomically". What I means, during the summing action, the elements of the vector may be modified by other threads, which leads to unknown result. Is there a lock-free way to prevent vector being modified until the summation is complete.

Storing a class that uses the PIMPL idiom in a std::vector

I am writing an application that needs to store objects of a class that uses the PIMPL idiom in a std::vector. Because the class uses std::unique_ptr to store a pointer to it's implementation and std::unique_ptr is not copyable, the class itself is not copyable. std::vector should still work in this case because the class is still movable.

To avoid creating a copy I tried using emplace_back to construct the elements directly into the vector, but for some reason it still complains that it is trying to call the copy constructor!

I've written a simple example to demonstrate the problem.

test.h:

#pragma once

#include <memory>

// Simple test class implemented using the PIMPL (pointer to implementation) idiom
class Test
{
public:
    Test(const int value);
    ~Test();

    void DoSomething();
private:

    // Forward declare implementation struct
    struct Impl;

    // Pointer to the implementation
    std::unique_ptr<Impl> m_impl;
};

test.cpp

#include "test.h"

#include <iostream>

// Implementation struct definition
struct Test::Impl
{
    Impl(const int value)
        : m_value(value)
    {}

    void DoSomething()
    {
        std::cout << "value = " << m_value << std::endl;
    }

private:
    int m_value;
};

// Construct the class and create an instance of the implementation struct
Test::Test(const int value)
    : m_impl(std::make_unique<Impl>(value))
{}

Test::~Test() = default;

// Forward function calls to the implementation struct
void Test::DoSomething()
{
    m_impl->DoSomething();
}

main.cpp:

#include "test.h"

#include <vector>

int main()
{
    std::vector<Test> v;

    // Even though I'm using "emplace_back" it still seems to be invoking the copy constructor!
    v.emplace_back(42);

    return 0;
}

When I try to compile this code I get the following error:

error C2280: 'Test::Test(const Test &)': attempting to reference a deleted function

This leads to two questions...

  1. Why is it attempting to use the copy constructor even though I explicitly used emplace_back?

  2. How can I get this to compile without errors? The object is movable so according to the standard it should be able to be stored in a std::vector.

Automatically downcast a shared_ptr in parent class to child class type

I have a virtual parent class for collecting reports with its associated report struct. The reports should be rendered as a JSON string in the end, so I'm using https://github.com/nlohmann/json to help me with that.

I create different different child classes to generate such reports of the respective child report structs, and the challenge is that each child report may have slightly different fields, but inherit some from the parent. I have the macros that are needed to convert the structs to JSON representation, defined per report type. This is the code so far:

/**
 * Compile with nlohmann json.hpp
 */

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

#include "json.hpp"
using json = nlohmann::json;

struct Report {
  // make abstract
  virtual ~Report() {}
  std::string type = "main_report";
  int foo = 0;
};

struct ChildAReport : public Report {
  std::string type = "child_a_report";
  int bar = 1;
};

struct ChildBReport : public Report {
  std::string type = "child_b_report";
  int baz = 2;
};

NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(ChildAReport, type, foo, bar)
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(ChildBReport, type, foo, baz)

class Parent {
protected:
  std::vector<std::shared_ptr<Report>> reports;
  virtual void run() = 0;
  virtual std::string get_report() = 0;
};

class ChildA : public Parent {
public:
  virtual void run() override
  {
    ChildAReport r;
    r.foo = 1;
    r.bar = 2;
    reports.push_back(std::make_shared<ChildAReport>(r));
  }

  std::string get_report() override {
    std::shared_ptr<Report> r = reports.back();
    std::shared_ptr<ChildAReport> cr = std::dynamic_pointer_cast<ChildAReport>(r);
    json r_json = *cr;
    return r_json.dump();
  }
};

class ChildB : public Parent {
public:
  virtual void run() override
  {
    ChildBReport r;
    r.foo = 1;
    r.baz = 3;
    reports.push_back(std::make_shared<ChildBReport>(r));
  }

  std::string get_report() override {
    std::shared_ptr<Report> r = reports.back();
    std::shared_ptr<ChildBReport> cr = std::dynamic_pointer_cast<ChildBReport>(r);
    json r_json = *cr;
    return r_json.dump();
  }
};

int main(int argc, char *argv[])
{
  ChildA ca = ChildA();
  ca.run();
  std::cout << ca.get_report() << std::endl;

  ChildB cb = ChildB();
  cb.run();
  std::cout << cb.get_report() << std::endl;
}

The code is compiled with json.hpp and no further dependencies.

I am expecting this output:

{"bar":2,"foo":1,"type":"child_a_report"}
{"baz":3,"foo":1,"type":"child_b_report"}

Now, in order to actually generate the JSON, I use the get_report() method. I learned that I have to downcast the pointer to the Report struct to the actual ChildA or ChildB struct, because otherwise it won't properly convert to JSON. This is tedious; as you can see, the code is repeated almost verbatim in every possible child class. The run() function is not the problem – here's where all sorts of magic happens, which differs on a per-class basis.

Is there a way I can pull this up to the parent class without having to explicitly specify the type of cast that is to be made before converting to JSON? Ideally this could be inferred depending on the actual type that get_report() is being run on ...

mardi 29 juin 2021

Message queue for two cpp file with windows API

To send the message in the Queue from one source file and get the message in another source file.I read the docs from Microsoft and try to implement as below

test2.cpp - post the message main.c - get the Message

Testing1: If i execute the same code in single file that get executed and i receive the data

Testing : Same code is written in two separate file "if (msg.message == WM_YOUR_MESSAGE)" these statement does not get satisfied.

/* Unique IDs for Window messages to exchange between the worker and the GUI thread. */
#define WM_YOUR_MESSAGE   ( WM_USER + 3 )

 typedef struct
{
int SomeData1;
int SomeData2;
int SomeDataN;
} MessageData;

volatile DWORD ThreadID_GUI;

void __cdecl ThreadProc(void* aArg)
{
    MessageData* data;

   for (;; )
   {
      Sleep(500);

    /* Allocate memory for a new message data structure */
    data = (MessageData*)malloc(sizeof(*data));

    /* Initialize the message data structure with some information to transfer
       to the GUI thread. */
    data->SomeData1 = 1234;
    data->SomeData2 = 4567;
    data->SomeDataN = 7894;

   PostThreadMessage(ThreadID_GUI, WM_YOUR_MESSAGE, 0, (LPARAM)data);
}  }

main.c

#include<test.h>
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
                 _In_opt_ HINSTANCE hPrevInstance,
                 _In_ LPWSTR    lpCmdLine,
                 _In_ int       nCmdShow)
   {
    UNREFERENCED_PARAMETER(hPrevInstance);
    UNREFERENCED_PARAMETER(lpCmdLine);

// TODO: Place code here.

ThreadID_GUI = GetCurrentThreadId();

/* Start some background thread */
_beginthread(ThreadProc, 0, 0);

// Initialize global strings
LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadStringW(hInstance, IDC_TESTMESSAGEQUEUE, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);

// Perform application initialization:
if (!InitInstance (hInstance, nCmdShow))
{
    return FALSE;
}

HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_TESTMESSAGEQUEUE));

MSG msg;

// Main message loop:
while (GetMessage(&msg, NULL, 0, 0))
{
        /* STEP 3: React on the message sent from the foreign thread */
        if (msg.message == WM_YOUR_MESSAGE)
        {
            MessageData* tmp = (MessageData*)msg.lParam;

                if (tmp->SomeData1 == 1234) {
                printf("someData\n");
            }
            /* Free the data structure associated to the message */
            free(tmp);
        }
        TranslateMessage(&msg);
        DispatchMessage(&msg);
}

return (int) msg.wParam;

}

Equivalent of RcppArmadillo in the R package cpp11

The "new" cpp11 R package is very interesting. I was wondering if there are any plans of implementing something similar to RcppArmadillo which is a huge deal-breaker for Rcpp(Armadillo) users. I know that RcppArmadillo and cpp11 can co-exist which is not really what I had in mind.

Linked list in a class is not removing an element

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

using namespace std;

struct Node
{
    int x;
    Node* next = nullptr;
};

typedef Node* nodeptr;

class L
{
    private: 
        nodeptr head = nullptr;
        int lengthCount = 0;
    public: 
        void add(const int data);
        void print();
        void find(const int data);
        void pop(const int data);
        void listSize();
};

void L:: listSize()
{
    cout << "The size of the link list is:  " << lengthCount << endl;
}

void L::add(const int data)
{
    lengthCount += 1;
    Node* newNode = new Node; 
    newNode->x = data;  
    
    if(head == nullptr)
    {
        head = newNode; 
    }
    else
    {
        nodeptr temp = head;
        while(temp->next != nullptr)
        {
            temp = temp->next;
        }
        temp->next = newNode;
    }
}

void L::pop(const int data)
{
    if(head == nullptr)
    {
        cout << "Empty List" << endl;
    }   
    else if(head->x == data)
    {
        head = head->next;
    }
    else
    {
        nodeptr temp = head->next; 

        while(temp != nullptr)
        {
            if(temp-> x != data)
            {
                temp = temp->next;
            }
            else
            { 
                if(temp->next != nullptr)
                {   
                    temp = temp->next;
                }
                else
                {
                    temp->next = nullptr;
                }
                break;
            }
        }
    }
}

void L::find(const int data)
{
    if(head == nullptr)
    {
        cout << "Empty List" << endl;
    }
    else 
    {
        nodeptr temp = head;
        
        for(temp; temp != nullptr; temp = temp->next)
        {
            if(temp->x == data)
            {
                cout << "Found" << endl;
                break;
            }
            if(temp->next == nullptr)
                cout << "Not Found" << endl;    
        }
    }
}

void L::print()
{
    nodeptr temp = head;
    string line(20,'-');
    cout << "Print list" << endl;
    cout << line << endl;
    while(temp != nullptr)
    {
        cout << temp->x << endl;
        temp = temp->next;
    }
    cout << line << endl;
}

int main()
{
    vector <int> val;
    for(int i = 0; i < 10; i++)
        val.push_back(5*i);
    cout << "Printing list" << endl;
    for(auto i : val)
            cout << i << " ";
    cout << endl;
    L listObj;
    cout << "Adding list" << endl;
    for(auto i : val)
        listObj.add(i);
    listObj.print();
    listObj.listSize();
    listObj.find(15);
    listObj.print();
    cout << "popping 10" << endl;
    listObj.pop(10);
    listObj.print();
}

The problem that I am having is, I am not able to modify the actually memory of a linked list while using a class.

Im not sure what did I do wrong.

If adding works, i would say the idea of removing a value should work as well.

the remove function is called pop. the pop function is not removing the value 10, so i am not sure why.

If it is a function that is not in a class, i would say i need to pass a head pointer with & operator then i can actually modify the value.

Please let me know where did I do wrong.

Thanks

Can map::find and iterator::second be used in one condition

I have such a piece of code:

std::map<int, int> mp;
// do something
auto itor = mp.find(some_value);
if (itor != mp.end() && itor->second == some_other_value) {
    // do something
}

I'm worrying about which expression would be evaluated first, itor != mp.end() or itor->second == some_other_value?

If the second one is evaluated firstly (because of some compiler-optimization maybe?), it might get an undefined behavior because itor == mp.end() may be true.

Should I worry about this issue so that I have to code like this:

if (itor != mp.end) {
    if (itor->second == some_other_value) {
        // do something
    }
}

How to link Boost Regex C++ on Mac from Source?

I have downloaded the whole Boost source from https://www.boost.org/doc/libs/1_72_0/libs/regex/doc/html/index.html and I have the instructions of installation:

tar -vcf boost_1_76_0.tar
./bootstrap.sh --with-toolset=clang --with-libraries=program_options,regex,filesystem,system
./b2
sudo ./b2 install

Then I got a message that everything has been successfully installed:

The following directory should be added to compiler include paths:

    /Users/3omni/Documents/GitHub/PERSONAL/GEN/boost_1_76_0

The following directory should be added to linker library paths:

    /Users/3omni/Documents/GitHub/PERSONAL/GEN/boost_1_76_0/stage/lib

Now, I have a code where I load the Boost regex header:

#include <boost/regex.hpp>

[More code...]

And now the problem is with library linking, I have tried to compile with:

gcc  -I/Users/3omni/Documents/GitHub/PERSONAL/GEN/boost_1_76_0 -L/Users/3omni/Documents/GitHub/PERSONAL/GEN/boost_1_76_0/stage/lib -O3 -o readvcf readvcf.cc -lboost_regex

(Not sure if I should use -lboost_regex but that's something I found in the internet).

And this fails horribly with ...

Undefined symbols for architecture x86_64:
  "std::logic_error::what() const", referenced from:
      vtable for boost::wrapexcept<std::invalid_argument> in readvcf-3b61f4.o
      vtable for boost::wrapexcept<std::logic_error> in readvcf-3b61f4.o
  "std::runtime_error::what() const", referenced from:
      vtable for boost::wrapexcept<std::runtime_error> in readvcf-3b61f4.o
      vtable for boost::regex_error in readvcf-3b61f4.o
      vtable for boost::wrapexcept<boost::regex_error> in readvcf-3b61f4.o
  "std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::compare(char const*) const", referenced from:
      char* boost::re_detail_500::re_is_set_member<char*, char, boost::regex_traits<char, boost::cpp_regex_traits<char> >, unsigned int>(char*, char*, boost::re_detail_500::re_set_long<unsigned int> const*, boost::re_detail_500::regex_data<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > > const&, bool) in readvcf-3b61f4.o
      std::__1::__wrap_iter<char const*> boost::re_detail_500::re_is_set_member<std::__1::__wrap_iter<char const*>, char, boost::regex_traits<char, boost::cpp_regex_traits<char> >, unsigned int>(std::__1::__wrap_iter<char const*>, std::__1::__wrap_iter<char const*>, boost::re_detail_500::re_set_long<unsigned int> const*, boost::re_detail_500::regex_data<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > > const&, bool) in readvcf-3b61f4.o
  "std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::compare(unsigned long, unsigned long, char const*, unsigned long) const", referenced from:
      unsigned int boost::re_detail_500::find_sort_syntax<boost::re_detail_500::cpp_regex_traits_implementation<char>, char>(boost::re_detail_500::cpp_regex_traits_implementation<char> const*, char*) in readvcf-3b61f4.o
      boost::re_detail_500::lookup_default_collate_name(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&) in readvcf-3b61f4.o
  "std::__1::__vector_base_common<true>::__throw_length_error() const", referenced from:
      VCF2SNP(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, int, int) in readvcf-3b61f4.o
      boost::re_detail_500::basic_regex_parser<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::parse_open_paren() in readvcf-3b61f4.o
      boost::re_detail_500::basic_regex_parser<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::parse_alt() in readvcf-3b61f4.o
      boost::re_detail_500::basic_regex_parser<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::parse_perl_extension() in readvcf-3b61f4.o
      void boost::re_detail_500::named_subexpressions::set_name<char>(char const*, char const*, int) in readvcf-3b61f4.o
      boost::re_detail_500::basic_regex_parser<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::parse_set_literal(boost::re_detail_500::basic_char_set<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >&) in readvcf-3b61f4.o
      boost::re_detail_500::basic_regex_creator<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::create_startmaps(boost::re_detail_500::re_syntax_base*) in readvcf-3b61f4.o
      ...
  "std::__1::__vector_base_common<true>::__throw_out_of_range() const", referenced from:
      boost::re_detail_500::basic_regex_parser<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::parse_open_paren() in readvcf-3b61f4.o
      boost::re_detail_500::basic_regex_parser<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::parse_perl_extension() in readvcf-3b61f4.o
  "std::__1::__basic_string_common<true>::__throw_length_error() const", referenced from:
      boost::re_detail_500::cpp_regex_traits_char_layer<char>::init() in readvcf-3b61f4.o
      std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > std::__1::operator+<char, std::__1::char_traits<char>, std::__1::allocator<char> >(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&) in readvcf-3b61f4.o
      boost::re_detail_500::cpp_regex_traits_implementation<char>::lookup_classname(char const*, char const*) const in readvcf-3b61f4.o
      boost::re_detail_500::cpp_regex_traits_implementation<char>::lookup_classname_imp(char const*, char const*) const in readvcf-3b61f4.o
      boost::re_detail_500::cpp_regex_traits_implementation<char>::error_string(boost::regex_constants::error_type) const in readvcf-3b61f4.o
      boost::re_detail_500::cpp_regex_traits_implementation<char>::lookup_collatename(char const*, char const*) const in readvcf-3b61f4.o
      boost::re_detail_500::lookup_default_collate_name(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&) in readvcf-3b61f4.o
      ...
  "std::__1::locale::has_facet(std::__1::locale::id&) const", referenced from:
      boost::re_detail_500::cpp_regex_traits_base<char>::imbue(std::__1::locale const&) in readvcf-3b61f4.o
      std::__1::basic_filebuf<char, std::__1::char_traits<char> >::basic_filebuf() in readvcf-3b61f4.o
  "std::__1::locale::use_facet(std::__1::locale::id&) const", referenced from:
      getAlleles(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::vector<std::__1::vector<bool, std::__1::allocator<bool> >, std::__1::allocator<std::__1::vector<bool, std::__1::allocator<bool> > > >&, int) in readvcf-3b61f4.o
      VCF2SNP(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, int, int) in readvcf-3b61f4.o
      std::__1::basic_filebuf<char, std::__1::char_traits<char> >::imbue(std::__1::locale const&) in readvcf-3b61f4.o
      boost::re_detail_500::cpp_regex_traits_base<char>::imbue(std::__1::locale const&) in readvcf-3b61f4.o
      boost::cpp_regex_traits<char>::toi(char const*&, char const*, int) const in readvcf-3b61f4.o
      std::__1::basic_ostream<char, std::__1::char_traits<char> >& std::__1::__put_character_sequence<char, std::__1::char_traits<char> >(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, char const*, unsigned long) in readvcf-3b61f4.o
      std::__1::basic_filebuf<char, std::__1::char_traits<char> >::basic_filebuf() in readvcf-3b61f4.o
      ...

And much more. Up to:

      _main in readvcf-3b61f4.o
      std::__1::basic_istringstream<char, std::__1::char_traits<char>, std::__1::allocator<char> >::~basic_istringstream() in readvcf-3b61f4.o
      virtual thunk to std::__1::basic_istringstream<char, std::__1::char_traits<char>, std::__1::allocator<char> >::~basic_istringstream() in readvcf-3b61f4.o
      ...
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I have run out of ideas and I cannot find any solution. Please, any help would be really appreciated! Thank you in advance

How to assign a value in const unordered_map to another const variable - C++

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

void fun(const unordered_map<int, vector<int>>& direct_paths) {
    const int var = direct_paths[1][0];
    cout << var;
}

int main()
{
    unordered_map<int, vector<int>> a;
    a[1] = vector<int> {1,2,3};
    fun(a);
    return 0;
}

The above code outputs the following error:

error: passing ‘const std::unordered_map<int, std::vector<int> >’ as ‘this’ argument discards qualifiers [-fpermissive]
  const int var = direct_paths[1][0];
                                ^

Where as The below code doesn't output any compilation error:

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

void fun(const vector<int>& direct_paths) {
    const int var = direct_paths[1];
    cout << var;
}

int main()
{
    vector<int> a;
    a = vector<int> {1,2,3};
    fun(a);
    return 0;
}

Questions:

  1. Can I assign the value in a key-value pair of an unordered_map somehow?
  2. Why is assigning an integer from vector taken from const unordered_map<int, vector&> disallowed? & from const vector allowed?

Thanks in advance!

VEH hook acceleration

I am trying to accelerate the speed of VEH hook. Veh hook class that I found from https://github.com/hoangprod/LeoSpecial-VEH-Hook/blob/master/LeoSpecial.h

#pragma once
#include <Windows.h>
#include <stdio.h>
#include <iostream>

#ifdef _WIN64
#define XIP Rip
#else
#define XIP Eip
#endif



class LeoHook {
public:
    static bool Hook(uintptr_t og_fun, uintptr_t hk_fun);
    static bool Unhook();

private:
    static uintptr_t og_fun;
    static uintptr_t hk_fun;
    static PVOID VEH_Handle;
    static DWORD oldProtection;

    static bool AreInSamePage(const uint8_t* Addr1, const uint8_t* Addr2);
    static LONG WINAPI LeoHandler(EXCEPTION_POINTERS *pExceptionInfo);
};

uintptr_t LeoHook::og_fun = 0;
uintptr_t LeoHook::hk_fun = 0;
PVOID LeoHook::VEH_Handle = nullptr;
DWORD LeoHook::oldProtection = 0;

bool LeoHook::Hook(uintptr_t original_fun, uintptr_t hooked_fun)
{
    LeoHook::og_fun = original_fun;
    LeoHook::hk_fun = hooked_fun;

    //We cannot hook two functions in the same page, because we will cause an infinite callback
    if (AreInSamePage((const uint8_t*)og_fun, (const uint8_t*)hk_fun))
        return false;

    //Register the Custom Exception Handler
    VEH_Handle = AddVectoredExceptionHandler(true, (PVECTORED_EXCEPTION_HANDLER)LeoHandler);

    //Toggle PAGE_GUARD flag on the page
    if(VEH_Handle && VirtualProtect((LPVOID)og_fun, 1, PAGE_EXECUTE_READ | PAGE_GUARD, &oldProtection))
        return true;
    
    return false;
}

bool LeoHook::Unhook()
{
    DWORD old;
    if (VEH_Handle && //Make sure we have a valid Handle to the registered VEH
        VirtualProtect((LPVOID)og_fun, 1, oldProtection, &old) && //Restore old Flags
        RemoveVectoredExceptionHandler(VEH_Handle)) //Remove the VEH
        return true;

    return false;
}

LONG WINAPI LeoHook::LeoHandler(EXCEPTION_POINTERS *pExceptionInfo)
{
    if (pExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_GUARD_PAGE_VIOLATION) //We will catch PAGE_GUARD Violation
    {
        if (pExceptionInfo->ContextRecord->XIP == (uintptr_t)og_fun) //Make sure we are at the address we want within the page
        {
            pExceptionInfo->ContextRecord->XIP = (uintptr_t)hk_fun; //Modify EIP/RIP to where we want to jump to instead of the original function
        }

        pExceptionInfo->ContextRecord->EFlags |= 0x100; //Will trigger an STATUS_SINGLE_STEP exception right after the next instruction get executed. In short, we come right back into this exception handler 1 instruction later
        return EXCEPTION_CONTINUE_EXECUTION; //Continue to next instruction
    }

    if (pExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_SINGLE_STEP) //We will also catch STATUS_SINGLE_STEP, meaning we just had a PAGE_GUARD violation
    {
        DWORD dwOld;
        VirtualProtect((LPVOID)og_fun, 1, PAGE_EXECUTE_READ | PAGE_GUARD, &dwOld); //Reapply the PAGE_GUARD flag because everytime it is triggered, it get removes

        return EXCEPTION_CONTINUE_EXECUTION; //Continue the next instruction
    }

    return EXCEPTION_CONTINUE_SEARCH; //Keep going down the exception handling list to find the right handler IF it is not PAGE_GUARD nor SINGLE_STEP
}

bool LeoHook::AreInSamePage(const uint8_t* Addr1, const uint8_t* Addr2)
{
    MEMORY_BASIC_INFORMATION mbi1;
    if (!VirtualQuery(Addr1, &mbi1, sizeof(mbi1))) //Get Page information for Addr1
        return true;

    MEMORY_BASIC_INFORMATION mbi2;
    if (!VirtualQuery(Addr2, &mbi2, sizeof(mbi2))) //Get Page information for Addr1
        return true;

    if (mbi1.BaseAddress == mbi2.BaseAddress) //See if the two pages start at the same Base Address
        return true; //Both addresses are in the same page, abort hooking!

    return false; 
}

The hook is working fine without any problem. But it cost me a lot of FPS drop from a process that I injected. As I googled the most answer is saying reduce the amount of logic that have been use in hook. My hook method

__declspec(naked) void HookSend()
{
    __asm 
    {
        jmp dwAddress
    }
}

As you see it doesn't have much logic that include in a function. But it still cost me a lot of fps. The research number two is saying to copied all page function then modify the ASM of page function. But I have no idea how to copy a page function. So I need some guide how to copy a page function or another method to accelerate the VEH hook.

Thank you.

How to build CMake version of HDF5 with C++11 ABI?

in our company we are moving to use C++11 ABI, but our code uses HDF5 library. I found the sources for the given version, but just as usual -- open source software comes with zero documentation. I could not figure out how to build it with the C++11 ABI.

Is there a way?

Or better yet, is there a way to just install this version (on RedHat?)

Check resource before and after the lock

I've run into code that simplified looks like this

inline someClass* otherClass::getSomeClass()
{
    if (m_someClass)
        return m_someClass.get();

    std::unique_lock<std::shared_mutex> lock(m_lock);
    if (m_someClass)
        return m_someClass.get();

    m_someClass= std::make_unique<someClass>(this);
    return m_someClass.get();
}

So it seems it's a pattern to be sure thread safety of creation of someClass object. I don't have much experience in multithreading, but this code doesn't look nice to me. Is there some other way to rewrite this or it's a way it should be?

DoEvent() in Windows and Linux errors

I wanted to write a function DoEvent in C++. I found on DoEvents equivalent for C++?

and on In C/C++, which function is like DoEvents( )

Here is the code:

 void DoEvents()
    {
        MSG msg;           // Error 1

        while ( PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE ) )   //Error 2
        {
            if ( GetMessage(&msg, NULL, 0, 0))
            {
                TranslateMessage(&msg);
                DispatchMessage(&msg);
            }
            else
                break;
        }
    }

I have two questions:

Q1. What is the equivalent of DoEvent() in Linux?

Q2.[Resolved] I got errors when I try to use it on windows using Qt creator. resolved by including #include <Windows.h>

Error1 : unknown type name 'MSG'

Error2 : use of undeclared identifier'PM_NOREMOVE'

Any Help, please?

is std::sort safe on this case [duplicate]

I've such a piece of code in my project:

vector<int> vec;
int begin = 0, end = 0;
for(...) {
    for (...) {
        if (x) {
            vec.push_back(some_value);
            end++;
        }
    }
    std::sort(vec.begin() + begin, vec.begin() + end, std::greater<int>());
    begin = end;
}

I'm trying to sort the vector vec piece by piece. But the bool x may be false. In this case, begin equals to end, so it may execute such a code: std::sort(vec.begin() + 3, vec.begin() + 3, std::greater<int>());

Is this safe even if vec.begin() + begin may not be able to be dereferenced? Or must I add a condition as below:

if (begin < end) {
    std::sort(vec.begin() + begin, vec.begin() + end, std::greater<int>());
}

How to impliment subscribe and publish working seperatly in same cpp file [closed]

I am not much familiar with mqtt and am doing an R&D work on the same; How do i run a mosquitto_subscribe() seperate and publish messages seperatly ; ie susbcribed topics will be processed in 5 min interval and messages will be published in 1 sec interval ; The subscriber will be subscribing to seperate topic published from another application, and I am using libmosquitto .

Boost::spirit::qi extract parameters values from the line

I need to parse parameters values from the next line:

#EXT-X-KEY:METHOD=AES-128,URI="http://example.ru/123.key",IV=0x07a6ed33e15beca7f64e57e5137f7fde,KEYFORMAT="identity",KEYFORMATVERSIONS="1/2/3/4/5"

Parameters description:

METHOD (REQUIRED PARAMETER) could contain: NONE, AES-128, SAMPLE-AES values

URI (REQUIRED PARAMETER) is quoted string URL

IV (OPTIONAL PARAMETER) is hexadecimal-sequence, an unquoted string of characters from the set [0..9] and [A..F] that is prefixed with 0x or 0X. The length of IV is 32 symbols except of 0x prefix.

KEYFORMAT (OPTIONAL PARAMETER) is quoted string

KEYFORMATVERSIONS (OPTIONAL PARAMETER) is quoted string containing one or more positive integers separated by the "/" character (for example, "1", "1/2", or "1/2/5")

Also the order of the arguments is not important, i.e the line can take the following form

#EXT-X-KEY:URI="http://example.ru/123.key",IV=0x07a6ed33e15beca7f64e57e5137f7fde,METHOD=AES-128,KEYFORMAT="identity"

I wrote the following code to parse this line, but I'm newest in boost and I understand that this code unefficient, I didn't take into account all the requirements for the IV and KEYFORMATVERSIONS parameters. Also I don't know how to take into account the rule: "the order of the arguments is not important".

Should I inherit from qi::grammar, to wrote separate parser?

If you have any ideas how I can improve this code or how I can take into account all conditions please help me.

enum class KeyMethod {
    NONE,
    AES_128,
    SAMPLE_AES
};

struct KEY_METHOD_ : boost::spirit::qi::symbols<char, KeyMethod> {
    KEY_METHOD_() {
        add
            ("NONE", KeyMethod::NONE)
            ("AES-128", KeyMethod::AES_128)
            ("SAMPLE-AES", KeyMethod::SAMPLE_AES)
        ;
    }
};

// #EXT-X-KEY:<attribute-list>
bool PARSE_EXT_X_KEY(const std::string& line, ParserState& stateObj) {
    stateObj.isMediaPlaylist = true;

    namespace qi = boost::spirit::qi;
    KEY_METHOD_ keyMethod;

    KeyMethod method;
    std::string uri;
    std::string iv;
    std::string keyformat;
    std::string keyformatVersion;

    if (!qi::parse(begin(line), end(line),
        ( "#EXT-X-KEY:" >> 
        ("METHOD=" >> keyMethod) >> 
        (",URI=\"" >> +(qi::char_ - '"') >> '"') >>
        -(",IV=" >> (qi::string("0x") | qi::string("0X")) >> +(qi::char_ - ',')) >>
        -(",KEYFORMAT=\"" >> +(qi::alnum - '"') >> '"') >>
        -(",KEYFORMATVERSIONS=\"" >> +(qi::char_ - '"') >> '"') >>
        qi::eoi ), 
        method,
        uri,
        iv,
        keyformat,
        keyformatVersion)
    ) {
        return false;
    }

    return true;
}

lundi 28 juin 2021

static and dynamic linking in one Visual Studio project [closed]

I want to link some libraries statically and others dynamically in Visual Studio. At least for learning purpose.

I want to link bullet physics statically so I linked these libs BulletDynamics.lib BulletCollision.lib LinearMath.lib Running the code:

#include "btBulletDynamicsCommon.h"
int main(int argc, char** argv)
{
    btDefaultCollisionConfiguration* collisionConfiguration = new btDefaultCollisionConfiguration();
}

it didn't work with this log:

1>------ Build started: Project: btTest, Configuration: Release x64 ------
1>BulletCollision.lib(btDefaultCollisionConfiguration.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MD_DynamicRelease' in Source.obj
1>BulletCollision.lib(btConvexConvexAlgorithm.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MD_DynamicRelease' in Source.obj
1>BulletCollision.lib(btEmptyCollisionAlgorithm.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MD_DynamicRelease' in Source.obj
1>BulletCollision.lib(btConvexConcaveCollisionAlgorithm.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MD_DynamicRelease' in Source.obj
1>BulletCollision.lib(btCompoundCollisionAlgorithm.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MD_DynamicRelease' in Source.obj
1>BulletCollision.lib(btCompoundCompoundCollisionAlgorithm.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MD_DynamicRelease' in Source.obj
1>BulletCollision.lib(btConvexPlaneCollisionAlgorithm.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MD_DynamicRelease' in Source.obj
1>BulletCollision.lib(btBoxBoxCollisionAlgorithm.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MD_DynamicRelease' in Source.obj
1>BulletCollision.lib(btSphereSphereCollisionAlgorithm.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MD_DynamicRelease' in Source.obj
1>BulletCollision.lib(btSphereTriangleCollisionAlgorithm.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MD_DynamicRelease' in Source.obj
1>BulletCollision.lib(btActivatingCollisionAlgorithm.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MD_DynamicRelease' in Source.obj
1>BulletCollision.lib(btPersistentManifold.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MD_DynamicRelease' in Source.obj
1>BulletCollision.lib(btManifoldResult.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MD_DynamicRelease' in Source.obj
1>BulletCollision.lib(btPolyhedralContactClipping.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MD_DynamicRelease' in Source.obj
1>BulletCollision.lib(btCollisionShape.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MD_DynamicRelease' in Source.obj
1>BulletCollision.lib(btConvexShape.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MD_DynamicRelease' in Source.obj
1>BulletCollision.lib(btConvexPolyhedron.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MD_DynamicRelease' in Source.obj
1>BulletCollision.lib(btCollisionAlgorithm.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MD_DynamicRelease' in Source.obj
1>BulletCollision.lib(btPolyhedralConvexShape.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MD_DynamicRelease' in Source.obj
1>BulletCollision.lib(btSdfCollisionShape.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MD_DynamicRelease' in Source.obj
1>BulletCollision.lib(btHashedSimplePairCache.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MD_DynamicRelease' in Source.obj
1>BulletCollision.lib(btMiniSDF.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MD_DynamicRelease' in Source.obj
1>LinearMath.lib(btConvexHullComputer.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MD_DynamicRelease' in Source.obj
1>LinearMath.lib(btGeometryUtil.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MD_DynamicRelease' in Source.obj
1>LINK : warning LNK4098: defaultlib 'LIBCMT' conflicts with use of other libs; use /NODEFAULTLIB:library
1>C:\Users\Alexey\source\repos\btTest\x64\Release\btTest.exe : fatal error LNK1319: 24 mismatches detected
1>Done building project "btTest.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

So I googled my problem and I knew that Visual Studio expects dynamic linking. In order to change that behavior I changed Runtime library to Multi-threaded (/MT) in C/C++ Code Generation. And the code just worked. Which is great.

But if I am adding openGL using glfw + glad with libs glfw3.lib and opengl32.lib. Running this code (which works with default Runtime option).

#include <glad/glad.h> #include <GLFW/glfw3.h>

int main(int argc, char** argv)
{
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    }

I got this log:

1>------ Build started: Project: btTest, Configuration: Release x64 ------ 1>LINK : warning LNK4098: defaultlib 'MSVCRT' conflicts with use of other libs; use /NODEFAULTLIB:library 1>glfw3.lib(window.obj) : error LNK2001: unresolved external symbol __imp_strncpy 1>glfw3.lib(input.obj) : error LNK2001: unresolved external symbol __imp_strncpy 1>glfw3.lib(win32_joystick.obj) : error LNK2001: unresolved external symbol __imp_strncpy 1>glfw3.lib(input.obj) : error LNK2001: unresolved external symbol __imp_strcspn 1>glfw3.lib(input.obj) : error LNK2001: unresolved external symbol __imp_strspn 1>glfw3.lib(input.obj) : error LNK2001: unresolved external symbol __imp_realloc 1>glfw3.lib(win32_monitor.obj) : error LNK2001: unresolved external symbol __imp_realloc 1>glfw3.lib(monitor.obj) : error LNK2001: unresolved external symbol __imp_realloc 1>glfw3.lib(context.obj) : error LNK2001: unresolved external symbol __imp___stdio_common_vsscanf 1>C:\Users\Alexey\source\repos\btTest\x64\Release\btTest.exe : fatal error LNK1120: 5 unresolved externals 1>Done building project "btTest.vcxproj" -- FAILED. ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

So how could I use both these bullet physics openGL libraries? This is part of C++ that I really have problem with and which also scares me. So any suggestions of how I could improve in that aria will be appreciated.

How to pass smart pointer instead of "this" in C++ 11?

I am using C++ 11 compiler. I have two classes - class Test and class TestHelper. The class Test is a friend-to-class TestHelper. The class Test is only which we can access from outside. Now, we want to call Test API i.e. setVal(). This setVal() should call Test2 API i.e. setX and is expecting this pointer. I don't want to use this pointer but want to use a smart pointer instead. How can I do so? The notion of this kind of desirability is because of the fact that in reality, my class Test is pretty big. So, I am trying to make a helper class for Test i.e.

class TestHelper;

class Test
{
    friend class TestHelper;
    int x;
public:
    void display() {
        std::cout << x;
     }
    void setVal(int val) {
        TestHelper testH;
        testH.setX(this, 324);
    }
};

class TestHelper
{
public:
    void setX(Test *test, int val) {
        /** some algorithm here and then  change val to something else */
        test->x = val*100;
    }
};

int main()
{
    std::cout << "Hello World!\n";
    Test x;
    x.setVal(130);
}

I tried changing the prototype from void setX(Test *test, int val) to void setX( std::shared_ptr test, int val) but don't know how to pass this pointer as std::shared_ptr test here.

Generate executable a.out from cpp mentioned in .pro file in yocto build

I am using yocto build. I have .pro files and recipes(.bb) which build all cpp files present in .pro file. Recently I added two new cpp file i.e. gtest_main.cpp and lgeplugin_Test.cpp in .pro file. As show below

lgeplugin.pro

QMAKE_CXXFLAGS += -g
QMAKE_CFLAGS += -g
CFLAGS += \
           -Wall \
          -Wextra \
          -fPIC \
          -std=c++11



TARGET = lgeplugin
TEMPLATE = lib

message(Building)

INCLUDEPATH += ${Root}/include/ALL \
               ${Root}/include/gtest \

 DEFINES += USE_LGE_TREE
 SOURCES += ../../src/lgeplugin.cpp

 contains(DEFINES, LGE_PLUGIN) {
   
SOURCES     += \
                ../../src/internalclient.cpp \
                ../../src/Event.cpp \
                ../../src/gtest_main.cpp \
                ../../src/lgeplugin_Test.cpp
LIBS += -lLGEFramework -lgtest
    } 

lgeplugin.bb

QMAKE_PROFILES = "${S}/lgeplugin.pro"
do_install() {
        install -d ${D}/usr/lib
        cp -a ${B}/liblgeplugin.so* ${D}/usr/lib
}

Requirement : I need executable(a.out) of the newly added file i.e. gtest_main.cpp and lgeplugin_Test.cpp

Include different file with defining preprocessor variable

I saw very nice example for using different classes using -D compile switch.

However, in my use case, the thing is bit different and I can don't know how to do it.

For multiplexing API, I have 3 classes in 3 different files:

poll.h   -> class PollSelector   -> generic poll() works everywhere
epoll.h  -> class EPollSelector  -> Linux only epoll support
kqueue.h -> class KqueueSelector -> MacOS only kqueue

All 3 clases have same methods, so I use:

#include "selector/poll.h"
using MySelector = PollSelector;

I am thinking, if there a way to be able to do it with -D switch, but in same time, if I add additional multiplexing class, to be able to switch it only with -D flag, without edit the file that use it.

The way I imaging it is to have command like:

gcc -Dkqueue file.h

this automatically do

#include "selector/kqueue.h";
using MySelector = kqueue_selector; // I will do this typedef in kqueue.h so it will compile

Can this be done in clean way, without "diving" in C preprocessor?

Here are the original link to source
https://github.com/nmmmnu/HM4/tree/master/net/selector

Problem reading a formatted text file in C++

High guys, officially my first post. I'm sure the Stack is full of answers, but the problem that I need help with is a little bit specific. So here goes nothing...

The Task:

I'm doing a small school project and in one part of my program I need to read the temperature measurements at different locations, all from a single formatted text file. The data inside the file is written as follows:

23/5/2016
Location 1
-7,12,-16,20,18,13,6
9/11/2014
Location 2
−1,3,6,10,8
9/11/2014
Location 3
−5,−2,0,3,1,2,−1,−4

The first row represents the date, second row the location and the third row represents the all the measurements the were taken on that day (degrees Celsius). The code that I wrote for this part of the program looks something like this:

tok.seekg(0, std::ios::beg);
int i = 0;
double element;
char sign = ',';
while (!tok.eof()) {
vector_measurements.resize(vektor_measurements.size() + 1);
tok >> vektor_measurements.at(i).day >> sign >> vektor_measurements.at(i).month >>
    sign >> vektor_measurements.at(i).year >> std::ws;
std::getline(tok, vektor_measurements.at(i).location);
sign = ',';
while (tok && sign == ',') {
  tok >> element;
  vektor_measurements.at(i).measurements.push_back(element);
  sign = tok.get();
}
if (!tok.eof() && !tok) {
  tok.clear();
  break;
}
vektor_measurements.at(i).SetAverage();
i++;

The code that I'm presenting is linked to a class:

struct Data {
  std::string location;
  std::vector<int> measurements;
  int day, month, year;
  double average = 0;

  void SetAverage();
  int GetMinimalTemperature();
  int GetMaximalTemperature();
};

I've already checked and confirmed that the file exists and the stream is opened in the correct mode without any errors; all class methods working as intended. But here's the problem. Later on, after the data is sorted (the part of data that has been successfully read), it fails to correctly print the data on the screen. I get something like:

Location 2
Date: 9/11/2014
Minimal temperature: 0
Maximal temperature: 0
Average temperature: 0

Location 1
Date: 23/5/2016
Minimal temperature: -16
Maximal temperature: 20
Average temperature: 6.57143

; but I expect:

Location 3
----------
Date: 9/11/2014
Minimal temperature: -5
Maximal temperature: 3
Average temperature: -0.75

Location 2
----------
Date: 9/11/2014
Minimal temperature: -1
Maximal temperature: 10
Average temperature: 5.20

Location 1
----------
Date: 23/5/2016
Minimal temperature: -16
Maximal temperature: 20
Average temperature: 6.57143

The Problem:

The order of the locations is good, since I'm sorting from the lowest to the highest average temperature. But no matter the number of locations, the first location is always correct, the second one only has zero's, and every other location isn't even printed on the screen. What do I need to change in order for my program to read the data properly? Or am I just missing something? Forgive me for any spelling mistakes I made since English isn't my native language. Thank you all in advance, any help is appreciated!

GetQueuedCompletionStatus returns back error 327 (0x147)

I am using GetQueuedCompletionStatus like this

 BOOL ret = GetQueuedCompletionStatus(ReadPort,
                                            &NumberBytes,
                                            &Key,
                                            &CompletedOverlapped,
                                            INFINITE); 
        if (!ret)
        {
            DWORD lastError = GetLastError();
            printf("IOCP error %u\n", lastError);
            break;
        }

Every now and then I would get an error of 327 (0x147) which I am not sure why ? Any suggestions on why this might be happening ?

For reference this is 327 error description: 327 (0x147)

The command specified a data offset that does not align to the device's granularity/alignment.

What changed with "converting constructor"s at C++11? [duplicate]

Today I was surprised by this paragraph at cppreference:

Converting constructor

A constructor that is not declared with the specifier explicit and which can be called with a single parameter (until C++11) is called a converting constructor.

The "(until C++11)" bit seems to be referring to the phrase "which can be called with a single parameter".

I didn't know this changed at C++11. What's the change? What kind of "converting constructor" can take more than one argument? (If that's what it is referring to.)

(I suppose it could be referring to constructors that have more than one argument but those extra arguments - or all of them - have default values. But default values for arguments have been in C++ forever. So did something change there - before C++11 you couldn't implicitly convert with a constructor that took default arguments? But this example at wandbolt shows that that did work in C++03.)

Dynamic Programming C++ | MAXSUB3CONS [closed]

Subsequence that does not contain 3 adjacent elements in the sequence Initially Given a sequence of N positive integer elements. Find the maximum sum of the subsequences obtained from the original sequence for no three consecutive elements in the first sequence in the subsequence)

Input:

  • An integer N is the number of elements (1 ≤ 1000)
  • The second line writes N integers in the sequence, the elements have values in [1,104] Output:- Print an integer that is the maximum sum

Example: 1. Input: 3 1 2 3 Output: 5

2. Input: 5 3000 2000 1000 3 Output: 5013

  • The sequence arr={1,2,3} is the sequence with the largest sum of {2,3} because it is not possible to select all 3 elements into the sequence child
  • The sequence arr[] = {3000, 2000, 1000, 3, 10} has the sequence 3000 + 2000 + 3 + 10 = 5013

Can you help me that?

How do I make the map CONTAINER be allocated on the heap?

Basically I have this map container :

map <int, double> r_t_plus_1;

I know that r_t_plus_1 is on the stack, and its elements go into dynamic allocation. I want to know whether I can get the container on heap, through an allocator property or is there any better way to do so?

Is this request frequency limiter thread safe?

In order to prevent excessive server pressure, I implemented a request frequency limiter using a sliding window algorithm, which can determine whether the current request is allowed to pass according to the parameters. In order to achieve the thread safety of the algorithm, I used the atomic type to control the number of sliding steps of the window, and used unique_lock to achieve the correct sum of the total number of requests in the current window. But I'm not sure whether my implementation is thread-safe, and if it is safe, whether it will affect service performance. Is there a better way to achieve it?

class SlideWindowLimiter
{
public:
  bool TryAcquire();
  void SlideWindow(int64_t window_number);

private:
  int32_t limit_;   // maximum number of window requests
  int32_t split_num_;   // subwindow number
  int32_t window_size_; // the big window
  int32_t sub_window_size_;  // size of subwindow = window_size_ / split_number
  
  int16_t index_{0};  //the index of window vector
  std::mutex mtx_;
  std::vector<int32_t> sub_windows_;  // window vector 
  std::atomic<int64_t> start_time_{0};  //start time of limiter
}

bool SlideWindowLimiter::TryAcquire() {
   int64_t cur_time = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
   auto time_stamp = start_time_.load();
   int64_t window_num = std::max(cur_time - window_size_ - start_time_, int64_t(0)) / sub_window_size_;
    
   std::unique_lock<std::mutex> guard(mtx_, std::defer_lock);
   if (window_num > 0  && start_time_.compare_exchange_strong(time_stamp, start_time_.load() + window_num*sub_window_size_)) {
     guard.lock();
     SlideWindow(window_num);
     guard.unlock();
   }
 
   monitor_->TotalRequestQps();
   {
     guard.lock();
     int32_t total_req = 0;
     std::cout<<" "<<std::endl;
     for(auto &p : sub_windows_) {
       std::cout<<p<<" "<<std::this_thread::get_id()<<std::endl;
       total_req += p;
     }
 
     if(total_req >= limit_) {
       monitor_->RejectedRequestQps();
       return false;
     } else {
       monitor_->PassedRequestQps();
       sub_windows_[index_] += 1;
       return true;
     }
     guard.unlock();
   }
 }

void SlideWindowLimiter::SlideWindow(int64_t window_num) {
   int64_t slide_num = std::min(window_num, int64_t(split_num_));  
   for(int i = 0; i < slide_num; i++){
     index_ += 1;
     index_ = index_ % split_num_;
     sub_windows_[index_] = 0;
   }
 }

dimanche 27 juin 2021

repeated error sstream: No such file or directory

From this tutorial site, I ran this code below as .c file,

#include<graphics.h>
#include<stdio.h>
#include<conio.h>

void main(void) {
    int gdriver = DETECT, gmode;
    int x1 = 200, y1 = 200;
    int x2 = 300, y2 = 300;
    clrscr();

    initgraph(&gdriver, &gmode, "c:\\turboc3\\bgi");
    line(x1, y1, x2, y2);
    getch();
    closegraph();
}

Unfortunately, I got this error

[Error] sstream: No such file or directory

From this site, I saved the code in .cpp file and I ran it successfully without any error. However, no graphic drawing shows, its only the command prompt that appears. This link did not work either. Please, is there any workaround to make it work.

Note: I use TDM-GCC 4.9.2 64-bit Release

How do I find out the type of this map in a range based for loop?

map <int, map <int, double> > adj_list_M;

I want to run a range based for loop, iterating through this map, and using auto is risky. So I want to know the type I can use for getting the references of the elements.

Also please verify whether this is correct for doing that :

for( auto& ele : adj_list_M )

Thank you in advance!

Qt: Qt 6.1.1 Failed to create vertex shader: Error 0x80070057

Guys! I'm a new user of qt and I faced a problem with qml. This issue has already been discussed in this article, but for python. I write in C ++/Qt 6.1.1, QtCreator 4.15.1 for open source. Help me please.

Here is the crux of the problem: qml does not work, Application output writes the following message: "Failed to create vertex shader: Error 0x80070057: ???????? ????? ???????. Failed to build graphics pipeline state ".

The Qt documentation says that this is because of "Scene Graph Adaptations". Here is the link: https://doc-snapshots.qt.io/qt6-dev/qtquick-visualcanvas-adaptations.html.

I tried to use this method from the article in main: QQuickWindow :: setSceneGraphBackend ("QT_QUICK_BACKEND"); For it, you also need to include the library QQuickWindow.

However, Qt gives the following error: Could not create scene graph context for backend 'QT_QUICK_BACKEND' - check that plugins are installed correctly in C: /Qt/6.1.1/mingw81_64/plugins Here I no longer understand what to do ...

I provide the code for clarity. Since in qml it is enough to create a window and include the Rectangle {} in it.

I took the code from the example (tried 3 QtQuick examples). Here is the main function code:

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickWindow>

int main(int argc, char *argv[])
{
    QQuickWindow::setSceneGraphBackend("QT_QUICK_BACKEND");
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl("qrc:/sidepanel.qml"));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

QML code:

import QtQuick
import QtQuick.Controls

ApplicationWindow {
    id: window
    width: 360
    height: 520
    visible: true
    title: qsTr("Side Panel")

    //! [orientation]
    readonly property bool inPortrait: window.width < window.height
    //! [orientation]

    ToolBar {
        id: overlayHeader

        z: 1
        width: parent.width
        parent: Overlay.overlay

        Label {
            id: label
            anchors.centerIn: parent
            text: "Qt Quick Controls"
        }
    }

    Drawer {
        id: drawer

        y: overlayHeader.height
        width: window.width / 2
        height: window.height - overlayHeader.height

        modal: inPortrait
        interactive: inPortrait
        position: inPortrait ? 0 : 1
        visible: !inPortrait

        ListView {
            id: listView
            anchors.fill: parent

            headerPositioning: ListView.OverlayHeader
            header: Pane {
                id: header
                z: 2
                width: parent.width

                contentHeight: logo.height

                Image {
                    id: logo
                    width: parent.width
                    source: "images/qt-logo.png"
                    fillMode: implicitWidth > width ? Image.PreserveAspectFit : Image.Pad
                }

                MenuSeparator {
                    parent: header
                    width: parent.width
                    anchors.verticalCenter: parent.bottom
                    visible: !listView.atYBeginning
                }
            }

            footer: ItemDelegate {
                id: footer
                text: qsTr("Footer")
                width: parent.width

                MenuSeparator {
                    parent: footer
                    width: parent.width
                    anchors.verticalCenter: parent.top
                }
            }

            model: 10

            delegate: ItemDelegate {
                text: qsTr("Title %1").arg(index + 1)
                width: listView.width
            }

            ScrollIndicator.vertical: ScrollIndicator { }
        }
    }

    Flickable {
        id: flickable

        anchors.fill: parent
        anchors.topMargin: overlayHeader.height
        anchors.leftMargin: !inPortrait ? drawer.width : undefined

        topMargin: 20
        bottomMargin: 20
        contentHeight: column.height

        Column {
            id: column
            spacing: 20
            anchors.margins: 20
            anchors.left: parent.left
            anchors.right: parent.right

            Label {
                font.pixelSize: 22
                width: parent.width
                elide: Label.ElideRight
                horizontalAlignment: Qt.AlignHCenter
                text: qsTr("Side Panel Example")
            }

            Label {
                width: parent.width
                wrapMode: Label.WordWrap
                text: qsTr("This example demonstrates how Drawer can be used as a non-closable persistent side panel.\n\n" +
                           "When the application is in portrait mode, the drawer is an interactive side panel that can " +
                           "be swiped open from the left edge. When the application is in landscape mode, the drawer " +
                           "and the content are laid out side by side.\n\nThe application is currently in %1 mode.").arg(inPortrait ? qsTr("portrait") : qsTr("landscape"))
            }
        }

        ScrollIndicator.vertical: ScrollIndicator { }
    }
}

Why is the map value not updating?

I have this free function in my code :

void changeRanks(int n, map<int, double>& id_rank_map)
{
  cout << "n : " << n << endl;
  
  for(auto itr : id_rank_map)
  {
    itr.second = double(1) / double(n);
  }
}

I've verified that 'n' is not 0, but still each value in 'id_rank_map' is 0.00 even after the execution of the line inside the for loop, when accessed from the 'main' function.

How do I update this?

Implement the custom move constructor and assignment for my problem

I wrote the c++ code, because im learning c++ and practicing struct, class, move ctr, copy constructor, inheritance, unique pointer, etc. however, It provided me the following problem that x3 and rrr are suffering from linkage issue, means, it is just a simple copy by value and both pointers are pointing to the same memory location. I dont know how to implement the custom move constructor and assignment for my problem to solve this issue?

#include <iostream>
#include<memory>


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

    void show();
    family();
    ~family();
    family(int i, int j, int k);


    family& operator = (const family& v); //l -value ref
    family& operator=(family&& v);

};


void family::show(){
    std::cout<< x << y << z <<std::endl;
}

family::family(int i, int j, int k)
:x{i},y{j},z{k}
{std::cout << "custom ctor\n";}

family::family()=default;
family::~family()= default;


struct family2{
    int xx{};
    int yy{};
    virtual void show() const noexcept { std::cout << "Bau\n"; }
    family2();
    ~family2();
    family2(  int f,  int g);
    
};


family2::family2()=default;
family2::~family2()= default;
family2::family2(  int f,  int g) : xx{f},yy{g}{}


struct pr : public family2{
    pr() = default;
    ~pr()= default;
    pr(  int xx,  int yy) : family2{xx, yy} {}
    void show() const noexcept override { std::cout << "mau\n"; }

};

int main(){

family kkk{1,2,3};
kkk.show();

family lll;
lll.x= 8;
lll.show();


auto ooo= std::make_unique< family> (7,8,9);
ooo->show();


std::unique_ptr <family> unq (new family (88,88,88));
//std::unique_ptr <family> ppp (88,88,88); error
unq->show();

std::unique_ptr <family >unq2 (std::move(unq));
unq2->show();

unq.reset(new family(9,9,90));
unq->show();


family *uu = unq.release();
//uu->x= 999999;
uu->show();

if(unq == nullptr)
    std::cout<< "oooo" <<std::endl;

 family2* rrr = new pr{11, 11};  // daynamic polymorphysem
    std::cout << "through pointer\n";
    rrr->show();

family2 *x3{std::move(rrr)};  // move ctor
x3->show();

}


Error of defining brace-enclosed initializer list when I use std::move

I wrote the c++ code, because im learning c++ and practicing struct, class, move ctr, copy constructor, inheritance, unique pointer, etc. however, It provided me the following error when I want to use std::move in the last line of code with the raw pointer, does anyone knows how can I solve the issue?

#include <iostream>
#include<memory>


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

    void show();
    family();
    ~family();
    family(int i, int j, int k);


    family& operator = (const family& v); //l -value ref
    family& operator=(family&& v);

};


void family::show(){
    std::cout<< x << y << z <<std::endl;
}

family::family(int i, int j, int k)
:x{i},y{j},z{k}
{std::cout << "custom ctor\n";}

family::family()=default;
family::~family()= default;


struct family2{
    int xx{};
    int yy{};
    virtual void show() const noexcept { std::cout << "Bau\n"; }
    family2();
    ~family2();
    family2(  int f,  int g);
    
};


family2::family2()=default;
family2::~family2()= default;
family2::family2(  int f,  int g) : xx{f},yy{g}{}


struct pr : public family2{
    pr() = default;
    ~pr()= default;
    pr(  int xx,  int yy) : family2{xx, yy} {}
    void show() const noexcept override { std::cout << "mau\n"; }

};

int main(){

family kkk{1,2,3};
kkk.show();

family lll;
lll.x= 8;
lll.show();


auto ooo= std::make_unique< family> (7,8,9);
ooo->show();


std::unique_ptr <family> unq (new family (88,88,88));
//std::unique_ptr <family> ppp (88,88,88); error
unq->show();

std::unique_ptr <family >unq2 (std::move(unq));
unq2->show();

unq.reset(new family(9,9,90));
unq->show();


family *uu = unq.release();
//uu->x= 999999;
uu->show();

if(unq == nullptr)
    std::cout<< "oooo" <<std::endl;

 family2* rrr = new pr{11, 11};  // daynamic polymorphysem
    std::cout << "through pointer\n";
    rrr->show();

family2 x3{std::move(rrr)};  // move ctor
x3->show();

}



no matching function for call to 'family2::family2(<brace-enclosed initializer list>)'
   94 | family2 x3{std::move(rrr)};  // move ctor
      |                          ^
tam5.cpp:47:1: note: candidate: 'family2::family2(int, int)'
   47 | family2::family2(  int f,  int g) : xx{f},yy{g}{}
      | ^~~~~~~
tam5.cpp:47:1: note:   candidate expects 2 arguments, 1 provided
tam5.cpp:45:1: note: candidate: 'family2::family2()'
   45 | family2::family2()=default;
      | ^~~~~~~
tam5.cpp:45:1: note:   candidate expects 0 arguments, 1 provided
tam5.cpp:34:8: note: candidate: 'constexpr family2::family2(const family2&)'
   34 | struct family2{
      |        ^~~~~~~
tam5.cpp:34:8: note:   no known conversion for argument 1 from 'std::remove_reference<family2*&>::type' {aka 'family2*'} to 'const family2&'
tam5.cpp:95:3: error: base operand of '->' has non-pointer type 'family2'
   95 | x3->show();
      |   ^~


What is const & method in C++

I saw code like that.

What this & means and what is the official name of this kind of methods?

struct S{
    int get() const &{
        return 5;
    }
};

int main(){
    S s;
    return s.get();
}

decltype and auto feature in C++11

why both auto and decltype. cant auto only solve the purpose ?? what is output of this program Can someone give an example how auto and decltype is used in templates

 template <class A, class B>
auto findMin(A a, B b) -> decltype(a < b ? a : b)
{
    return (a < b) ? a : b;
}
  
// driver function to test various inference
int main()
{
    // This call returns 3.44 of doubale type
    cout << findMin(4, 3.44) << endl;
  
    // This call returns 3 of double type
    cout << findMin(5.4, 3) << endl;
  
    return 0;
}

multiple definition of `var'; obj/Class.o:(.bss+0x0): first defined here

I have a GlobalVars.h file in which I declare some variables (mutexes, condition_variables, ints...) that I want to use from other cpp files. In those cpp files, I include that GlobalVars.h with include guards, and when I compile the whole project, it gives me the next error:

g++ -o exec/Manager obj/Manager.o -pthread -std=c++11 obj/PaySystem.o obj/SSOOIIGLE.o 
/usr/bin/ld: obj/PaySystem.o:(.bss+0x40): multiple definition of `semMutexPay'; obj/Manager.o:(.bss+0x0): first defined here
/usr/bin/ld: obj/PaySystem.o:(.bss+0x80): multiple definition of `waitPayFinish'; obj/Manager.o:(.bss+0x40): first defined here
/usr/bin/ld: obj/PaySystem.o:(.bss+0x210): multiple definition of `counter'; obj/Manager.o:(.bss+0x1d0): first defined here
...

My files: GlobalVars.h:

std::mutex semMutexPay;
std::mutex waitPayFinish;
int counter;

PaySystem.cpp:

#ifndef __VARS_H__
#define __VARS_H__
#include "GlobalVars.h"
#endif

void PaySystem::operator()() {
  while(true) {
    std::unique_lock<std::mutex> ulPayQueue(semMutexPay);
    if (counter > 5)
      doOtherStuff();
  }
}

Manager.cpp:

#ifndef __VARS_H__
#define __VARS_H__
#include "GlobalVars.h"
#endif
#ifndef __PAY_SYSTEM_H__
#define __PAY_SYSTEM_H__
#include "SistemaPago.h"
#endif

int main(int argc, char *argv[]) {
  PaySystem ps;
  std::thread paySystemThread(ps);
  doSomeStuff();
}

void someMethod() {
  counter++;
}

My makefile:

DIROBJ := obj/
DIREXE := exec/
DIRHEA := include/
DIRSRC := src/

CFLAGS := -I $(DIRHEA) -c -Wall -ansi
LDLIBS := -pthread -std=c++11
CC := g++

all: dirs PaySystem Manager 

dirs:
    mkdir -p $(DIROBJ) $(DIREXE)

Manager: $(DIROBJ)Manager.o
    $(CC) -o $(DIREXE)$@ $^ $(LDLIBS) $(DIROBJ)PaySystem.o

PaySystem: $(DIROBJ)SistemaPago.o

$(DIROBJ)%.o: $(DIRSRC)%.cpp
    $(CC) $(CFLAGS) $^ -o $@ $(LDLIBS)

clean: 
    rm -rf *~ core $(DIROBJ) $(DIREXE) $(DIRHEA)*~ $(DIRSRC)*~

I tried doing the include guard in other ways but none works.

how does new operator works in this C++ escape code expression must have a constant value

I tried to create an array like this

#include <iostream>

int main()
{
    int row, col;
    int arr[row][col]; //expression must have a constant value
}

but that didn't work so searched and then I found this code

    int row, col;
    std::cin >> row >> col;
    int** arr = new int* [row];
    for (int i = 0; i < row; i++)
        arr[i] = new int[col];

    // use the array

    //deallocate the array
    for (int i = 0; i < row; i++)
        delete[] arr[i];
    delete[] arr;

can someone explain this code to me and say how does it work?

samedi 26 juin 2021

This code worked on visual studio code but wouldn't work in visual studio 2019

I have this code that converts a wave file into an array of ints in order to send it to a server.

-This code worked well in visual studio code but didn't work on visual studio 2019 and it keeps giving me this error, can you please help me.

-I want it to work in visual studio 2019 because I used to work with it for unreal and also I don't have that much time to adapt to visual studio code with unreal because the project deadline is really soon.

This is The Code:

            #include <iostream>
            #include <fstream>
            #include <cstring>
            #include <cstdlib>
            using namespace std;
            
            struct WavData{
                public:
                    int16_t* data;
                    long size;
                    
                    WavData(){
                        data=NULL;
                        size=0;
                    }   
            };
            
            
            void loadWavFile(const char* filePath,WavData *ret){
                FILE* wavFile=fopen(filePath,"r");
                if(wavFile){
                    cout<<"wav file has been opened"<<endl;
                    char id[5];
                    int32_t size;
                    int16_t format_tag,channels,block_align,bits_per_sample;
                    int32_t format_length,sample_rate,avg_bytes_sec,data_size;      
                    
                    fread(id,sizeof(char),4,wavFile);
                    id[4]='\0';
                    
                    if(!strcmp(id,"RIFF")){
                        fread(&size,sizeof(int16_t),2,wavFile);
                        fread(id,sizeof(char),4,wavFile);
                        id[4]='\0';
            
                        if(!strcmp(id,"WAVE")){
                            fread(id,sizeof(char),4,wavFile);
                            fread(&format_length,sizeof(int16_t),2,wavFile);
                            fread(&format_tag,sizeof(int16_t),1,wavFile);
                            fread(&channels,sizeof(int16_t),1,wavFile);
                            fread(&sample_rate,sizeof(int16_t),2,wavFile);
                            fread(&avg_bytes_sec,sizeof(int16_t),2,wavFile);
                            fread(&block_align,sizeof(int16_t),1,wavFile);
                            fread(&bits_per_sample,sizeof(int16_t),2,wavFile);
                            fread(id,sizeof(char),4,wavFile);
                            fread(&data_size,sizeof(int16_t),2,wavFile);
                            
                            ret->size=data_size/sizeof(int16_t);
                            // Dynamically allocated space, remember to release
                            ret->data=(int16_t*)malloc(data_size);
                            fread(ret->data,sizeof(int16_t),ret->size,wavFile);
                        }
                        else{
                            cout<<"Error: RIFF File but not a wave file\n";
                        }
                    }
                else{
                    cout<<"ERROR: not a RIFF file\n";
                }
                }
                fclose(wavFile);
            }
            
            void freeSource(WavData* data){
                free(data->data);
            }
            
            int main(){
                WavData song;
                ofstream out("Another.txt");
                const char* fname="Another.wav"; 
                loadWavFile(fname,&song);
                cout<<song.size<<endl;
            
                for(long i=0;i<song.size;i++){
                    out<<song.data[i]<<',';
                }
            
                out.close();

                freeSource(&song);
                return 0;
            }

This is the bug it gives when it stops debugging

These are the warnings it gives after compiling

How can I create an iterator of a range of indexes in C++11?

I'm working with an API that takes a start and end iterator, and runs async work on the objects in that range. However, in one case I want to iterate over indexes of objects, not objects (from 0 to myVector.size() - 1). I could create a simple vector of those indexes and use its .begin() and .end() iterators, but that has unacceptable performance overhead.

What's the easiest way to create two iterators, where iterating from the first one to the second takes you from 0 to N?

How to slowdown an output character by character? (Mac OS)

My goal is to output a string of characters one by one. But when I run it, it staggers and ends up just outputting the entire string with no delay in-between characters. I am currently running this code on a Mac operating system.

#include <iostream>
#include <thread>
#include <chrono>

/**
    Asks user to input name.
    @param usrName Displays the the prompt asking for their name.
*/
void displaySequence(std::string usrName);

int main() {
    std::string prompt = "Name: ";
    std::string clientName;

    displaySequence(prompt);
    std::cin >> clientName;
    

    return 0;
}

void displaySequence(std::string usrName) {
    for (int i = 0; i < (int) usrName.length(); i++) {
        std::cout << usrName.at(i) << " ";
        std::this_thread::sleep_for(std::chrono::milliseconds(20));
    }
}

What will I have to write in my program so that it would only accept commas in their proper location (i.e. cannot input 10,00.0 , 100,0.2334, etc)?

I am taking a summer course in computer science, and I get assigned two projects a week, so bear with me if I'm getting some terminology wrong.

This week, I was able to get the first one done, but not the second one. In the second assignment, we were required to rewrite the ReadDouble function so that it's more user-friendly; user-friendly as in allowing the user to input commas along with numbers. Additionally,

  1. we were required to allow the first character to be a number, plus or minus sign, or a decimal point.

  2. All other characters can be a number, comma, or decimal point (if there already wasn't one).

  3. As mentioned, commas must be written in properly (we can't allow the user to input 10,00.244, 343,2.334, or some nonsensical number like that).

  4. No commas should be allowed after the decimal point.

  5. Only one decimal point should be allowed in the number.

So far, I was able to able to meet 1), 2), and 5). 3) and 4)? Not so much.

The underlying issue is that I don't know what classes, objects, and whatnot I should be using to make the program read the string input and determine if the commas were inserted properly. I have an idea that I would need to use something similar to the "input.length()" code, set it as a variable that can be compared in an if statement to ensure that the amount of digits until the next comma can be used is met.

I also tried writing a for loop that would check after the decimal place for commas or any other invalid character, but I didn't know what to write down as its initialization. How would I get the for loop to start looking from the decimal after it's aware that one decimal exists?

Another major issue I am encountering is that when I input something like 1.2, it is displayed as 12, meaning that "atof(convert.cstr())" has stripped the decimal from the return value. However, when I enter it as just .2, it comes out as 0.2.

I will provide the code of what I have written so far along with the code of what a friend has suggested to me.

My code:

#include <iostream> 
#include <cstdlib>
#include <string>
#include <climits>

using namespace std;

// Main Menu Error Prototype
double ReadDouble(string prompt);

double ReadDouble(string prompt)
{
    string input;
    string convert;
    bool isValid = true;

    do {
        // Reset the flag to valid input
        isValid = true;

        // Read input from user
        cout << prompt;
        cin >> input;

        // Validate user input
        // Check the first character is a number, + or -
        int decimal = 0;
        if (input[0] != '+' && input[0] != '-' && input[0] != '.' && isdigit(input[0]) == 0) {
            cout << "Error! Input was not an integer.\n";
            isValid = false;
        }
        else {
            if (input[0] == '.') {
                decimal++;
                //cout << "." << endl;
            }
            convert = input.substr(0, 1);
        }

        // check that the remaining characters are numeric
        long len = input.length();
        for (long index = 1; index < len && isValid == true && decimal <= 1; index++) {
            if (input[index] == ',') {
                ;  // do nothing if character is a ','
            }
            else if (input[index] == '.') {
                decimal++; // do nothing if character is a '.'
                if (decimal > 1) {
                    cout << "Error! You can have only one decimal point.\n";
                    isValid = false;
                }
            }
            else if (isdigit(input[index]) == 0) {
                cout << "Error! Input was not an integer.\n";
                isValid = false;
            }
            
            else {
                convert += input.substr(index, 1);
            }
            
        }


        // Start looking where the decimal starts 

        /*
        long decimal=input.find('.');
        for (decimal; decimal < len && isValid==true; decimal++) {
            if (input[decimal] =='.') {
                ; // do nothing if character is a '.'
            }

        }
        */
        //cout << "\nDecimal value is " << decimal << endl; -- Test Code
    } while (isValid == false);

    
    double returnvalue = atof(convert.c_str());
    
    return returnvalue;
}

int main()
{
    double x = ReadDouble("Enter a value: ");
    cout << "Value entered was " << x << endl;
    return 0;
}

My friend's incomplete code:

ReadDouble(){
     isValid = true

     do{
            get user input and set it to a variable called input
            set output variable to a variable called output
            bool hasDecimal = false;
            int digitsUntilNextComma = 3

            for(i = 0; i < input length; i++){
                    if(input[i] == ','){
                             if((i < 3 && i > 0) || digitsUntilNextComma == 0){
                                     digitsUntilNextComma = 3;
                                     output += input[i];
                             }else{ //if it gets to here the comma was in a bad place like ,123 or 12,12,123
                                        isValid = false; 
                                        i = input length  //breaks out of for loop
                              }
                    } else if(input[i] == '.'){
                             if(i < 3 || digitsUntilNextComma == 0){
                                     if(hasDecimal){ //if this is true then the input had 2 decimals 
                                               isValid = false; 
                                               i = input length  //breaks out of for loop
                                      }else{
                                              hasDecimal = true;
                                              digitsUntilNextComma = 3;
                                              output += input[i];
                                       }
                             }else{ //if it gets to here, a previous comma was in a bad place like 12,34.56
                                      isValid = false; 
                                      i = input length  //breaks out of for loop
                              }
                    }else{
                            output += input[i];
                            digitsUntilNextComma--;
                    }
            }
          
     }while(isValid == false)
}

I hope what I provided wasn't too vague or messy. Again, I had little exposure to programming in the past, so forgive me if I mess some terminology up.

Vector not defined

I have added bits/stdc+.h and vector both. Still this error is coming . Can anyone tell me why this is happening.

#include <bits/stdc++.h>
#include<vector>
void rotate(int arr[], int n);

int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int n;
        scanf("%d",&n);
        int a[n] , i;
        for(i=0;i<n;i++)
        scanf("%d",&a[i]);
        rotate(a, n);
        for (i = 0; i < n; i++)
            printf("%d ", a[i]);
        printf("\n");
    }
        return 0;
}
// } Driver Code Ends


//User function Template for C++

void rotate(int arr[], int n)
{
    vector<int> a;
    a[0] = arr[n-1];
    for(int i = 0 ; i<n-1 ;i++)
      {
          a.insert(a.back(), arr[i]);
      }
      
   for(int j : a)
    cout<<j;
}

main.cpp:30:5: error: ‘vector’ was not declared in this scope vector a; ^~~~~~

C++ : Ambiguous Behavior of Ternary Operator

I tried and tested the following code to understand the behavior of ternary operator. But it is only making things complicated for me. The code:

#include<iostream>
using namespace std;

void print(bool a, bool b, bool c) {
    int x, y, z, w;
    cout << (a ? (b ? x = 5 + b : y = 10 + b) : (c ? z = 15 + c : w = 20 + c)) << endl;
    cout << x << " " << y << " " << z << " " << w << endl;
}

int main() {
    cout << "Hello world!\n";
    print(false, false, false);
    print(false, false, true);
    print(false, true, false);
    print(false, true, true);
    print(true, false, false);
    print(true, false, true);
    print(true, true, false);
    print(true, true, true);
    return 0;
}

And the output of this is as follows:

Hello world!
20
0 0 0 20
16
0 0 16 20
20
0 0 16 20
16
0 0 16 20
10
0 10 16 20
10
0 10 16 20
6
6 10 16 20
6
6 10 16 20

It doesn't look like this is following a procedure similar to the standard if-else procedure. Any guesses?

std::vector.erase() only erases half of what it should

I have a program where I have to delete some entries of a vector of structs. Im doing it like this

  for(int i=0; i<molec.size(); i++)
    {
      if(!molec[i].mine)
        molec.erase(molec.begin()+i);
    }

molec.mine is a boolean defined in the struct. The problem is that when I do this, it erases exactly half of the elements with molec.mine=false. I tried to search for some alternatives and found that I could do it with

vector.erase(std::remove(vec.begin(),vec.end(),1963),vec.end());

The thing with this is that I don't know how to do it with a vector of structs.

How can I solve this problem?

C++, Check if Instance comes before Another in memory?

I have 2 pointers to nodes in C++:

MallocMetadata *first_node, MallocMetadata *second_node

How can I check if the first_node comes first in memory before second_node (Both in heap and by first I mean lower address).

  1. Is it true to use: if(first_node < second_node) ?

  2. Let's suppose I want to check if first_node's place in memory is a multiplication of 8 how to do this:

I tried:

assert(first_node%8 ==0);

But, doesn't compile and I get:

Invalid operands to binary expression ('MallocMetadata *' and 'int')

Can anyone point out the error in my C++ program for constructor? [closed]

#include <iostream> 
using namespace std;
class person
 {
 long id;
 char name[30];
 char gender;
 float income;

public:
 person();
 person(long,char[],char,float);
 void display()
  {
   std::cout << id << name <<gender <<income << '\n';
  }

    };
  person::person()
  {
   id=0;
   strcp(name,"NOT KEYED");
    gender='';
    income=0;
   }
   person::person(long uid,char n[],char g,float inc)
    {
     id=uid;
     strcp(name,n);
     gender=g;
     income=inc;
    }
   int main() {
    person p1;
    std::cout << "Objectdetails" << '\n';
    p1.display();
    return 0;
     }

I have created a class here and within the class i have declared two constructor first one is default constructor and second oone is parameterised constructor .I have perfectly written the code but i am encounteriong with errors here which i am unable to understand can anybody help me?? error

Using wxLogMessage to Log into wxTextCtrl from different implementation Files - wxWidgets

Hi i am outputting/logging messages using wxLogMessage() into a wxTextCtrl. For the textctrl i have created a separate class called MyLog that contains a wxTextCtrl and it uses something like:

wxTextCtrl *textCtrl = new wxTextCtrl(...);
wxLog::SetActiveTarget(new wxLogTextCtrl(textCtrl));

Then i have another class called MyFrame and from MyFrame constructor i can use wxLogMessage("My First log message"); to log into the textCtrl. This works correctly and the message is successfully logged into the textCtrl. But the problem is that i have many other classes as well like MyPanel, Calculate, Compress and i want to use wxLogMessag() command from inside these classes to log into the same textCtrl that i created earlier. But when i use wxLogMessage("Second message"); from inside any of these other classes the message is not logged into the textCtrl and instead a message dialog box opens up having the same message we passed. So my questions are:

  1. How can i log messages into the textCtrl that i created inside class MyLog from inside the other classes.
  2. I looked into the samples directory of wxWidgets and there in the events folder. And in one of the example files called gestures.cpp they have used the statement delete wxLog::SetActiveTarget(new wxLogTextCtrl(textCtrl)); instead of using wxLog::SetActiveTarget(new wxLogTextCtrl(textCtrl));. So which one of the above should i use? Will wxWidgets handle the destruction by its internal mechanism or should i write delete explictly while using the command wxLog::SetActiveTarget(new wxLogTextCtrl(textCtrl)); in the constructor of the class MyLog?
  3. Also, as i mentioned, i have several implementation files and each one of them has a different role. For example. the Calculate class do some calculation and stores the result into some object. Similarly for other classes as well. Now my question is as my application starts using MyApp and then MyFrame classes which are part of the gui process, should i create a separate thread for the work of another classes. That is the gui will be in the main thread and then i can create a separate thread which will do all the non-gui related task like calculating something etc. Or should i use only a single thread. If i need to create a separate thread for the non-gui part then how can i log messages from those other classes(that are in the other thread) into the textCtrl that i created in the MyLog class which is in the main gui thread?

Majority Element

On trying to find the majority element I came up with this code. But the expected output is not printed. What is wrong with this code. Plz Help!!!!!!

Input : {3, 3, 4, 2, 4, 4, 2, 4, 4} Output : 4 Explanation: The frequency of 4 is 5 which is greater than half of the size of the array size.

Input : {3, 3, 4, 2, 4, 4, 2, 4} Output : No Majority Element Explanation: There is no element whose frequency is greater than half of the size of the array size.

#include <iostream>
using namespace std;

int main()
{
int i,count = 1 , max = 0,n;
cin >> n;
int a[n];
for(i=0 ; i<n ; i++) {
    cin >> a[n];
}

for(i = 1 ; i<n ; i++) {
    if(a[max] == a[i]){
        count += 1;
    }
    else {
        count -= 1;
    }
    
    if(count == 0){
        max = i;
        count =1;
    }
}
if(count > n / 2) {
    cout << a[max];
}
else {
    cout<<"No Max Element";
}

return 0;
}

Analogy of IntelliJ IDEA for C++ development on Windows

I'm going to start developing some C++ projects using at least C++11 standard. I have tried Code::Blocks and Netbeans 8.2 IDE. I prefer Netbeans 8.2 but I've got some warnings in the IDE when using C++11 syntaxes whereas the code still compiled, run and produced correct result.

I'm a big fan of IntelliJ IDEA. The dark theme of IntelliJ also one of my preferences. This is also one of my dislike for Code::Blocks and Netbeans 8.2. Is there an analogy of IntelliJ IDEA, but for C++ development? I know CLion but I can't afford to that.