lundi 28 février 2022

Bigint array multiply i tried this code and it didn't work with multiply more than two digits numbers

i tried this code and it didn't work with multiply more than two digits numbers


LargeInteger LargeInteger :: operator*(const LargeInteger& L) const{
    `LargeInteger obj;
    LargeInteger R;`
    short int counter = 0;
    int c = 0;
    short int x, y;
    for (int i = 0; i  1)
                {
                    obj.length++;
                    counter--;
                }
                else
                {
                    if (x * y + c >= 10 && j == MaxNumber(L).length - 1)
                    {
                        obj.number[j] = x * y + c;
                        obj.number[j] %= 10;
                        obj.number[j++] = c;
                        obj.length +=2;
                    }
                    else {
                        obj.number[j] = x * y + c;
                        c = obj.number[j] / 10;
                        obj.number[j] %= 10;
                        obj.length++;
                    }
                }
            }
        else counter++;
        counter++;
        R = R + obj; 
    }

    return R;
}

i did plus operator for bigint class and I have make operator for multiply but it's not work with 2 digits multiply can some one help me \this if my code

Why doesn't g++ recognize stoi even using C++11?

I have this function in C++11:

bool ccc(const string cc) {
    
vector<string> digits;
    
int aux;
    
for(int n = 0; n < cc.length(); ++n) {
    
digits.push_back(to_string(cc[n])); }
    
for(int s = 1; s < digits.size(); s += 2) {
    
aux = stoi(digits[s]);
    
aux *= 2;
    
digits[s] = to_string(aux);
    
aux = 0;
    
for(int f = 0; f < digits[s].length(); ++f) {
    
aux += stoi(digits[s][f]); }
    
digits[s] = to_string(aux);
    
aux = 0; }
    
for(int b = 0; b < digits.size(); ++b) {
    
aux += stoi(digits[b]); }
    
aux *= 9;
    
aux %= 10;
    
return (aux == 0); }

And I get this error when compiling with g++ with the -std=c++11 flag:

crecarche.cpp: In function ‘bool ccc(std::string)’:
    
crecarche.cpp:18:12: error: no matching function for call to ‘stoi(__gnu_cxx::__alloc_traits<std::allocator<char>, char>::value_type&)’
    
18 | aux += stoi(digits[s][f]); }
        |        ~~~~^~~~~~~~~~~~~~

But I used the stoi function after and I did not get any error with that line.

Why is the compiler throwing me this error and how can I fix it?

why C++ header and implementation files do not link? [duplicate]

I am implementing a simple Stack class and when I include the header file into my main.cpp file there are undefined reference error for every function that I used in main function. But move the implementations from "stack.cpp" to the end of "stack.h", and it works.
These are the files from the project:
stack.h

#ifndef STACK_H
#define STACK_H

#include <exception>
#include <string>
#include <initializer_list>

class StackException : public std::exception {
public:
    StackException() = default;
    explicit StackException(const std::string& msg) : message{msg} {}
    explicit StackException(const char* msg) : message{msg} {}
    virtual ~StackException() = default;

    virtual const char* what(void) const noexcept { return message.c_str(); }
private:
    std::string message;
};

template<typename T>
class Stack {
public:
    Stack(const uint64_t& = 8);
    Stack(const std::initializer_list<T>&);
    Stack(const Stack<T>&);
    Stack(const Stack<T>&&) noexcept;
    ~Stack();

    T& top(void) const;
    void push(const T&);
    const T& pop(void);
    bool isEmpty(void) const;
    bool isFull(void) const;
    const uint64_t& size(void) const;

    Stack& operator=(const Stack&);
    bool operator==(const Stack&) const;
private:
    T* _arr;
    uint64_t _size;
    uint64_t _allocated;
    void reset(void);
    void extend(void);
    void shrink(void);
};

#endif // STACK_H

stack.cpp

#include "stack.h"

template<typename T>
Stack<T>::Stack(const uint64_t& capacity)
{
    _size = 0;
    _allocated = capacity;
    _arr = new T[_allocated];
}

template<typename T>
Stack<T>::Stack(const std::initializer_list<T>& il) : Stack() {
   for(T item : il) insert(item);
}

template<typename T>
Stack<T>::Stack(const Stack<T>& other) : Stack{other._allocated} {
    _size = other._size;
    for(int i = 0; i < _allocated; i++) _arr[i] = other._arr[i];
}

template<typename T>
Stack<T>::Stack(const Stack<T>&& other) noexcept {
    _size = other.size;
    _allocated = other._allocated;
    _arr = other._arr;
    other._arr = nullptr;
    other.reset();
}

template<typename T>
Stack<T>::~Stack(void) {
    reset();
}

template<typename T>
void Stack<T>::reset(void) {
    if(_arr != nullptr) {
        delete[] _arr;
        _arr = nullptr;
    }
    _size = 0;
    _allocated = 0;
}

template<typename T>
void Stack<T>::extend(void) {
    Stack<T> temp{std::move(*this)};
    _arr = new T[temp._allocated * 2];
    _allocated = temp._allocated * 2;
    _size = temp._size;

    for(int i = 0; i < temp._allocated; i++) _arr[i] = temp._arr[i];
}

template<typename T>
void Stack<T>::shrink(void) {
    Stack<T> temp{std::move(*this)};
    _arr = new T[temp._allocated / 2];
    _allocated = temp._allocated / 2;
    _size = temp._size;

    for(int i = 0; i < _allocated; i++) _arr[i] = temp._arr[i];
}

template<typename T>
T& Stack<T>::top() const {
    if(isEmpty()) throw StackException("Stack is empty!");
    return _arr[_size - 1];
}

template<typename T>
void Stack<T>::push(const T& item) {
    if(isFull()) extend();
    _arr[_size++] = item;
}

template<typename T>
const T& Stack<T>::pop(void) {
    if(isEmpty()) throw StackException("Stack is empty!");
    if(_size <= _allocated / 4) shrink();
    T& temp = _arr[--_size];
    return temp;
}

template<typename T>
bool Stack<T>::isEmpty(void) const {
    return _size == 0;
} 

template<typename T>
bool Stack<T>::isFull(void) const {
    return _size >= _allocated;
}

template<typename T>
const uint64_t& Stack<T>::size(void) const {
    return _size;
}

template<typename T>
Stack<T>& Stack<T>::operator=(const Stack<T>& other) {
    if(&other == this) return *this;

    if(other._allocated != _allocated) {
        delete[] _arr;
        _arr = new T[other._allocated];
        _allocated = other._allocated;
    }
    _size = other.size;
    for(int i = 0; i < _allocated; i++) _arr[i] = other._arr[i];

    return *this;
}

template<typename T>
bool Stack<T>::operator==(const Stack<T>& other) const {
    if(_size != other._size) return false;

    for(int i = 0; i < _size; i++) {
        if(_arr[i] != other._arr[i]) return false;
    }

    return true;
}

main.cpp

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

int main() {
    Stack<int> test(8);
    test.push(3);
    cout << test.size() << endl;
    return 0;
}

In "main.cpp" I replaced #include "stack.h" with #include "stack.cpp and it worked without error. Using g++ stack.cpp main.cpp -o a outputs the same errors when I use #include "stack.h".
This is certainly not my first time separating headers and implementations in multiple files but this is quite new to me. So shall I go on and use #include "stack.cpp" (which I don't suppose is a good idea)? Is there any reason to this?

OpenCV putText() is too slow for multiple lines. How to speed it up?

I need to overlay about ~50 lines of text on a video stream from an IP camera. But I have found that I cannot use the newline character in putText(), I have to split and print each line individually, which means multiple calls to putText(). This method slows down the video stream from 30 fps to ~3 fps and overloads the video encoder in my IP camera. Are there any methods to improve performance when calling putText multiple times? My code is similar to the following:

void* TextThread(){
    std::vector<std::string> infoValues{...};
    int verticalShift = 0;
    for (auto it = infoValues.begin(); it != infoValues.end(); ++it, verticalShift++){
        cv::putText(img, *it, cv::Point(1470, 30 + 25*verticalShift), FONT_HERSHEY_SIMPLEX, 0.85, cv::Scalar(255, 0, 0), 2, LINE_AA);
    }
}

dimanche 27 février 2022

Why G++ does not recognize stoi even using C++11?

So I have this function in C++11:

bool ccc(const string cc) {
    
vector<string> digits;
    
int aux;
    
for(int n = 0; n < cc.length(); ++n) {
    
digits.push_back(to_string(cc[n])); }
    
for(int s = 1; s < digits.size(); s += 2) {
    
aux = stoi(digits[s]);
    
aux *= 2;
    
digits[s] = to_string(aux);
    
aux = 0;
    
for(int f = 0; f < digits[s].length(); ++f) {
    
aux += stoi(digits[s][f]); }
    
digits[s] = to_string(aux);
    
aux = 0; }
    
for(int b = 0; b < digits.size(); ++b) {
    
aux += stoi(digits[b]); }
    
aux *= 9;
    
aux %= 10;
    
return (aux == 0); }

And I get this error when compiling with G++ WITH THE -std=c++11 flag:

crecarche.cpp: In function ‘bool ccc(std::string)’:
    
crecarche.cpp:18:12: error: no matching function for call to ‘stoi(__gnu_cxx::__alloc_traits<std::allocator<char>, char>::value_type&)’
    
18 | aux += stoi(digits[s][f]); }
        |        ~~~~^~~~~~~~~~~~~~

But I used the stoi function after and I did not get any error with that line.

Why is the compiler throwing me this error and how can I fix it?

Thanks in advanced.

how to return how many times has a recursive function been called in C++?

void funct(int n)
{
    int steps = 0;
    if(n != 1){
        steps++;
        if((n % 2) == 0){
            funct(n/2);
        }
        else if((n % 2) != 0){
            funct((3*n + 1));
        }
        cout << steps << " ";

    }
    
}

I tried this code, but it only returns 1 in a few times and i want my code to return how many times has 1 been returned.

Getting a runtime error using set as a map key value

I am getting a runtime error on a few test cases, i suspect it has something to do with my use of multiset as a map key value , the number of sets i use in the map is less than 100,000 each. I have no real other way of doing this problem without a map or a multiset. Nothing should go out of bounds, it should be impossible for the code to access and empty set

map<multiset<long long>, long long> ma;
map<multiset<long long>, long long> mb;
set<multiset<long long> > v;

int main(){
    long long w,k;
    cin>>w>>k;
    if(w==1){
         long long n;
    cin>>n;
    long long a[n+5];
    long long sorta[n+5];
    long long ld=0;
    sorta[0]=0;
    for(long long i=1; i<=n; i++){
        cin>>a[i];
        if(a[i]<a[i-1]){
            ld=i;
        }
        sorta[i]=ld;
    }
    long long m;
    cin>>m;
        long long b[m+5];
        long long sortb[m+5];
        sortb[0]=0;
        ld=0;
     for(long long i=1; i<=m; i++){
        cin>>b[i];
        if(b[i]<b[i-1]){
            ld=i;
        }
        sortb[i]=ld;
    }
    multiset <long long> s;
    long long las=0;
    for(long long i=1; i<=min(n,k); i++){
        s.insert(a[i]);
        
            las=a[1];
        
    }   
    if(1>=sorta[k]){
        ma[s]++;
        v.insert(s);
    }

    for(long long i=k+1; i<=n; i++){
        s.erase(s.find(las));
        s.insert(a[i]);
        las=a[i-k+1];
        if(sorta[i]<=i-k+1){
            ma[s]++;

            v.insert(s);
        }
    }
    s.clear();
    for(long long i=1; i<=min(m,k); i++){
        s.insert(b[i]);
        las=b[1];
    }   
    if(sortb[k]<=1){
        mb[s]++;
    }
    for(long long i=k+1; i<=m; i++){
        s.erase(s.find(las));
        s.insert(b[i]);
        las=b[i-k+1];
        if(sortb[i]<=i-k+1){
            mb[s]++;
        }
    }
    long long pas=0;
    set< multiset<long long> >:: iterator ii;
    for(ii=v.begin(); ii!=v.end(); ii++ ){
        pas+=ma[*ii]*mb[*ii];

    }
    cout<<pas;
    return 0;
    }
}

Choosing numbers from a vector so that the sum of their absolute differences is smaller than a given number [closed]

