jeudi 30 mars 2023

is it bad to hash raw buffer by using std::string as a wrapper?

C++ std::hash<> has some standard specializations for fix-sized basic types, and std::string family, which is the only one having variable memory size(and std::vector<bool> too, unconcerned here)

once we tend to hashing multiple variables or a buffer, we need to implement a hashing algorithom, which is hard to remember and easily be wrong.

std::string can be used as a buffer(std::vector<std::byte> is better, I know), and if we store utf-8 string(which have bytes other than ASCII) in it, it is likely hashes well too.

what is the disadvantage like this:

std::string hash_wrapper(4 * 4, '\0');
int* write_ptr = reinterpret_cast<int*>(hash_wrapper.data());

write_ptr[0] = val1;
write_ptr[1] = val2;
write_ptr[2] = val3;
write_ptr[3] = val4;

std::unordered_map<std::string, int> ht;
ht[hash_wrapper] = val;

mercredi 29 mars 2023

HLS : Cellular Automata

So I have been trying to build the following, using Vitis HLS:

ca.hpp:

#include <cstdio>
#include <cinttypes>

#include "ap_axi_sdata.h"
#include "hls_stream.h"

#define N 8

typedef int DataType;

typedef hls::axis<DataType, 0, 0, 0> packet;
typedef hls::stream<packet> stream;

bool is_equal(DataType previous_state[3], DataType test[3]);
DataType rule30(DataType previous_state[3]);

template <typename T> void ca(T input[N], T output[N]);

ca.cpp:

#include "ca.hpp"

DataType rule30_111[3] = {1, 1, 1};
DataType rule30_110[3] = {1, 1, 0};
DataType rule30_101[3] = {1, 0, 1};
DataType rule30_011[3] = {0, 1, 1};
DataType rule30_100[3] = {1, 0, 0};
DataType rule30_010[3] = {0, 1, 0};
DataType rule30_001[3] = {0, 0, 1};
DataType rule30_000[3] = {0, 0, 0};

bool is_equal(DataType previous_state[3], DataType test[3]){
    int check = 1;
    for(int j = 0; j < 3; j++){
        check = previous_state[j]==test[j];
        if(check == 0){
            return 0;
        }
    }
    return 1;
}

DataType rule30(DataType previous_state[3]){
    if(is_equal(previous_state, rule30_111)){
        return 0;
    } else if(is_equal(previous_state, rule30_110)){
        return 0;
    } else if(is_equal(previous_state, rule30_101)){
        return 0;
    } else if(is_equal(previous_state, rule30_011)){
        return 1;
    } else if(is_equal(previous_state, rule30_001)){
        return 1;
    } else if(is_equal(previous_state, rule30_010)){
        return 1;
    } else if(is_equal(previous_state, rule30_100)){
        return 1;
    } else if(is_equal(previous_state, rule30_000)){
        return 0;
    } else {
        return -1;
    }
}

template <typename T> void ca(T input[N], T output[N]) {
    for(int i = 0; i < N; i++){
        if(i > 0 and i < N - 1){
            T previous_state[3] = {input[i - 1], input[i], input[i + 1]};
            output[i] = rule30(previous_state);
        }
    }
}

void cellular_autmata(stream &signal, stream &result) {
#pragma HLS INTERFACE axis port=signal
#pragma HLS INTERFACE axis port=result
#pragma HLS INTERFACE ap_ctrl_none port=return

    DataType in[N];
    DataType out[N];

read:
    for(int i = 0; i < N; i++){
        packet temp = signal.read();
        in[i] = temp.data;
    }

    ca<DataType>(in, out);

write:
    for(int i = 0; i < N; i++){
        packet temp;
        temp.data = out[i];
        ap_uint<1> last = 0;
        if(i == N - 1){
            last = 1;
        }
        temp.last = last;
        temp.keep = -1;
        result.write(temp);
    }
}

ca_tb.cpp:

#include "ca.hpp"

void sw_ca(DataType input[], DataType output[]) {
    for(int i = 0; i < N; i++){
        if(i > 0 and i < N - 1){
            DataType rule[3] = {input[i - 1], input[i], input[i + 1]};
            output[i] = rule30(rule);
        }
    }
}

int main(void) {
    /*initialise*/
    int i, err;

    DataType in[N] = {0,0,1,1,0,0,1,1};
    DataType out_sw[N];
    DataType out_hw[N];

    std::cout << "signal in:" << std::endl;
    for (i = 0; i < N; i++) {
        //in[i] = i % 2;
        out_sw[i] = 0;
        out_hw[i] = 0;
        std::cout << in[i] << " ";
    }
    std::cout << std::endl;

    std::cout << std::endl;

    /* software */
    sw_ca(in, out_sw);
    std::cout<<"software kernel complete\n"<<std::endl;

    /* hardware */
    ca<DataType>(in, out_hw);
    std::cout<<"hardware kernel complete\n"<<std::endl;

    /* comparison */
    err = 1;
    std::cout << "signal out:" << std::endl;
    for(i = 0; i < N; i++){
        if(out_sw[i] != out_hw[i]){
            err = 0;
        }
        std::cout << out_hw[i] << " ";
    }
    std::cout<<std::endl;

    if (err == 1) {
        printf("Test successful!\r\n");
        return 0;
    }
    printf("Test failed\r\n");
    return 1;
}

Testbench runs fine...

And am repeatedly getting the error from vitis when trying to synthesize:

ERROR: [HLS 214-157] Top function not found: there is no function named 'ca' cellular_automata:cellular_automata Mar 29, 2023, 3:14:13 PM

Would massively appreciate any pointers here!

So for this system, I would expect a Vivado IP to be generated, but the Vitis compilation is halted with the error shown above

variadic class template can't compile

template<typename... Types>
class Tuple;

// recursive case:
template<typename Head, typename... Tail>
class Tuple<Head, Tail...>
{
 private:
  Head head;
  Tuple<Tail...> tail;
 public:
  // constructors:
  Tuple() {
  }
  Tuple(Head const& h, Tuple<Tail...> const& t)
    : head(h), tail(t) {
  }
  //...

  Head& getHead() { return head; }
  Head const& getHead() const { return head; }
  Tuple<Tail...>& getTail() { return tail; }
  Tuple<Tail...> const& getTail() const { return tail; }
};

// basis case:
template<>
class Tuple<> {
  // no storage required
};

int main()
{
    Tuple<int,double> (1,4.5);
}

compiling it with g++ 11.3.0, I get this errors:

error: no matching function for call to ‘Tuple<int, double>::Tuple(int, double)’

why does this error happen and how to fix them?

mardi 28 mars 2023

Question's accepted Answer is wrong . . .Answer should be revised for future reference

Here the answer is accepted but this is wrong answer. The statement is not correct. The number of explicit parameters a member function takes depends on the number of arguments required by the function.

Answer should be: Since the left-hand operand of this operator* (const float &m, const vector &v) is a float and not a vector object, it cannot be a member function of the Vector class. Therefore, this function is implemented as a non-member function outside the Complex class/or say friend function. Same goes to the const vector vector::operator* (const vector &v, const float &m) with difference now float at right-hand. Kindly verify . .

When should propagate_on_container_copy_assignment and propagate_on_container_move_assignment be true?

I am trying to understand allocators, but I do not understand exactly the uses of some standard aliases. In particular, I have already read in cppreference the consequences of the propagate_on_container_copy_assignment and propagate_on_container_move_assignment aliases on container's assignment operations:

propagate_on_container_copy_assignment

If (this member is derived from std::true_type and) the allocators of the source and the target containers do not compare equal, copy assignment has to deallocate the target's memory using the old allocator and then allocate it using the new allocator before copying the elements (and the allocator).

propagate_on_container_move_assignment

If this member is not provided or derived from std::false_type and the allocators of the source and the target containers do not compare equal, move assignment cannot take ownership of the source memory and must move-assign or move-construct the elements individually, resizing its own memory as needed.

Reading the notes below and checking some implementations of containers, it seems the cost of the assignment operation depends from the value of these aliases, if the source and the target allocators do not compare equal. Then, if an allocator provides fast allocate and deallocate operations but has the 'wrong' values for these aliases, the cost can be very high.

In general, under what conditions should the designer of a custom allocator mark one or the other alias as true or false?

NOTE: I am not asking what the designer or the container should do if these aliases are true or false, but in which conditions the designer of the allocator should declare them as true or false.

What exactly is the difference between static constexpr const char * vs static const char * const in member variables

My question is are these two definitions below the same?


Class A 
{
    public: 
        static constexpr const char *something = "Something";
} 

And

Class A 
{
    public: 
        const char * const something = "Something";
} 

I understand that constexpr expressions are always evaluated at compile time and const expressions may or may not be. But in my particular case, it's just a string literal. Which means, the second expression

const char * const

also should be evaluated at compile time as per my understanding. Is my understanding right? Or, does the constexpr expression has any advantage over the const one?

Also, I'm aware that I can't declare a non-static member as constexpr because it won't be able to initialize until the object is instantiated. I wonder if this static adds any advantage to the constexpr expression in terms of efficiency?

Basically, I want to declare some constant strings and I want to do it in the most efficient way as this is for a firmware with limited memory and there are probably some 1000's of constant string literals.

lundi 27 mars 2023

SFINAE for std::reference_wrapper constructors

The implementation of std::reference_wrapper in cppreference has the following constructor. Can someone explain what detail::FUN<T>(..) does or provide some detail as to what this SFINAE construct is trying to accomplish? Is this just to make sure U& is convertible to T&?

    namespace detail {
      template <class T> constexpr T& FUN(T& t) noexcept { return t; }
      template <class T> void FUN(T&&) = delete;
    }
    // construct/copy/destroy
    template <class U, class = decltype(
        detail::FUN<T>(std::declval<U>()),
        std::enable_if_t<!std::is_same_v<reference_wrapper, std::remove_cvref_t<U>>>()
    )>
    constexpr reference_wrapper(U&& u)
        noexcept(noexcept(detail::FUN<T>(std::forward<U>(u))))
        : _ptr(std::addressof(detail::FUN<T>(std::forward<U>(u)))) {}
 

Since brace-initializataion is possible, why do we still have std::make_pair? What's the purpose or advantage of it? [duplicate]

As we know, both of these ways to assign are possible. Why we still have std::make_pair?

std::pair<int, char> myPair1 = { 1,'a' };
std::pair<int, char> myPair2 = std::make_pair(1, 'a');

I'm not here to criticize the syntax. I just really want to know what's the advantage for us to use std::make_pair instead of directly using the curly braces.

Actually, I think the only advantage is that it can make our code more readable, like you're passing the parameter with std::make_pair instead of the curly braces. It makes it easier to tell that you're passing a pair. Since the curly brace can refer to something more, like a tuple or array.

dimanche 26 mars 2023

Why my vscode always print following logs when I run program?

Vscode always print following logs when I run program. enter image description here

I don't want to print this log.. What I have to do not to display this log in terminal?

[My launch.json] { "version": "0.2.0", "configurations": [ { "name": "(gdb) Start", "type": "cppdbg", "request": "launch", "program": "${fileDirname}\exe\${fileBasenameNoExtension}.exe", "args": [], "cwd": "${fileDirname}\exe", "environment": [], "externalConsole": false, "MIMode": "gdb", "miDebuggerPath": "C:\mingw64\bin\gdb.exe", }

]

}

I tried googling, but no solutions worked.

samedi 25 mars 2023