I have n integers in a file (unsorted and the numbers can repeat). I am given another integer S.

I have to find the maximum number of integers from the file so that the sum of their absolute differences is smaller than or equal to S.

For example, for 3 numbers, it means that

|x-y|+|x-z|+|y-z|<=S

samedi 26 février 2022

How to use nested namespace to avoid ambiguity?

I have the following operators defined in the corresponding namespaces:

namespace literals
{

constexpr ID operator"" _ID(const unsigned long long dyngateID)
{
    // ...
    // return a constructed id
}

namespace multiplied
{

constexpr ID operator"" _ID(const unsigned long long dyngateID)
{
    // ...
    // return an id constructed in a specific way
}

} // namespace multiplied
} // namespace literals

In a .cpp file I would like to use both functions, hence I've declared using namespace literals and when I am declaring using namespace multiplied in a concrete function I am getting ambiguous call to overloaded function compile error. How can I differentiate these functions?

Test.cpp

using namespace literals;

void f()
{
    // here I am using literals' _ID which is fine
    const Type id{1_ID};
}
void g()
{
    // here I want to use multiplied's _ID, but obviously I am failing to do so
    using namespace multiplied;
    const Type id{1_ID};
}

std::valarray and type of iterators

Since C++11 std::valarray has iterators, provided through the std::begin() and std::end() interfaces. But what is the type of those iterators (so that I can declare them properly)?

The following does not compile with a no template named 'iterator' in 'valarray<_Tp>' error:

template <typename T>
class A {
private:
  std::valarray<T> ar;
  std::valarray<T>::iterator iter;
public:
  A() : ar{}, iter{std::begin(ar)} {}
};

decltype shows the type of the iterator to be that of a pointer to a ``valarray` element. Indeed, the following does compile and seems to work fine:

template <typename T>
class A {
private:
  std::valarray<T> ar;
  T* iter;
public:
  A() : ar{}, iter{std::begin(ar)} {}
};

What am I missing? Isn't there a proper iterator type to use for the declare in the class?

when build elasticfusion ,error about pthread,

termination shows:

-- Looking for pthread.h
-- Looking for pthread.h - found
-- Performing Test CMAKE_HAVE_LIBC_PTHREAD
-- Performing Test CMAKE_HAVE_LIBC_PTHREAD - Failed
-- Looking for pthread_create in pthreads
-- Looking for pthread_create in pthreads - not found
-- Looking for pthread_create in pthread
-- Looking for pthread_create in pthread - found
-- Found Threads: TRUE  
-- Found CUDA: /usr (found version "10.1") 
-- Found SuiteSparse

and the camke errorlog shows:

Performing C SOURCE FILE Test CMAKE_HAVE_LIBC_PTHREAD failed with the following output:
Change Dir: /home/csl/wenjin/ElasticFusion/Core/build/CMakeFiles/CMakeTmp

Run Build Command(s):/usr/bin/make cmTC_6d9a0/fast && /usr/bin/make -f CMakeFiles/cmTC_6d9a0.dir/build.make CMakeFiles/cmTC_6d9a0.dir/build
make[1]: 进入目录“/home/csl/wenjin/ElasticFusion/Core/build/CMakeFiles/CMakeTmp”
Building C object CMakeFiles/cmTC_6d9a0.dir/src.c.o
/usr/bin/cc   -DCMAKE_HAVE_LIBC_PTHREAD   -o CMakeFiles/cmTC_6d9a0.dir/src.c.o   -c /home/csl/wenjin/ElasticFusion/Core/build/CMakeFiles/CMakeTmp/src.c
Linking C executable cmTC_6d9a0
/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_6d9a0.dir/link.txt --verbose=1
/usr/bin/cc  -DCMAKE_HAVE_LIBC_PTHREAD    -rdynamic CMakeFiles/cmTC_6d9a0.dir/src.c.o  -o cmTC_6d9a0 
/usr/bin/ld: CMakeFiles/cmTC_6d9a0.dir/src.c.o: in function `main':
src.c:(.text+0x3e): undefined reference to `pthread_create'
/usr/bin/ld: src.c:(.text+0x4a): undefined reference to `pthread_detach'
/usr/bin/ld: src.c:(.text+0x5b): undefined reference to `pthread_join'
collect2: error: ld returned 1 exit status
make[1]: *** [CMakeFiles/cmTC_6d9a0.dir/build.make:87:cmTC_6d9a0] 错误 1
make[1]: 离开目录“/home/csl/wenjin/ElasticFusion/Core/build/CMakeFiles/CMakeTmp”
make: *** [Makefile:121:cmTC_6d9a0/fast] 错误 2

although I have search many methods to solve it, it does nothing ,could you help me?

I've seen that Doxygen needs to be installed before, but I'm sure I've installed it and added header files. I don't know what else can be done

vendredi 25 février 2022

Producing a library with a recent gcc and consuming it with an older gcc - Why are there issues despite the same C++ version?

Don't ask me why I am doing what I am doing... that would be a long story. For now, the purpose of this post is to learn and to understand why things don't work the way I expect. Possibly my expectations are wrong ?

  • So initially I build my own SystemC 2.3.3 library from source using a recent compiler, say gcc 10.2.0. However, to preserve backwards compatibility with older gccs, I request C++11 :

    ./configure CXXFLAGS="-DSC_CPLUSPLUS=201103L"
    
  • Next I want to build an application using an older gcc that supports C++11 (and the same ABI), say gcc 8.2.0, :

    g++ -std=c++11 sc_main.cpp -I/path/to/systemc/include -L/path/to/systemc/lib -lsystemc -lm -o sim
    

To my surprise, link fails:

libsystemc.so: undefined reference to `std::__cxx11::basic_stringstream<char, std::char_traits<char>, std::allocator<char> >::basic_stringstream()

In effect, comparing the outputs of

nm --demangle `/path/to/gcc/10.2.0/bin/g++ --print-file-name libstdc++.so` | grep "std::__cxx11::basic_stringstream<char, std::char_traits<char>, std::allocator<char> >::"

and

nm --demangle `/path/to/gcc/8.2.0/bin/g++ --print-file-name libstdc++.so` | grep "std::__cxx11::basic_stringstream<char, std::char_traits<char>, std::allocator<char> >::"

reveals some differences. Indeed, the former contains std::basic_stringstream<char, std::char_traits<char>, std::allocator<char> >::basic_stringstream() whereas the latter doesn't.

Is this expected ? Does it mean that in general, it is necessary but not sufficient for the producer and the consumer of a library to use the same C++ version (and the same ABI) ? Or is there something else going on that I don't understand ?

It is proper to make mt19937 static in a class

Let's say I have a class as below:

class Test {
public:
    Test() : mt((std::random_device())()), dist1(0, 10), dist2(0, 100) {}
    void func() {
        if (dist1(mt) < 4) {
            // do something
        }
    }
    void func2() {
        if (dist2(mt) > 25) {
            // do something
        }
    }
private:
    std::mt19937 mt;
    std::uniform_int_distribution<int> dist1;
    std::uniform_int_distribution<int> dist2;
};

As you see, there are two functions, they all need a random number to do something.

In this case, can I make the data member std::mt19937 mt as static and initialize it in cpp file?

class Test {
...
private:
    static std::mt19937 mt;
...
};
// cpp file
std::mt19937 Test::mt((std::random_device())());

I just tried and it seemed to work. But I don't know if there is something wrong with it.

Test t1; t1.func(); t1.func2();
Test t2; t2.func(); t2.func2();

Can I say that static or non-static won't cause any difference for the piece of code?

jeudi 24 février 2022

Why it is not possible to use unique_ptr in QFuture?

Here is my sample code, I am std::vector<std::unique_ptr<std::string>> as future result.

#include "mainwindow.h"
#include <QLineEdit>
#include <QtConcurrent/QtConcurrent>
#include <vector>

MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent) {
    auto model = new QLineEdit(this);
    this->setCentralWidget(model);

    auto watcher = new QFutureWatcher<std::vector<std::unique_ptr<std::string>>>(/*this*/);
    auto future  = QtConcurrent::run([this]() -> std::vector<std::unique_ptr<std::string>> {
        std::vector<std::unique_ptr<std::string>> res;
        for (int k = 0; k < 100; ++k) {
            auto str = std::make_unique<std::string>("Hi");
            res.push_back(std::move(str));
        }
        return res;
    });

    connect(watcher, &QFutureWatcher<std::vector<std::unique_ptr<std::string>>>::finished, this, [=]() {
        for (const auto &item : future.result()){
            model->setText(model->text() + QString::fromStdString(*item));
        }
        delete watcher;
    });
    watcher->setFuture(future);
}

MainWindow::~MainWindow() {

}

But this code can't compile. Here is the log,

/Users/ii/QT/qt-everywhere-src-6.2.0-beta4/include/QtCore/qfuture.h:328:12: note: in instantiation of member function 'std::vector<std::unique_ptr<std::string>>::vector' requested here
    return d.resultReference(0);
           ^