Red Black Trees C++

This is a basic RED-BLACK Tree program which works fine for most part other than the insertion and Deletion. I tried a debugger but am still unable to find the problem. The preorder is E C B A D I G F H K, where as it is supposed to be E B A C D H F G I K. The postorder is A B D C F H G K I E, where as it is supposed to be A C B E G K I H F D. And the inorder is A B C D E F G H I K

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


template <typename keytype, typename valuetype>                                       //one lesson try to fit for of the functions from the private so that the access can be easier

class RBTree{
    private:
        struct Node{
            bool color;                                                         //color is true for red and false for black
            int size;
            Node *left, *right, *parent;
            keytype key;
            valuetype val; 
        };

        Node* root;

        Node* newNode(keytype k, valuetype v, bool color = true){            //usually starts with the root and then the leaves can be placed to the left and right
            Node *newRBNode = new Node;
            newRBNode->color = color;
            newRBNode->key = k;
            newRBNode->left = NULL;
            newRBNode->right = NULL;
            newRBNode->parent = NULL;
            newRBNode->size = 1;                                                //size 1 as it is 1 leaf initially
            newRBNode->val = v;
            return newRBNode;
        }

        void clearMemory(Node *current) {
            if (current == NULL){                                               //uses recursion to go through the tree and delete the leaves
                return;
            }

            clearMemory(current->left);
            if (current->left != NULL){
                free(current->left);
            }
            clearMemory(current->right);
            if (current->right != NULL){
                free(current->right);
            }
        }

        int size(Node* current){
            if (current == NULL){
                return 0;
            }
            return current->size;
        }

        Node* leftRotate(Node* current){
            Node* y = current->right;
            current->right = y->left;
            y->left = current;
            y->color = y->left->color;
            y->left->color = true;

            current->size = size(current->left) + size(current->right) + 1;
            y->size = size(y->left) + size(y->right) + 1;
            return y;

        }

        Node* rightRotate(Node* current){                                                            //conventional rotation from textbook and updates the size
            Node* y = current->left;
            current->left = y->right;
            y->right = current;
            y->color = y->right->color;
            y->right->color = true;

            current->size = size(current->left) + size(current->right) + 1;
            y->size = size(y->left) + size(y->right) + 1;
            return y;

        }

        Node* copy(Node* current){                                                       //uses recursion to copy
            Node* node = newNode(current->key, current->val, current->color);
            if (current->left != NULL){
                node->left = copy(current->left);
            }

            if(current->right != NULL){
                node->right = copy(current->right);
            }

            node->size = current->size;
            return node;
        }

        void colorFlip(Node* current){
            current->color = !(current->color);                                                               //flips the color of the parent and the children (usually one red and two blacks)
            current->left->color = !(current->left->color);
            current->right->color = !(current->right->color);
        }

        bool isRed(Node* current){                                                                  //needs fixing
            if (current == NULL){
                return false;
            }
            return (current->color);
        }

        Node* Insertion(Node* current, keytype key, valuetype val){                                                       //Messed up
            if (current == NULL){
                Node* test = newNode(key, val);
                return test;
            }

            if (isRed(current->left) && isRed(current->right)){
                colorFlip(current);
            }

            if (key < current->key){
                current->left = Insertion(current->left, key, val);
            }

            else if (key > current->key){
                current->right = Insertion(current->right, key, val);
            }

            else if (current->key == key){
                current->val = val;
            }

            if (isRed(current->right)){                                                                     //if right node is red before the introduced rode then rotation happens
                current = leftRotate(current);
            }

            if (isRed(current->left) && isRed(current->left->left)){                                        //conflict happens and the rotation starts
                current = rightRotate(current);
            }

            if(isRed(current->right)){                                                                      //fixes up the whole tree after deletion
                current = leftRotate(current);
            }

            if (isRed(current->left) && isRed(current->left->left)){
                current = rightRotate(current);
            }

            if (isRed(current->left) && isRed(current->right)){
                colorFlip(current);
            }

            current->size = size(current->left) + size(current->right) + 1;
            return current;
        }

        Node* Deletion(Node* current, keytype key){                                                                             //Gotta fix it
            if (key < current->key){                                                                                            //uses the textboob delete fixation function
                if (!isRed(current->left) && !isRed(current->left->left)){
                    colorFlip(current);

                if (isRed(current->right->left)){
                    current->right = rightRotate(current->right);
                    current = leftRotate(current);
                    colorFlip(current);
                    }
                }

                current->left = Deletion(current->left, key);
            }

            else {
                if (isRed(current->left)){
                    current = rightRotate(current);
                }

                if ((key == current->key) && (current->right == NULL)){
                    return NULL;
                }

                if(!isRed(current->right) && !isRed(current->right->left)){
                    colorFlip(current);

                    if (isRed(current->left->left)){
                    current = rightRotate(current);
                    colorFlip(current);
                    }

                }

                if (current->key == key){
                    Node* y = current->right;

                    while(y->left != NULL){
                        y = y->left;
                    }

                    current->key = y->key;
                    current->val = y->val;
                    current->right = Deletion(current->right, current->key);
                }

                else{
                    current->right = Deletion(current->right, key);
                }
            }

            if(isRed(current->right)){                                                                      //fixes up the whole tree after deletion
                current = leftRotate(current);
            }

            if (isRed(current->left) && isRed(current->left->left)){
                current = rightRotate(current);
            }

            if (isRed(current->left) && isRed(current->right)){
                colorFlip(current);
            }

            current->size = size(current->left) + size(current->right) + 1;
            return current;
        } 

        valuetype* findVal(Node* current, keytype key){
            if (current == NULL){
                return NULL;
            }

            else if (current->key == key){
                return &(current->val);
            }

            else if(current->key > key){
                return findVal(current->left, key);
            }

            else if(current->key < key){
                return findVal(current->right, key);
            }

            return NULL;
        }

        keytype Position(Node* current, int sample){
            int pos = size(current->left) + 1;

            if (pos == sample){
                return current->key;
            }

            else if(sample < pos){
                return Position(current->left, sample);
            }

            else{
                return Position(current->right, sample-pos);
            }
        }

        int Rank(Node* current, keytype key){
            if(current == NULL){
                return 0;
            }

            else if(current->key > key){
                return Rank(current->left, key);
            }

            else if(current->key < key){
                return (size(current->left) + 1 + Rank(current->right, key));
            }

            else if(current->key == key){
                return (current->size - size(current->right));
            }

            else{
                return 0;
            }
        }

        keytype* find_sucessor(Node* current, keytype K){
            Node* successor = NULL;
            while(current){
                if (current->key > K){
                    successor = current;
                    current = current->left;
                }

                else{
                    current = current->right;
                }
            }
            return &(successor->key);
        }

        keytype* find_predecessor(Node* current, keytype K){
            Node* predecessor = NULL;
            while(current){
                if (current->key >= K){
                    current = current->left;
                }

                else{
                    predecessor = current;
                    current = current->right;
                }
            }
            return &(predecessor->key);
        }
        

        void print_preorder(Node* current){
            if (current == NULL){
                return;
            }

            cout << current->key << " ";
            print_preorder(current->left);
            print_preorder(current->right);
        }

        void print_postorder(Node* current){
            if (current == NULL){
                return;
            }

            print_postorder(current->left);
            print_postorder(current->right);
            cout << current->key << " ";
        }

        void print_inorder(Node* current){
            if (current == NULL){
                return;
            }

            print_inorder(current->left);
            cout << current->key << " ";
            print_inorder(current->right);
        }



    public:

        RBTree(){
            root = NULL;
        }

        RBTree(keytype k[], valuetype v[], int S){                                                              //black children all of them
            root = NULL;                                                                                        //wrong gsfsdfsdf
            int middle = (S-1)/2;


            // for (int i = middle; i > 0; i--){                                                                   //insert from half till zero then half to full
            //     root = Insertion(root, k[i], v[i]);
            //     root->color = false;
            // }

            // for (int i = 0; i < S; i++){
            //     root = Insertion(root, k[i], v[i]);
            //     root->color = false;                                                                            //false is black and true is red
            // }
            root = Insertion(root, k[middle], v[middle]);
            root->color = false;

            for (int i = 1; i <= middle; i++){
                root = Insertion(root, k[middle-i], v[middle-i]);
                root->color = false;
                root = Insertion(root, k[middle+i], v[middle+i]);
                root->color = false;
            }

            if (((2*middle)) != (S-1)){
                root = Insertion(root, k[S-1], v[S-1]);
                root->color = false;
            }
        }

        RBTree(const RBTree<keytype, valuetype> &A){
            root = copy(A.root);
        }
        
        RBTree<keytype, valuetype>& operator=(const RBTree<keytype, valuetype> &A){
            root = copy(A.root);
            return *this;
        }

        ~RBTree(){
            clearMemory(root);
            free(root);
        }

        valuetype* search(keytype k){
            return findVal(root,k);
        }

        void insert(keytype k, valuetype v){
            root = Insertion(root, k, v);
            root->color = false;
        }

        int remove(keytype k){
            if (search(k) == NULL){
                return 0;
            }

            int node = size(root);
            root = Deletion(root, k);

            return (node - size(root));
             
        }

        int rank(keytype k){
            return Rank(root,k);
        }

        keytype select(int pos){
            return Position(root, pos);
        }

        keytype* successor(keytype k){
            return find_sucessor(root, k);
        }

        keytype* predecessor(keytype k){
            return find_predecessor(root, k);
        }

        int size(){
            return size(root);
        }

        void preorder(){
            print_preorder(root);
            cout << endl;
        }

        void inorder(){
            print_inorder(root);
            cout << endl;
        }

        void postorder(){
            print_postorder(root);
            cout << endl;
        }

};

When I try to insert: A","B","C","D","E","F","G","H","I","K", I get the inorder correctly. But the postorder and preorder are incorrect. What do I do so that 3 of the views can be outputted correctly? I really appreciate your help.

c++ map is empty despite initialisation [closed]

Hi so I have the following map declaration

std::map<std::array<int, 2>, std::vector<totalState>, ArrayCompare> totalResponse;

where total state is a custom struct array compare is the custom comparator function

In my cpp file class constructor I initialise the map like so

playerState::playerState(GameObject* theEnemy, GameObject* thePlayer) {
        playerForwardState = still;
        playerSideState = still_side;
        playerTrack = thePlayer;
        enemy = theEnemy;
        temporaryState = new totalState();
        currentState = new totalState();
        currentState->forwardResponse = currentStateForward::non_forward;
        currentState->sidewardsResponse = currentStateSideward::non_side;
        setInitialPosition();
        oldPosition = thePlayer->GetTransform().GetPosition();
        totalResponse = {
         { {0, 0},  },
         { {0, 1},  },
         { {0, 2},  },
         { {0, 3},  },
         { {0, 4},  },
         { {1, 0},  },
         { {1, 1},  },
         { {1, 2},  },
         { {1, 3},  },
         { {1, 4},  },
         { {2, 0},  },
         { {2, 1},  },
         { {2, 2},  },
         { {2, 3},  },
         { {2, 4},  },
         { {3, 0},  },
         { {3, 3},  },
         { {3, 4},  },
         { {4, 0},  },
         { {4, 3},  },
         { {4, 4},  },
         { {5, 0},  },
         { {5, 3},  },
         { {5, 4},  }
        };
    }

the issue is when I run the code the map is empty could an issue with the array compare lead to this? thanks for any help!