/Users/ii/CLionProjects/simpleQT/mainwindow.cpp:22:40: note: in instantiation of function template specialization 'QFuture<std::vector<std::unique_ptr<std::string>>>::result<std::vector<std::unique_ptr<std::string>>, void>' requested here
        for (const auto &item : future.result()){
                                       ^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.1.sdk/usr/include/c++/v1/__memory/base.h:103:16: note: candidate template ignored: substitution failure [with _Tp = std::unique_ptr<std::string>, _Args = <std::unique_ptr<std::string> &>]: call to implicitly-deleted copy constructor of 'std::unique_ptr<std::string>'
constexpr _Tp* construct_at(_Tp* __location, _Args&& ...__args) {
               ^

is it possible to increase speed of interpreter without using vm?

I am making a simple programming language like LUA.I cannot able to create a VM because it is designed to interpret after forming an AST .it is slow ,There is any way to improve speed and performance of the interpreter ? . is it possible to interpret directly during parsing ? (without making an abstract syntax tree)

Behaviour of threads using conditional variables

Im trying to solve producent-consumer problem with conditional variables and I met a strange behaviour of my program. I was trying to understand it but I need some help. The program which I wrote shows that sometimes the state variable goes over desired value, here 10. I need exactly 10 values. I think that this depends on the random delay time. How could I manage my problem?

#include <iostream>
#include <thread>
#include <mutex>
#include <random>
#include <queue>
#include <fstream>
#include <sstream>
#include <condition_variable>

void producer_task(std::mutex& buff_mtx, int& state, std::condition_variable& cv){
    while(1){
        // simulate delay of reading data from sensor
        static thread_local std::mt19937 generator(0);
        std::uniform_int_distribution<int> sleep_distribution(100,5000);
        std::this_thread::sleep_for(std::chrono::milliseconds(sleep_distribution(generator)));
        {
            std::lock_guard<std::mutex> lk_guard(buff_mtx);
            // add data to buffor
            state++;
        }
        cv.notify_all();
    }
}

void consumer_task(std::mutex& buff_mtx, int& state, std::condition_variable& cv){
    while(1){
        std::unique_lock<std::mutex> lk_guard(buff_mtx);
        cv.wait(lk_guard, [&state](){std::cout << state << std::endl; return state == 10;});
        state = 0;
        // after there is state == 10, print 10 readings from buffer
    }
}

int main(){
    std::vector<std::thread> threads;
    std::mutex buff_mtx;
    std::condition_variable cv;
    int state = 0;
    for(int i = 0; i < 5; i++){
        threads.emplace_back(producer_task,std::ref(buff_mtx),std::ref(state), std::ref(cv));
    }
    threads.emplace_back(consumer_task,std::ref(buff_mtx),std::ref(state), std::ref(cv));
    for(auto& thread : threads){
        thread.join();
    }
}

what are some differences between c++11 and c++14 [closed]

for example Digit Separators

int x = 10000000;   // (1)
int y = 10'000'000; // (2), C++14

Example Snippet, legal in both C++11 and C++14, but with different behavior.

#define M(x, ...) __VA_ARGS__

int a[] = { M(1'2, 3'4, 5) };

// int a[] = { 5 };        <-- C++11
// int a[] = { 3'4, 5 };   <-- C++14
//                              ^-- semantically equivalent to `{ 34, 5 }`

In this case

Why is this function of the inherited QWidget class considered private

define a subclass of QWidget which has a public static member function, but when I call it in other classes. clion told me it's private. This is the definition of my class

#ifndef MAIN_WINDOW_H
#define MAIN_WINDOW_H
#include <thread>
#include <QStandardItem>
#include "ui_MainWindow.h"
#include "V5RPCPP/StrategyServer.h"
#include "strategy/StrategyBase.h"

class MainWindow : public QWidget {
 Q_OBJECT

public:
  explicit MainWindow(QWidget *parent = nullptr);
  QStandardItemModel  item_model;
  static void Log(std::string message, std::string sender, Severity severity);
  void output_log(char* log);;
  static MainWindow* mainwindow;
  static MainWindow* get_mainwindow_ptr();
private:
  StrategyInterface* strategy = nullptr;
  V5RPC::StrategyServer* strategy_server = nullptr;
  Ui_MainWindow ui;
  std::unique_ptr<std::thread> server_thread = nullptr;
  pthread_t server_thread_id;
  bool is_running = false;
  private slots:
  void on_open_file_dialog_btn_clicked();
  void on_log_level_combo_box_currentIndexChanged(int index);
  void on_log_filter_line_edit_textChanged(const QString& text);
  void on_port_test_btn_clicked() const;
  void on_start_stop_btn_clicked();
  void on_side_yellow_check_box_stateChanged(int state);
  void flip_strategy_status();
  void start_strategy_server();
  void stop_strategy_server();
};

#endif

this is my call enter image description here

MFC CMenu strange draw background behavior

I tried to draw the menu background in MFC Dlg App.

But I found if I declare CMenu subMenu in OnInitDialog(), the background color works well. If I declare CMenu subMenu in Head file or like CMenu* subMenu=new CMenu; in OnInitDialog(), the Item's background will not be changed.This is weird and seems to be related to the CMenu lifetime.

Variable:

CMenu  m_accountMenu;
CMenu subMenu;

CMFCApplication3Dlg::OnInitDialog()

......some code
// TODO: Add extra initialization here
m_accountMenu.CreateMenu();
subMenu.CreatePopupMenu();
m_accountMenu.AppendMenuW(MF_BYPOSITION | MF_POPUP | MF_STRING , (UINT)subMenu.m_hMenu, _T("Sub Info"));
subMenu.AppendMenuW(/*MF_MENUBREAK|*/  MF_STRING | MF_ENABLED , 1001, _T("sub Info1"));  //  note: MF_MENUBREAK can make it work  
subMenu.AppendMenuW(MF_STRING | MF_ENABLED , 1002, _T("sub Info2"));

CBrush cBrush;
cBrush.CreateSolidBrush(RGB(255, 0, 0));
MENUINFO mi = { 0 };
mi.cbSize = sizeof(MENUINFO);
mi.fMask = MIM_BACKGROUND;
mi.hbrBack = cBrush;

SetMenuInfo(m_accountMenu.GetSubMenu(0)->GetSafeHmenu(), &mi);
cBrush.Detach();
SetMenu(&m_accountMenu);

Can someone help me unravel the mystery? Any useful information will be appreciated.

mercredi 23 février 2022

storing std::reference_wrapper

I was hoping infer std::reference_wrapper<MyType> to MyType& automagically on bool operator<(. It is not matching the method. But the code is compiling when I add additional bool operator<( method. Am I missing something?

#include <iostream>
#include <set>
#include <functional>


class MyType {
public:
    bool operator<(const MyType& target) const {
        return this < &target;
    }
};

// it doesn't compile if remove the method below.
bool operator<(const std::reference_wrapper<MyType>& a, const MyType& b) {
    return a.get() < b;
}

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

    std::set<std::reference_wrapper<MyType>> types;

    MyType t1, t2, t3;

    types.insert(std::ref(t1));
    types.insert(std::ref(t2));
    types.insert(std::ref(t3));
    types.insert(std::ref(t1));

    std::cout << "size: " << types.size() << std::endl;

    return 0;
}

Conditional Incrementing Incorrectly

My function

int numSteepSegments(const int heights[], int arrSize) {

    int mile = 0, steep_count = 0;

    while (mile <= arrSize) {
        int height = heights[mile];
        int height_next = heights[mile + 1];
        if ((height + 1000) < height_next) {
            ++steep_count;
        } else if ((height - 1000) > height_next) {
            ++steep_count;
        }
        cout << heights[mile] << endl;
        cout << steep_count << endl;

        ++mile;
    }
    return steep_count;
}

is spitting out twice as many steep_count than it is supposed to.

With the array: 1200, 1650, 3450, 2800, 2900, 1650, 1140, 1650, 1200, and the arrSize = 9, what am I missing?

the cout's are:

1200
0
1650
1
3450
1
2800
1
2900
2
1650
2
1140
2
1650
2
1200
3
1746942513
4

What is that last value? It's obviously not in the array, and I can't see it belonging anywhere near the numbers I'm dealing with. What am I not seeing in my conditionals that's causing the wrong increments to steep_count?

How to grab a user ID from user input and store as a value in a hashtable C++

I am having trouble understanding how to add a userid that the user inputs from command line into a hash table. I have already written the hash table and know it might need editing to do this and I have read that setting an array might work but the issue is that I use the insertion function for the hash table but once I leave the function that grabs the user input it disappears and now the has table is empty. I get that I might need to return something and the function that grabs the user input returns nothing at the moment. I am just confused and Google is not helping for the past 3 hours. Either posting here will help or ill get downvoted, worth a shot.

There are 3 files, the main function is in main.cpp, I have a header file, and a hashtable.cpp file. The insertion function in hashtable.cpp looks like this:

void hash_table::insertion(int key, string value)
{
    int hash_value = hash_function(key);
    auto& cell = table[hash_value];
    auto bItr = begin(cell);
    bool key_exists = false;

    for(;bItr != end(cell); bItr++)
    {
        if (bItr->first == key)
        {
            key_exists = true;
            bItr->second = value;
            cout << "[WARNING] Key exists. Value has been replaced." << endl;
            break;
        }
    }

    if(!key_exists)
    {
        cell.emplace_back(key, value);
    }
    else 
    {
        return;
    }

}

Cool, so I should be able to do this in another function:

hash_table HT;

    int hash_id = random_number();

    cout << "Enter your preferred username: \n";
    cin >> r_user;

    cout << "Enter your preferred password: \n";
    cin >> r_password;

    //inserts the randomly generated ID for the user and the password into the hash table
    HT.insertion(hash_id, r_password);

    //gives the user thier unique user ID by printing to the console
    cout << "[IMPORTANT] Your ID is: " << hash_id << "\n";

    //use the stream to append the username and password to the records file 
    ofstream f1("records.txt", ios::app);
    f1 << hash_id << ' ' << r_user << ' ' << r_password << endl;

    cout << "Your registration was successful! \n";

    HT.print_table();

    main();

I know that the hash_id should be left to be random generated, I just haven't implemented that yet. Even so I can't think of how to get the users id from the input into the table. When the function goes back to main(); there is no longer anything in the table anymore. I have tried making the function with int,string parameters and then returning but that is also not helping. Any suggestions? I am not looking for you guys to do homework for me I am just 100% stuck and need a push. I am still learning C++ (by force). Let me know if there is needed clarification, sorry for the excessive explanation.

Execute method on expression end in C++?

I'm designing a custom task management system. For this I'm overloading the + and - operators so they gain an alternative meaning:

const auto& scope = fsm::enter +STATE_TO_SET -LOCK_TO_ACQUIRE;

You can imagine that STATE_TO_SET and LOCK_TO_ACQUIRE are both enum values which are "added" to the objects member variables one after another. Now, there should be a method in the fsm::enter-object that triggers once all + and - operations are done (e.g. to set the state and acquire the lock). Is this doable somehow in C++11?

Where to use an rvalue as a function parameter?

I know there are plenty of questions about the argument, but I still don't understand some basic stuff about rvalues.

Supposing I have a function of this kind:

/* 1 */ void func( std::string s ) { /* do something with s */ }

which I use in this way:

int main()
{
  func( "a string" );
}

In a case like that, in which I pass this string to the function func wouldn't be better to always define this kind of function in this way:

/* 2 */ void func( std::string&& s ) { /* do something with s */ }

My question is: wouldn't be always better to use /* 2 */ instead of /* 1 */ in cases like the one of this example? And if not, why and where should I use the one or the other? The fact is that, if I understood well, in /* 2 */ the parameter is moved and will never be used outside of the function scope, right?

Can I use thread.h from C11 in C++?

I don't want to use C++11 std::thread because of exceptions. Is it possible to use C11's threads from C++ (for some version)?

Memory Crash on Intel CPU when running OpenCL code for particular input

I'm working on running my OpenCL codes on CPU and GPU. I'm experiencing some memory crash issue when I run my OpenCL code on CPU that is for particular input vector...I'm not seeing the issue when I run the same code for same vector on GPU. After the kernel execution, when I execute any other opencl functions or printf it's showing "Access violation Error". I'm not experiencing the same error when I run on GPU. Then on further debugging, when I changed the order of buffer creation (clCreateBuffers) , it is working fine without any issue. Say previously I created buffers in this order buffer1, buffer 2, buffer 3, it showed exception. Now when I changed to buffer1, buffer3, buffer2, it is running fine and no access violation error is thrown on CPU. And also when the buffers are in this order buffer1, buffer2, buffer3 and I additionally created buffer4 (which is just dummy buffer we are not using that in code), program is executed successfully.

Can anyone please explain me why this error is happening. It's something weird that same code is working fine on GPU and even other input vectors are getting properly executed on CPU, while at the same time when we run a particular vector with different order of buffer creation the error is not happening.

Thanks.

mardi 22 février 2022

output returns a "terminate called after throwing an instance of 'std::invalid_argument' what(): stoi" [closed]

Unrelated to my homework but when I run my codes, my output returns "terminate called after throwing an instance of 'std::invalid_argument' what(): stoi" at the end of the run. Wondering if any experts can explain why such thing is happening?

found out that if my getline(infile,test); is inside the while loop, I would not get the what() stoi error but my date will get totally messed up. tried to do some research on google but couldnt get a proper answer why that is happening

#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include "Date.h"
#include "Time.h"
#include "Vector.h"

using namespace std;

typedef struct {
    Date d;
    Time t;
    float speed;
} WindLogType;

    ostream & operator <<( ostream & os, const WindLogType& wl );
    istream & operator >>( istream& input, WindLogType& wl );

int main()
{   Vector<WindLogType> windLogs;
    string day,month,year,hours,minss,strInput;
    string test;
    WindLogType windlogs2;
    ifstream infile("test.csv");
    if(!infile) return -1;

    infile >> windlogs2;
    getline(infile,test);
    ofstream outfile("outputFile.txt.");
    while (!infile.eof()){

    getline(infile,day, '/');
    windlogs2.d.SetDay(stoi(day));
    getline(infile,month, '/');
    windlogs2.d.SetMonth(stoi(month));
    getline(infile,year, ' ');
    windlogs2.d.SetYear(stoi(year));
    getline(infile,hours, ':');
    windlogs2.t.SetHours(stod(hours));
    getline(infile,minss,',');
    windlogs2.t.SetMins(stod(minss));
    getline(infile,strInput,',');
    getline(infile,strInput,',');
    getline(infile,strInput,',');
    getline(infile,strInput,',');
    getline(infile,strInput,',');
    getline(infile,strInput,',');
    getline(infile,strInput,',');
    getline(infile,strInput,',');
    getline(infile,strInput,',');
    getline(infile,strInput,',');
    windlogs2.speed = (stof(strInput));
    getline(infile,strInput,',');
    getline(infile,strInput,',');
    getline(infile,strInput,',');
    getline(infile,strInput,',');
    getline(infile,strInput,',');
    getline(infile,strInput,',');
    getline(infile,strInput);

    outfile << windlogs2 << endl;
    cout << windlogs2 << endl;
  }
    return 0;
}

    ostream & operator <<( ostream & os, const WindLogType& wl )
    {
        os << wl.d << wl.t << " Speed: " << wl.speed << '\n';
        return os;
    }
    istream & operator >>( istream& input, WindLogType& wl )
    {
        input >> wl.d >> wl.t >> wl.speed;
        return input;
    }

Sample of the codes used to run with this codes

https://i.stack.imgur.com/nESvO.png

Reading files and output is skipping lines

This is homework but im stuck wondering where i went wrong. any help from you experts would be appreciated greatly!

Intended Output : Date: 31/3/2016 Time: 09:00 Speed: 6

Date: 31/3/2016 Time: 09:10 Speed: 5

Date: 31/3/2016 Time: 09:20 Speed: 5

Date: 31/3/2016 Time: 09:30 Speed: 5

Date: 31/3/2016 Time: 09:40 Speed: 6

and so on, basically in sequence

Current output Date: 31/3/2016 Time: 22:20 Speed: 4

Date: 31/3/2016 Time: 22:40 Speed: 4

Date: 31/3/2016 Time: 23:0 Speed: 3

Date: 31/3/2016 Time: 23:20 Speed: 4

Date: 31/3/2016 Time: 23:40 Speed: 5

as you can see, its skipping in 20mins interval. im not sure where in my code is causing this.

#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include "Date.h"
#include "Time.h"
#include "Vector.h"

using namespace std;
typedef struct {
    Date d;
    Time t;
    float speed;
} WindLogType;

ostream & operator <<( ostream & os, const WindLogType& wl );
istream & operator >>( istream& input, WindLogType& wl );

int main()
{   Vector<WindLogType> windLogs;
    string day,month,year,hours,minss,strInput;
    string test;
    WindLogType windlogs2;
    ifstream infile("test2.csv");
    if(!infile) return -1;

infile >> windlogs2;
while (!infile.eof()){
//infile >> windlogs2;

getline(infile,strInput); //skip the first line
getline(infile, strInput, '/');
windlogs2.d.SetDay(stoi(strInput));
getline(infile,strInput, '/');
windlogs2.d.SetMonth(stoi(strInput));
getline(infile,strInput, ' ');
windlogs2.d.SetYear(stoi(strInput));
getline(infile,strInput, ':');
windlogs2.t.SetHours(stod(strInput));
getline(infile,strInput,',');
windlogs2.t.SetMins(stod(strInput));
getline(infile,strInput,',');
getline(infile,strInput,',');
getline(infile,strInput,',');
getline(infile,strInput,',');
getline(infile,strInput,',');
getline(infile,strInput,',');
getline(infile,strInput,',');
getline(infile,strInput,',');
getline(infile,strInput,',');
getline(infile,strInput,',');
windlogs2.speed = (stof(strInput));
getline(infile,strInput,',');
getline(infile,strInput,',');
getline(infile,strInput,',');
getline(infile,strInput,',');
getline(infile,strInput,',');
getline(infile,strInput,',');
getline(infile,strInput,',');

ofstream outfile("outputFile.txt.");
outfile << windlogs2 << '\n';
cout << windlogs2 << '\n';



 }

    return 0;
    
}

ostream & operator <<( ostream & os, const WindLogType& wl )
{
    os << wl.d << wl.t << " Speed: " << wl.speed << '\n';

        return os;
}
istream & operator >>( istream& input, WindLogType& wl )
{
    input >> wl.d >> wl.t >> wl.speed;
    return input;
}

Does this statement allow inheritance to properly work?

I'm doing a project on multilevel inheritance with a deck of playing cards. While working on the project, i received a compilation error in my program that was specifically for the suit classes (diamond.cpp, heart.cpp, etc.) constructor that stated

error: no matching function for call to 'RedCard::RedCard()'

I realized that this was because the RedCard and BlackCard clases did not have a default constructor. I was able to fix this by putting:

Heart::Heart(int v) : RedCard(v)

for the suit class constructor in order to specify the program to call the parametrized constructor rather than the non-existent default constructor. I know that a class does not need to have a default constructor, and the class that a higher up class Card has a default constructor.

My question is: does what I did allow inheritance to work?

The heirarchy of the programs inheritance structure is here:

link: https://imgur.com/a/aQvub9n

Text

One thing I did notice while trying to finish the program, is that in my RedCard and BlackCard classes, there's a Description method we are to use. The switch statement that is in it uses throws an error saying that the "value" variable from the Card Class is inaccessible, so I presume I'm doing something wrong with the RedCard and BlackCard Classes.

This is the Card.cpp file:

#include <iostream>
#include <cstdlib>
#include "card.h"

Card::Card()  // Default Constructor: Initializes value to 0, color to "unknown", and suit to 'U'
{
  int value = 0;
  string color = "unknown";
  char suit = 'U';

} 

Card::Card(int v)  // Parameterized Constructor: Initializes value to v, color to "unknown", and suit to 'U'
{
  value = v; 
  color = "unknown";
  suit = 'U';
}  

int Card::GetValue() const  // Returns variable value
{
  return value;
}

string Card::GetColor() const  // Returns variable color
{
  return color;
}

char Card::GetSuit() const  // Returns variable suit
{
  return suit;
}

void Card::SetValue(int v)  // Sets value to v
{
  value = v;
}

void Card::SetColor(string c)
// Sets color to c
{
  color = c;
}

void Card::SetSuit(char s)
// Sets suit to s
{
  suit = s;
}


string Card::Description() const   // Outputs card characteristics - value as a string
// DO NOT MODIFY THIS METHOD !!!!
{
  string d = "Value = ";    // temporary variable used to accumulate result

  switch (value)            // Append card value to variable's value
  {
    case 2:   d = d + "2";    break;      // Number cards
    case 3:   d = d + "3";    break;
    case 4:   d = d + "4";    break;
    case 5:   d = d + "5";    break;
    case 6:   d = d + "6";    break;
    case 7:   d = d + "7";    break;
    case 8:   d = d + "8";    break;
    case 9:   d = d + "9";    break;
    case 10:  d = d + "10";   break;
    
    case 11:  d = d + "J";    break;      // Face cards
    case 12:  d = d + "Q";    break;
    case 13:  d = d + "K";    break;
    case 14:  d = d + "A";    break;

    default:  d = d + "?";    break;      // Unknown card
  }

  return d;                 // Return string describing card value
}

This is the Card.h file

#include <string>
using namespace std;

#ifndef CARD_H
#define CARD_H

class Card                      // Class modeling Card ADT
{
 private:
  int value;                    // Card value: 2-10 for number cards, 11-14 for JQKA; 0 for unknown
  string color;                 // Card color: "red", "black", or "unknown"
  char suit;                    // Card suit: 'H' for hearts, 'D' for diamonds, 'C' for clubs, 'S' for spades or 'U' for unknown

 public:
  //******** Add Constructor Prototypes Below  *********//
  Card();      // Default constructor prototype: creates card with value 0, color unknown, and suit U
    
  Card(int v);      // Parameterized constructor prototype: creates card with value v, color unknown, and suit U
    
  //******** Add Transformer Prototypes Below *********//
  void SetValue(int v);      // SetValue prototype: Sets card value equal to v
  void SetColor(string c);      // SetColor prototype: Sets color value equal to c
  void SetSuit(char s);      // SetSuit prototype:  Sets suit value equal to s

  //******** Add Observer Prototypes Below *********//
  int GetValue() const;         // GetValue prototype: Returns current value of value
  string GetColor() const;      // GetColor prototype: Returns current value of color
  char GetSuit() const;     // GetSuit prototype:  Returns current value of suit
  string Description() const;      // Description prototype: Polymorphic Function!!!
                                // Outputs card characteristics - value as a string (see sample output from p01input1.txt)
};
#endif

***The blackcard.cpp file is here and is the same for redcard.cpp: ***

#include <iostream>
#include <cstdlib>

#include "blackcard.h"

BlackCard::BlackCard(int v)
{

}
string BlackCard::Description() const
{
    string d = "Value = ";    // temporary variable used to accumulate result

    switch (value)            // Append card value to variable's value
    {

    case 2:   d = d + "2";    break;      // Number cards
    case 3:   d = d + "3";    break;
    case 4:   d = d + "4";    break;
    case 5:   d = d + "5";    break;
    case 6:   d = d + "6";    break;
    case 7:   d = d + "7";    break;
    case 8:   d = d + "8";    break;
    case 9:   d = d + "9";    break;
    case 10:  d = d + "10";   break;
    
    case 11:  d = d + "J";    break;      // Face cards
    case 12:  d = d + "Q";    break;
    case 13:  d = d + "K";    break;
    case 14:  d = d + "A";    break;

    default:  d = d + "?";    break;      // Unknown card  
    }
  return d;                 // Return string describing card value
}

An example file for what my original issue above is heart.cpp:

#include <iostream>
#include <cstdlib>

#include "heart.h"

Heart::Heart(int v) : RedCard(v)
{

}

string Heart::Description() const
{
    string d = "Value = ";    // temporary variable used to accumulate result
    
    switch (value)            // Append card value to variable's value
    {
        
    case 2:   d = d + "2";    break;      // Number cards
    case 3:   d = d + "3";    break;
    case 4:   d = d + "4";    break;
    case 5:   d = d + "5";    break;
    case 6:   d = d + "6";    break;
    case 7:   d = d + "7";    break;
    case 8:   d = d + "8";    break;
    case 9:   d = d + "9";    break;
    case 10:  d = d + "10";   break;
    
    case 11:  d = d + "J";    break;      // Face cards
    case 12:  d = d + "Q";    break;
    case 13:  d = d + "K";    break;
    case 14:  d = d + "A";    break;

    default:  d = d + "?";    break;      // Unknown card
    
    }

  return d;                 // Return string describing card value
}

I aplogize in advance for the length of the question and if anything is missing. It's a rather large project and the issue is hard to describe with how manny files are involved.

Please let me know if i'm needing to clarify anything. I appreciate any advice and your time.

lundi 21 février 2022

About `std::conditional_variable`. Why this code snippet stall?

Why this code snippet stall?

The program intends to output firstsecondthird whereas the program stalls after firstsecond has been printed.

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

class Foo {
public:
    Foo() {
        
    }

    void first(std::function<void()> printFirst) 
    {
        {
            std::unique_lock<std::mutex> lk(mutex);
                         
            cv1.wait(lk, [this](){return 1==state;});

            doing = 1;
            // printFirst() outputs "first". Do not change or remove this line.
            printFirst();
                
            state = 2;
        }

        cv2.notify_one();
    }

    void second(std::function<void()> printSecond) 
    {
        {
            std::unique_lock<std::mutex> lk(mutex);
            if(state !=2 )
            {
                if((1 == state)&&(1 != doing))
                {
                    lk.unlock();
                    cv1.notify_one();
                }
            }
                        
            cv2.wait(lk, [this](){return 2==state;});

            doing = 2;
            // printSecond() outputs "second". Do not change or remove this line.
            printSecond();
            
            state = 3;
        }

        cv3.notify_one();
    }

    void third(std::function<void()> printThird) 
    {
        {
            std::unique_lock<std::mutex> lk(mutex);
            if(state !=3 )
            {
                if((1 == state)&&(1 != doing))
                {
                    lk.unlock();
                    cv1.notify_one();
                }
                else if((2 == state)&&(2 != doing))
                {
                    lk.unlock();
                    cv2.notify_one();
                }
            }
                        
            cv3.wait(lk, [this](){return 3==state;});

            // printThird() outputs "third". Do not change or remove this line.
            printThird();
            
            state = 3;
        }
    }

private:
    std::condition_variable cv1;
    std::condition_variable cv2;
    std::condition_variable cv3;
    std::mutex mutex;
    int state{1};
    int doing{0};
};

int main()
{
    Foo foo;

    std::vector<std::thread> threads;

    std::this_thread::sleep_for(std::chrono::milliseconds(300));
    threads.push_back(std::thread([&](){foo.second([]()->void{std::cout <<"second" <<std::endl;});}));

    std::this_thread::sleep_for(std::chrono::milliseconds(300));
    threads.push_back(std::thread([&](){foo.first([]()->void{std::cout <<"first" <<std::endl;});}));

    std::this_thread::sleep_for(std::chrono::milliseconds(300));
    threads.push_back(std::thread([&](){foo.third([]()->void{std::cout <<"third" <<std::endl;});}));

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

    for(auto itr=threads.begin(); itr!=threads.end(); itr++)
    {
        itr->join();
    }
}

AVX performance slower for bitwise xor op and popcount

I am new to writing some avx intrinsics based code so need some help in understanding if my observations are expected. I have 2 methods implementing distance computations, both methods take 2 float arrays and its dimension and returns a float distance. The first method computes a euclidean distance

   static float
    compute_l2Square(const void *pVect1v, const void *pVect2v, const void *qty_ptr) {
        float *pVect1 = (float *) pVect1v;
        float *pVect2 = (float *) pVect2v;
        size_t qty = *((size_t *) qty_ptr);
        float __attribute__((aligned(32))) TmpRes[8];
        size_t qty16 = qty >> 4;

        const float *pEnd1 = pVect1 + (qty16 << 4);

        __m256 diff, v1, v2;
        __m256 sum = _mm256_set1_ps(0);

        while (pVect1 < pEnd1) {
            v1 = _mm256_loadu_ps(pVect1);
            pVect1 += 8;
            v2 = _mm256_loadu_ps(pVect2);
            pVect2 += 8;
            diff = _mm256_sub_ps(v1, v2);
            sum = _mm256_add_ps(sum, _mm256_mul_ps(diff, diff));

            v1 = _mm256_loadu_ps(pVect1);
            pVect1 += 8;
            v2 = _mm256_loadu_ps(pVect2);
            pVect2 += 8;
            diff = _mm256_sub_ps(v1, v2);
            sum = _mm256_add_ps(sum, _mm256_mul_ps(diff, diff));
        }

        _mm256_store_ps(TmpRes, sum);
        return TmpRes[0] + TmpRes[1] + TmpRes[2] + TmpRes[3] + TmpRes[4] + TmpRes[5] + TmpRes[6] + TmpRes[7];
    }

The second method computes a bitwise xor and then counts number of 1 i.e hamming distance

static float compute_hamming(const void* __restrict pVect1v,
                     const void* __restrict pVect2v,
                     const void* __restrict qty_ptr) {
   float *pVect1 = (float *) pVect1v;
   float *pVect2 = (float *) pVect2v;
   size_t qty = *((size_t *)qty_ptr);
   uint64_t __attribute__((aligned(32))) TmpRes[4];
   size_t qty16 = qty >> 4;

   const float *pEnd1 = pVect1 + (qty16 << 4);
   int res = 0;
   __m256 diff, v1, v2;
    while (pVect1 < pEnd1) {
              v1 = _mm256_loadu_ps(pVect1);
              pVect1 += 8;
              v2 = _mm256_loadu_ps(pVect2);
              pVect2 += 8;
              diff = _mm256_xor_ps(v1, v2);
              _mm256_store_si256( (__m256i*)TmpRes,  _mm256_castps_si256(diff));
              res += __builtin_popcountll(TmpRes[0]) + __builtin_popcountll(TmpRes[1])
              + __builtin_popcountll(TmpRes[2]) + __builtin_popcountll(TmpRes[3]);

              v1 = _mm256_loadu_ps(pVect1);
              pVect1 += 8;
              v2 = _mm256_loadu_ps(pVect2);
              pVect2 += 8;
              diff = _mm256_xor_ps(v1, v2);
              _mm256_store_si256( (__m256i*)TmpRes,  _mm256_castps_si256(diff));
              res += __builtin_popcountll(TmpRes[0]) + __builtin_popcountll(TmpRes[1])
                            + __builtin_popcountll(TmpRes[2]) + __builtin_popcountll(TmpRes[3]);
          }
  return res;
    }

For the same number of bits, l2 square distance computation is much faster than hamming i.e almost 2x-4x 9 ( i.e computing l2 distance for 512 bits which 16 floats is faster than computing hamming on the 16 floats) . I am not really sure if this is expected . To me it seems that popcount and storing the results to temp is causing some slowness , because when i modify the l2 distance computation to do xor operation instead of sub i.e replace _mm256_sub_ps with _mm256_xor_ps the l2 computation becomes more fast.

I am benchmarking on a mac os, which has avx instruction support. Also another observation is a non avx implementation of hamming distance using just loop : sum += popcount(vec_a[i] ^ vec_b[i]) is also giving similar numbers as avx implementation . I also checked that avx instructions and methods are invoked just for sanity checks.

Need some help and recommendations on improving the performance since the bottleneck is distance computation method.

Understanding a custom sort comparator - How to know what a true return means

I came across this sort comparator for a vector std::vector<foo>

bool comp(foo& x, foo& y) 
{
    return x.a < y.a;
}

Can someone explain what this does ? Does this mean that if a function returns false. foo x will be on the top and y at the bottom. Basically I am trying to understand is how do i know which element gets to be on the top ?

Power BI measure by percentage

I try to create a measure in Power BI that return from increasing from sales table by 2%. I try many times but I couldn't get a correct result. anyone please help out Thanks

when I call a function it returns a random valued array instead of the "right one" [closed]

I'm trying to improve myself in competitive programming and I'm trying to do a easy task in a hard way. I'm trying to split an array in two arrays (even and odd positions), apply the QuickSort on each of the two and then putting them together once again.

But I have some wrong output, probably I'm getting something wrong with pointers.

int arr[5] = {5, 4, 1, 3, 2};
int** a;
int size = sizeof(arr) / sizeof(arr[0]);
a = makearrs(arr, size);

Here's where I call the function makearrs passing it the array and the fixed size (I could pass 5 but I just calculated it).

Here's the function makearrs

int** makearrs(int* arr, int size){
int size_arr = size / 2;
int even_arr[size_arr + 1];  //[0, 1, 2, 3, 4]
int pair_arr[size_arr + 1];
// Inizializzo
for(int i = 0; i<=size_arr; i++){
    even_arr[i] = 0;
    pair_arr[i] = 0;
}
int j = 0;
for(int i=0; i<size; i = i+2){          //Lettura sicura, va bene per entrambi i casi.
    pair_arr[j] = arr[i];
        if(i+1 != size) {
            even_arr[j] = arr[i + 1];
        }
    j++;
}
int ** a = makepairs(pair_arr, even_arr);
return a;

And finally the function makepairs which creates an array of pointers (two-sized) containing the two arrays (even and odd position array).

int** makepairs(int* arr, int* arr2) {
int** ptr = new int*[2];
ptr[0] = arr;
ptr[1] = arr2;
return ptr;

If I try to for-print the resulting

 int * even;
even = a[1];
int * pair;
pair = a[0];
for(int i=0; i<3; i++){
    cout << even[i];
    cout << "\n";
    cout << pair[i];
    cout << "\n";

I get this output: 4 47398584 1 1 -325478504 47398584

Getting an error while using begin and end iterators

vector <vector<int> > v8;
int N;
cin >> N;
for (int i = 0; i < N; i++)
{
    int n;
    cin >> n;
    vector <int> temp;
    for (int i = 0; i < n; i++)
    {
        int x;
        cin >> x;
        temp.push_back(x);
    }
    v8.push_back(temp);
    
}

vector <int> ::iterator it;
for (it = v8.begin(); it < v8.end(); it++)
{
    cout << (*it) << " ";
}

I'm getting this error:

no operator "=" matches these operandsC/C++(349)
intro.cpp(161, 13): operand types are: __gnu_cxx::__normal_iterator<int *, std::vector<int, std::allocator<int>>> = __gnu_cxx::__normal_iterator<std::vector<int, std::allocator<int>> *, std::vector<std::vector<int, std::allocator<int>>, std::allocator<std::vector<int, std::allocator<int>>>>>

How should I solve this??

dimanche 20 février 2022

Use-case: Python with Cython vs. C++ [closed]

I was playing with high-performance Python and came across Cython and its friends. It looks like a perfect solution - getting the best of both worlds - Python's easy for humans, and C++ and C's speed.

Also, modern C++ is somewhat more similar to Python, which I see as a sign that Python is good for humans.

If Python could be as fast as C with the help of Cython and friends, what's the reason to use C++ anymore? Could you name some use-cases that C++ still does better? And, when is C++ the only choice?

Getting an error while using begin and end in iterators in C++

vector <vector<int> > v8;
int N;
cin >> N;
for (int i = 0; i < N; i++)
{
    int n;
    cin >> n;
    vector <int> temp;
    for (int i = 0; i < n; i++)
    {
        int x;
        cin >> x;
        temp.push_back(x);
    }
    v8.push_back(temp);
    
}

vector <int> ::iterator it;
for (it = v8.begin(); it < v8.end(); it++)
{
    cout << (*it) << " ";
}

I'm getting this error: no operator "=" matches these operandsC/C++(349) intro.cpp(161, 13): operand types are: __gnu_cxx::__normal_iterator<int *, std::vector<int, std::allocator>> = __gnu_cxx::__normal_iterator<std::vector<int, std::allocator> *, std::vector<std::vector<int, std::allocator>, std::allocator<std::vector<int, std::allocator>>>>

How should I solve this??

Cannot figure out how to link date file together with result file

i need help with my Date.h & Date.cpp. cant figure out how to display it in my result.cpp & result.h, please use getline if you are able to. Will include all my files to help you run the whole thing. im stuck at this for sometime and couldnt figure it out.

Date.cpp

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

Date::Date()
{
   dates = 0;
   monthDates = "No new Month Yet.";
   yearDates = 0;
}

Date::Date(unsigned day, string& month, unsigned year)
{
   dates = day;
   monthDates = month;
   yearDates = year;
}

void Date::SetDay(unsigned day)
{
   dates = day;
}
unsigned Date::GetDay() const
{
   return dates;
}

void Date::SetMonth(const string& month)
{
   monthDates = month;
}
void Date::GetMonth(string& month) const
{
   month = monthDates;
}

void Date::SetYear(unsigned year)
{
   yearDates = year;
}
unsigned Date::GetYear() const
{
   return yearDates;
}


istream & operator >> (istream & input,Date & D)
{

}

ostream & operator << (ostream & os, const Date & D)
{

}

Date.h

#ifndef DATE_H
#define DATE_H

#include <string>
#include <iostream>
using namespace std;
class Date
{
   public:
       Date();
       Date(unsigned day, string& month, unsigned year);

       void SetDay(unsigned day);
       unsigned GetDay() const;
       void SetMonth(const string& month);
       void GetMonth(string& month) const;
       void SetYear(unsigned year);
       unsigned GetYear() const;

       //friend ostream & operator <<( ostream & os, const Date & D );
       //friend istream & operator >>( istream & input, Date & D );

   private:
       int dates;
       string monthDates;
       int yearDates;
};
       ostream & operator <<( ostream & os, const Date & D );
       istream & operator >>( istream & input, Date & D );
#endif // DATE_H

Result.cpp

#include "Result.h"
#include "UNIT.H"
#include "Date.h"
#include<sstream>


Result::Result()
{
   this->R_marks = 0;

}


Result::Result(Unit& U, Date& D , float m_marks)
{
   R_Unit = U;
   R_Date = D;
   R_marks = m_marks;
}

void Result::SetUnit(Unit& U)
{
   R_Unit = U;
}

void Result::GetUnit(Unit& U) const
{
   U = R_Unit;
}

void Result::GetDate(Date& D) const
{
   D = R_Date;
}
void Result::SetDate(Date& D)
{
   R_Date = D;
}

void Result::SetMarks(float m_marks)
{
   R_marks = m_marks;
}

float Result::GetMarks() const
{
   return R_marks;
}

unsigned Result::GetCredits() const
{
   return R_Unit.GetCredits();
}
void Result::SetCredits(unsigned cred)
{
   credits = cred;
}

 

istream & operator >> (istream & input,Result & Re)
{
   input >> Re.R_Unit >> Re.R_marks;
   /*
   Unit unit;
   input >> unit;
   Re.SetUnit(unit); */
   string strInput;
   getline(input, strInput,',');
   stringstream ss(strInput);
   float x = 0;
   ss >> x;
   Re.SetMarks(x);

   //getline(input,strInput,',');
   //stringstream ds(strInput);

   return input;


}

ostream & operator << (ostream & os, const Result & Re)
{   //Unit unit;
   //unit = Re.GetUnit();
   //os << Re.GetUnit() << " Marks: " << Re.GetMarks() << '\n';
   //os << Re.R_Unit << " Marks: " << Re.R_marks<< '\n';
   os << Re.R_Unit << " Marks: " << Re.GetMarks() << '\n';
   //os << Re.R_Unit << " Dates: " << Re.GetDate() << Re.<<'\n';
   return os;
}

Result.h

#ifndef RESULT_H
#define RESULT_H

//This is a C++ string library
#include <string.h>
#include <string>
#include "Unit.H"
#include "Date.h"


using namespace std;

class Result
{
   public:
       Result();
       Result(Unit& U, Date& D , float m_marks);

       unsigned GetCredits() const;
       void SetCredits(unsigned cred);
       float GetMarks() const ; //{return R_marks;}
       void SetMarks(float m_marks); //{R_marks = m_marks;}

       void GetUnit(Unit& U) const; //{U = R_Unit;}
       void SetUnit(Unit& U); //{R_Unit = U;}

       void GetDate(Date& D) const;
       void SetDate(Date& D);

       friend ostream & operator <<( ostream & os, const Result & Re );
       friend istream & operator >>( istream & input, Result & Re );

   private:
       Unit R_Unit;
       Date R_Date;
       float R_marks;
       int credits;


};

   //ostream & operator <<( ostream & os, const Result & Re );
   //istream & operator >>( istream & input, Result & Re );


#endif // RESULT_H

Unit.cpp

#include "Unit.h"
#include <sstream>
#include <string>
#include <iostream>
#include <fstream>

Unit::Unit()
{
//name[0] = '\0';
//unitID[0] = '\0';
unitID = "No Unit ID Yet.";
unitName = "No Unit Name yet.";
credits = 0;
}

Unit::Unit(string& ID, string& nam, unsigned cred)
{
   unitName = nam;
   unitID = ID;
   credits = cred;
}

void Unit::GetUnitID(string& unitsID) const
{
   unitsID = unitID;
}
void Unit::SetUnitID(const string& unitsID)
{
   unitID = unitsID;
}

void Unit::GetUnitName(string& unitsName) const
{
   unitsName = unitName;
}
void Unit::SetUnitName(const string& unitsName)
{
   unitName = unitsName;
}
unsigned Unit::GetCredits() const
{
   return credits;
}
void Unit::SetCredits(unsigned cred)
{
  credits = cred;
}


istream & operator >>( istream & input, Unit & U)
{
 //input >> U.unitID >> U.name >> U.credits;
 string strInput;

 getline(input,strInput, ',');
 U.SetUnitID(strInput);

 getline(input, strInput, ',');
 U.SetUnitName(strInput);

 getline(input, strInput, ',');
 stringstream ss(strInput);
 int x = 0;
 ss >> x;
 U.SetCredits(x);

 return input;
}

ostream & operator <<( ostream & os, const Unit & U )
{
   string uName;
   string uID;
   U.GetUnitName(uName);
   U.GetUnitID(uID);
   os  << " Unit: " << uName << '\n'
       << " Unit ID: " << uID << '\n'
       << " Credits: " << U.GetCredits() << '\n';
       return os;
}

Unit.h

#ifndef UNIT_H
#define UNIT_H

#include <iostream>
#include <string>
#include <string.h>  // C string library

using namespace std;

const unsigned UnitNameSize = 100;
const unsigned UnitIDsize = 10;

class Unit {
public:
 Unit();
 //Unit( const char * ID, char * nam, unsigned cred );
 Unit(string& ID, string& nam, unsigned cred);
 Unit(const Unit & other);

 unsigned GetCredits() const;
 // Get the number of credits.
 void SetCredits( unsigned cred );
 // Set the number of credits.

 void GetUnitName(string& unitsName) const;
 void SetUnitName(const string& unitsName);
 void GetUnitID(string& unitsID) const;
 void SetUnitID(const string& unitsID);

 //friend ostream & operator <<( ostream & os, const Unit & U );
 //friend istream & operator >>( istream & input, Unit & U );

private:
 //char name[UnitNameSize];  // course name, C style string. not a C++ string object
 string unitName;
 string unitID;
//  char unitID[UnitIDsize];
 int credits;   // number of credits
};
 ostream & operator <<( ostream & os, const Unit & U );
 istream & operator >>( istream & input, Unit & U );


#endif

Main.cpp

#include <iostream>
#include <fstream>
#include "Unit.h" // Course class declaration
#include "regist.h"  // Registration class declaration


using namespace std;

int main()
{

 ifstream infile( "Resultsinput.txt" );
 if( !infile ) return -1;

 Registration R;
 infile >> R;

 ofstream ofile( "Resultsoutput.txt" );

// Use a debugger and track down the calls made "behind the scene"
 ofile << R
   << "Number of Units = " << R.GetCount() << '\n'
   << "Total credits = " << R.GetCredits()<< '\n';

 return 0;
}

Regist.h

// REGIST.H - Registration class definition
// author KRI
// modified smr

#ifndef REGIST_H
#define REGIST_H


#include <iostream>
#include "Result.h"

using namespace std;

const unsigned MaxResultsUnit = 100;

class Registration {
public:
 Registration();

 unsigned GetCredits() const;
 unsigned GetCount() const;


 friend ostream & operator <<( ostream & os,
        const Registration & R);

 friend istream & operator >>( istream & input,
        Registration & R );

private:
 long studentId;             // student ID number
 unsigned semester;          // semester year, number
 unsigned count;             // number of courses
 Result Results[MaxResultsUnit]; // array of courses
};

inline unsigned Registration::GetCount() const
{
 return count;
}

#endif

Regist.cpp

#include "regist.h"


Registration::Registration()
{
 count = 0;
}

unsigned Registration::GetCredits() const
{
 unsigned sum = 0;
 for(unsigned i = 0; i < count; i++)
   sum += Results[i].GetCredits();

 return sum;
}


istream & operator >>( istream & input, Registration & R )
{
 input >> R.studentId >> R.semester >> R.count;

 for(unsigned i = 0; i < R.count; i++)
   input >> R.Results[i];  // track down which >> operator is called. Hint: look at what is being input.


 return input;
}

ostream & operator <<( ostream & os, const Registration & R )
{
 os << "Student ID: " << R.studentId << '\n'
    << "Semester:   " << R.semester << '\n';

 for(unsigned i = 0; i < R.count; i++)
   os << R.Results[i] << '\n';

 return os;
}

Resultsinput.txt

123456789 1 2 ICT283,Data Structure And Abstractions,3,90,1,2,2019 ICT287,Computer Graphics,3,97, 1,1,2018

What causes this code to trigger implicit int narrowing?

The following code makes clang to fail when -Wc++11-narrowing is specified

#include <stdint.h>

extern uint8_t numbers[];
extern int n;

uint8_t test(int num) {
    uint8_t a{n > 0 ? *numbers : 2};
    return a;
}

(Same code in godbolt: https://godbolt.org/z/nTKqT7WGd)

8:15: error: non-constant-expression cannot be narrowed from type 'int' to 'uint8_t' (aka 'unsigned char') in initializer list [-Wc++11-narrowing]
    uint8_t a{n > 0 ? *numbers : 2};

I read the standard and related issues but I cannot comprehend why a ternary operation with two results that are uint8_t or can be transparently narroweduint8_t (i.e: constant 2) result in a promotion to int that then wants to be explicitly narrowed.

Can someone explain why this happens? Thanks!

unexpected result of pcl::SACsegmentation

Win 11 Pro PCL 1.12.1 Visual Studio

I want to segment a plane within point cloud using SACsegmentation module and get some unexpected result. Though I solve this problem then, I want to know the reason causing the problem. I want to segment the ground(as blue line set showed), but the code returns the gross one as showed with red lines. enter image description here here is the code and pcd file. https://github.com/PointCloudLibrary/pcl/files/8101342/compress.zip And after sampling down the point cloud with UniformSample module, it generates the right result. Is it possible that the size of point cloud has some influence

c++ concurrent hash map with thread-safe find insert count erase and iterator?

I am currently using std::unordered_map container to perform these operations find() insert() erase() count() and to iterate in this container. to increase the performance of my algorithm I need to use all of my CPU threads so I need to use a concurrent container that permit many threads to operate a thread-safe find() insert() erase() count() and iteration on common data.

my first attempt is using tbb::concurrent_unordered_map unfortunately this container does not provide safe_erase() function.

my second attempt is to use tbb::concurrent_hash_map as proposed in many SO posts post1 post2 post3 that provides thread-safe finding, inserting and erasing. But according to this Answer tbb::concurrent_hash_map does not permit safe iterator and they proposed some libraries that provide a collection of concurrent data structures and memory reclamation algorithms such as facebook folly, xenuim that give customizable concurrent_hash_map files, when I checked the source code I got lost how to use those header files.

Also I noticed that std::unordered_map member functions find, insert, end() return an iterator while tbb::concurent_hash_map member functions return a bool and it does not provide thread-safe iterator and find and insert use const_accessor and accessor

this is my class that i am trying to make run in parallel:

query.h

#define CHUNK 32

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

class query {
  friend auto operator<<(std::ostream &, const query &) -> std::ostream &;
public:
  static size_t DT;
  query() = default;
  virtual ~query() = default;
  // Add a query point to d-tree.
  auto increase(const size_t &) -> query &;
  // Check whether a point is query point.
  auto checks(const size_t &) -> bool;
  // Remove a query point.
  auto remove(const size_t &) -> query &;
  // The number of query points.
  auto size() -> size_t;
private:
  static auto chunk_(size_t) -> size_t;
  size_t calculate_ = 0;
  std::vector<size_t> blank_;
  std::array<std::unordered_map<size_t, std::vector<size_t>>, CHUNK> container_;
};

query.cpp

#include "query.h"
size_t query::DT = 0;

auto operator<<(std::ostream &out, const query &query) -> std::ostream & {
  for (auto &&tree : query.container_) {
    for (auto &&s: tree) { out << s.first << std::endl; }
  }
  return out;
}

auto query::increase(const size_t &s) -> query & {
  auto &&it = container_[chunk_(s)].find(s);
  if (it != container_[chunk_(s)].end()) {return *this;}
  std::vector<size_t> v;
  container_[chunk_(s)].insert(std::make_pair(s, v));
  ++calculate_;
  return *this; }

auto query::checks(const size_t &p) -> bool {
    return container_[chunk_(p)].count(p);  }

auto query::remove(const size_t &s) -> query & {
  container_[chunk_(s)].erase(s);
  --calculate_;
  return *this; }

auto query::size() -> size_t { return calculate_;}

auto query::chunk_(size_t index) -> size_t {
  return (int) index % CHUNK;   }

things that I tried:

I am wondering if something like this would be possible:

...// add this to query.h
#include "tbb/concurrent_hash_map.h"
#include <tbb/parallel_for.h>
...
std::array<tbb::concurrent_hash_map<size_t, std::vector<size_t>>, CHUNK> container_;
... // change this in query.cpp
auto query::increase(const size_t &s) -> query & {
  tbb::concurrent_hash_map<size_t, std::vector<size_t>>::const_accessor cacc;
  tbb::concurrent_hash_map<size_t, std::vector<size_t>>::accessor acc;
  auto &&it = container_[chunk_(s)].find(cacc,s);
  if (it != container_[chunk_(s)].end()) {return *this;}
  std::vector<size_t> v;
  container_[chunk_(s)].insert(acc, std::make_pair(s, v));
  ++calculate_;
  return *this; }
...

// later these query functions will be used in other files inside for loops
...
tbb::parallel_for( tbb::blocked_range<size_t>(0,width),
                       [&](tbb::blocked_range<size_t> r)
             {
             for (size_t i=r.begin(); i<r.end(); ++i)
             {
             query.increase(window_[i]);
             }
              });    
...         

errors that I get:

in this line: if (it != container_[chunk_(s)].end()){...}

error: no operator "!=" matches these operands operand types are: bool != ...

I think because find() returns a bool, but end() returns an iterator.

notes that I found in SO answer:

it says that  you don't need a find() method for your task since insert() methods create the element if it does not exist.

What might be the problem? What's the best way to achieve this in my code? Thanks.

samedi 19 février 2022

Why is compiler giving error while using make_unique with array?

Why can't i initialize a unique pointer

#include <iostream>
#include <memory>

class Widget
{
    std::unique_ptr<int[]> arr;
    
public:
    Widget(int size)
    {
        arr = std::make_unique<int[size]>();
    }
    ~Widget()
    {
        
    }
};

int main()
{
    
}

I am not able to understand the meaning of below error messages. What is wrong with my invocation of arr = std::make_unique<int[size]>();

I am just trying to create a class with unique pointer member which manages an array. How should I change the below program and WHY?

Error(s):
1129699974/source.cpp: In constructor ‘Widget::Widget(int)’:
1129699974/source.cpp:13:43: error: no matching function for call to ‘make_unique<int [size]>()’
         arr = std::make_unique<int[size]>();
                                           ^
In file included from /usr/include/c++/7/memory:80:0,
                 from 1129699974/source.cpp:4:
/usr/include/c++/7/bits/unique_ptr.h:824:5: note: candidate: template<class _Tp, class ... _Args> typename std::_MakeUniq<_Tp>::__single_object std::make_unique(_Args&& ...)
     make_unique(_Args&&... __args)
     ^~~~~~~~~~~
/usr/include/c++/7/bits/unique_ptr.h:824:5: note:   template argument deduction/substitution failed:
/usr/include/c++/7/bits/unique_ptr.h: In substitution of ‘template<class _Tp, class ... _Args> typename std::_MakeUniq<_Tp>::__single_object std::make_unique(_Args&& ...) [with _Tp = int [size]; _Args = {}]’:
1129699974/source.cpp:13:43:   required from here
/usr/include/c++/7/bits/unique_ptr.h:824:5: error: ‘int [size]’ is a variably modified type
/usr/include/c++/7/bits/unique_ptr.h:824:5: error:   trying to instantiate ‘template<class _Tp> struct std::_MakeUniq’
/usr/include/c++/7/bits/unique_ptr.h:830:5: note: candidate: template<class _Tp> typename std::_MakeUniq<_Tp>::__array std::make_unique(std::size_t)
     make_unique(size_t __num)
     ^~~~~~~~~~~
/usr/include/c++/7/bits/unique_ptr.h:830:5: note:   template argument deduction/substitution failed:
/usr/include/c++/7/bits/unique_ptr.h: In substitution of ‘template<class _Tp> typename std::_MakeUniq<_Tp>::__array std::make_unique(std::size_t) [with _Tp = int [size]]’:
1129699974/source.cpp:13:43:   required from here
/usr/include/c++/7/bits/unique_ptr.h:830:5: error: ‘int [size]’ is a variably modified type
/usr/include/c++/7/bits/unique_ptr.h:830:5: error:   trying to instantiate ‘template<class _Tp> struct std::_MakeUniq’
/usr/include/c++/7/bits/unique_ptr.h:836:5: note: candidate: template<class _Tp, class ... _Args> typename std::_MakeUniq<_Tp>::__invalid_type std::make_unique(_Args&& ...) <deleted>
     make_unique(_Args&&...) = delete;
     ^~~~~~~~~~~
/usr/include/c++/7/bits/unique_ptr.h:836:5: note:   template argument deduction/substitution failed:
/usr/include/c++/7/bits/unique_ptr.h: In substitution of ‘template<class _Tp, class ... _Args> typename std::_MakeUniq<_Tp>::__invalid_type std::make_unique(_Args&& ...) [with _Tp = int [size]; _Args = {}]’:
1129699974/source.cpp:13:43:   required from here
/usr/include/c++/7/bits/unique_ptr.h:836:5: error: ‘int [size]’ is a variably modified type
/usr/include/c++/7/bits/unique_ptr.h:836:5: error:   trying to instantiate ‘template<class _Tp> struct std::_MakeUniq’

Why is compiler not happy while using make_unique with array?

Why can't i initialize a unique pointer

#include <iostream>
#include <memory>

class Widget
{
    std::unique_ptr<int[]> arr;
    
public:
    Widget(int size)
    {
        arr = std::make_unique<int[size]>();
    }
    ~Widget()
    {
        
    }
};

int main()
{
    
}

I am not able to understand the meaning of below error messages. What is wrong with my invocation of arr = std::make_unique<int[size]>();

I am just trying to create a class with unique pointer member which manages an array. How should i change the below program and WHY?

Error(s):
1129699974/source.cpp: In constructor ‘Widget::Widget(int)’:
1129699974/source.cpp:13:43: error: no matching function for call to ‘make_unique<int [size]>()’
         arr = std::make_unique<int[size]>();
                                           ^
In file included from /usr/include/c++/7/memory:80:0,
                 from 1129699974/source.cpp:4:
/usr/include/c++/7/bits/unique_ptr.h:824:5: note: candidate: template<class _Tp, class ... _Args> typename std::_MakeUniq<_Tp>::__single_object std::make_unique(_Args&& ...)
     make_unique(_Args&&... __args)
     ^~~~~~~~~~~
/usr/include/c++/7/bits/unique_ptr.h:824:5: note:   template argument deduction/substitution failed:
/usr/include/c++/7/bits/unique_ptr.h: In substitution of ‘template<class _Tp, class ... _Args> typename std::_MakeUniq<_Tp>::__single_object std::make_unique(_Args&& ...) [with _Tp = int [size]; _Args = {}]’:
1129699974/source.cpp:13:43:   required from here
/usr/include/c++/7/bits/unique_ptr.h:824:5: error: ‘int [size]’ is a variably modified type
/usr/include/c++/7/bits/unique_ptr.h:824:5: error:   trying to instantiate ‘template<class _Tp> struct std::_MakeUniq’
/usr/include/c++/7/bits/unique_ptr.h:830:5: note: candidate: template<class _Tp> typename std::_MakeUniq<_Tp>::__array std::make_unique(std::size_t)
     make_unique(size_t __num)
     ^~~~~~~~~~~
/usr/include/c++/7/bits/unique_ptr.h:830:5: note:   template argument deduction/substitution failed:
/usr/include/c++/7/bits/unique_ptr.h: In substitution of ‘template<class _Tp> typename std::_MakeUniq<_Tp>::__array std::make_unique(std::size_t) [with _Tp = int [size]]’:
1129699974/source.cpp:13:43:   required from here
/usr/include/c++/7/bits/unique_ptr.h:830:5: error: ‘int [size]’ is a variably modified type
/usr/include/c++/7/bits/unique_ptr.h:830:5: error:   trying to instantiate ‘template<class _Tp> struct std::_MakeUniq’
/usr/include/c++/7/bits/unique_ptr.h:836:5: note: candidate: template<class _Tp, class ... _Args> typename std::_MakeUniq<_Tp>::__invalid_type std::make_unique(_Args&& ...) <deleted>
     make_unique(_Args&&...) = delete;
     ^~~~~~~~~~~
/usr/include/c++/7/bits/unique_ptr.h:836:5: note:   template argument deduction/substitution failed:
/usr/include/c++/7/bits/unique_ptr.h: In substitution of ‘template<class _Tp, class ... _Args> typename std::_MakeUniq<_Tp>::__invalid_type std::make_unique(_Args&& ...) [with _Tp = int [size]; _Args = {}]’:
1129699974/source.cpp:13:43:   required from here
/usr/include/c++/7/bits/unique_ptr.h:836:5: error: ‘int [size]’ is a variably modified type
/usr/include/c++/7/bits/unique_ptr.h:836:5: error:   trying to instantiate ‘template<class _Tp> struct std::_MakeUniq’

'HTTPREQ' in namespace 'std' does not name a type

I don't know much but for project I'm working on cpp code need help on this there are two files one is headerfile HTTPClient.h and other HTTPClient.cpp HTTPClient.h

#ifndef HTTPClient_H_
#define HTTPClient_H_
#define HTTPCLIENT_1_1_COMPATIBLE
#include <memory>
#include <Arduino.h>
#include <WiFiClient.h>
#include <WiFiClientSecure.h>
#define HTTPCLIENT_DEFAULT_TCP_TIMEOUT (5000)
using namespace std;
#define HTTPC_ERROR_CONNECTION_REFUSED  (-1)
#define HTTPC_ERROR_SEND_HEADER_FAILED  (-2)
#define HTTPC_ERROR_SEND_PAYLOAD_FAILED (-3)
#define HTTPC_ERROR_NOT_CONNECTED       (-4)
#define HTTPC_ERROR_CONNECTION_LOST     (-5)
#define HTTPC_ERROR_NO_STREAM           (-6)
#define HTTPC_ERROR_NO_HTTP_SERVER      (-7)
#define HTTPC_ERROR_TOO_LESS_RAM        (-8)
#define HTTPC_ERROR_ENCODING            (-9)
#define HTTPC_ERROR_STREAM_WRITE        (-10)
#define HTTPC_ERROR_READ_TIMEOUT        (-11)
#define HTTP_TCP_BUFFER_SIZE (1460)
typedef enum {
    HTTP_CODE_CONTINUE = 100,
    HTTP_CODE_SWITCHING_PROTOCOLS = 101,
    HTTP_CODE_PROCESSING = 102,
    HTTP_CODE_OK = 200,
    HTTP_CODE_CREATED = 201,
    HTTP_CODE_ACCEPTED = 202,
    HTTP_CODE_NON_AUTHORITATIVE_INFORMATION = 203,
    HTTP_CODE_NO_CONTENT = 204,
    HTTP_CODE_RESET_CONTENT = 205,
    HTTP_CODE_PARTIAL_CONTENT = 206,
    HTTP_CODE_MULTI_STATUS = 207,
    HTTP_CODE_ALREADY_REPORTED = 208,
    HTTP_CODE_IM_USED = 226,
    HTTP_CODE_MULTIPLE_CHOICES = 300,
    HTTP_CODE_MOVED_PERMANENTLY = 301,
    HTTP_CODE_FOUND = 302,
    HTTP_CODE_SEE_OTHER = 303,
    HTTP_CODE_NOT_MODIFIED = 304,
    HTTP_CODE_USE_PROXY = 305,
    HTTP_CODE_TEMPORARY_REDIRECT = 307,
    HTTP_CODE_PERMANENT_REDIRECT = 308,
    HTTP_CODE_BAD_REQUEST = 400,
    HTTP_CODE_UNAUTHORIZED = 401,
    HTTP_CODE_PAYMENT_REQUIRED = 402,
    HTTP_CODE_FORBIDDEN = 403,
    HTTP_CODE_NOT_FOUND = 404,
    HTTP_CODE_METHOD_NOT_ALLOWED = 405,
    HTTP_CODE_NOT_ACCEPTABLE = 406,
    HTTP_CODE_PROXY_AUTHENTICATION_REQUIRED = 407,
    HTTP_CODE_REQUEST_TIMEOUT = 408,
    HTTP_CODE_CONFLICT = 409,
    HTTP_CODE_GONE = 410,
    HTTP_CODE_LENGTH_REQUIRED = 411,
    HTTP_CODE_PRECONDITION_FAILED = 412,
    HTTP_CODE_PAYLOAD_TOO_LARGE = 413,
    HTTP_CODE_URI_TOO_LONG = 414,
    HTTP_CODE_UNSUPPORTED_MEDIA_TYPE = 415,
    HTTP_CODE_RANGE_NOT_SATISFIABLE = 416,
    HTTP_CODE_EXPECTATION_FAILED = 417,
    HTTP_CODE_MISDIRECTED_REQUEST = 421,
    HTTP_CODE_UNPROCESSABLE_ENTITY = 422,
    HTTP_CODE_LOCKED = 423,
    HTTP_CODE_FAILED_DEPENDENCY = 424,
    HTTP_CODE_UPGRADE_REQUIRED = 426,
    HTTP_CODE_PRECONDITION_REQUIRED = 428,
    HTTP_CODE_TOO_MANY_REQUESTS = 429,
    HTTP_CODE_REQUEST_HEADER_FIELDS_TOO_LARGE = 431,
    HTTP_CODE_INTERNAL_SERVER_ERROR = 500,
    HTTP_CODE_NOT_IMPLEMENTED = 501,
    HTTP_CODE_BAD_GATEWAY = 502,
    HTTP_CODE_SERVICE_UNAVAILABLE = 503,
    HTTP_CODE_GATEWAY_TIMEOUT = 504,
    HTTP_CODE_HTTP_VERSION_NOT_SUPPORTED = 505,
    HTTP_CODE_VARIANT_ALSO_NEGOTIATES = 506,
    HTTP_CODE_INSUFFICIENT_STORAGE = 507,
    HTTP_CODE_LOOP_DETECTED = 508,
    HTTP_CODE_NOT_EXTENDED = 510,
    HTTP_CODE_NETWORK_AUTHENTICATION_REQUIRED = 511
} t_http_codes;
typedef enum {
    HTTPC_TE_IDENTITY,
    HTTPC_TE_CHUNKED
} transferEncoding_t;
typedef enum {
    HTTPC_DISABLE_FOLLOW_REDIRECTS,
    HTTPC_STRICT_FOLLOW_REDIRECTS,
    HTTPC_FORCE_FOLLOW_REDIRECTS
} followRedirects_t;
#ifdef HTTPCLIENT_1_1_COMPATIBLE
class TransportTraits;
typedef std::unique_ptr<TransportTraits> TransportTraitsPtr;
#endif
namespace HTTPREQ{
class HTTPClient
{
public:
    HTTPClient();
    ~HTTPClient();
    bool begin(WiFiClient &client, String url);
    bool begin(WiFiClient &client, String host, uint16_t port, String uri = "/", bool https = false);
#ifdef HTTPCLIENT_1_1_COMPATIBLE
    bool begin(String url);
    bool begin(String url, const char* CAcert);
    bool begin(String host, uint16_t port, String uri = "/");
    bool begin(String host, uint16_t port, String uri, const char* CAcert);
    bool begin(String host, uint16_t port, String uri, const char* CAcert, const char* cli_cert, const char* cli_key);
#endif
    void end(void);
    bool connected(void);
    void setReuse(bool reuse);
    void setUserAgent(const String& userAgent);
    void setAuthorization(const char * user, const char * password);
    void setAuthorization(const char * auth);
    void setAuthorizationType(const char * authType);
    void setConnectTimeout(int32_t connectTimeout);
    void setTimeout(uint16_t timeout);
    void setFollowRedirects(followRedirects_t follow);
    void setRedirectLimit(uint16_t limit);
    bool setURL(const String &url);
    void useHTTP10(bool usehttp10 = true);
    int GET();
    int PATCH(uint8_t * payload, size_t size);
    int PATCH(String payload);
    int POST(uint8_t * payload, size_t size);
    int POST(String payload);
    int PUT(uint8_t * payload, size_t size);
    int PUT(String payload);
    int sendRequest(const char * type, String payload);
    int sendRequest(const char * type, uint8_t * payload = NULL, size_t size = 0);
    int sendRequest(const char * type, Stream * stream, size_t size = 0);
    void addHeader(const String& name, const String& value, bool first = false, bool replace = true);
    void collectHeaders(const char* headerKeys[], const size_t headerKeysCount);
    String header(const char* name);
    String header(size_t i);
    String headerName(size_t i);
    int headers();
    bool hasHeader(const char* name);
    int getSize(void);
    const String &getLocation(void);
    WiFiClient& getStream(void);
    WiFiClient* getStreamPtr(void);
    int writeToStream(Stream* stream);
    String getString(void);
    static String errorToString(int error);
protected:
    struct RequestArgument {
        String key;
        String value;
    };
    bool beginInternal(String url, const char* expectedProtocol);
    void disconnect(bool preserveClient = false);
    void clear();
    int returnError(int error);
    bool connect(void);
    bool sendHeader(const char * type);
    int handleHeaderResponse();
    int writeToStreamDataBlock(Stream * stream, int len);
#ifdef HTTPCLIENT_1_1_COMPATIBLE
    TransportTraitsPtr _transportTraits;
    std::unique_ptr<WiFiClient> _tcpDeprecated;
#endif
    WiFiClient* _client = nullptr;
    String _host;
    uint16_t _port = 0;
    int32_t _connectTimeout = -1;
    bool _reuse = true;
    uint16_t _tcpTimeout = HTTPCLIENT_DEFAULT_TCP_TIMEOUT;
    bool _useHTTP10 = false;
    bool _secure = false;
    String _uri;
    String _protocol;
    String _headers;
    String _userAgent = "ESP32HTTPClient";
    String _base64Authorization;
    String _authorizationType = "Basic";
    RequestArgument* _currentHeaders = nullptr;
    size_t           _headerKeysCount = 0;
    int _returnCode = 0;
    int _size = -1;
    bool _canReuse = false;
    followRedirects_t _followRedirects = HTTPC_DISABLE_FOLLOW_REDIRECTS;
    uint16_t _redirectLimit = 10;
    String _location;
    transferEncoding_t _transferEncoding = HTTPC_TE_IDENTITY;
};
}
#endif /* HTTPClient_H_ */

and the errors

HTTPClient.cpp:97:7: error: 'HTTPREQ' in namespace 'std' does not name a type
  std::HTTPREQ::HTTPREQ()
       ^
HTTPClient.cpp:104:14: error: scope 'HTTPREQ' before '~' is not a class-name
 int HTTPREQ::~HTTPREQ()
              ^

Error 1

main.cpp: In function 'void loop()':
main.cpp:670:16: error: expected primary-expression before 'http'
       HTTPREQ  http;
                ^
main.cpp:671:8: error: 'http' was not declared in this scope
        http.begin("http://xx.xx.xx:xxxx/");

Actually there's issue with HTTPClient because there's another HTTPClient cpp file and there's conflict class name(HTTPClient) so I tried namespace but I can't able to do that please help me in achieving this thanks in-advance......

Sets in STL of C++

I have been reading about set container from cplusplus.com, But I didn't understood what does the following line mean by ' direct iteration on subsets based on their order ' ?

Set containers are generally slower than unordered_set containers to access individual elements by their key, but they allow the direct iteration on subsets based on their order.

vendredi 18 février 2022

Is it mandatory for destructor to use delete when managed via unique pointer?

If a c++ resource is managed via unique_ptr then does the destructor of the class need to free the heap memory it allocated or it gets free automatically when the unique_ptr goes out of scope? For eg. In below example if I plan to create a unique_ptr to Entity class and I don't add delete in destructor then what will happen?

class Entity
{
private:
    int* data;
public:
    explicit Entity(const int size) { data = new int[size]; } // acquire
    ~Entity() { delete[] data; } // release
    void do_something() {}
};

void functionUsingEntity() {
    Entity e(100);   // lifetime automatically tied to enclosing scope

    e.do_something();

} // automatic destruction and deallocation for e

Edge cases when replacing a type alias with inheritance

I have a type Point that's simply an alias for Vector3: using Point = Vector3;

I'd like to be able to add functionality to Point, but no additional state. So I'd like to replace it with a class inheriting from Vector3:

class Point : public Vector3 {
  using Base = Vector3;
  using Base::Base;

  Point(const Base& base) : Base(base) {}
  Point(Base&&) : Base(std::move(base)) {}

  Point& operator=(const Base& base) { 
    Base::operator=(base); 
    return *this; 
  }

  Point& operator=(Base&& base) {
    Base::operator(std::move(base));
    return *this;
  }
};

This inherits the base class constructors and allows converting/moving values of Vector3 to Point since we could do that freely before.

The only thing that you could do before that you can't do with this method is freely casting pointers. Point* -> Vector3* still works, but Vector3* -> Point won't work implicitly anymore.

Are there any other corner cases when replacing a typedef in this fashion?

Error code 1236 from GetQueuedCompletionStatus function

I get error code 1236 from GetQueuedCompletionStatus() function, I tried to debug with vs but still cant figure it out. Any help would be greatly appreciated. Let me know if you may need anymore information. I create new thread whenever create room request sent to server. This is my workerThread:

unsigned __stdcall serverWorkerThread(void* completionPortID) {
    HANDLE completionPort = (HANDLE)completionPortID;
    DWORD transferredBytes, flag = 0;
    LPPER_HANDLE_DATA perHandleData;
    LPPER_IO_DATA perIoData;
    LPUSER user;
    while (1) {
        if (GetQueuedCompletionStatus(completionPort, &transferredBytes, (PULONG_PTR)&perHandleData, (LPOVERLAPPED*)&perIoData, INFINITE) == 0) {
            if (GetLastError() != 64) {
                printf("Error %d: GetQueuedCompletionStatus() failed\n", GetLastError());
            }
            else {
                user = (LPUSER)perIoData;
                disconnect(user);
            }
            return 0;
        }
        user = (LPUSER)perIoData;
        if (transferredBytes == 0) {
            disconnect(user);
            continue;
        }
        if (perIoData->operation == RECEIVE) {
            perIoData->recvBytes += transferredBytes;
        }
        else {
            perIoData->sendBytes -= transferredBytes;
            strcpy_s(perIoData->sendBuff, BUFF_SIZE, perIoData->sendBuff + transferredBytes);
        }
        int len;
        if (perIoData->sendBytes > 0) {
            sendMess(user);
        }
        else if ((len = checkEndMessage(perIoData->recvBuff, perIoData->recvBytes)) != -1) {
            string message(perIoData->recvBuff, perIoData->recvBuff + len - 2);
            string result = handleRequest(user, message);
            perIoData->recvBytes -= len;
            strcpy_s(perIoData->recvBuff, BUFF_SIZE, perIoData->recvBuff + len);
            strcpy_s(perIoData->sendBuff, BUFF_SIZE, result.c_str());
            strcat_s(perIoData->sendBuff, BUFF_SIZE, DELIMITER);
            perIoData->sendBytes = result.size() + 2;
            sendMess(user);
        }
        else {
            recvMess(user);
        }
    }
}

This is my room thread:

unsigned __stdcall examThread(void* ptrRoom) {
    LPROOM room = (LPROOM)ptrRoom;
    string question = "EXAM " + room->exam->question;
    std::chrono::system_clock::time_point startTime;
    getTime(room->startTime, startTime);
    std::this_thread::sleep_until(startTime);
    EnterCriticalSection(&criticalSection);
    room->status = ON_GOING;
    LeaveCriticalSection(&criticalSection);
    for (USER* user : room->contestant) {
        strcpy_s(user->perIoData.sendBuff, BUFF_SIZE, "STARTTEST ");
        strcat_s(user->perIoData.sendBuff, BUFF_SIZE, question.c_str());
        strcat_s(user->perIoData.sendBuff, BUFF_SIZE, "\r\n");
        sendMess(user);
    }
    std::this_thread::sleep_for(std::chrono::minutes(room->duration));
    EnterCriticalSection(&criticalSection);
    room->status = FINISH;
    LeaveCriticalSection(&criticalSection);
    std::this_thread::sleep_for(std::chrono::hours(1));
    EnterCriticalSection(&criticalSection);
    listRoom.erase(std::find(listRoom.begin(), listRoom.end(), room));
    LeaveCriticalSection(&criticalSection);
    delete room;
    return 0;
}

After sendMess(user), I return error code 1236 from GetQueuedCompletionStatus. This is my struct:

typedef struct PER_IO_DATA {
    WSAOVERLAPPED overlapped;
    WSABUF wBuff;
    char recvBuff[BUFF_SIZE];
    char sendBuff[BUFF_SIZE];
    int operation;
    int recvBytes;
    int sendBytes;
    PER_IO_DATA() {
        ZeroMemory(&overlapped, sizeof(WSAOVERLAPPED));
        ZeroMemory(recvBuff, BUFF_SIZE);
        ZeroMemory(sendBuff, BUFF_SIZE);
        sendBytes = 0;
        recvBytes = 0;
    }
} *LPPER_IO_DATA;

typedef struct USER {
    PER_IO_DATA perIoData;
    PER_HANDLE_DATA perHandleData;
    string name;
    int status;
    LPROOM inRoom;
    USER() {
        status = CONNECTED;
    }
} *LPUSER; 

sendMess function:

void sendMess(LPUSER user) {
    LPPER_HANDLE_DATA perHanleData = &(user->perHandleData);
    LPPER_IO_DATA perIoData = &(user->perIoData);
    DWORD transferredBytes, flag = 0;
    perIoData->operation = SEND;
    perIoData->wBuff.buf = perIoData->sendBuff;
    perIoData->wBuff.len = perIoData->sendBytes;
    if (WSASend(perHanleData->socket, &(perIoData->wBuff), 1, &transferredBytes, flag, &(perIoData->overlapped), 0) == SOCKET_ERROR) {
        if (WSAGetLastError() != WSA_IO_PENDING) {
            printf("Error %d: WSASend() 1 failed", WSAGetLastError());
        }
    }
}