How to scrape and download images from archillect.com using C++ in QT Framework?

I am trying to build a desktop application which can download image from archillect.com every hour and set it as my Windows wallpaper. But can't understand how to pull images from the site as it has so many pictures in the first page and only if you click one of the pictures, you get the real image link with higher resolution.

Can someone provide me a code snippet for the scrapper part?

#include <QCoreApplication>

#include <QFile>

#include <QNetworkAccessManager>

#include <QNetworkReply>

#include <QScreen>

#include <QStandardPaths>

void setDesktopWallpaper(const QString& imagePath) {

    const wchar_t* wallpaperPath = reinterpret_cast<const wchar_t*>(imagePath.utf16());

    SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, (void*)wallpaperPath, SPIF_UPDATEINIFILE);

}

void downloadImage(const QString& url, const QString& filePath) {

    QFile file(filePath);

    if (!file.open(QIODevice::WriteOnly)) {

        qWarning() << "Failed to open file for writing: " << filePath;

        return;

    }

    QNetworkAccessManager manager;

    QNetworkReply* reply = manager.get(QNetworkRequest(QUrl(url)));

    QCoreApplication::processEvents();

    while (!reply->isFinished()) {

        QCoreApplication::processEvents();

    }

    if (reply->error() != QNetworkReply::NoError) {

        qWarning() << "Failed to download image: " << reply->errorString();

        return;

    }

    const QByteArray data = reply->readAll();

    file.write(data);

    file.close();

    setDesktopWallpaper(filePath);

}

void changeWallpaperFromUrl(const QString& url) {

    const QString filePath = QStandardPaths::writableLocation(QStandardPaths::TempLocation) + "/wallpaper.jpg";

    downloadImage(url, filePath);

}

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

    QCoreApplication app(argc, argv);

    const QString url = "https://archillect.com/";

    changeWallpaperFromUrl(

URL);

    return app.exec();

}

Why is the default seed of `mt19937` 5489?

According to the Standard, the value of mt19937::default_seed is 5489u:

static constexpr result_type default_seed = 5489u;

This seems very artificial.

Is there any (mathematical or theoretical) reason behind this?

vendredi 24 mars 2023

Detecting end of input with cin.peek()

I am trying to do extraction operator overload that looks at each digit input from user and stores them into an array. Currently, the while loop I am using is not detecting the end of the input stream and the program is just continuously running.

I have tried running a while loop with the logic:

while (cin.peek() != EOF || cin.peek() == '\n') { ... //read in user input }

The input is coming from the terminal not a file.

Will an uninitialized local variable in C++ 11 lead to not compile?

The thing is that, on my environment (wsl+ubuntu+vscode), I’m writing my xxx.h file for an homework assignment, where I have an uninitialized local variable which will definitely not affect the function (just a debug counter). And using the same MAKEFILE the grader use, I’ve always been available to compile (and my VScode didn’t even show an warning for that), however in grader’s environment it doesn’t. Is that a reason for that?

I expect a reason why the outcome will be different

jeudi 23 mars 2023

What is the implementation of accessing a Virtual Function Table (vtbl) in C++? [closed]

Can someone please provide me with code and an explanation of how vtbl's are managed and accessed by the compiler and run time in virtual abstract classes and their inherited classes?

I'm reading about vtbl's in The C++ Programming Language, Fourth Edition, by Bjarne Stroustrup on p. 67.

How to understand the return type of `std::bind`?

A simple code snippet

#include <cstdio>
#include <functional>

int main() {
    auto f = std::bind(printf, "%d", std::placeholders::_2);
}

transforms to

#include <cstdio>
#include <functional>

int main()
{
  std::_Bind<int (*(const char *, std::_Placeholder<2>))(const char *, ...)> f = std::bind(printf, "%d", std::placeholders::_2);
  return 0;
}

using cppinsights.io (See https://cppinsights.io/s/71938cf6)

How to understand the int (*(const char *, std::_Placeholder<2>))(const char *, ...) part of return type std::_Bind<int (*(const char *, std::_Placeholder<2>))(const char *, ...)>?

I know that int (*)(const char *, ...) is a function pointer type, but what's the meaning of (*(const char *, std::_Placeholder<2>))? Is there any link to further understand this type?

mercredi 22 mars 2023

How detach my custom widget from Qt QWidgetList?

I have a container std::map<std::string, unique_ptr<ItemWidget>> widgets that contains pointers to my widgets, so all of my widgets exist separately and independend from QListWidget object. Sometimes i need to hide some of widgets temporarily, sometimes to delete ones finally. So my code implements this:

ui->listWidget->clear()
for (auto it : widgets) {
    auto item = new QListWidgetItem();
    item->setSizeHint(it->size());
    ui->listWidget->addItem(item);
    ui->listWidget->setItemWidget(item, it);
}

Now i read that ui->listWidget->clear() calls delete for all list's items. And thats why my list has all items with no data.

I want to list to delete my widgets from itself, but without any impact to my widgets. Can i?

mardi 21 mars 2023

Why explicitly delete the constructor allowing creating object using initialization {} [duplicate]

This code works, with the deleted constructor.

The class created with deleted constructor should not allow to the creation of an object for the class. Mainly such classes are used for static scope.

But C++ allows deleted constructor objects can be created using initialization. What is the point of explicit constructor not being allowed but initialization is allowed?

#include <iostream>

class A {
    A() = delete;
    
    A(const A&) = delete;
    A(A&&) = delete;
    
public:
    void function() { std::cout << "A\n"; }
};

int main()
{
    A a{};  // this works.
    
    a.function(); 
}

Openssl 3.0 problem with existing BIO communication

Earlier below code was working in openssl 1.0.2 on Windows:-

BIO_METHOD bio;    
memcpy(&bio, BIO_s_socket(), sizeof(BIO_METHOD));
bio.bwrite = SslBioWrite;
bio.bread = SslBioRead;
BIO *wbio = BIO_new(bio);
BIO_set_app_data(wbio, this);
BIO_set_fd(wbio, (int)_socket, BIO_NOCLOSE); //_socket is an already connected TCP socket
SSL_set_bio(_ssl, wbio, wbio); //_ssl is already setup ssl with ssl context
SSL_connect(_ssl); //==>> this works and gets connected

But in openssl 3.0, as BIO_METHOD structure has become opaque and BIO_s_socket() returns const BIO_METHOD pointer, above approach can't work. I tried below approach...

I tried below with openssl 3.0.8:-

const BIO_METHOD *bio = BIO_s_socket();
BIO_METHOD *tbio = BIO_meth_new(BIO_TYPE_SOCKET, "sslsocket");
assert(tbio);
assert(BIO_meth_set_write(tbio, SslBioWrite) == 1);
assert(BIO_meth_set_read(tbio, SslBioRead) == 1);
assert(BIO_meth_set_create(tbio, BIO_meth_get_create(biom)) == 1);
assert(BIO_meth_set_destroy(tbio, BIO_meth_get_destroy(biom)) == 1);
assert(BIO_meth_set_callback_ctrl(tbio, BIO_meth_get_callback_ctrl(biom)) == 1);
BIO *wbio = BIO_new(tbio);
BIO_set_app_data(wbio, this);
BIO_set_fd(wbio, (int)_socket, BIO_NOCLOSE); //_socket is an already connected TCP socket
SSL_set_bio(_ssl, wbio, wbio); //_ssl is already setup ssl with ssl context
SSL_connect(_ssl); ==>> this fails with error SSL_ERROR_SSL

C++ function pointer to C pointer in a general way

I have an embedded C generated source file that requires a function pointer. I need to give it a member function pointer from my C++ code. One of the solution I encountered was: Convert C++ function pointer to c function pointer . Specifically this one:

class MyCallbackClass
{

    void non_static_func(/* args */);

public:
    static void static_func(MyClass *ptr, /* other args */) {
        non_static_func(/* other args */);
    }
};

and giving the C function : c_library_function(MyCallabckClass::static_func)

This suits my system, as I am using c++11 , but can not involve any external libraries (std, bind), or heap allocation.

I would like to make it more general to any C callback I might need in the future.

How can I build MyCallbackClass according to the C typedef of the function pointer? so I can give it my C++ member function (of the same type) ? e.g.,

typedef int32_t (*Write_Func)(uint16_t, uint16_t, const uint8_t*, uint16_t);

How to iterate over multimap of struct C++ [closed]

I have a multimap of struct. How to iterate and get the Struct member value "scale" using the key "sourceID".

std::multimap<std::string /*sourceID*/, NumData> numDataMap;
    
struct typeData
{
   float value;
   std::string uom;
   float scale;
};
struct NumData 
{
   std::string cardinality;
   std::map<int/*cardinality*/, std::map<type, typeData>> dataMap;
};

Please suggest any alternate design how to containerize the above data.

lundi 20 mars 2023

I'm in my first C++ programming class and I don't understand what I'm suppose to do with my homework [closed]

Below here is word for word from my assignment. We did just go over arrays in our last chapter and I did struggle to understand everything along with file streaming (assuming thats even whats expected). I'm not looking for code, just some help breaking it down so it makes more sense. I should add, this chapter we are learning pointers so I'd assume that would play apart in the assignment:

Write a function that accepts an int array and the arrays’ size arguments. The function should:

1. create a new array that is twice the size of the argument array.
2. copy the contents of the argument array to the new array and initialize the unused elements
of the second array with 0.
3. return a pointer to the new array.

Demonstrate the function by using it in a main program that reads an integer N (that is not more
than 50) from standard input and then reads N integers from a file named data into an array (DO
NOT use an absolute path to the data file). The program then passes that array to your array
expander function, and displays the values of the new expanded array, one value per line.
You may assume that the file data has at least N values. If the integer read in from standard input
exceeds 50 or is less than 0 the program terminates with an appropriate message.

How to iterate over unique combinations of a 2d array. C++ [closed]

I am trying to find magic squares in C++ for a given NxN array. I need a method to go over all possible combinations of numbers from 1 to n^2.

I had a solution similar to bogo sort which just shuffled the array until a solution was found which is obviously a bad way but it worked for a 3x3 array.

I assume the way to go over all combinations would be using some kind of recursion function but I can't figure it out.

What is the use of *this in combine function given below

Sales_data& Sales_data::combine(const Sales_data &rhs)
{
units_sold += rhs.units_sold; // add the members of rhs into
revenue += rhs.revenue; // the members of ''this'' object
return *this; // return the object on which the function was called
}

I saw above method somewhere, and I am confused why *this pointer is being returned? even though without it (using void return type) function does the same thing. I am not an expert in C++, so can any one explain what am I missing?

dimanche 19 mars 2023

std::erase does not return an error when std::remove_if is used inappropriately in the erase-remove idiom

As we know, the erase-remove idiom can be used as a concise pattern to delete elements of a vector.

In particular, std::remove_if swaps elements inside the vector in order to put all elements that do not match the predicate towards the beginning of the container. These elements are then removed from the container.

This also means that if the predicate (body of the lambda function) returns true, then that element will be placed at the end of the vector.

It must be noted that within the erase remove idiom, both the erase and remove functions must get iterators to the same container. This means that if I try to provide a different iterator in the remove_if statement, the erase function must return an error.

But consider the code below:

vector<int> valsToRemove{ 4, 5, 6, 2, 3, 7, 10 };
    
vector<int> isValidToRemove{ 0, 1, 0, 1, 1, 0, 1 };
    
valsToRemove.erase(std::remove_if(isValidToRemove.begin(),
                                isValidToRemove.end(),
                                [&](int& x)-> bool { return x == 0; }), valsToRemove.end() );
                                
for( auto& val: valsToRemove ) {
        cout << val << "\t";
}

It turns out that I have a vector isValidToRemove which tells me whether an element of the valsToRemove vector must be retained or deleted based on "0" or "1" value. I use this within the remove_if statement to satisfy a predicate. In this case, due to different containers being used in the erase and remove_if functions, the erase function must return an error.

However, I get an arbitrary output which somehow appends additional elements of the vector. The output also varies across different instances/machines.

4 5 6 2 3 7 10 0 0 0 49 0 1 1 1 1

I just wanted to confirm if this should be the correct behavior or if it should be modified so that the correct error is returned to the user/client of this function.

Further, is there a concise way or a specific pattern to use a separate vector (such as isValidToRemove in the example above which might be received from an upstream component) to remove elements of a different vector (valsToRemove in the example above) instead of just using a for loop to remove these elements.

Why does high resolution clock from chrono library output 0 and reasonable values in seemingly random order?

I have a function that I was using the chrono library to benchmark- at times the output would be zero for time passed and sometimes a more reasonable value- in my case about 973,300 nanoseconds. I would like to know why this behaviour occurs specifically- as in why sometimes the output is zero but sometimes the 973,300 nanoseconds I mentioned above. I understand that there is a limit on precision intrinsic to any machine, but the fact that there is an output at times 0 or at other times more reasonable is what is getting to me.

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

void megu()
{
    for(int i = 0; i < 1000000; i++);
}

int main()
{
    auto start = chrono::high_resolution_clock::now();
    megu();
    auto end = chrono::high_resolution_clock::now();
    auto duration = chrono::duration_cast<chrono::nanoseconds>(end - start);
    cout << duration.count();

    return 0;
}

I attempted to run the code with longer and shorter run time functions (larger maximum value for i in function megu here, and it only happens with shorter run times. This points to it being a precision issue- if it was not for the "reasonable" values outputted in between the zero's having a low variance- maximum of 20 nanoseconds of difference between them (within that 973,300 nanosecond window). The sudden zero's then, have to be due to something else. I also tried running the function as many times as necessary in order to get X amount of reasonable values to take a decent average, and I do get enough of these reasonable values every time within a single program execution using a loop that discards 0 values (no batch file etc).

I am on Windows 11, Intel i7 processor.

samedi 18 mars 2023

Why my 4th Function is not providing the desired output? [closed]

I need to make any Inventory Management Application program using structures. At the start of program, data from files is loaded into arrays of structure. Then the user is provided with a menu and user's selection calls different functions like print stock, search Item, print sales, print sale Report, print purchases and purchase report. I need help with last three functions as I don't have any idea what to do. The Purchase functions should provide this output as depicted in the pic. `

`#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;`

`//Structures Declaration.
struct StockRecords
{
int code;
string name;
string type;
string manufac;
double price;
double discount;
int quantity;
};
struct SalesRecord
{
int invoiceNo;
string dateTime;
string name;
int numberOfItems;
double amount;
};
struct PurchaseRecord
{
int invoiceNo;
string supplier;
string prodName;
string type;
string manufac;
double price;
double discount;
int quantity;
};

//Global Constants Indicating Array Size.
const int X = 7, Y = 7, Z = 5;

////Function for loadind stock records from file into an array
void loadStock(StockRecords stock[X][Y])
{
//Creating an ifStream object to read from files.
ifstream inFile;
//Opening the file.
inFile.open("Stock.DB");
if(!inFile)
{
cout << "Error.";
}
 else
{
for(int i=0; i<X; i++)
{
inFile >> stock[i][0].code >> stock[i][1].name >> stock[i][2].type >> stock[i][3].manufac 
 >> stock[i][4].price >> stock[i][5].discount >> stock[i][6].quantity;
}
}
 //Closing the file.
    inFile.close();
}
/******************************************
 1. Function for Printing Stock on Console.
******************************************/
void printStock (StockRecords stock[X][Y])
{
    system("cls");
    cout << "________________________________________________________________________________________________________\n\n";
    cout << "                                         ==STOCK REPORT==         \n";
    cout << "________________________________________________________________________________________________________\n\n";
    cout << "Code"<< setw(14)<<"Name"<< setw(15)<<"Type"<< setw(22)<<"Manufacturer"<< setw(7)<<"Price"
         << setw(19) << "Discount(%)"<< setw(16)<<"Quantity" << endl << endl<< left;;
    cout << fixed << showpoint << setprecision(2);
    for (int i=0; i<X; i++)
    {
        cout << setw(14)<< stock[i][0].code << left<< setw(15) << stock[i][1].name << left<< setw(14) << stock[i][2].type << left 
                    << setw(14) << stock[i][3].manufac << left << setw(16) << stock[i][4].price << left << setw(16) 
                    << stock[i][5].discount << left << setw(16) << stock[i][6].quantity;
        cout << endl;
    }
    cout << "________________________________________________________________________________________________________\n\n";
}   

/***************************************************
  2. Function for Searching for an Item in an array.
***************************************************/
void searchItem (StockRecords stock[X][Y])
{
    stringstream x;
    string option;
    system("cls");
    cout << "_______________________________________________________________________\n\n";
    cout << "                        ==ITEM SEARCH==         \n";
    cout << "_______________________________________________________________________\n\n";
    cout << "                    ENTER PRODUCT NAME OR CODE::  ";
    cin >> option;
    cout << "_______________________________________________________________________\n\n";
    
    
    
    for(int i = 0; i<X; i++)
    {
        x << stock[i][0].code;
        if(x.str () == option || stock[i][1].name == option)
        {
            cout << stock[i][0].code << "\t" << stock[i][1].name << "\t" << stock[i][2].type << "\t" << 
                    stock[i][3].manufac << "\t" << stock[i][4].price << "\t" << stock[i][5].discount << 
                    "\t" << stock[i][6].quantity;
        }   
    }   
}
/**********************************************
  3. Function for Printing Sales Transactions.
**********************************************/
void sale (StockRecords stock[X][Y], SalesRecord sales[Z])
{
    //Creating an ofStream object to write to files.
    ofstream outFile;
    
    stringstream x;
    string name, option;
    int invoice, qty, item = 1;
    double totalBill = 0, total;
    char choice;
    system("cls");
    
    cout << "_______________________________________________________________________\n\n";
    cout << "                        ==SALE TRANSACTION==         \n";
    cout << "                          CUSTOMER: ";
    
    cin >> name;
    cout << "\n\n                          Invoice No: ";
    cin >> invoice;
    
    cout << "_______________________________________________________________________\n\n";
    do
    {
        //system("cls");
        cout << "\n\n                    ENTER PRODUCT NAME OR CODE::  ";
        cin >> option;
        cout << "\n                    ENTER QUANTITY::  ";
        cin >> qty;
        cout << "\n                    ADD ANOTHER (Y/N)::  ";
        cin >> choice;
        cout << "_______________________________________________________________________\n\n";
        cout << "S.NO\tItem Name\tUnits\tPrice\tTotal\n\n";
        
        for(int i = 0; i<X; i++)
        {
            x << stock[i][0].code;
            if(x.str () == option || stock[i][1].name == option)
            {
                total = stock[i][4].price * qty;
                totalBill += total;
                cout << item << "\t" << stock[i][1].name << "\t" 
                     << stock[i][6].quantity << "\t" << stock[i][4].price<< "\t" << total << endl;
item++;
/*sales[i].invoiceNo = invoice;  
sales[i].name = name;
sales[i].numberOfItems = item;
sales[i].amount = totalBill;*/
sales[item - 2].invoiceNo = invoice;
sales[item - 2].name = name;
sales[item - 2].numberOfItems = item - 1;
sales[item - 2].amount = totalBill;
            }
        }
cout << "\n Total Bill............" << totalBill; 
//Opening the file.
 outFile.open("Sale.DB");
if(!outFile)
{
cout << "Error.";
}
outFile << "Invoice No."<< setw(18)<<left<<"Date-Time"<< setw(18)<<"Customer Name"<< setw(17)
<<"No-Of-Items"<< setw(10)<<"Amount" << endl << endl;

outFile << setw(12) << left << sales[item - 2].invoiceNo
<< setw(18) << "3/20/2021-9:39PM"
<< setw(18) << sales[item - 2].name
<< setw(17) << sales[item - 2].numberOfItems
<< setw(10) << fixed << setprecision(2) << sales[item - 2].amount
<< endl;
outFile.close();        
 }while (choice != 'N' && choice != 'n'); 
}

/**************************************************
  4. Function for Printing Sales Report on Console.
**************************************************/
void salesReport(SalesRecord sales[Z])
{
system("cls");
//Creating an ifStream object to read from files.
ifstream inFile;
//Opening the file.
inFile.open("Sale.DB");
if(!inFile)
{
cout << "Error.";
}
cout << "_______________________________________________________________________\n\n";
cout << "                        ==SALES REPORT==         \n";
cout << "_______________________________________________________________________\n\n";
    
cout << "Invoice No."<< setw(13)<<"Date-Time"<< setw(18)<<"Customer Name"<< setw(17)
<<"No-Of-Items"<< setw(10)<<"Amount" << endl << endl<< left;
while(inFile >> sales[0].invoiceNo >> sales[1].dateTime >> sales[2].name 
>> sales[3].numberOfItems >> sales[4].amount);
{
cout << fixed << showpoint << setprecision(2);
    
cout << setw(14)<< sales[0].invoiceNo << left<< setw(15) << sales[1].dateTime << left<< setw(24) 
 << sales[2].name << left << setw(14) << sales[3].numberOfItems  << left << setw(16) << sales[4].amount;
cout << endl;
}
//Closing the file.
inFile.close();
}
/**************************************************
  5. Function for Printing Purchases on Console.
**************************************************/
void purchase (StockRecords stock[X][Y])
{
StockRecords *sptr;
string sup;
int invoice;
char opt;
system ("cls");
cout << "_______________________________________________________________________\n\n";
cout << "==PURCHASE==         \n";
cout << "SUPPLIER: ";
    
cin >> sup;
cout << "\n\n Invoice No: ";
cin >> invoice;
do
    {
cout << "_______________________________________________________________________\n\n";
cout << "PRODUCT NAME::   " 
cin >>  stock[0][0].name;
cout << "\nTYPE:: " << stock[0][1].type;
cout << "\n MANUFACTURES::   " << stock[X][Y].manufac;
cout << "\nRETAILPRICE::   " << stock[X][Y].price;
//cout << "COST:: " << stock[X][Y].name;
cout << "\nDISCOUNT(%)::   " << stock[X][Y].discount;
cout << "\nQTY::   " << stock[X][Y].quantity;
cout << endl << endl;
cout << "ADD ANOTHER? (Y/N)::   ";
cin >> opt;
}while (opt != 'N' && opt != 'n');
}
`/*void purchaseReport (StockRecords stock[], int x);*/`

{
int choice;
//Constant indicating the size of structure array.
    
    
//Declaring StockRecords Structure array.
StockRecords stock[X][Y];
SalesRecord sales[Z];
    
//Function Call to load stock from file into an array.
loadStock(stock);
    
    //do{
cout << " ____________________________________________\n\n";
cout << "==Test Departmental Store==         \n";
cout << "  ____________________________________________\n\n";
cout << "  Main Menu                  \n\n";
cout << "1-Print Stock                     \n";
cout << " 2-Search Item                     \n";
cout << "3-Sale                     \n";
cout << " 4-Sale Report                     \n";
cout << " 5-Purchase                    \n";
cout << "  6-Purchase Report                     \n";
cout << "  7-Exit                     \n\n\n";
cout << "  Date & Time: Day, Month, Date, Time, Year.\n";
cout << "  ____________________________________________\n  ";
cout << "  ENTER YOUR CHOICE (Menu No)::  ";
cin >> choice;
cout << "\n\n ____________________________________________"; 
//Validating the Input.
while (choice < 1 || choice > 7)
{
cout << "\n\nInvalid Input Entered.\n Enter Again: ";
cin >> choice;
}
switch (choice)
{
case 1:
{ 
printStock(stock);     //Function Call to print stock on console.
break;   
 }
case 2: 
{
searchItem(stock);     //Function Call to search for item in the array.
break;   
}
case 3:
{ 
sale(stock,sales);     //Function Call doing the sales.
break; 
}
case 4: 
{
salesReport(sales);     //Function Call doing the sales.
break;
}
case 5:
{ 
purchase(stock);
break;
 }
/*case 6: 
{
            
}*/
        
    
} 
//}while (choice != 7);


return 0;
    
}`

This is my source code. Kindly point out my errors and guide me what to do for the last three functions. The required functionality of program is shown in snapshot FUNCTIONALITY REQUIREMENTS The Program is supposed to provide the following outputs as shown in snapshots

c++ how to use universal reference in a function multiple times

This question is migrated from Code Review since it is marked off-topic over there

I need to pass an rvalue-reference (temporary) as a parameter to a function taking unversal reference. It be used multiple times inside. Each function calling it accepts rvalue-reference as special overload. My question is how we should forward the parameter.

Following is an example:

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

struct Game {
    Game(const std::string& n) : name(n) {}
    Game(std::string&& n) : name(std::move(n)) {}
    std::string name;
};

struct Student {
    // constructor: not important for the discussion
    Student(const string& n) : name(n){}
    Student(string&& n) : name(std::move(n)) {}

    // play has overloaded for several different types
    void play(const std::string& game) {
        cout << name << " plays |" << game << "| (L)"<< endl;
        games.emplace_back(game);
    }
    void play(std::string&& game) {
        cout << name << " plays |" << game << "| (R)"<< endl;
        games.emplace_back(std::move(game));
    }
    void play(const Game& game) {
        cout << name << " plays |" << game.name << "| (L)"<< endl;
        games.emplace_back(game);
    }
    void play(Game&& game) {
        cout << name << " plays |" << game.name << "| (R)"<< endl;
        games.emplace_back(std::move(game));
    }
    std::string name;
    std::vector<Game> games;
};

struct Class {
    // construct: not important here. Did not overload for &&
    Class(const vector<string>& names) {
        for (auto name : names) {
            students.emplace_back(std::move(name));
        }
    }
    
    // perfect forwarding works nice
    template <typename G>
    void play_by_first(G&& game) {
        if (students.size() == 0) return;
        students[0].play(std::forward<G>(game));
    }

    // this is relevant part. 
    // How to code for a generic game of type G and 
    // game might or might not be temporary
    template <typename G>
    void play(G&& game) {
        for (auto& student : students) {
            student.play(std::forward<G>(game)); // <--- how to change this line
        }
    }
    vector<Student> students;
};

int main() {
    // normal here
    Class grade1({"alice"});
    grade1.play("football");
    grade1.play(Game("basketball"));

    cout << endl;
    // Charlie has nothing to play
    Class grade2({"bob", "Charlie"});
    grade2.play(std::string{"football"});
    grade2.play(Game("basketball"));
}

try run

As you can see, when we only need to use it once, as in play_by_first, perfect forwarding (std::forward) will be the ultimate solution. However, when it used multiple times, the rvalues will be invalid after the first call.

Is there a standard way in modern c++ to handle this? I still wanna to have some optimization for temporaries. So at least the last call should resolve to the rvalue reference overload.

I also looked into the std library, tried to learn from implementations such as find_if where the predicator can be an rvalue reference and will be called multiple times. Howerver, it does not take universal reference, and cannot handle rvalue references specially.

CUDA Toolkit 12.1 - Issue when compiling samples

I installed Cudatoolkit 12.1 on laptop with Ubuntu 22.04. The GPU is the mobile RTX 3080, CPU is AMD 5900HX. GCC version is 12.2.

The install went fine and it mostly seems to be working fine. I decided to compile all the cuda samples and got this error -

>>> GCC Version is greater or equal to  5.1.0 <<<
/usr/local/cuda/bin/nvcc -ccbin g++ -I../../../Common -m64 --std=c++11 --threads 0 -gencode arch=compute_70,code=sm_70 -gencode arch=compute_75,code=sm_75 -gencode arch=compute_80,code=sm_80 -gencode arch=compute_86,code=sm_86 -gencode arch=compute_89,code=sm_89 -gencode arch=compute_90,code=sm_90 -gencode arch=compute_90,code=compute_90 -o simpleAWBarrier.o -c simpleAWBarrier.cu
/usr/local/cuda/bin/../targets/x86_64-linux/include/cuda/std/barrier(144): error: function "operator new" cannot be called with the given argument list
            argument types are: (unsigned long, cuda::std::__4::__barrier_base<cuda::std::__4::__empty_completion, 2> *)
         new (&__b->__barrier) __barrier_base(__expected); 
         ^

1 error detected in the compilation of "simpleAWBarrier.cu".
make: *** [Makefile:361: simpleAWBarrier.o] Error 255
>>> GCC Version is greater or equal to  5.1.0 <<<
/usr/local/cuda/bin/nvcc -ccbin g++ -I../../../Common -m64 --std=c++11 --threads 0 -gencode arch=compute_70,code=sm_70 -gencode arch=compute_75,code=sm_75 -gencode arch=compute_80,code=sm_80 -gencode arch=compute_86,code=sm_86 -gencode arch=compute_89,code=sm_89 -gencode arch=compute_90,code=sm_90 -gencode arch=compute_90,code=compute_90 -o globalToShmemAsyncCopy.o -c globalToShmemAsyncCopy.cu
/usr/local/cuda/bin/../targets/x86_64-linux/include/cuda/std/barrier(144): error: function "operator new" cannot be called with the given argument list
            argument types are: (unsigned long, cuda::std::__4::__barrier_base<cuda::std::__4::__empty_completion, 2> *)
         new (&__b->__barrier) __barrier_base(__expected); 
         ^

1 error detected in the compilation of "globalToShmemAsyncCopy.cu".
make[1]: *** [Makefile:355: globalToShmemAsyncCopy.o] Error 255

The error has shown up with at least two different programs. Both indicate an issue with in "...include/cuda/std/barrier".

Is this an issue with CUDA or the compile options?

vendredi 17 mars 2023

cpp11 assign values for struct with different name but exactly same element?

i got two structs, some part of the two struct have exactly same element type (and name), how can i assign one with another's value?

as below demostrated:


struct X
{
    struct
    {
        int a = 0;
        int b = 0;
    } z;
    int c = 0;
};


struct Y
{
    int a = 0;
    int b = 0;
};


int main()
{
    
    X x{1,2,3};
    Y y;
    
    // i know i can do 
    y.a = x.z.a;
    y.b = x.z.b;
    
    // but is there a simple way like:
    // y = x.z;
    
}

i looked into memcpy but in my real case, the X is much more complicated and dynamic length, memcpy looks not quit help for me. thx for any advice

jeudi 16 mars 2023

Smart Pointers and Exception

A practice question on C++ primer:

one easy way to make sure resources are freed is to use smart pointers.

Imagine we're using a network library that is used by both C and C++. Programs that use this library might contain code such as:

struct connection
{
    string ip;
    int port;
    connection(string i, int p) :ip(i), port(p) {};
};  // represents what we are connecting to

struct destination
{
    string ip;
    int port;
    destination(string i, int p) :ip(i), port(p) {};
};  // information needed to use the connection

void disconnect(connection c)
{
    cout << "Scoket(" << c.port << "," << c.port << ") disconnect" << endl;
}  //close the given connection

connection connect(destination* pDest)
{
    shared_ptr<connection> pConn(new connection(pDest->ip, pDest->port), disconnect );
    cout << "Scoket(" << pConn->ip << "," << pConn->port << ") connect" << endl;
    return *pConn;
}  // open the connection


void f(destination& d)
{
    connection c = connect(&d);
}

compile error:

error C2661: 'std::shared_ptr<connection>::shared_ptr': no overloaded function takes 2 arguments.

What's wrong with the code?

shared_ptr to templated base classes

I'm running into the following compilation issue with shared_ptr to templated base classes. I'm wondering why int cannot be deduced in this case from D? Does this have anything to do with the general case where D might be derived from B<int> and B<float> for example not being well formed?

#include <memory>
template <typename T>
struct B {
    virtual void foo() = 0;
};

struct D  : B<int> {
    void foo() override {}
};

template <typename T>
void func(std::shared_ptr<B<T>> sp) {

}

int main() {
    func(std::make_shared<D>());
}
<source>:17:5: error: no matching function for call to 'func'
    func(std::make_shared<D>());
    ^~~~
<source>:12:6: note: candidate template ignored: could not match 'B<type-parameter-0-0>' against 'D'
void func(std::shared_ptr<B<T>> sp) {
     ^
1 error generated.
Compiler returned: 1

The following works fine

#include <memory>
template <typename T>
struct B {
    virtual void foo() = 0;
};

struct D  : B<int> {
    void foo() override {}
};

template <typename T>
void func(B<T> * sp) {

}

int main() {
    func(new D);
}

Compilation error with xlc++ and aix (The #include file

I'm desperate, I can't find the reason for this compilation error:

The #include file <initializer_list> is not found

I'm compiling with c++11 flag: qlanglvl=extended0x The version of xlc++ is 16.1 in aix 7.2

Can anyone help me?

Many thanks.

using Rapidjson how to modify value of a particular key

 {
            "identifier":"Root",
            "type":"Structure",
            "uid":1,
            "address":"root",
            "parent":0
        },
//i tried to update address field using SetString and AddMember()
                 Value val;
                val.SetString(address.c_str(), address.length(),json_doc.GetAllocator());
                member.AddMember("address",val,json_doc.GetAllocator());

i tried to modify address's key value with new value which is stored in address variable

mercredi 15 mars 2023

Stack push pop top function unusual results

I first push into the stack and then pop from it. From the empty stack I cout stack.top() and it prints the element which I have pushed earlier. Why is it so??

        priority_queue<int, vector<int>, greater<int>>minHeap ;

        minHeap.push(1) ;
        minHeap.pop() ;
        cout << minHeap.top() ;

Why the output of this is 1??

mardi 14 mars 2023

I made an object pool and used it in the set/vector/map container. When it is released, it always crashes. I don't know why

I use a simple MFC CDialog project for code experiments. When I exit CDialog, I always crash when I release the pointer. The following is the structure code of my data storage

#include <set>
#include <map>
#include <string>
#include <memory>
#include <vector>
using namespace std;
#define SAFEDELETE(p) {if (p) { delete p; p = nullptr;}}
class CName
{
public:
    bool operator < (const CName& other) const
    {
        if (this->_server.compare(other._server) != 0)
        {
            return this->_server < other._server;
        }
        if (this->_source.compare(other._source) != 0)
        {
            return this->_source < other._source;
        }
        return false;
    }
public:
    string _server;
    string _source;
};

class Attributes
{
    public:
        Attributes() {}
        ~Attributes()
        {
            _enabled = false;
            _lTimeStamp = 0;
        }
        bool _enabled = false;
        long _lTimeStamp = 0;
};
using AttributesPtr = shared_ptr<Attributes>;
class TimeStampCompare
{
public:
    bool operator()(const AttributesPtr attr1, const AttributesPtr attr2) const
    {
        if (attr1 == nullptr || attr2 == nullptr)
        {
            return false;
        }
        return attr1->_lTimeStamp > attr2->_lTimeStamp;
    }
};
class Container;
using ContainerPtr = shared_ptr<Container>;
class Container
{
public:
    Container() {}
    ~Container()
    {
        Clear();
    }
    void Clear()
    {
        _name = "";
        _path = "";
        for (auto& iter : _cache)
        {
            iter.second.clear();
        }
        _cache.clear();
        _containers.clear();
    }
public:
        string _name;
        string _path;
        vector<ContainerPtr> _containers;
        map<CName, set<AttributesPtr, TimeStampCompare>> _cache;
};

Here is the code of my object pool

template <typename T>
class ObjectPool
{
public:
    ObjectPool(std::size_t size)
    {
        for (std::size_t i = 0; i < size; i++)
        {
            T* obj = new T();
            m_objs.push_back(obj);
        }
    }
    virtual ~ObjectPool()
    {
        for (auto iter = m_objs.begin(); iter != m_objs.end(); iter ++)
        {
            delete (*iter);
        }
        m_objs.clear();
    }
    template <typename... E>
    std::shared_ptr<T> getObject()
    {
        T* obj = iGetObject();
        if (obj != nullptr)
        {
            return std::shared_ptr<T>(obj, [this](T* ptr)->void
            {
                destroy1(ptr);
                std::unique_lock<std::mutex> lk(m_lock);
                m_objs.push_back(ptr);
            });
        }
        return nullptr;
    }   
private:
    std::deque<T*> m_objs;
    mutable std::mutex m_lock;
    T* iGetObject()
    {
        std::unique_lock<std::mutex> lk(m_lock);
        if (!m_objs.empty())
        {
            T* obj = m_objs.front();
            m_objs.pop_front();
            return obj;
        }
        return nullptr;
    }
    void destroy1(T* obj)
    {
        obj->~T();
    }
};

The following is the code for creating member variables and destructing in CMyDialog

//CMyDialog.h
ContainerPtr _root;
ObjectPool<Container>* _ContainerPool = nullptr;
ObjectPool<Attributes>* _AttributePool = nullptr;
//CMhDialog.cpp
//construction
_ContainerPool = new ObjectPool<Container>(1);
_AttributePool = new ObjectPool<Attributes>(1);
_root = _ContainerPool->getObject();
//destruction
_root = nullptr;
SAFEDELETE(_ContainerPool);
SAFEDELETE(_AttributePool);

Every time I call SAFEDELETE(_ContainerPool) in destruction, it will crash. I don't know why, I hope it can be released normally

E0441 argument list for class template "std::map" is missing (I can't use #include )? [closed]

All I am trying to do is make a map in C++, but I can't even use the map class.

#include statements: image

image

And if I don't use the line using map = std::map; it still gives me this when trying to actually create a map.

image

My map header file is up to date.

I tried updating my map header file, and re-phrasing my #include statement, and usage of the class as much as I could. I simply can't use maps?

Error calling a protected constructor of class clang::tooling::CommonOptionsParser

Following a basic Clang tutorial, I try to build an "out of the source" example and get a strange error using VSCode:

"calling a protected constructor of class 'clang::tooling::CommonOptionsParser'GCC"

(complete error details below)

when I try to compile this code:

#include <iostream>
#include "clang/Driver/Options.h"
#include "clang/AST/AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Frontend/ASTConsumers.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "clang/Rewrite/Core/Rewriter.h"

using namespace std;
using namespace clang;
using namespace clang::driver;
using namespace clang::tooling;
using namespace llvm;

Rewriter rewriter;
int numFunctions = 0;

int main( int argc, const char **argv ) {
    static llvm::cl::OptionCategory optionCategory( "tool options" );
    // parse the command-line args passed to your code
    Expected<tooling::CommonOptionsParser> expectedParser = clang::tooling::CommonOptionsParser::create(argc, argv, optionCategory);
    if (!expectedParser) {
        llvm::errs() << expectedParser.takeError();
        return 1;
    }
    CommonOptionsParser &optionsParser = expectedParser.get();
    // create a new Clang Tool instance (a LibTooling environment)
    ClangTool Tool( optionsParser.getCompilations(), optionsParser.getSourcePathList() );
 
    // run the Clang Tool, creating a new FrontendAction
    int result = Tool.run( newFrontendActionFactory<WrapperFrontendAction>().get() );

    errs() << "\nFound " << numFunctions << " functions.\n\n";
    // print out the rewritten source code ("rewriter" is a global var.)
    rewriter.getEditBuffer(rewriter.getSourceMgr().getMainFileID()).write(errs());
    return result;
}

I understand I should call create to get a new instance instead of referencing the constructor name, however, the CommonOptionsParser is declared as follows:

class CommonOptionsParser {

protected:
  /// Parses command-line, initializes a compilation database.
  ///
  /// This constructor can change argc and argv contents, e.g. consume
  /// command-line options used for creating FixedCompilationDatabase.
  ///
  /// All options not belonging to \p Category become hidden.
  ///
  /// It also allows calls to set the required number of positional parameters.
  CommonOptionsParser(
      int &argc, const char **argv, llvm::cl::OptionCategory &Category,
      llvm::cl::NumOccurrencesFlag OccurrencesFlag = llvm::cl::OneOrMore,
      const char *Overview = nullptr);

public:
  /// A factory method that is similar to the above constructor, except
  /// this returns an error instead exiting the program on error.
  static llvm::Expected<CommonOptionsParser>
  create(int &argc, const char **argv, llvm::cl::OptionCategory &Category,
         llvm::cl::NumOccurrencesFlag OccurrencesFlag = llvm::cl::OneOrMore,
         const char *Overview = nullptr);

  /// Returns a reference to the loaded compilations database.
  CompilationDatabase &getCompilations() {
    return *Compilations;
  }

This way specifying the namespace is "overriding" the create call and then the compiler gets confused?

Of course if I remove "clang::tooling::CommonOptionsParser::" then create is not found (Use of undeclared identifier 'create')

This is my compile_commands.json:

[
{
  "directory": "/Users/user/prjs/clang-tryout-3/build",
  "command": "/opt/homebrew/opt/llvm/bin/clang++ -I/opt/homebrew/opt/llvm/include -g -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX13.1.sdk -o CMakeFiles/Hello.dir/main.cpp.o -c /Users/user/prjs/clang-tryout-3/main.cpp",
  "file": "/Users/user/prjs/clang-tryout-3/main.cpp"
}
]

Complete error details:

[{
    "resource": "/Users/user/prjs/clang-tryout-3/main.cpp",
    "owner": "cmake-build-diags",
    "severity": 8,
    "message": "calling a protected constructor of class 'clang::tooling::CommonOptionsParser'",
    "source": "GCC",
    "startLineNumber": 27,
    "startColumn": 22,
    "endLineNumber": 27,
    "endColumn": 1000,
    "relatedInformation": [
        {
            "startLineNumber": 76,
            "startColumn": 3,
            "endLineNumber": 76,
            "endColumn": 1000,
            "message": "declared protected here",
            "resource": "/opt/homebrew/opt/llvm/include/clang/Tooling/CommonOptionsParser.h"
        }
    ]
}]

lundi 13 mars 2023

How can I figure out this warning about C++11 extensions [-Wc++11-extensions]? [duplicate]

I was following a C++ course video on YouTube about typedef. Instead of typedef, the instructor recommended to use using, but when I run the code I get a warning:

alias declarations are a C++11 extension [-Wc++11-extensions]

How do I remove this warning?

The code was like this:

#include <iostream>
#include <vector>
/*
typedef std::vector<std::pair<std::string, int>> pairlist_t;

int main()
{
   //std::vector<std::pair<std::string,int>> pairlist;
     pairlist_t pairlist;
     return 0;
}
*/
//typedef std::string text_t;
//typedef int number_t;
using text_t = std::string;
using number_t = int;
int main()
{
    //std::string firstName;
    text_t firstName = "Lee";
    number_t age = 21;
    std::cout << firstName << '\n';
    std::cout <<age << '\n';

}

Use VCPKG in Visual Studio Code, without using CMake

I want to use the VCPKG package manager, but I don't want to use CMake, I would like to access the .h that I installed just including it as a standard library, so as not to depend on other tools or editors/IDES. The code shows how I want to use it, in the visual studio code terminal it shows how I already installed the library from vcpkg, but I try to run the .cpp and it still doesn't recognize it

enter image description here

How to get gstream rtspsrc location uri or name of the element of current frame?

I have several rtspsrc source and using in my pipeline to make filter/calculations/object detection.

Is there any way to get current frame name or the rtspsrc location from the c++ to decide to branching the program ?

ie:

rtspsrc location=rtsp:///?h264x=4 name=source_2 message-forward=true rtspsrc location=rtsp:///?h264x=4 name=source_3 message-forward=true rtspsrc location=rtsp:///?h264x=4 name=source_4 message-forward=true

I want to get location=... or the name for current frame in my developed plugin.

Best

dimanche 12 mars 2023

Find max and min value in a 3D array using C++ [closed]

This is the question

I'm trying to print every value using for loop in this 3D array and save all values in an array(one-dimensional), then use the minmax_element() function to find max and min values. But now, I don't know how to save those values in an array(I am a beginner in c++ >-<).

for (int i = 0; i < 2; ++i)
    for (int j = 0; j < 2; ++j)
        for (int k = 0; k < 3; ++k)
            cout << "test[" << i << "][" << j << "][" << k << "] = " << test[i][j][k] << endl;

this can help me to get single value of whole 3D array and I want to store them in a one-dimentional array.

What is the code for Drag and Drop on Windows in c++?

You know sometimes you could grab a specific file and drop it onto an exe file. and the exe would read the file and do some processing and give an output how do you do that in c++? and in additon when we run that exe file we would get a window where you could drop the file onto there and it would the same work.

For example: In the above picture we could see that there is a file called "a.txt" and it is being dragged onto an exe file called "test1.exe" and it will read the file and give an output how do you do that.

or the this

where you could open the exe file and drag and drop the file onto there.

I would prefer both.

I would like the source code of the program.

samedi 11 mars 2023

How to acess the sea parton content in LHAPDF?

I recently install and implemented the LHAPDF in my program of c++ for the cross-sections calculations. But, I am interested in to see the individuals contribuitions of sea quarks and valence quarks. I know that each PDF pdf->xfxQ2(i, x, Q2) has the valence + sea content.

How can I acess these individuals contents?

Because, the valence, for example, to the proton, are in i = 1 (up) and i=2 (down). So, I need the valence part of the pdf->xfxQ2(i=1, 2, x, Q2) and I need the sea part of

pdf->xfxQ2(i=-5, -4, -3, -2, -1, 1, 2, 3, 4, 5, x, Q2)

And, in the sea part we have also the gluons pdf->xfxQ2(21, x, Q2).

Can anyone help me?

I am expect an explanation about the structure of LHAPDF.

UTF8 Support in C++

I'm trying to read a text through the command line, and then integrate its words into a map. The text contains commas, parentheses, etc., and also German letters such as ä, ö, ü, etc. I managed to remove all the punctuation and special characters, but I'm having trouble with the umlauts. Also, words like "don't" should be treated as two separate words, "don" and "t". Do you know how I can solve this problem in my code?

#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <cctype>
#include <algorithm>
#include <vector>

using namespace std;

bool compare(const pair<string, int>& a, const pair<string, int>& b) {
    if (a.second == b.second) {
        return a.first < b.first;
    }
    return a.second > b.second;
}

int main(int argc, char* argv[]) {
    // Check if filename is provided and if not give error message
    if (argc < 2) {
        cerr << "Error: filename not provided." << endl;
        return 1;
    }

    // Check for option flags
    bool ignoreCase = false;
    bool printList = false;
    for (int i = 2; i < argc; i++) {
        if (strcmp(argv[i], "-I") == 0) {
            ignoreCase = true;
        }
        if (strcmp(argv[i], "-l") == 0) {
            printList = true;
        }
    }

    // Open input file and if not give error message
    ifstream inFile(argv[1]);
    if (!inFile) {
        cerr << "Error: could not open file with name " << argv[1] << "." << endl;
        return 1;
    }

    // Read file and create a map
    map<string, int> word_count;
    string word;
    while (inFile >> word) {
        cout << word;
        // remove punctuation and special characters
        word.erase(remove_if(word.begin(), word.end(), [](char c) { return !isalpha(c) && !isdigit(c); }), word.end());
        // Convert to lowercase if option flag is set
        if (ignoreCase == true) {
            transform(word.begin(), word.end(), word.begin(), [](unsigned char c) { return tolower(c); });
        }
        // add word to map and increment count
        ++word_count[word];
    }


    // Get the inputfile name and find the position of the last dot in the input file name
    string inputFile = argv[1];
    size_t dotPos = inputFile.rfind('.');
    if (dotPos != string::npos) {
        // Remove everything after the last dot
        inputFile.erase(dotPos);
    }

    // Print the word count to console and output file
    string outFilename = "a01508252-" + inputFile + ".out";
    ofstream outFile(outFilename);

    if (printList == false) {
        int totalValues = 0;
        for (const auto& pair : word_count) {
            cout << pair.first << ": " << pair.second << endl;
            totalValues += pair.second;
        }
        outFile << word_count.size() << " / " << totalValues << endl;
    } else { // print word count

        vector<pair<string, int>> sorted_word_count(word_count.begin(), word_count.end());
        sort(sorted_word_count.begin(), sorted_word_count.end(), compare);

        for (const auto& pair : sorted_word_count) {

            cout << pair.first << "\t" << pair.second << endl;
            outFile << pair.first << "\t" << pair.second << endl;
        }
    }
    outFile.close();

    return 0;
}

The file I want to read in is

Die Bürgschaft

Friedrich von Schiller


Zu Dionys, dem Tyrannen, schlich
Damon, den Dolch im Gewande:
Ihn schlugen die Häscher in Bande,
"Was wolltest du mit dem Dolche? sprich!"
Entgegnet ihm finster der Wüterich.
"Die Stadt vom Tyrannen befreien!"
"Das sollst du am Kreuze bereuen."

"Ich bin", spricht jener, "zu sterben bereit
Und bitte nicht um mein Leben:
Doch willst du Gnade mir geben,
Ich flehe dich um drei Tage Zeit,
Bis ich die Schwester dem Gatten gefreit;
Ich lasse den Freund dir als Bürgen,
Ihn magst du, entrinn' ich, erwürgen."

Da lächelt der König mit arger List
Und spricht nach kurzem Bedenken:
"Drei Tage will ich dir schenken;
Doch wisse, wenn sie verstrichen, die Frist,
Eh' du zurück mir gegeben bist,
So muß er statt deiner erblassen,
Doch dir ist die Strafe erlassen."

Und er kommt zum Freunde: "Der König gebeut,
Daß ich am Kreuz mit dem Leben
Bezahle das frevelnde Streben.
Doch will er mir gönnen drei Tage Zeit,
Bis ich die Schwester dem Gatten gefreit;
So bleib du dem König zum Pfande,
Bis ich komme zu lösen die Bande."

Und schweigend umarmt ihn der treue Freund
Und liefert sich aus dem Tyrannen;
Der andere ziehet von dannen.
Und ehe das dritte Morgenrot scheint,
Hat er schnell mit dem Gatten die Schwester vereint,
Eilt heim mit sorgender Seele,
Damit er die Frist nicht verfehle.

Da gießt unendlicher Regen herab,
Von den Bergen stürzen die Quellen,
Und die Bäche, die Ströme schwellen.
Und er kommt ans Ufer mit wanderndem Stab,
Da reißet die Brücke der Strudel hinab,
Und donnernd sprengen die Wogen
Des Gewölbes krachenden Bogen.

Und trostlos irrt er an Ufers Rand:
Wie weit er auch spähet und blicket
Und die Stimme, die rufende, schicket.
Da stößet kein Nachen vom sichern Strand,
Der ihn setze an das gewünschte Land,
Kein Schiffer lenket die Fähre,
Und der wilde Strom wird zum Meere.

Da sinkt er ans Ufer und weint und fleht,
Die Hände zum Zeus erhoben:
"O hemme des Stromes Toben!
Es eilen die Stunden, im Mittag steht
Die Sonne, und wenn sie niedergeht
Und ich kann die Stadt nicht erreichen,
So muß der Freund mir erbleichen."

Doch wachsend erneut sich des Stromes Wut,
Und Welle auf Welle zerrinnet,
Und Stunde an Stunde entrinnet.
Da treibt ihn die Angst, da faßt er sich Mut
Und wirft sich hinein in die brausende Flut
Und teilt mit gewaltigen Armen
Den Strom, und ein Gott hat Erbarmen.

Und gewinnt das Ufer und eilet fort
Und danket dem rettenden Gotte;
Da stürzet die raubende Rotte
Hervor aus des Waldes nächtlichem Ort,
Den Pfad ihm sperrend, und schnaubet Mord
Und hemmet des Wanderers Eile
Mit drohend geschwungener Keule.

"Was wollt ihr?" ruft er vor Schrecken bleich,
"Ich habe nichts als mein Leben,
Das muß ich dem Könige geben!"
Und entreißt die Keule dem nächsten gleich:
"Um des Freundes willen erbarmet euch!"
Und drei mit gewaltigen Streichen
Erlegt er, die andern entweichen.

Und die Sonne versendet glühenden Brand,
Und von der unendlichen Mühe
Ermattet sinken die Kniee.
"O hast du mich gnädig aus Räubershand,
Aus dem Strom mich gerettet ans heilige Land,
Und soll hier verschmachtend verderben,
Und der Freund mir, der liebende, sterben!"

Und horch! da sprudelt es silberhell,
Ganz nahe, wie rieselndes Rauschen,
Und stille hält er, zu lauschen;
Und sieh, aus dem Felsen, geschwätzig, schnell,
Springt murmelnd hervor ein lebendiger Quell,
Und freudig bückt er sich nieder
Und erfrischet die brennenden Glieder.

Und die Sonne blickt durch der Zweige Grün
Und malt auf den glänzenden Matten
Der Bäume gigantische Schatten;
Und zwei Wanderer sieht er die Straße ziehn,
Will eilenden Laufes vorüber fliehn,
Da hört er die Worte sie sagen:
"Jetzt wird er ans Kreuz geschlagen."

Und die Angst beflügelt den eilenden Fuß,
Ihn jagen der Sorge Qualen;
Da schimmern in Abendrots Strahlen
Von ferne die Zinnen von Syrakus,
Und entgegen kommt ihm Philostratus,
Des Hauses redlicher Hüter,
Der erkennet entsetzt den Gebieter:

"Zurück! du rettest den Freund nicht mehr,
So rette das eigene Leben!
Den Tod erleidet er eben.
Von Stunde zu Stunde gewartet' er
Mit hoffender Seele der Wiederkehr,
Ihm konnte den mutigen Glauben
Der Hohn des Tyrannen nicht rauben."

"Und ist es zu spät, und kann ich ihm nicht,
Ein Retter, willkommen erscheinen,
So soll mich der Tod ihm vereinen.
Des rühme der blut'ge Tyrann sich nicht,
Daß der Freund dem Freunde gebrochen die Pflicht,
Er schlachte der Opfer zweie
Und glaube an Liebe und Treue!"

Und die Sonne geht unter, da steht er am Tor,
Und sieht das Kreuz schon erhöhet,
Das die Menge gaffend umstehet;
An dem Seile schon zieht man den Freund empor,
Da zertrennt er gewaltig den dichten Chor:
"Mich, Henker", ruft er, "erwürget!
Da bin ich, für den er gebürget!"

Und Erstaunen ergreifet das Volk umher,
In den Armen liegen sich beide
Und weinen vor Schmerzen und Freude.
Da sieht man kein Auge tränenleer,
Und zum Könige bringt man die Wundermär';
Der fühlt ein menschliches Rühren,
Läßt schnell vor den Thron sie führen,

Und blicket sie lange verwundert an.
Drauf spricht er: "Es ist euch gelungen,
Ihr habt das Herz mir bezwungen;
Und die Treue, sie ist doch kein leerer Wahn -
So nehmet auch mich zum Genossen an:
Ich sei, gewährt mir die Bitte,
In eurem Bunde der Dritte!"

The output I get:

und 55
die 41
er  25
der 24
da  17
den 16
dem 15
ich 15
das 11
mit 10
des 9
du  8
an  7
freund  7
mir 7
nicht   7
sich    7
von 7
doch    6
ihm 6
ihn 6
sie 6
so  6
zu  6
zum 6
aus 5
in  5
mich    5
ans 4
drei    4
ein 4
es  4
ist 4
kein    4
leben   4
sonne   4
stunde  4
tyrannen    4
am  3
bis 3
dir 3
gatten  3
knig    3
kommt   3
kreuz   3
man 3
mu  3
schnell 3
schwester   3
sieht   3
spricht 3
strom   3
tage    3
treue   3
ufer    3
um  3
vor 3
will    3
als 2
angst   2
armen   2
auch    2
auf 2
bande   2
bin 2
bitte   2
blicket 2
dritte  2
eilenden    2
euch    2
freunde 2
frist   2
geben   2
gefreit 2
gewaltigen  2
hat 2
hervor  2
ihr 2
im  2
kann    2
keule   2
knige   2
land    2
mein    2
o   2
ruft    2
schon   2
seele   2
soll    2
stadt   2
steht   2
sterben 2
stromes 2
tod 2
vom 2
was 2
welle   2
wenn    2
wie 2
wird    2
zeit    2
zurck   2
    1
abendrots   1
andere  1
andern  1
arger   1
auge    1
bche    1
bckt    1
bedenken    1
beflgelt    1
befreien    1
beide   1
bereit  1
bereuen 1
bergen  1
bezahle 1
bezwungen   1
bist    1
bleib   1
bleich  1
blickt  1
blutge  1
bogen   1
brand   1
brausende   1
brcke   1
brennenden  1
brgen   1
brgschaft   1
bringt  1
bume    1
bunde   1
chor    1
damit   1
damon   1
danket  1
dannen  1
deiner  1
dich    1
dichten 1
dionys  1
dolch   1
dolche  1
donnernd    1
drauf   1
drohend 1
durch   1
eben    1
eh  1
ehe 1
eigene  1
eile    1
eilen   1
eilet   1
eilt    1
empor   1
entgegen    1
entgegnet   1
entreit 1
entrinn 1
entrinnet   1
entsetzt    1
entweichen  1
erbarmen    1
erbarmet    1
erblassen   1
erbleichen  1
erfrischet  1
ergreifet   1
erhhet  1
erhoben 1
erkennet    1
erlassen    1
erlegt  1
erleidet    1
ermattet    1
erneut  1
erreichen   1
erscheinen  1
erstaunen   1
erwrgen 1
erwrget 1
eurem   1
fat 1
felsen  1
ferne   1
fhlt    1
fhre    1
fhren   1
finster 1
flehe   1
fleht   1
fliehn  1
flut    1
fort    1
fr  1
freude  1
freudig 1
freundes    1
frevelnde   1
friedrich   1
fu  1
gaffend 1
ganz    1
gebeut  1
gebieter    1
gebrget 1
gebrochen   1
gegeben 1
geht    1
gelungen    1
genossen    1
gerettet    1
geschlagen  1
geschwtzig  1
geschwungener   1
gewaltig    1
gewande 1
gewartet    1
gewhrt  1
gewinnt 1
gewlbes 1
gewnschte   1
giet    1
gigantische 1
glaube  1
glauben 1
gleich  1
glhenden    1
glieder 1
glnzenden   1
gnade   1
gndig   1
gnnen   1
gott    1
gotte   1
grn 1
habe    1
habt    1
hast    1
hauses  1
heilige 1
heim    1
hemme   1
hemmet  1
henker  1
herab   1
herz    1
hier    1
hinab   1
hinein  1
hlt 1
hnde    1
hoffender   1
hohn    1
horch   1
hrt 1
hscher  1
hter    1
irrt    1
jagen   1
jener   1
jetzt   1
kniee   1
komme   1
konnte  1
krachenden  1
kreuze  1
kurzem  1
lange   1
lasse   1
laufes  1
lauschen    1
lchelt  1
lebendiger  1
leerer  1
lenket  1
liebe   1
liebende    1
liefert 1
liegen  1
list    1
lsen    1
lt  1
magst   1
malt    1
matten  1
meere   1
mehr    1
menge   1
menschliches    1
mhe 1
mittag  1
mord    1
morgenrot   1
murmelnd    1
mut 1
mutigen 1
nach    1
nachen  1
nahe    1
nchsten 1
nchtlichem  1
nehmet  1
nichts  1
nieder  1
niedergeht  1
opfer   1
ort 1
pfad    1
pfande  1
pflicht 1
philostratus    1
qualen  1
quell   1
quellen 1
rand    1
rauben  1
raubende    1
rauschen    1
redlicher   1
regen   1
reiet   1
rette   1
rettenden   1
retter  1
rettest 1
rhme    1
rhren   1
rieselndes  1
rotte   1
rubershand  1
rufende 1
sagen   1
schatten    1
scheint 1
schenken    1
schicket    1
schiffer    1
schiller    1
schimmern   1
schlachte   1
schlich 1
schlugen    1
schmerzen   1
schnaubet   1
schrecken   1
schweigend  1
schwellen   1
sei 1
seile   1
setze   1
sichern 1
sieh    1
silberhell  1
sinken  1
sinkt   1
sollst  1
sorge   1
sorgender   1
sperrend    1
sphet   1
sprengen    1
sprich  1
springt 1
sprudelt    1
spt 1
stab    1
statt   1
stet    1
stille  1
stimme  1
strae   1
strafe  1
strahlen    1
strand  1
streben 1
streichen   1
strme   1
strudel 1
strzen  1
strzet  1
stunden 1
syrakus 1
teilt   1
thron   1
toben   1
tor 1
treibt  1
trnenleer   1
trostlos    1
tyrann  1
ufers   1
umarmt  1
umher   1
umstehet    1
unendlichen 1
unendlicher 1
unter   1
verderben   1
vereinen    1
vereint 1
verfehle    1
verschmachtend  1
versendet   1
verstrichen 1
verwundert  1
volk    1
vorber  1
wachsend    1
wahn    1
waldes  1
wanderer    1
wanderers   1
wanderndem  1
weinen  1
weint   1
weit    1
wiederkehr  1
wilde   1
willen  1
willkommen  1
willst  1
wirft   1
wisse   1
wogen   1
wollt   1
wolltest    1
worte   1
wterich 1
wundermr    1
wut 1
zerrinnet   1
zertrennt   1
zeus    1
ziehet  1
ziehn   1
zieht   1
zinnen  1
zwei    1
zweie   1
zweige  1

What I should get out

und 55
die 41
er  25
der 24
den 16
da  15
dem 15
ich 15
das 11
mit 10
des 9
du  8
an  7
freund  7
mir 7
nicht   7
sich    7
von 7
doch    6
ihm 6
ihn 6
sie 6
so  6
zu  6
zum 6
aus 5
in  5
mich    5
ans 4
drei    4
ein 4
es  4
ist 4
kein    4
leben   4
sonne   4
stunde  4
tyrannen    4
am  3
bis 3
dir 3
gatten  3
kommt   3
kreuz   3
könig   3
man 3
muß 3
schnell 3
schwester   3
sieht   3
spricht 3
strom   3
tage    3
treue   3
ufer    3
um  3
vor 3
will    3
als 2
angst   2
armen   2
auch    2
auf 2
bande   2
bin 2
bitte   2
blicket 2
daß 2
dritte  2
eilenden    2
euch    2
freunde 2
frist   2
geben   2
gefreit 2
gewaltigen  2
hat 2
hervor  2
ihr 2
im  2
kann    2
keule   2
könige  2
land    2
mein    2
o   2
ruft    2
schon   2
seele   2
soll    2
stadt   2
steht   2
sterben 2
stromes 2
tod 2
vom 2
was 2
welle   2
wenn    2
wie 2
wird    2
zeit    2
zurück  2
abendrots   1
andere  1
andern  1
arger   1
auge    1
bedenken    1
beflügelt   1
befreien    1
beide   1
bereit  1
bereuen 1
bergen  1
bezahle 1
bezwungen   1
bist    1
bleib   1
bleich  1
blickt  1
blut    1
bogen   1
brand   1
brausende   1
brennenden  1
bringt  1
brücke  1
bunde   1
bäche   1
bäume   1
bückt   1
bürgen  1
bürgschaft  1
chor    1
damit   1
damon   1
danket  1
dannen  1
deiner  1
dich    1
dichten 1
dionys  1
dolch   1
dolche  1
donnernd    1
drauf   1
drohend 1
durch   1
eben    1
eh  1
ehe 1
eigene  1
eile    1
eilen   1
eilet   1
eilt    1
empor   1
entgegen    1
entgegnet   1
entreißt    1
entrinn 1
entrinnet   1
entsetzt    1
entweichen  1
erbarmen    1
erbarmet    1
erblassen   1
erbleichen  1
erfrischet  1
ergreifet   1
erhoben 1
erhöhet 1
erkennet    1
erlassen    1
erlegt  1
erleidet    1
ermattet    1
erneut  1
erreichen   1
erscheinen  1
erstaunen   1
erwürgen    1
erwürget    1
eurem   1
faßt    1
felsen  1
ferne   1
finster 1
flehe   1
fleht   1
fliehn  1
flut    1
fort    1
freude  1
freudig 1
freundes    1
frevelnde   1
friedrich   1
fuß 1
fähre   1
fühlt   1
führen  1
für 1
gaffend 1
ganz    1
ge  1
gebeut  1
gebieter    1
gebrochen   1
gebürget    1
gegeben 1
geht    1
gelungen    1
genossen    1
gerettet    1
geschlagen  1
geschwungener   1
geschwätzig 1
gewaltig    1
gewande 1
gewartet    1
gewinnt 1
gewährt 1
gewölbes    1
gewünschte  1
gießt   1
gigantische 1
glaube  1
glauben 1
gleich  1
glieder 1
glänzenden  1
glühenden   1
gnade   1
gnädig  1
gott    1
gotte   1
grün    1
gönnen  1
habe    1
habt    1
hast    1
hauses  1
heilige 1
heim    1
hemme   1
hemmet  1
henker  1
herab   1
herz    1
hier    1
hinab   1
hinein  1
hoffender   1
hohn    1
horch   1
hält    1
hände   1
häscher 1
hört    1
hüter   1
irrt    1
jagen   1
jener   1
jetzt   1
kniee   1
komme   1
konnte  1
krachenden  1
kreuze  1
kurzem  1
lange   1
lasse   1
laufes  1
lauschen    1
lebendiger  1
leerer  1
lenket  1
liebe   1
liebende    1
liefert 1
liegen  1
list    1
lächelt 1
läßt    1
lösen   1
magst   1
malt    1
matten  1
meere   1
mehr    1
menge   1
menschliches    1
mittag  1
mord    1
morgenrot   1
murmelnd    1
mut 1
mutigen 1
mühe    1
nach    1
nachen  1
nahe    1
nehmet  1
nichts  1
nieder  1
niedergeht  1
nächsten    1
nächtlichem 1
opfer   1
ort 1
pfad    1
pfande  1
pflicht 1
philostratus    1
qualen  1
quell   1
quellen 1
rand    1
rauben  1
raubende    1
rauschen    1
redlicher   1
regen   1
reißet  1
rette   1
rettenden   1
retter  1
rettest 1
rieselndes  1
rotte   1
rufende 1
räubershand 1
rühme   1
rühren  1
sagen   1
schatten    1
scheint 1
schenken    1
schicket    1
schiffer    1
schiller    1
schimmern   1
schlachte   1
schlich 1
schlugen    1
schmerzen   1
schnaubet   1
schrecken   1
schweigend  1
schwellen   1
sei 1
seile   1
setze   1
sichern 1
sieh    1
silberhell  1
sinken  1
sinkt   1
sollst  1
sorge   1
sorgender   1
sperrend    1
sprengen    1
sprich  1
springt 1
sprudelt    1
spähet  1
spät    1
stab    1
statt   1
stille  1
stimme  1
strafe  1
strahlen    1
strand  1
straße  1
streben 1
streichen   1
strudel 1
ströme  1
stunden 1
stößet  1
stürzen 1
stürzet 1
syrakus 1
teilt   1
thron   1
toben   1
tor 1
treibt  1
trostlos    1
tränenleer  1
tyrann  1
ufers   1
umarmt  1
umher   1
umstehet    1
unendlichen 1
unendlicher 1
unter   1
verderben   1
vereinen    1
vereint 1
verfehle    1
verschmachtend  1
versendet   1
verstrichen 1
verwundert  1
volk    1
vorüber 1
wachsend    1
wahn    1
waldes  1
wanderer    1
wanderers   1
wanderndem  1
weinen  1
weint   1
weit    1
wiederkehr  1
wilde   1
willen  1
willkommen  1
willst  1
wirft   1
wisse   1
wogen   1
wollt   1
wolltest    1
worte   1
wundermär   1
wut 1
wüterich    1
zerrinnet   1
zertrennt   1
zeus    1
ziehet  1
ziehn   1
zieht   1
zinnen  1
zwei    1
zweie   1
zweige  1