dimanche 28 février 2021

Qt C++11 Handing out raw pointer from QList

I am working on a problem where I have some sort of custom made "container" DTO which contains a series of items. The user of the class should be able to retrieve an item at a position from the container. I wanted the container to not keep a refrence of raw pointers to the items it contains, but really own them so no custom destructor is necessary. This is what I came up with:

#include <QList>

class MyItem {

public:
    MyItem(int n) : number(n){}

private:
    int number;
};

class MyContainer {

public:
    void addItem(MyItem item){
        m_items.append(item);
    }

    MyItem* getItemAt(int pos){
           if(pos < m_items.size() && pos >= 0){
                return &(m_items.at(pos));
           }
           return nullptr;
    }

private:
    QList<MyItem> m_items;

};


int main(){

    MyContainer container;

    MyItem item1(4);
    container.addItem(item1);

    MyItem* item_ptr = container.getItemAt(0);
    return 0;
}

And in the return of the getItemAt function I am getting this error:

main.cpp:21:24: error: cannot initialize return object of type 'MyItem *' with an rvalue of type 'const MyItem *'

My function needs to return a non const value, because the caller needs to modify the retrieved object. Is there a way to fix this? Is this the best solution for avoiding the destructor and indicating to the caller that the return value is empty.

I know there are several ways to do this:

  • return an optional: unfortunately I am bound to C++11 so not an option
  • throw an exception: I really dislike this option since the codebase has 0 exceptions atm, and I rather not introduce them here.

Value of variable changes automatically in C++

I am coding a simple stack program for the students. the code is as below:

/**
 * This is a menu driven program to use stack
 * */

#include <iostream>

using namespace std;

const int stack_size = 10;
class Stack
{
private:
    /* data */
    int top;
    int data[stack_size - 1];

public:
    Stack()
    {
        top = -1;
    }
    ~Stack() {}

    void push(int x)
    {
        if (top == stack_size)
        {
            cout << "Error: Stack overflow..." << endl;
        }
        else
        {
            data[++top] = x;
            cout << "Item " << x << " pushed successfully..." << endl;
        }
    }

    void pop()
    {
        if (top == -1)
        {
            cout << "Error: Stack underflow..." << endl;
        }
        else
        {
            cout << "Item poped is: " << data[top--] << endl;
        }
    }
    void display()
    {
        cout << "Items in the stack" << endl;
        cout << "------------------" << endl;
        if (top == -1)
        {
            cout << "Stack is empty..." << endl;
        }
        else
        {
            for (int i = top; i >= 0; i--)
            {
                cout << data[i] << endl;
                ;
            }
        }
    }
};

int main()
{
    Stack s;
    char choice;
    int loop = 1, x;
    while (loop == 1)
    {
        cout << "Menu" << endl;
        cout << "1. Push" << endl;
        cout << "2. Pop" << endl;
        cout << "3. Display" << endl;
        cout << "4. Exit" << endl;
        cout << "Enter your choice: ";
        cin >> choice;
        switch (choice)
        {
        case '1':
            //push
            cout << "Enter value to push: ";
            cin >> x;
            s.push(x);
            break;
        case '2':
            //pop
            s.pop();
            break;
        case '3':
            //display
            s.display();
            break;
        case '4':
            //exit
            loop = 0;
            break;
        default:
            //invalid
            cout << "Error: Invalid Selection..." << endl;
            break;
        }
        //fflush(stdin);
    }
}

the problem is when I push 10 Items continuously, then after the 10th element, the value of the loop variable changes automatically. e.g. If I input 10 at the 10th iteration, after the push operation, the value of the loop becomes 10, if I input 11 at the 10th iteration, the value of loop becomes 11 and the while loop breaks. Please someone help me to figure out why this is happening.

Tools using vscode with mingw-64 and C/C++ extension pack and code runner extension.

std::unique_ptr::reset overloads questions

From the https://en.cppreference.com/w/cpp/memory/unique_ptr/reset members of the primary template, unique_ptr

void reset( pointer ptr = pointer() ) noexcept;     (1)     

        
template< class U >
void reset( U ) noexcept;       (2)     
void reset( std::nullptr_t p = nullptr ) noexcept;      (3)     

For me it seems that for (1) if no parameter is giver then default constructor of the pointer's type will be called. But it should behave as a nullptr, so that the pointer inside unique_ptr will be deleted and it will be set to null, how come?

Explanation for the (2) is

2) Behaves the same as the reset member of the primary template, except that it will only participate in overload resolution if either:    
    U is the same type as pointer, or
    pointer is the same type as element_type* and U is a pointer type V* such that V(*)[] is convertible to element_type(*)[].

I can't really understand it, can somebody please explain/rephrase?

One-Definition Rule Followed, but C++ throws Redefinition Error

Very strange redefinition error in C++, especially as every other file including main is error-free.

I have my headers (various animals) and an implementation file "animals.cpp".

My headers follow the format:

class Mammal : public Animal{
    public:
        Mammal(){} //empty constructor
        virtual ~Mammal(){} // destructor
        void createNewMammalObject(std::string name, std::string trackingNum, std::string nurse, std::string subType, std::string type){}
        std::string getSubtype() {}
        void setSubtype(std::string subType){}
        int getNursing(){}
        void setNursing(int nursing){}
        void setType(std::string type){}
        int getNumEggs(){}

    protected:
        int nursing;
};

And implementation in the implementation file looks like:

Mammal::Mammal() {} //empty constructor

virtual Mammal::~Mammal(){} // destructor

void Mammal::createNewMammalObject(std::string name, std::string code,std::string nurse,std::string subType, std::string type){
    this->setNursing(nursing);
    this->setSubType(subType);
    this->createNewAnimalObject(name, trackingNum,subType,type);
}

std::string Mammal::getSubtype() {
    return subType;
}

void Mammal::setSubtype(std::string subType) {
    this->subType = subType;
}

int Mammal::getNursing() {
    return this->nursing;
}

void Mammal::setNursing(int nursing) {
    this->nursing = nursing;
}

void Mammal::setType(std::string type){
    this->type = type;
}

int Mammal::getNumEggs() {
    return 0;
}

My #includes for the implementation file are:

#include "animal.h"
#include "oviparous.h"
#include "mammal.h"
#include "crocodile.h"
#include "goose.h"
#include "pelican.h"
#include "bat.h"
#include "seaLion.h"
#include "whale.h"

All headers and implementation follow this format to follow the One-Definition, except for animal.h which is an abstract class and does contain function definitions. All other functions are definitely only defined once. However, after building the project, EVERY function in the implementation file is saying it's a redefinition and pointing back to the headers as the original definition. I'm incredibly confused. Is this an Eclipse problem? Should my abstract class be defined in my implementation file like the other headers?

When std::map/std::set should be used over std::unordered_map/std::unordered_set?

As in new standards std::unordered_map/std::unordered_set were introduced, which uses hash function and have in average constant complexity of inserting/deleting/getting the elements, in case where we do not need to iterate over the collection in particular order, it seems there is no reason to use "old" std::map/std::set? Or there are some other cases/reasons when std::map/std::set would be a better choice? Like would they be for ex. less memory consuming, or their only pros over the "unordered" versions is the ordering?

C++ static constant array initialization inside class

I want to create a constant and static integer array as a public class variable. It is neat to define it and initialize it right away. See code below for complete example.

#include <iostream>

class Foo {
public:
    constexpr static int arr[3][2] = {
            {1, 2},
            {3, 4},
            {5, 6}
    };
};

int main() {
    for (int i = 0; i < 3; i++) {
        std::cout << "Pair " << Foo::arr[i][0] << ", " << Foo::arr[i][1] << std::endl;
    }
    return 0;
}

However, compiling code above using g++ --std=c++11 test.cpp produces

/usr/bin/ld: /tmp/ccc7DFI5.o: in function `main':
test.cpp:(.text+0x2f): undefined reference to `Foo::arr'
/usr/bin/ld: test.cpp:(.text+0x55): undefined reference to `Foo::arr'
collect2: error: ld returned 1 exit status

Is this not possible in C++ ? More likely I am missing some part about C++ and its static variable initialization policy.

How to separate a line into different variables in C++

I'm new to C++ and programming in general and I would like to know if there is a way to separate a line from a text file into different variables. For example, I want to separate this:

GreenTea limited 24 Instock

And assign each word/number into different variables:

string product;
string type;
int code;
string availability;

How can I achieve this easily? I've used a for loop so that I can find a space and take the substring of the word in order to separate it, but this seems highly inefficient and time consuming.

Functions referencing arrays not giving any output

My code is simply not giving me any output when I try to use the functions. The code compiles correctly, and everything works except calling functions. I am compiling in Unix using the command g++ -std=c++11 Golf.cpp (this is required, I cannot change how the file can be compiled). I have tried filling in the parameters when I go to execute the function, but that is proving more harmful than good. Here is the code:

/*Name:Zayn Severance
Date: 2/28/2021
Section: COP3363
Assignment: Module 4 assignment 2
DueDate: 2/28/2021
About this project: Calculate scores for golf.
Assumptions: Assumes correct user input.

All work below was performed by Zayn Severance*/

#include <iostream>
#include <algorithm>
int getValidScore()
{
    bool isScoreValid = false;
    int scoreCheck = 0;
    while (isScoreValid == false)
    {

        std::cout << "Enter in a positive number greater than 0...";
        std::cin >> scoreCheck;
        if (scoreCheck >= 18 && scoreCheck <= 300)
        {
            isScoreValid = true;
        }
        else
        {
            isScoreValid = false;
        }
    }
}

int getValidPlayer()
{
    bool isNumGreater0 = false;
    int playerCheck = 0;
    std::cout << "Please enter in the score ...";
    while (isNumGreater0 == false)
    {
        std::cin >> playerCheck;
        if (playerCheck >= 1 && playerCheck <= 3)
        {
            isNumGreater0 = true;
        }
        else
        {
            isNumGreater0 = false;
            std::cout << "Please enter in a valid score (18...300) ...";
        }
    }
    return playerCheck;
}

void displayScores(int* scores, std::size_t NUM_PLAYERS)
{
    std::cout << "Display Scores\n\tPlayer 1\tPlayer2\tPlayer3\n\t";
    for (int i = 0; i < 3; ++i)
    {
        std::cout << scores[i] << "\t";
    }
}

void ChangeAScore(int *scores, std::size_t NUM_PLAYERS)
{
    int playerFinder = getValidPlayer();
    playerFinder = playerFinder - 1;
    int scoreFinder = getValidScore();
    scores[playerFinder] = scoreFinder;
}

void displayPlayerLowestScore(int* scores, std::size_t NUM_PLAYERS)
{
    int temp = scores[0];
    int winning = 0;
    for (int i = 0; i < NUM_PLAYERS; i++)
    {
        if (temp > scores[i])
        {
            winning = i;
            temp = scores[i];
        }
    }
    winning = winning + 1;
    std::cout << "The player with the lowest score is " << winning;
}

int main() {
    const int NUM_PLAYERS = 3;
    int scores[NUM_PLAYERS] = { 118,98,68 };
    int options = 0;
    //if options is 4 the loop ends, and the program stops
    while (options != 4) {

        int options;
        std::cout << "1) Display the scores\n2) Change a score\n3) Display player with the lowest score\n4) Quit\nSelect an option (1..4)..";
        std::cin >> options;
        int num = 0;
        //Display Scores
        if (options == 1) 
        {
            displayScores;
        }
        //Change Scores
        else if (options == 2) 
        {
            ChangeAScore;
        }
        //
        else if (options == 3) 
        {
            displayPlayerLowestScore;
        }
        //
        else if (options == 4)
        {
            std::cout << "Bye.\n";
            return 0;
        }

        //In case you miss the instructions and put in a letter
        else if (!std::cin) 
        {
            std::cout << "That was not a number. Invalid input.\n";
            std::cin.clear();
            std::cin.ignore(1024, '\n');
            options = 0;
        }
        //Any other input
        else 
        {
            std::cout << "Invalid input.\n";
            options = 0;
        }
    }
    return 0;
}

If anyone could tell me my mistake (I assume it's small, I'm quite new) I would be grateful.

How an exit code is determined in a multithreaded program when one of the threads fails?

struct func
{
    int& i;
    func(int& i_):i(i_){}
    void operator()()
    {
        for (unsigned j = 0; j < 1000000; ++j)
        {
            ++i;
        }
    }
};

int main()
{
    int some_local_state = 0;
    func my_func(some_local_state);
    std::thread my_thread(my_func);
    my_thread.detach();
    return 0;
}

Output is

(process 1528) exited with code -1073741819

What determines the exit code? What does detaching mean for a Windows process?

Calling class vector after storing another class inside the vector

heres my code, vector class lines2D

vector<Line2D> lines2D;

lines2D.push_back(Line2D(Point2D(xAxis, yAxis), Point2D(zAxis, wAxis)));

Stored data into the lines2D vector with another class Point2D constructor.

but now how do I call it to display the data inside the vector lines2D?

usually I would use for(int i =0; i<lines2D.size();i++) { cout << lines2D.at(i) << endl; }

But with the another class method in it i was not able to figure out the syntax.

I want to get results like

line2D.pt1.getX(), line2D.pt1.getY() line2D.pt2.getY(), line2D.pt2.getY()

basically to get the Point2D(x, y) Point2D(x, y) that is stored in my Line2D class.

Insert func for an AVL Tree [closed]

How can implement an insert function for an AVL tree class. The argument to be passed to the function is the node to be inserted in the tree. Thanks

How does cv::calcHist(params) work under the hood?

I am trying to create a custom function to calculate histogram of individual channels of an image in C++ . I know cv::calcHist(params) does this already and i am trying to compare the correctness of my custom function by comparing the output of cv::calcHist(param). And i see i am getting a different output then the one i get using the cv::calcHist(params)

Below is my function:

int generateHistograms(const cv::Mat& img, int* blueChnl, int* redChnl , int* greenChnl)
{
    MatConstIterator_<Vec3b> it, end;
    for( it = img.begin<Vec3b>(), end = img.end<Vec3b>(); it != end; ++it)
    {
      (*(blueChnl+(*it)[0]))++;
      (*(redChnl+(*it)[0]))++;
      (*(greenChnl+(*it)[0]))++;
    }

}

I ran this function on the image given at the cv::calcHist(param) tutorial page.I also ran the cv::calcHist(param) given in the tutorial. Below is a snippet:

vector<Mat> bgr_planes;
split( src, bgr_planes );
int histSize = 256;
float range[] = { 0, 256 }; //the upper boundary is exclusive
const float* histRange = { range };
bool uniform = true, accumulate = false;
Mat b_hist, g_hist, r_hist;
calcHist( &bgr_planes[0], 1, 0, Mat(), b_hist, 1, &histSize, &histRange, uniform, accumulate );
calcHist( &bgr_planes[1], 1, 0, Mat(), g_hist, 1, &histSize, &histRange, uniform, accumulate );
calcHist( &bgr_planes[2], 1, 0, Mat(), r_hist, 1, &histSize, &histRange, uniform, accumulate );

and got the following histogram outputs from cv::caclHist() and my function respectively. On inspection of the frequency of individual pixels, i see that the frequency for a pixel value was 0 at a lot of places in b_hist but not in blueChnl and almost everywhere the values were different. Also the frequency for the pixel values calculated using my function was as large as 1500 but b_hist has had all the frequency <256.

What am i doing wrong here ?

Un normalized image using cv::calcHist()

enter image description here

How does user defined conversion sequence work in C++ when initializing objects?

I have some question regarding user defined conversion sequence when performing copy initialization. let's say

#include <iostream>
struct Doodle {
  operator char() { return 'd' };
};

struct Penta {
  Penta(double) {};
  Penta()  = default;
};

int main() {
  Doodle d; 
  Penta p = 3.34; // works
  Penta another = d;

}

In last line it calls conversion function on d and calls Penta(double) constructor. What if I had a constructor that takes Doodle ? Will it call operator char() or Penta that takes Doodle constructor? I wish I could remember all those implicit conversion rules and sometimes these implicit conversions will be a headache in my opinion.

samedi 27 février 2021

Static Member Variable, Qualified Name is Not Allowed

I've searched other answer's on SO and feel like I'm following the format correctly, so not sure what Im doing wrong and am at my wits end with this one....

class DBwrapper {
    private:
        static std::string DBfile;
        //static char DBfile[];
#include "DBwrapper.h"
#include <string>
int main()
{
    std::string DBwrapper::DBfile = "library.db3";
    std::string DBwrapper::DBfile{"library.db3"};
}

In VS, I get red squiggles in main.cpp under DBwrapper::DBfile saying "Qualified name is not allowed". I've tried with char [] as well as const/not const.

Inheriting a variable from a class

I am working on a project which has an abstract class A and several classes, suppose class B, C, D which all inherit publicly from class A.

Class A has a bunch of getters and setters as well as a few private member variables.

One of these member variables is a string called name.

Another one of these member variables is a character called abbreviation, which holds the first character of the name string.

How can I go about setting the string and character variables without needing getters and setters to name them in the code of functions I write. I do not want to have to set them at the start of the program run.

Is it possible to set them in their constructors? For example:

// B constructor
B::B() {
name = "B is the name of this variable";
abbreviation = 'B';
}

Thanks in advance ! :D

What should the error statements be for exit 3 and 4 in my c++ simple buffer code?

I need to input error statements above exits three and four and then actually force the code to go to these error statements so I can have screenshot proof that they are working. However, I can't quite work out what should be in each. My initial thoughts are 'the output file can't be created for 3 and 'The file you want to read from is empty' for 4, but I can't seem to trigger these errors so I feel like that's not correct.

#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <iostream>

using namespace std;

#define BUF_SIZE 500
#define OUTPUT_MODE 0700


int main(int argc, char *argv[])
{
    int in_file, out_file;
    int read_size = 1, write_size;
    char buf[BUF_SIZE];
    if (argc != 3){ 
        cout<<"The command-line input does not contain 3 arguments"<<endl;
        exit(1);
        }
     in_file= open(argv[1], O_RDONLY);
     if (in_file  < 0) {
        cout<<"The file you are trying to copy from doesnt exist"<<endl;
        exit(2);
        }
    out_file = creat(argv[2], OUTPUT_MODE);
    if (out_file < 0) {
        cout<<"Error statement 3"<<endl;
            exit(3);
        }
    while (read_size > 0) {
            read_size = read(in_file, buf, BUF_SIZE);
            if (read_size <0){
            cout<<"Error statement 4"<<endl;
                exit(4);
            }
            write_size = write(out_file, buf, read_size);
            if (write_size<=0){
                close(in_file);
                close(out_file);
                cout<<"Reading and writing from and to files is complete"<<endl;
                exit(5);
               }
             }
}

How do you read in 4 different integers from a single line in a txt file opened in the command line? [closed]

Ron Bowmanr much longer CPER211 lab section 05 and 06.       
75 50 57 6          
Section 05 test scores:

This is the txt file I am trying to read from. I need the 4 numbers assigned to 4 different variables using the ignore function. I used

inFile.ignore(INT_MAX,'\n');
inFile >> arg1;

to find the first number in the txt file but I can't find the other 3 numbers to assign them to variables like I did for the first number.

Conditionally defining method for container class

Is it possible (and is it a good idea) to conditionally define methods for some container class (template<typename ThingType> class Container) depending on the type of its elements? I first thought it was possible after reading about std::enable_if, but now I am not certain I understand.

Below is my attempt (click here to run on ideone). In the case that std::is_base_of<ThingBase, ThingType>::value is false, a return type for p will not be defined. I figured the compiler would just instantiate the object of a class without that method. But it turns out it doesn't compile.

Is there another tool for the job? Or should I write two Container-like classes that have different behavior depending on what ThingType is? Or maybe this is a job for a specialization.

#include <iostream>
#include <type_traits>
#include <vector>


class ThingBase {
public:
    virtual void printHi() = 0;
    
};

class Thing : public ThingBase
{
    void printHi(){
        std::cout << "hi\n";
    }   
};


template<typename ThingType>
class Container{
private:
    std::vector<ThingType> m_things;
public:

    typename std::enable_if<std::is_base_of<ThingBase, ThingType>::value>::type p()
    {
        m_things[0].printHi();
    };
};


int main() {
    
    //Container<Thing> stuff; // works!
    Container<int> stuff; // doesn't work :(
    
    return 0;
}

undefined reference to in c++ / omnet++

I am using omnet++ that follows c++, I want to make one simple controller. I want to change the value of static members of the controller from another file. But when I compile the code it generates undefined references.

My code is written following, Kindly suggest to me what should I do, Thanks in advance.

//controlTest.h
namespace OPTxGsPON {
class controlTest:public cSimpleModule, public cListener 
{
public:
    static controlTest* bb;
    static int bbb;
};
}; //namespace
//User.h
namespace OPTxGsPON {
class User :public cSimpleModule
{
protected:
    virtual void initialize();
};
}; //namespace
//User.cc
namespace OPTxGsPON {
void User::initialize()
{
     controlTest::bb=new controlTest();
     controlTest::bbb=12;
}
}; //namespace

Error: ../out/gcc-release/src/User/User.o:User.cc:(.rdata$.refptr._ZN9OPTxGsPON11controlTest2bbE[.refptr._ZN9OPTxGsPON11controlTest2bbE]+0x0): undefined reference to `OPTxGsPON::controlTest::bb'

Please guide me How will I fix it...

vendredi 26 février 2021

codechef isrec wrong answer

I am facing a wrong answer on my submission. I have run all the test cases that came to my mind but unfortunately all seem to give the correct output. I even checked out others' submissions but didn't get very far. Apparently idea seems to be fine but maybe I am missing some serious detail. I simply have no idea.

The link to the question is: https://www.codechef.com/CCRC21C/problems/ISREC

My code is:


    #include<bits/stdc++.h>
    using namespace std;
    
    int num_consec_ones(string row,int m)
    {
        int c=0;
        for(int i=0;i<m;i++)
        {
            if(row[i]==1)   c++;
            if(c>1 && row[i-1]==0 && row[i]==1)   
            {
                c=-1;
                break;
            }
        }
        return c;
        
    }
    int start_index(string row,int m)
    {
        for (int i=0;i<m;i++)
        {
            if(row[i]==1)
            return i;
        }
    }
    
    void solve()
    {
        int n,m,flag=0;;
        cin>>n>>m;
        vector<string>row;
       // row.reserve(n);
        for(int i=0;i<n;i++)
        {
            string str;
            cin>>str;
            row.push_back(str);
            for(int j=0;j<m;j++)
               row[i][j]=row[i][j]-'0';
    
        }
        set<int>s;
        for(int j=0;j<n;j++)
        {
            if(num_consec_ones(row[j],m)==-1)
            {
                cout<<"No"<<endl;
                return;
            }
            if(num_consec_ones(row[j],m) && flag==1 && num_consec_ones(row[j-1],m)==0)
            {
                cout<<"No"<<endl;
                return;
            }
            if(num_consec_ones(row[j],m) && flag==0)
            {
                s.insert(num_consec_ones(row[j],m));
                flag=1;
            }
        }
        if(s.size()==1)
        {
            set<int>start;
            for(int j=0;j<n;j++)
            {
                if(num_consec_ones(row[j],m))
                {
    
                    start.insert(start_index(row[j],m));
                }
            }
            if(start.size()==1)
            {
                cout<<"Yes"<<endl;
                return;
            }
            else{
                cout<<"No"<<endl;
                return;
            }
    
        }
        
    }
    
    int main()
    {
        int t;
        cin>>t;
        while(t--)
        {
            solve();
        }
    }

Please help me out. Thank you!

Having trouble figuring out how to output only the largest output of a function

I am writing a code that uses a function I made to calculate the likeness scores between strings of numbers and letters which are supposed to represent playing cards. For example the string "H8C6D6" represents 8 of hearts, 6 of clubs, and 6 of diamonds. Anyway, the new function I'm writing takes a string whose length is greater than or equal to the golden sequence (aka the string it is being compared to in order to calculate the likeness score) and calculates the likeness score for all the substrings that are of equal length to the golden sequence. The problem I am running into is that I am only supposed to output the largest likeness score, but instead all of the likeness scores are being outputted. I'm not sure how to fix this. I have tried functions such as fmax(), but they have not worked for me. Any help would be greatly appreciated.

#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;


double calcLikenessScore(string seq1, string seq2)
{
    int n=seq1.length(); //length of seq1
    int m=seq2.length(); //length of seq2
    if(n != m) //if lengths of both the strings are not equal then we return -1
    return -1;
    int match_cards = 0; //variable to store the matching cards 
    int bonus = 0; //variable to store the bonus
    for(int i = 0; i < n; i += 2)
    {
        if(seq1[i] == seq2[i]) //if the suit of both the sequences is equal
        {
            match_cards++; //matching cards is incremented by 1
            if(seq1[i + 1] == seq2[i + 1]) //if the rank of both sequences is also equal 
            {
                bonus++; //bonus is incremented by 1.
            }
        }
    }
    int total_cards = n / 2; //total cards are length/2.
    double likeness_score = double(match_cards) / double(total_cards) + bonus; //calculating 
likeness_score 
    return likeness_score; 
}


double bestLikenessScore(string seq1 , string gold_seq)
{
    int n = seq1.length(); //Length of sequence 1
    int m = gold_seq.length(); //Length of golden sequence
    if (n < m) //If the length of sequence 1 is not greater than or equal to the golden 
sequence, then it will return -1
    return -1;
    int i;
    for (int i; i < n; i += 2)
    {
        string str1 = seq1.substr(i , m); //String that holds substring values of seq1
        double d = calcLikenessScore(str1 , gold_seq); //Function to calculate Likeness 
scores of substrings
        if (str1.length() == m)
        {
            cout << d << endl; //Outputs likeness scores, but how can I make it so it will 
only output the largest value
        }
    }
    return 0;
}


int main()
{
    string s1; //First string to test; should be of greater or equal length to s2(gold_seq)
    string s2; //Golden Sequence
    cout << "enter first string: " << endl;
    cin >> s1;
    cout << "enter second string: " << endl;
    cin >> s2;
    double c = bestLikenessScore(s1 , s2); //Runs all substrings through calcLikenessScore() 
function, and outputs the lkeness scores of substrings
    return 0;
}

How to calculate word frequency in a list using C++?

So I have some words in a file. I read them to a List then I'm trying to find the frequency of each word. My problem is that I have to follow a certain implementation for the list which isn't very flexible. Here's the List class:

const int maxListSize = 50;

template<class T>
class List {
private:
    int numberOfElements;
    int currentPosition;
    T data[maxListSize];
public:
    List() {
        numberOfElements = 0;
        currentPosition = -1;
    }
    void insert(T element) {
        if (numberOfElements >= maxListSize) {
            cout << "List is Full" << endl;
            return;
        }
        data[numberOfElements] = element;
        numberOfElements++;
    }

    bool first(T &element) {
        if (numberOfElements == 0) {
            cout << "List is Empty" << endl;
            return false;
        }
        else {
            currentPosition = 0;
            element = data[currentPosition];
            return true;
        }
    }

    bool next(T &element) {
        //Check if the user called the first function
        if (currentPosition < 0) {
            cout << "Please call the first function before calling the next" << endl;
            return false;
        }
        if (currentPosition >= numberOfElements - 1) {
            //cout << "No next item" << endl;
            return false;
        }
        currentPosition++;
        element = data[currentPosition];
        return true;
    }
};

Assume my list is called names. How can I get the frequency of each word?

In what situation would C++11 = default constructor be different from a constructor taking no parameters and an empty body?

I know that if a parametrized constructor is provided, the implicit default constructor is not generated.

If we have a constructor taking no parameters and an empty body it can play the role of a default constructor.

class Box {
public:
  Box(int value) : x(value) {}  // parametrized constructor
  Box() {}  // default constructor
private:
  int x;
};

In C++11 we can write = default to specify that we want the implicitly generated default constructor to be present, even if we have already a parametrized constructor.

class Box {
public:
  Box(int value) : x(value) {}  // parametrized constructor
  Box() = default;
private:
  int x;
};

I am wondering, is there a difference between these two syntaxes for specifying a default constructor explicitly? Are they equivalent or not? Is a constructor taking no parameters and no body really a default constructor or is it something else?

I want to ask, can there be a situation in which the constructor taking no parameters and no body have a different behavior than the C++11 = default constructor? Obscure and arcane examples are welcome.

How to compare the elements on two arrays on C++

A c ++ problem where I have to determine if the user hit the target. After entering the coordinates of where enemies coulb be, the user then enters more coordinates and I must compare them, print YES if the element[i] of the attacks matches any element of enemies [n]. I know that I'm comparing positions and not elements that's why it's not working but I'm lost.I also tried to solve it by making only one array but it felt better this way.

    #include <iostream>
    using namespace std;

    int main()
    {
    int n, k, b;
    int enemies[];
    int attacks[];
    
    cin>>n;
    for (int i=0; i<n; i++) {
        cin>>b;
        enemies[i]=b;
    }
    
    cin>>k; 
    for (int i=0; i<k; i++) {
        cin>>b;
        atacks[i]=b;
    }
    
    for(int i=0; i<k; i++){
       if(atacks[i]==enemies[i]){
                cout<<"YES"<<endl;
       }
       else{
           cout<<"NO"<<endl;
       }
    
    return 0;
}

ICC not recognizing stream move semantics

I have the following piece of code that works with -std=c++0x under recent GCC (9.3.1) and clang (7.0.1). It does not work under older GCC (4.8.5), but that's OK. I am now trying to get it to work under ICC (19.0.5.281 20190815).

inline std::istringstream setup_extraction_stream(const std::string buffer, const std::string searchkey)
{
    const size_t offset = buffer.find(searchkey);
    std::istringstream iss(buffer);
    if (offset != std::string::npos)
    {
        iss.seekg(offset);
    }
    return iss;
}

My understanding is that this works because std::istringstream has an implicit move constructor, so there's no copying happening here. However ICC does not seem to have such a move constructor.

error: function "std::basic_istringstream<_CharT, _Traits, _Alloc>::basic_istringstream(const std::basic_istringstream<char, std::char_traits<char>, std::allocator<char>> &) [with _CharT=char, _Traits=std::char_traits<char>, _Alloc=std::allocator<char>]" (declared implicitly) cannot be referenced -- it is a deleted function
    return iss;
           ^

How can I work around this?

Shared pointer confusion

I'm currently learning the smart pointers and I got a bit confused. Why the shared pointer does not print the memory address that stores as raw pointer neither with simple print nor with get() ?

int x = 100;
int* y = &x;
std::cout<<&x<<std::endl;
std::cout<<y<<std::endl;

std::shared_ptr<int> x2 = std::make_shared<int>(x);
std::cout<<x2.get()<<std::endl


0x7ffe965e20b4                                                                                                       
0x7ffe965e20b4                                                                                                       
**0x2176c30**  so why this value is for both x2.get() and x2 ? 

Thank you

Why is std::declval not constexpr?

As in question - why is code like this illegal in cpp?

static_assert(std::declval<std::array<int, 4>>().size() == 4);

Is it an overlook in standard or there is some deeper rationale why std::declval is not constexpr?

Sorting out int variables from a .txt file (fstream, c++)

I have a .txt file with these this line on the top '12 4 25 257' each of the numbers spaced out by a ' ' and the line ends with '\n'

I have these variables and a function getFirstLine:

int A;
int B;
int C;
int D;
ifstream File("a.txt");
void getFirstLine(int &A, int &B, int &C, int &D)
{
 int list[] = {A, B, C, D};
    string myText;
    getline(File, myText);
    int size = myText.size();
    cout << size;
    for (int i = 0; i < size; i++)
    {
        if (myText[i] != ' ')
        {
            list[i] = (int)myText[i] - 48;
            cout << list[i] << endl;
        }
    }
}

I want to basically save the first number on A, second on B, third C etc...

I cant seem to get this working sadly :( Can someone help me with this?

Output should look like:

A = 12,
B = 4,
C = 25,
D = 257,

Tensor creation and destruction within a while loop in libtorch C++

I have just started with libtorch and I am having some trouble with while loops and tensors :roll_eyes: So, my main func looks like so:

int main()
{

  auto tensor_create_options = torch::TensorOptions().dtype(torch::kFloat32).device(torch::kCPU).requires_grad(false);
  torch::Tensor randn_tensor = torch::randn({10}, tensor_create_options);

  while (randn_tensor.sizes()[0] > 5)
  {
    std::cout << "==> randn_tensor shape: " << randn_tensor.sizes() << std::endl;
    randn_tensor.reset(); //reset();
    torch::Tensor randn_tensor = torch::randn({3}, tensor_create_options);
    std::cout << "==> randn_tensor shape 3: " << randn_tensor.sizes() << std::endl;

  }

  return 0;
}

and I get thrown this:

==> randn_tensor shape: [10]
==> randn_tensor shape 3: [3]
terminate called after throwing an instance of 'c10::Error'
  what():  sizes() called on undefined Tensor

Essentially, what I want to do is recreate the tensor within the while loop and ensure that the sizes of this newly created tensor is reflected in the while(recreated_tensor_size SOME_CONDITION){}

Interestingly, it seems to have cerated the tensor of reduced size but the while loop does not seem to recognise this.

Thank you!

When should we write our own move constructor (move assignment operator)

A user-defined move constructor and move assignment operator could have been omitted in all examples explaining move semantics I have seen so far because compilers generated ones will do the job.

The answers I found in stackoverflow will not go beyond the "Rule of three" (Rule of five) - so if a class defines any of the following then it should probably explicitly define all five.

But for copy constructor and all other members the reason is obvious and an example could be written easily to show what issues can occur if user-defined copy constructor doesn't exist.

In wikipedia we can find:

A user-defined copy constructor is generally needed when an object owns pointers or non-shareable references, such as to a file.

So the question is if there are examples that will show if user-defined move constructor or move assignment operator are really needed or I can assume that in 99% of cases compiler generated ones will be enough.

jeudi 25 février 2021

Getting an unknown error: operand types are incompatible ("char *" and "char")C/C++(42)

I am currently trying to write a function in c++ that will tell me the number of vowels when characters are inputted. However, I am running into a problem when I try to make if statements that will allow the code to count the vowels. The error is: operand types are incompatible ("char *" and "char")C/C++(42). My equals signs have the red squiggly lines under them meaning there is an error and I'm just not sure what to do to fix it.

The code is not finished by the way I just want to get this error out of the way before I move on.

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


char isVowel(char word , int count) { 
    char word[100];
    int count = 0;
    while (word != '\0') {
        if (word == 'a' || word == 'e' || word == 'i' || word == 'o' || word == 'u') 
        count++;
    }
    return 0;
}

c++ ifstream fail() flag is on but no error shown by strerror()

I had code like below. I feel like the file stream didn't reach the file end, because ln_cnt value isn't equal to the feature count (i.e. number of polyline features) shown in QGIS.

Such inequality happend when the shapefile is large so I can't count features one by one, but I used small-sized shapefile for test already and my code works well.

polyline_class line_1;

int ln_cnt ++; // the counter for counting the lines that's read

ifstream reader("some_polyline.shp", ios::in | ios::binary);

while (!reader.eof()){

    shp_read_pnt(&reader, &line_1);
    ln_cnt ++;

}

cout << ".good() = " << reader.good() << "\n";
cout << ".bad() = " << reader.bad()   << "\n";
cout << ".fail() = " << reader.fail() << "\n";
cout << ".eof() = " << reader.eof()   << "\n";
cerr <<  "Error: " << strerror(errno);
reader.close();

The result is :

.good() = 0
.bad() = 0
.fail() = 1
.eof() = 1
Error: No error

Is there an error, actually ?

Error LNK2005 DllMain already defined in uafxcw.lib(dllmodul.obj)

I have dll project. I added to my solution other quite big project that I want to use as a lib in my dll. But when I started to use new project from my dll project, I had several linking errors, also like in this question error LNK2005: new and delete already defined in LIBCMTD.lib(new.obj)

I've put into "Additional dependency" and "ignore specific library" uafxcwd.lib;Libcmtd.lib, and errors about new, delete etc now is gone, but I still got the error about DllMain.

I've also tried to put

extern "C" { int __afxForceUSRDLL; }

line to the cpp with DllMain and got additional error

Error   LNK2005 __afxForceUSRDLL already defined in dllmain.obj 

I'm completely at a loss

Find out who included header from project's External dependencies

I'm creating dll project with Visual Studio. I have quite a lot of files in my External dependencies, and now I'm particularly interested to find out who included wtypes.h as it's now have some name conflicts with files from other projects I'm including. Is it a way to find out through which files wtypes.h got into my project?

deduced conflicting types for parameter '_BIter' ('int*' and 'int')

I was trying to implement a simple reverse array function:

void reverse(int (&arr)[], int n)
{
  int start = 0, end = n - 1;

  while (start <= end)
  {
    int temp = arr[start];
    arr[start] = arr[end];
    arr[end] = temp;
    start++;
    end--;
  }
}

In my main() I have this:

int brr[9]{10, 20, 30, 40, 50, 60, 70, 80, 90};
for (int i = 0; i < 9; i++)
{
  cout << brr[i] << " ";
}
cout << endl;

reverse(brr, 9);
for (int i = 0; i < 9; i++)
{
  cout << brr[i] << " ";
}

How ever I am not able to figure out why I am getting this error:

no matching function for call to 'reverse(int [9], int)'
65 |   reverse(brr, 9);

no known conversion for argument 1 from 'int [9]' to 'int (&)[]'
12 | void reverse(int (&arr)[], int n)

deduced conflicting types for parameter '_BIter' ('int*' and 'int')
65 |   reverse(brr, 9);

I want to know what is this behavior and how to correct it?

Thanks!

Explanation on additional dependency libs when creating dll project in Visual Studio

when creating dll project in visual studio (2017 in my case) there are quite a lot of libs out into additional dependencies

kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;

Is there somewhere a descriptions why so many are needed?

Segmentation Fault Error when assigning values to array

I'm currently doing a basic simulation problem in USACO. I'm pretty sure I've done the algorithm for this problem correctly, however, when I try to assign values to array, I get the error: run: line 1: 3 Segmentation fault (core dumped) LD_LIBRARY_PATH=/usr/local/gcc-9.2.0/lib64 ./a.out. This is my code:

#include <iostream>
#include<string>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include<vector>
#include <cmath>
#include <array>
using namespace std;
void setIO(string s) { // the argument is the filename without the extension
    freopen((s+".in").c_str(),"r",stdin);
    freopen((s+".out").c_str(),"w",stdout);
}
int main() {
    // setIO("speeding");
    string new_signal = "";
    int m, n; cin >> m >> n;
    int arr1[n+m] = {0};
    int arr2[n+m] = {0};
    for(int i = 0; i < n+m; i++) {
        int a, b; cin >> a >> b;
        arr1[i] = a;
        arr2[i] = b;
        // cout << n+m;
    }
    
    int road_limits[100] = {0};
    int counter = 0;
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < arr1[i]; j++) {
            road_limits[counter] = arr2[i];
            counter++;
        }
    }
    counter = 0;
    int max_over_limit = -200;
    for(int i = n; n < n+m; n++) {
        for(int j = 0; j < arr1[i]; j++) {
            if((arr2[i] - road_limits[counter]) > max_over_limit){
                max_over_limit = (arr2[i] - road_limits[counter]);
            }
            counter++;
        }
    }
    
    cout << max_over_limit;
    return 0;
}

After debugging with print statements, it appears that my code gets the Segmentation Fault error somewhere in the first for loop where I assign the values of arr1 and arr2(no cout statements run past that point). I'm not why this would be the case though. I'm relatively new to using C++, so is there something that I'm misunderstanding that causes this error?

C++ 11 Program: Main Menu keeps re-looping once wrong input is entered

I am working on a program that takes in point 2D, point 3D, line3D and line3D numbers from text file. This text file will then be run through the program in which its data can be sorted based on the user's preference. So far there has been no issues with the program other than the fact that the menu constantly loops again and again upon inputting an invalid input. Any help would be appreciated.

int displayMainMenu(string f, string sC, string sO)
{
    int choice;
    
    cout << endl << "NIL" << endl
         << "NIL" << endl
         << "--------------------------------------------" << endl
         << "Welcome to Program" 
         << endl << endl
         << "1) \t Read in data" << endl
         << "2) \t Specify filtering criteria (current: " << f << ")" << endl
         << "3) \t Specify sorting criteria (current: " << sC << ")" << endl
         << "4) \t Specify sorting order (current: " << sO << ")" << endl
         << "5) \t View data" << endl
         << "6) \t Store data" << endl
         << "7) \t Quit" << endl
         << endl << "Please enter your choice: ";
    cin >> choice;
    
    return choice;
}

int integerValidation(int option, string f, string sC, string sO)
{   
    switch (option)
    {
        case 1:
        case 2:
        case 3:
        case 4:
        case 5: 
        case 6:
        case 7: return option; 
        default: do
             {
                cout << endl << "You have entered an invalid menu option. Please re-enter..."
                             << endl;
                option = displayMainMenu(f, sC, sO);
                
             } while ((option != 1) || (option != 2) || (option != 3) ||
                      (option != 4) || (option != 5) || (option != 6) || (option != 7));
    }
    
    return option;
}

Is it possible to detect if a class has a member with a certain type/return type without knowing the member's name?

I would like to detect if a certain class has member variables/functions of a specific type/return type, without knowing the name of these variables (there is no fixed format of naming them).

for example:

struct Wheel{
    int wheel_size;
}

struct Bike{
    private:
    Wheel weel_1;
    Wheel weel_2;

    public:
    Wheel get_wheel_1();
    Wheel get_wheel_2();
}

Is it possible to determine if Bike has a member of type Wheel or a function of return type Wheel without knowing the names of these members?

Context: I am working on an open source autopilot project. For communication messages, we need to set timestamps for synchronization purposes (Code for setting the timestamp for messages is specified here)

Sometimes these messages have nested messages and the timestamp of each nested message should be updated as well. So I wanted to check if a message has a nested message and if so, I should update the timestamp of both the outer and the inner message/messages.

Note: The C++ code of the messages is auto-generated from a message definition file.

RAM leaks on stl containers?

I have a RAM limit on my project, as it contains a lot of data manipulation . The problem is, I noticed that calling std::set<std::pair<int64_t, int64_t>>::clear() does not actually free any memory. The code for reproducing the problem:

std::set<std::pair<int64_t, int64_t>> stltest;
for (size_t i=1; i<=250000; i++)
{
    stltest.insert({i, i});
}
std::cout << " "; // place for a breakpoint
stltest.clear();
std::cout << " "; // place for a breakpoint

On ubuntu 20.04, standart c++ compiler this thing takes 17,7 MB and it doesn't give it back. Probably clear() just sets size() to zero, but does nothing with contents, which is weird. Am I dumb or am I dumb? Can I get the memory back, I really need it.

Edit: Tried to manually create new and delete after and still can't get my memory back.

Create a Shared library and use it in another project

I have a c++ project with following structure:

.
├── include
│   ├── common.h
│   ├── os.h
│   ├── helper.h
│
├── lib
|   ├── libcrypto.so
│   ├── libssl.so
|   ├── ...
|
└── src
    ├── common.c
    ├── helper.c

Now I want to make a shared or any kind of library of this whole project so that I can include helper.h header in some other c++ project totally independent of this one and call some function declared in this header file.

I tried making a shared library with the following CMakeLists file:

cmake_minimum_required(VERSION 3.0)

project(helperlib)

link_directories(lib)

file(GLOB SOURCES src/*.c)

include_directories(include)

add_library(${PROJECT_NAME} SHARED ${SOURCES})

install(TARGETS ${PROJECT_NAME} DESTINATION lib/${PROJECT_NAME})

file(GLOB HEADERS include/*.h)
install(FILES ${HEADERS} DESTINATION include/${PROJECT_NAME})

But when I use the libhelperlib.so file generated by cmake in another project and use #include "helper.h", it gives me error. Can anyone suggest how to do this. Thanks!

EDIT: This is the structure of the other project:

.
├── include
│   ├── constants.h
│   ├── datetime.h
│   ├── 
│
├── lib
|   ├── libhelperlib.so
│   ├── libboost_system.so
|   ├── liboost_system.a
|
└── src
    ├── constants.c
    ├── datetime.c
    ├── main.c

And CMakeLists.txt that I'm using for it is:

cmake_minimum_required(VERSION 3.0)

project(testProj)

include_directories(include)
link_directories(lib)

file(GLOB SOURCES src/*.c)
file(GLOB HEADERS include/*.h)

add_executable(testProj ${SOURCES} ${HEADERS})
target_link_libraries(testProj crypto helperlib boost_system)

And when I'm using #include "helper.h" in main .c it gives following error:

fatal error: helper.h: No such file or directory

Unable to pass 2D character array to function(C++)

I am trying to pass a 2-D character array to a function however vs code gives me the following error message:

cannot convert 'char ()[3]' to 'char ()[10]'gcc

Here is the code:

#include<string>
using namespace std;
void NodeDetect(char grid[][3], int height, int width)
{
    cout << "\nThe grid output:\n";
    for(int i = 0; i < height; ++i)
    {
        for(int j = 0; j < width; ++j)
            if(grid[i][j] == '0')
            {
                cout << '\n' <<  i << '\t' << j << ", ";

                if(grid[i][j + 1] == '0' && (j + 1) < width)//right neighbour
                    cout << i << '\t' << (j + 1) << ", ";
                else if(grid[i][j + 1] == '.' || (j + 1) == width)
                    cout << "-1 -1, ";

                if(grid[i + 1][j] == '0' && (i + 1) < height)//bottom neighbour
                    cout << (i + 1) << '\t' << j << ", ";
                else if(grid[i + 1][j] == '.' || (i + 1) == height)
                    cout << "-1 -1";
            }
            cout << '\n';
    }
}
int main()
{
    string line;
    char grid[3][3];
    int height, width;                          //height = rows
    cout << "Enter the height and the width:\t";//width = columns
    cin >> height >> width;
    cout << "\nEnter the strings:\n";
    for(int i = 0; i < height; ++i)//initializing the grid
        cin >> grid[i];

    /*
    cout << "\nThe grid:\n";
    for(int i = 0; i < height; ++i)     //displaying the grid
    {
        for(int j = 0; j < width; ++j)
            cout << grid[i][j] << '\t';
        cout << '\n';
    }
    */
    NodeDetect(grid, height, width);
    return 0;
}

I am trying to pass the 2D array grid to the function NodeDetect

mercredi 24 février 2021

What is this `(*(T*)nullptr)` old trick?

I have just read Is declval<T>() the same as (*(T*)nullptr)? and just realized that I haven't heard of the (*(T*)nullptr) trick before. If I analyze that snippet, it doesn't give me too much information, beside that (quoting the answer)

you can get an instance of T in a decltype without needing to worry about T's constructor

and also the example found there is just very trivial:

struct B {
    A a;
};
typedef decltype((*(B*)nullptr).a) T1;

so, can please someone explain to me what this (*(T*)nullptr) trick is and why (and how) would I want to use it (beside of the example above)?

Access Violation Writing Location after Vector Resize? [closed]

I am bit confused on what could cause this.

Basically I have code doing this:

 std::vector<uint8_t> buffer;
 buffer.resize(size);
 memcpy(buffer.data(), data_, size);

Then after some amount time of this running I will get:

Access Violation Writing Location 0x000002484FC0B060

on the memcpy

The application has many threads going. I am fairly sure that buffer is not being touched by any other thread during this. But am curious, am I missing something here? Aside from some other thread touching buffer between the resize and memcpy, is there anyway the reference to buffer.data could end with write violation?

Encountering an undefined reference link error when attempting to use the Google GCS C++ library

We have a need to use Google's GCS C++ client library. We've downloaded the library (version 1.23.0) and all of its dependencies. We've built those libraries. I am attempting to modify one of the sample programs that Google supplies along with their GCS C++ library. Background: we're running on RHEL 7, gcc 7.4.0, GCS C++ 1.23.0 and building using the std=C++11 keyword.

The sample program creates credentials and a client handle. It then uses that handle to exercise various API methods in the GCS C++ library.

The relevant portion of the sample code I have follows:

std::string authBuffer = ""; //Deleted actual key for obvious reasons

// The credentials are successfully created:
auto creds = gcs::oauth2::CreateServiceAccountCredentialsFromJsonContents( authBuffer );

// As is the client handle:
gcs::Client client=gcs::Client(gcs::ClientOptions(*creds));

// This code will build and run without error:
auto writer = client.WriteObject(std::string("temp"), "quickstart.txt");
writer << "Hello world!";
writer.Close();

// However this is the problem line of code:
auto bucketReader = client.ListBucketsForProject( std::string( "my_project" ) );

As stated in the comments above, the bucket reader code fails to link. I encounter the following link error:

In function `google::cloud::v1::StatusOr<google::cloud::storage::v1::BucketMetadata>::StatusOr(google::cloud::v1::Status)': <first part of path snipped>/gc-cpp/google-cloud-cpp-1.23.0/install6/include/google/cloud/status_or.h:118: undefined reference to `google::cloud::v1::internal::ThrowInvalidArgument(char const*)'

sample.o: In function `_ZNK4absl14lts_2020_09_2316variant_internal17PerformVisitationIZN6google5cloud2v18internal11StreamRangeINS4_7storage2v114BucketMetadataEE4NextEvE13UnpackVariantJNS0_7variantIJNS5_6StatusESA_EEEEE3RunIJLm0EEJLm18446744073709551615EEEEvSt17integral_constantIbLb1EENS0_16integer_sequenceImJXT_EEEEDpSI_ImXT0_EE':

<first part of path snipped>/abseil-cpp/abseil-cpp-20200923.3/install6/include/absl/types/internal/variant.h:942: undefined reference to `absl::lts_2020_09_23::variant_internal::ThrowBadVariantAccess()'

All of which is a bunch of gooblty-gook upon first glance. I mean we all know what an undefined reference is, but why is this happening within the GCS C++ library code? It's almost as if Google is utilizing some type of macro build magic in order to tell me that I have malformed code of some sort. I'm not certain where I am going awry though.

Interestingly, if I comment the bucket reader statement out, then the program will build and run without incident. I can see the new quickstart.txt file appear in the bucket within the project in my GCS account via a web browser.

So what gives with this bucket reader business? If coryan is reading this, I'd appreciate feedback. I decided to use the GCS C++ library based in part on his previous feedback in a separate SO question. Thanks!

Function returns const ref to std::unique_ptr, can it return null?

I have a function that return const ref to a std::unique_ptr. I'm getting this ptr from some container. I want to have a possibility to return nullptr or something when in my container of std::unique_ptr there is no appropriate object to the input values. It seems to be impossible with const ref. There is definitely an option to return const raw pointer, but I would like to stick to std::unique_ptr if it's possible.

Treat std::string containing control characters as literal C++ [closed]

I have C++ application. There I am receiving string with this format: "SessionIwithcharacter,\x03" (Note \x03)

When I print it I can see this: SessionIwithcharacter,^C

My question is, is there any way in C++ to treat that character literally?

I am using C++11

Thanks in advance

Should FreeLibrary be called at the end of the program?

I haven't found this in the documentation: if I need a DLL handler until the end of the program, should I still call FreeLibrary before my caller program ends, or it's not required?

C++, addition of unsigned offset how to solve?

I was trying to solve the following problem on leetcode:

https://leetcode.com/explore/interview/card/top-interview-questions-medium/103/array-and-strings/779/

Given a string s, find the length of the longest substring without repeating characters.

Example 1:

Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3.

Constraints:

0 <= s.length <= 5 * 104 s consists of English letters, digits, symbols and spaces.

My suggested solution is:

class Solution {
public:
    const int MAX_LEN = 128;
    int lengthOfLongestSubstring(string s) {
        int max_len=0;
        int n=s.length();
        for (int i=0;i<n;++i)
        {
            int len=0;
            vector<int> his(MAX_LEN,0);
            for (int j=i;j<i+MAX_LEN, j<n;++j)
            {
                if (his[s[j]-'a']!=0)
                    break;
                ++his[s[j]-'a'];
                ++len;
                if (len>max_len) max_len=len;
            }
        }
        return max_len;
    }
};

but when I compile it on the website I get an error with the following input: " "

Line 1034: Char 34: runtime error: addition of unsigned offset to 0x615000003280 overflowed to 0x61500000317c (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:34

LoadLibrary can't load dll from he folder where executable is situated

In which project setting, or in some other place should can I set that the LoadLibrary will find the dll that is situated in the same folder as the executable of the program that use this dll?

Currently LoadLibrary fails to load such dll, if I set the full path it loads ok. I though dll from the same folder should be loaded without any problems

Is there a way to pas rvalue reference of some unique_ptr to thread pool

I'm using C++11 (I can't use newer C++'s standards). I can't pass a function with rvalue reference of unique_ptr to my thread pool.

Here is a simple code.

Working with test2 function and not working with test1.

#include "thread-pool.hpp"
#include <iostream>
#include <string>

struct Mystruct
{
    int a;
    int b;
    std::string c;
};

void test1(int id, std::unique_ptr<Mystruct>&& ms, int a)
{
    while (true)
    {
        std::cout << ms->c << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(a));
    }
}

void test2(int id, std::string&& c, int a)
{
    while (true)
    {
        std::cout << c << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(a));
    }
}

int main()
{
    ctpl::thread_pool p(10);
    Mystruct* ms = new Mystruct;
    std::unique_ptr<Mystruct> msp(ms);
    p.push(test1, msp, 10);
    p.push(test2, "this is the end", 10);
    p.push(test2, "hello from the other side", 5);
    return 0;
}

I am getting these errors:

no instance of overloaded function "ctpl::thread_pool::push" matches the argument list
C2893   Failed to specialize function template 'std::future<unknown-type> ctpl::thread_pool::push(F &&,Rest &&...)'
C2780   'std::future<unknown-type> ctpl::thread_pool::push(F &&)': expects 1 arguments - 3 provided
C2672   'ctpl::thread_pool::push': no matching overloaded function found

I am using vit vit repository for my thread pool implementations.I am using this link for thread pool implementation for my thread-pool.hpp file.

I can't change my test1's function arguments due i am using another API. Is there a way to pass this function to my thread pool object or another implementation of thread pool.

mardi 23 février 2021

Linkage multiple inclusion in C++ [duplicate]

I have written a C++ code using 3 files. Here are the file names and their overall structures:

graph.h:

#ifndef GRAPH_H
#define GRAPH_H

/*some header files included here*/

using namespace std;
const int max = 1000;
int var;

/*class Graph defined here*/

#endif
graph.cpp:

#include "graph.h"
/*class Graph functions implemented here*/
main.cpp:

#include "graph.h"
using namespace std;
/*main() function implemented here*/

I use the following commands to compile the code:

g++ -std=c++11 -Wno-deprecated -O3 -c  main.cpp
g++ -std=c++11 -Wno-deprecated -O3 -c  graph.cpp
g++ -O3  main.o graph.o -o myProg

The first two commands go fine, but the third command (the link step) produces the following error:

graph.o:(.bss+0x0): multiple definition of `var'
main.o:(.bss+0x0): first defined here
collect2: error: ld returned 1 exit status

I have used header guards in graph.h. Also, if I eliminate "graph.h" from "graph.cpp" and "main.cpp" then these files will not compile. Please help me figure out what I am doing wrong. Thank you very much!

Make decision depending on variadic types

I know I have made the title as blurry as possible, but the sample will hopefully set the goals.

I have a Base class and families of Derived classes (classy OOD, nothing more).
Furthermore I have a function which takes variadic templates and I want to make decision depending on those templates.

template<typename... Ts>
void do_smth(std::vector<std::shared_ptr<Base>>& vec) {
    for (auto&& ptr: vec) {
        if the static type of ptr is one of Ts.. then do smth.
    }
}

And I intend to call the function as this:

do_smth<Deived1, Derived2>(vec);

I know I could forward the Ts... to std::variant check with hold_alternative or smth like this, but I have only types not values. And to complicate the matters, my compiler is limitied with C++14 support.
Can someone please suggest some tiny/elegant solution to this?

Use enum from dll

I'm exporting some functions from a dll, and in some functions as a parameter I'm using enum, declaring in the dll project. What is a proper for the projects that will use this dll to find out about this enum, if they will use dll via explicit linking with LoadLibarary/GetProcAddress functions?

In implicit linking it seems easy, I just include this enum when including dll's headers.

Is in case of explicit linking I still need to include my dll's header with enum to the project that will use the dll?

How to sort and unique eigen matrix?

I am trying to sort a matrix and apply unique on in first and second column.

For an example:

3 98 31
3 99 31
2 98 31
2 99 31
2 98 31
3 91 31
3 98 31

After sorting and applying unique, I need

2 98 31
2 99 31
3 91 31
3 98 31
3 99 31

I tried to adopt [this solution][1] to my problem, but I could not able to make it work.

Here the code I tried:

void eigen_sort_unique_rows_by_head(Eigen::MatrixXi& A_nx3)
{
    std::vector<Eigen::VectorXi> vec;
    for (int64_t i = 0; i < A_nx3.rows(); ++i)
        vec.push_back(A_nx3.row(i));
 
    std::sort(vec.begin(), vec.end(), [](Eigen::VectorXi const& t1, Eigen::VectorXi const& t2){ return t1(0) < t2(0) ; } );
  //std::sort(vec.begin(), vec.end(), [](Eigen::VectorXi const& t1, Eigen::VectorXi const& t2){ return t1(1) < t2(1) ; } );
       //Here I am missing something, I tried with extra line of code it did not work
    
    auto it = std::unique(vec.begin(), vec.end());
    vec.resize(std::distance(vec.begin(),it));
    std::cout<<" vector size "<<vec.size()<<std::endl;

    A_nx3.resize(vec.size(),3);
    for (int64_t i = 0; i < vec.size(); ++i)
        A_nx3.row(i) = vec[i];
};

Can someone help me with this problem?

Thanks in advance. [1]: Sort Eigen matrix column values by ascending order of column 1 values

C++ creating a new object of class?

I was given the following details about a data structure:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */

How can I probably create a new ListNode and a pointer to it?

I tried:

ListNode *result=ListNode(10);

but didn't work

cout in multithread WITHOUT LOCK in C++20

I'm writing in C++20. Here's a very simple program that asks three threads to print some string. For example, we ask thread 1 to print "This is thread1", and thread 2 to print "This is thread2", and thread 3 to print "This is thread3".

However, I notice that in the printThread function that passed into threads, if we are not using a lock, we can get print results that mingle among threads. Such as This is This thread2 is thread3. I would like to avoid such intervening, so I wrote my code with mutex:

#include <iostream>
#include <string.h>
#include <thread>
#include <mutex>
using namespace std;


mutex m_screen;
void printCnt()
{   
    lock_guard guard(m_screen);
    cout << "Func Start" << endl;
    // Fetch the thread ID of the thread which is executing this function
    thread::id threadID = this_thread::get_id();
    
    cout << "Thread [" << threadID << "] has been called " endl;
    
    
}

// g++ foo.cpp =pthread

int main(){
    thread t1(printCnt);
    thread t2(printCnt);
    thread t3(printCnt);

    t1.join();
    t2.join();
    t3.join();

    cout << "done" << endl;
    
}

I wonder if there's any way that can achieve the same effect like mutex, but without a lock?

Adding Gravity component to Acceleration

first thing first, thank you so much for helping me with this problem.

I am working on a ROS-C++ Project. Problem:

i have a vector of positions (x, y, z) and a vector of time stamp with 10 times per second sampling(10Hz), from these two vector i need to output:

  • A vector of velocities
  • A vector of Accelerations
  • A vector of Accelerations with gravity component

For the first two requests i did:

Velocity = dx/dt;

Acceleration = dv/dt

basically the medium Velocity and medium Acceleration.

Where: dx = Xi - Xi-1;

dt = ti - ti-1 and so on...

I really don't know if there are other or better solutions than these like if there is a C++ library that makes a function from a vector input and get the instantaneous velocity/acceleration but i am open to new solutions, maybe Alglib...

Now my real problem is considering the Gravity component in the last vector: i have accelerations but i don't think the solution would be cutting 9.8 from them :') I really searched everywhere but all i have are these vectors, i can also get the orientations values (x, y, z, w) but i don't think they are necessary for this problem?

C++11: inconsistent warnings for out-of-order instance member initialization

The following code crashes, raising std::bad_alloc or sometimes std::logic_error.

#include <string>

class Crasher {
public:
    Crasher() : value(default_value) {}
private:
    std::string value;
    const std::string default_value = "default is yours";
};


int main(void) {
    Crasher();
}

I believe the reason is that the members are initialized out of order, and when value is being intialized in initializer list, default_value hasn't yet been initialized.

However, I don't get any compiler warnings or errors with -Wall enabled. However if I change value and default_value to a POD type like int, then I get a warning from g++:

$ g++ -Wall crasher.cpp 
crasher2.cpp: In constructor ‘Crasher::Crasher()’:
crasher2.cpp:5:23: warning: ‘*<unknown>.Crasher::default_value’ is used uninitialized in this function [-Wuninitialized]
    5 |     Crasher() : value(default_value) {}
      |              

Why do I not get a warning when the type is std::string? Is this a compiler problem, or a quirk of the language?

BOOST 1.73.0 Interprocess string allocator error

I'm trying to allocate a string inside a custom object SharedValue in shared memory using Boost 1.73.0

My object:

typedef boost::interprocess::allocator<char, boost::interprocess::managed_shared_memory::segment_manager> char_allocator;

class SharedValue {
public:
  SharedValue(const char_allocator& ca);
  boost::interprocess::basic_string<char, std::char_traits<char>, char_allocator> val;
};

SharedValue::SharedValue(const char_allocator& ca) : val(ca) {}

Then in the shared memory builder:

boost::interprocess::managed_shared_memory shm(boost::interprocess::open_or_create, "SharedMemory", 65536);
boost::interprocess::managed_shared_memory::allocator<char>::type ca(shm.get_allocator<char>());
auto *value = shm.find_or_construct<SharedValue>(string(ID + "_" + name + "_SharedValueSHM").c_str())(ca);

And it gives me this error:

In file included from boost/include/boost/interprocess/containers/string.hpp:23,
                 from SharedValue.h:24,
                 from SharedValue.cpp:13:
boost/include/boost/container/string.hpp: In instantiation of ‘boost::container::dtl::basic_string_base<Allocator>::members_holder::members_holder() [with Allocator = boost::interprocess::allocator<char, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> >]’:
boost/include/boost/container/string.hpp:100:18:   required from ‘boost::container::dtl::basic_string_base<Allocator>::basic_string_base() [with Allocator = boost::interprocess::allocator<char, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> >]’
boost/include/boost/container/string.hpp:643:16:   required from ‘boost::container::basic_string<CharT, Traits, Allocator>::basic_string() [with CharT = char; Traits = std::char_traits<char>; Allocator = boost::interprocess::allocator<char, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> >]’
SharedValue.cpp:19:50:   required from here
boost/include/boost/container/string.hpp:220:27: error: no matching function for call to ‘boost::interprocess::allocator<char, boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index> >::allocator()’
  220 |          : allocator_type()
      |                           ^
In file included from boost/include/boost/interprocess/segment_manager.hpp:38,
                 from boost/include/boost/interprocess/detail/managed_memory_impl.hpp:30,
                 from boost/include/boost/interprocess/managed_shared_memory.hpp:25,
                 from SharedValue.h:21,
                 from SharedValue.cpp:13:
boost/include/boost/interprocess/allocators/allocator.hpp:142:4: note: candidate: ‘template<class T2> boost::interprocess::allocator<T, SegmentManager>::allocator(const boost::interprocess::allocator<T2, SegmentManager>&)’
  142 |    allocator(const allocator<T2, SegmentManager> &other)
      |    ^~~~~~~~~
boost/include/boost/interprocess/allocators/allocator.hpp:142:4: note:   template argument deduction/substitution failed:
In file included from boost/include/boost/interprocess/containers/string.hpp:23,
                 from SharedValue.h:24,
                 from SharedValue.cpp:13:
boost/include/boost/container/string.hpp:220:27: note:   candidate expects 1 argument, 0 provided
  220 |          : allocator_type()
      |                           ^
In file included from boost/include/boost/interprocess/segment_manager.hpp:38,
                 from boost/include/boost/interprocess/detail/managed_memory_impl.hpp:30,
                 from boost/include/boost/interprocess/managed_shared_memory.hpp:25,
                 from SharedValue.h:21,
                 from SharedValue.cpp:13:
boost/include/boost/interprocess/allocators/allocator.hpp:136:4: note: candidate: ‘boost::interprocess::allocator<T, SegmentManager>::allocator(const boost::interprocess::allocator<T, SegmentManager>&) [with T = char; SegmentManager = boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index>]’
  136 |    allocator(const allocator &other)
      |    ^~~~~~~~~
boost/include/boost/interprocess/allocators/allocator.hpp:136:4: note:   candidate expects 1 argument, 0 provided
boost/include/boost/interprocess/allocators/allocator.hpp:131:4: note: candidate: ‘boost::interprocess::allocator<T, SegmentManager>::allocator(boost::interprocess::allocator<T, SegmentManager>::segment_manager*) [with T = char; SegmentManager = boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index>; boost::interprocess::allocator<T, SegmentManager>::segment_manager = boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index>]’
  131 |    allocator(segment_manager *segment_mngr)
      |    ^~~~~~~~~
boost/include/boost/interprocess/allocators/allocator.hpp:131:4: note:   candidate expects 1 argument, 0 provided

Anyone have some ideas to solve this error?

Thanks

Visual Studio can not find my header files

I'm struggling with problem with headers in visual studio. I tried to add specific paths but it doesn't work. Any idea why it occurs? I attached screen shot with my issue.

1: This the image of my visual studio cockpit

Thank you in advance for your help

How to append two xml file in tinyxml2

I have two XML file.

first.xml

<?xml version="1.0" encoding="UTF-8"?>
<Average>
    <source unit="FP">
        <brand name="Add" abbreviation="addition" value="0">            
            <mask value="1" name="Integer"/>
            <description></description>
        </brand>
        <brand name="Sub" abbreviation="substraction" value="1">            
            <mask value="1" name="Integer"/>
            <description></description>
        </brand>
    </source>
</Average>

second.xml

<source unit="PE">
    <brand name="Mul" abbreviation="multiplication" value="0">            
            <mask value="1" name="Integer"/>
            <description></description>
    </brand>
    <brand name="Div" abbreviation="division" value="0">            
            <mask value="1" name="Integer"/>
            <description></description>
    </brand>
</source>

I want to append the content of second.xml file to first.xml file

Expected Output:

<?xml version="1.0" encoding="UTF-8"?>
<Average>
    <source unit="FP">
        <brand name="Add" abbreviation="addition" value="0">            
            <mask value="1" name="Integer"/>
            <description></description>
        </brand>
        <brand name="Sub" abbreviation="substraction" value="1">            
            <mask value="1" name="Integer"/>
            <description></description>
        </brand>
    </source>
    <source unit="PE">
    <brand name="Mul" abbreviation="multiplication" value="0">            
            <mask value="1" name="Integer"/>
            <description></description>
    </brand>
    <brand name="Div" abbreviation="division" value="0">            
            <mask value="1" name="Integer"/>
            <description></description>
    </brand>
</source>
</Average>

Here is what I was trying:

#include<iostream>
#include<string>
#include "tinyxml2.h"

void doAccess(const std::string& first, const std::string& second)
{
    std::string outFile = "output.xml";
    tinyxml2::XMLDocument doc;

    if (tinyxml2::XML_SUCCESS == doc.LoadFile(first.c_str()))
    {
        std::cout << "File is Present\n";
        doc.SaveFile(outFile.c_str());
    }

    if (tinyxml2::XML_SUCCESS == doc.LoadFile(second.c_str()))
    {
        std::cout << "File is Present\n";
        doc.SaveFile(outFile.c_str());
    }
}

int main()
{
    std::string first = "first.xml";
    std::string second = "second.xml";

    doAccess(first , second);

    return 0;
}

Any help would be highly appreciated.

C++ generic callback implementation

I have a code that takes messages from flash player in a form of XML parse them into function and arguments and calls a registered callback for that function. The piece of code that I want to replace is something nicely done (almost) generic Callback mechanism: code for the generic callback implementation of flashSDK (ASInterface.inl).

The problem with it is that this code is written for flash and I want to replace the flash and use other service that will have the same interface. Is there any standard implementation of this callback mechanism (std? boost? something else open sourced?)?

This code implements generic callbacks mechanism that you can register function with number of arguments and types in a map:

void SomethingHappened(int a, int b) {print a + b;}
void SomethingElseHappened(string abcd) {print abcd;}
callbacks["SomethingHappened"] = &SomethingHappened;
callbacks["SomethingElseHappened"] = &SomethingElseHappened;

and than search for it and call with an array of arguments:

Callbacks::iterator itCallback = callbacks.find(functionName);
if (itCallback != callbacks.end())
{
    HRESULT result = itCallback->second.Call(arguments, returnValue);
}

full usage example:

//init callbacks
typedef std::map<std::wstring, Callback> callbacks;
void SomethingHappened(int a, int b) {print a + b;}
void SomethingElseHappened(string abcd) {print abcd;}
callbacks[functionName] = &SomethingHappened;

void MessageArrived(string xmlInput)
{
    string functionName = parseFunctionName(xmlInput);
    Callbacks::iterator itCallback = callbacks.find(functionName);
    if (itCallback != callbacks.end())
    {
        //parse arguments
        std::vector<std::wstring> args;
        _Args::split(xml, args);
        ASValue::Array arguments;
        for (size_t i = 0, s = args.size(); i < s; ++i)
        {
            ASValue arg; arg.FromXML(args[i]);
            arguments.push_back(arg);
        }
        ASValue returnValue;
        //***this is where the magic happens: call the function***
        HRESULT result = itCallback->second.Call(arguments, returnValue);
        return result;
    }
}

lundi 22 février 2021

(C++) Does C++ has hoisting of class?

I've herad that it's illegal to implement member function in different scope such as...

class Foo{
   public:
      Foo();
}

int main(){
   Foo :: Foo(){   // implementation must be held in same scope where class is: global scope
      std::cout << "Hello" << std::endl;
   }
}

So I thought defineing a class inside main function would make it possible to implement method inside main.

#include <iostream>

int main() {

class Person {
  public:
    std::string name;
    int age;
    Person(std::string name, int age);
};

Person ::Person(std::string name, int age)
    : name(name), age(age) {
    std::cout << "Person class created as" << name << " " << age << std::endl;
}

    Person yun("yun", 18);

    std::cout << yun.name;

    Person *john = new Person("John", 15);
}

But code above spit out error as : qualified-id in declaration before '(' token
which is same error i've seen when implement method in different scope.

Is it something to do with hoisting that I've seen at JavaScript? so that class definition goes outside of main?

What makes this deconstruct never be called

I am trying to understand the memory leak. I don't understand why below MyInt deconstruct in main is never called and a memory leak happens.

  class MyInt
    {
        int *_p; 
    public:
        MyInt(int *p = NULL) { _p = p; }
        ~MyInt() 
        { 
            delete _p; 
        }
        int &operator*() { return *_p; }
    };

int main()
{
    double t[] = {1.0, 2.0, 3.0, 4.0, 5.0};
    for (size_t i = 0; i < 5; ++i)
    {
        MyInt *en = new MyInt(new int(i));
        std::cout << **en << "/" << t[i] << " = " << **en / t[i] << std::endl;

    return 0;
}

c++ A Generic Callback object implementation

I'm currently using an implementation of callback mechanism from flash for c++, ASInterface.inl you can see an example here:

https://github.com/cpzhang/bud/blob/a37348b77fb2722c73d972a77827056b0b2344f6/trunk/tool/flash/ASInterface.inl#L393.

I'm looking for a standard implementation for generic callback like that (in std or in boost or something else), that is not coupled with flash player. What it does basically is to implement a generic Callback object that can be called with arbitrary number of arguments of primitive types.

typedef std::map<std::wstring, Callback> callbacks;
string functionName = "SomethingHappened";
string xml = "<some xml document/>";
Callbacks::iterator itCallback = callbacks.find(functionName);
if (itCallback != callbacks.end())
    {
        //parse arguments
        std::vector<std::wstring> args;
        _Args::split(xml, args);
        ASValue::Array arguments;
        for (size_t i = 0, s = args.size(); i < s; ++i)
        {
            ASValue arg; arg.FromXML(args[i]);
            arguments.push_back(arg);
        }
        ASValue returnValue;
        //***this is where the magic happens: call the function***
        HRESULT result = itCallback->second.Call(arguments, returnValue);
        return result;
    }

Unresolved external symbol during dll linking

ALL,

I have a static link library which exports a class. This class contains a member of std::mutex.

When I link this library to my main project there is no problem, but when I try to link the library to dynamic link library in the same project I'm getting the undefined external symbol.

I double check and all the libraries I link are the same.

Whats weird is that the linker complain about the member and not the class itself.

What could be the issue?

TIA!

P.S. if it matter - I'm working with msvc 2017 on Windows 8.1.

Can anyone help how to fix runtime error in this code?

Task is to determine the count of substrings, where the count of digit C is exactly P

Input Format: The first line contains integer t denoting the number of test cases, For the next 2*t (2 lines for each test case), the first line contains two integers P and C, and the second line contains a string. Let us denote the string by symbol s. Constraints:

1<=t<=10

1<=P,|s|<=1000000

0<=C<=9

Time Limit: 1 second Output Format: For each test case, the first and only line of output contains the answer as described in task.

Sample Input 1:

2

1 2

212

4 5

55555

Sample Output 1:

4

2

Explanation: For First test case: {2}, {2,1}, {1,2}, {2} are the substrings that contains digit 2 exactly 1 time.

For Second test case: {5,5,5,5}, {5,5,5,5} are the substrings that contains digit 5 exactly 4 times .

I am getting runtime error in this

        using namespace std; 
          
        
        int countSubString(string s, char c, int k) 
        { 
        
            int leftCount = 0, rightCount = 0; 
          
           
            int left = 0, right = 0; 
          
            int freq = 0; 
          
            int result = 0, len = s.length(); 
          
            
            while (s[left] != c && left < len) { 
                left++; 
                leftCount++; 
            } 
          
            
            right = left + 1; 
            while (freq != (k - 1) && (right - 1) < len) { 
                if (s[right] == c) 
                    freq++; 
                right++; 
            } 
          
          
            while (left < len && (right - 1) < len) { 
          
                
                while (s[left] != c && left < len) { 
                    left++; 
                    leftCount++; 
                } 
          
            
                while (right < len && s[right] != c) { 
                    if (s[right] == c) 
                        freq++; 
                    right++; 
                    rightCount++; 
                } 
          
                
                result = result + (leftCount + 1) * (rightCount + 1); 
          
                
                freq = k - 1; 
          
            
                leftCount = 0; 
                rightCount = 0; 
          
                left++; 
                right++; 
            } 
          
            return result; 
        } 
          
        // Driver code 
        int main() 
        { 
            int t;
            cin>>t;
            while(t--){
                
            
            string s;
            
            cin>> s[1000000];
            char c;
                cin>>c;
            int k;
                cin>>k;
          
            cout << countSubString(s, c, k); 
          
            return 0; 
            }
        } 

singleton and new operator - thread safety

I know that Scott Meyers Singleton is thread safe for C++11 and above. Does the following code is thread safe (for C++11 and above) ?

class T
{
    static T* obj;
public:
    T& GetInstance()
    {
        if (!obj)
        {
            obj = new T();
        }
        return *obj;
    }
};
T* T::obj=nullptr;

Problem with count the decimal part by C++?

I'm a newbie in C++. I got trouble when count the decimal part by C++, here is the example and code:

example:

   3.01: count of decimal part is 2
103.939: count of decimal part is 3

code:

int result = 0;
double d   = 4.01;

while(true) {
    cout << "(int)d: " << (int)d << endl;
    if(d == (int)d) break;

    d *= 10;
    cout << "d *= 10: " << d << endl;

    result++;
}
cout << result << endl;

console:

int(d): 4
d *= 10: 40.1
int(d): 40
d *= 401
int(d): 400
d *= 10: 4010
int(d): 4009
...

what happens to 4.01? And the same strange result when the double = 5.01 etc. I know it's the problem of precision when convert DOUBLE to INT, but I'm really curious about how it happens when the test doubles like 4.01, 5.01, etc.

And in addition, how to modify the if state correct to test 4.01?

compare boost::geometry::model::box

is it already implemented functions in boost to compare squares of boost::geometry::model::box? I need to find among the vector of boost::geometry::model::box one with the smallest square. From https://www.boost.org/doc/libs/1_65_1/libs/geometry/doc/html/geometry/reference/models/model_box.html it seems they don't have overloaded compression operators, so I need to manually calculate the squares and then compare them, or there is something already for that in boost? And in general is there some general documentation in boost?

Meson build of harfbuzz in pango complains that c++11 is not enabled, but it is in meson.build for harfbuzz

I've gone down a rabbit hole trying to build the latest verison of librsvg. My local Fedora 33 system has librsvg2-2.50.3-1 and produces good images, but the production server Centos 7.9 has 2.40.20-1 and doesn't fill curved paths using a bitmap pattern properly. Anyway, I'm trying to build newer versions of these packages on a Centos 7.9 production server, first working on a freshly installed Centos 7.9 on a local VM to get the basics working. Environment:

  • gcc 4.8.5-44
  • meson 0.57.1
  • ninja 1.10.0
  • Installed yum group "Development Tools" and set up EPEL repo for cargo & rust.

I've got to the point that I need a newer version of pango, so have grabbed pango-1.48.2 src from https://download.gnome.org/sources/pango/1.48/ and am attempting to build it. I've not used meson or ninja before but I have rusty old Unix build skills from 10 years ago that I'm trying to apply to these new tools.

It seems pango will autodetect missing libraries, or where the installed version is not high enough, and will download and build them. One of these is harfbuzz, and this is failing:

# /usr/local/bin/meson setup builddir
# /usr/local/bin/meson configure builddir/ -Dprefix=/usr/local
# ninja -C builddir/
../subprojects/harfbuzz/src/hb.hh:450:1: warning: identifier 'static_assert' is a keyword in C++11 [-Wc++0x-compat]

And later:

./subprojects/harfbuss/src/hb.hh:450:15: error: expected constructor, destructor, or type conversion before '(' token
 static_assert ((sizeof (int8_t) == 1), "");

It looks like I need to specify c++11 as the language, however in subprojects/harfbuzz/meson.build it looks like it's enabled:

  default_options: [
  ... skip ...
  'cpp_std=c++11'

(see https://github.com/harfbuzz/harfbuzz/blob/master/meson.build)

I've put some more complete output in gists (too long for stackoverflow, it rejects my post), first from the meson setup in which it detects my harfbuzz library is not at sufficient version, so it downloads (I think it's github master from the look of subprojects/harfbuzz.wrap):

https://gist.github.com/neekfenwick/836682eaff7f9e3dbbe62664a8e44ef6

And the output from the build step.. the c++11 stuff starts pretty early on, e.g. warning: identifier ‘static_assert’ is a keyword in C++11:

https://gist.github.com/neekfenwick/4581c5f83d4319bf1f011da0012a7dfd

I thought I could cd subprojects/harfbuzz and retry the build command to test building that one part of the overall pango build, but there is no Makefile or configure script, as if autogen.sh was not run. However, if I charge in there and run a build as best I know, it works:

$ cd subprojects/harfbuzz
$ ./autogen.sh
$ ./configure --prefix=/usr/local
$ make

Succeeds. Something about how ninja is building it using the pango configuration is broken.

That configure command for harfbuzz does output these interesting lines:

checking whether g++ supports C++11 features by default... no
checking whether g++ supports C++11 features with -std=gnu++11... yes

However, simply running make succeeds, so harfbuzz seems to have the required c++11 flags turned on in a local build, why would it fail when built from the enclosing pango build process?

Where should I be poking around next to move this forward?

dimanche 21 février 2021

Unknown Syntax When Using c++11 instead if c++14

I have come across the following error when I am compiling code. I have tried to look through my code to find the conversion error, but I don't see it.

The error occurs when compiling on compiles and runs on g++ (GCC) 8.3.1 20191121 (Red Hat 8.3.1-5)

When I compile on Ubuntu, I get no errors and it runs. (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0

This is the error.

/builddir/build/BUILD/gcc-8.3.1-20191121/obj-x86_64-redhat-linux/x86_64-redhat-linux/libstdc++-v3/include/bits/basic_string.h:1067: std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::reference std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::operator[](std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::size_type) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>; std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::reference = char&; std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::size_type = long unsigned int]: Assertion '__pos <= size()' failed.
Aborted (core dumped)

All of my header and class files.

Node.h

#ifndef NODE_HPP
#define NODE_HPP
#include <string>

class Node
{
    private:
        std::string value;
        Node* next;
        std::string password;
    public:
        Node();
        Node(std::string value, std::string password);
        std::string GetValue();
        void SetNext(Node* next);
        Node* GetNext();
        std::string GetPW();

};


#endif

Node.cpp

#include "node.hpp"
#include <string>

//This creates an empty node, the constructor.
Node::Node()
{
    this->value = "";
    this->next = nullptr;
    this->password = "";
}

//Creates a node with the passed variables
Node::Node(std::string value, std::string password)
{
    this->value = value;
    this->password = password;
    this->next = nullptr;
}

//Returns the username.
std::string Node::GetValue()
{
    return this->value;
}

//Sets the next node in the list.
void Node::SetNext(Node* next)
{
    this->next = next;
}

//Returns the next node in the list.
Node* Node::GetNext()
{
    return this->next;
}

//Returns the password of the current node.
std::string Node::GetPW()
{
    return this->password;
}

hash.hpp

#ifndef HASH_HPP
#define HASH_HPP
#include <string>
#include "node.hpp"
#include "linked_list.hpp"



class Hash
{
    private:
        static const int tableSize = 29009;
        int hashIndex(std::string);
        LinkedList* hashTable[tableSize];
    public:
        Hash();
        void insert(std::string username, std::string password);
        bool search(std::string searchValue, std::string comparePW);
        ~Hash();
    };
    #endif

hash.cpp

#include "hash.hpp"
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;

//Constructor that initiates each linked list in the hash table array.
Hash::Hash()
{
    for (int x = 0; x < tableSize; x++)
        hashTable[x] = new LinkedList;
}

//This places a node into the appropriate bucket in the has table.
void Hash::insert(std::string username, std::string password)
{
    hashTable[hashIndex(username)]->InsertAtHead(username, password);
}

//Here is where the appropriate hash table is figured out.
int Hash::hashIndex(std::string key)
{
    unsigned int index;
    unsigned int keyLength = key.size();
    for (unsigned int x = 0; x < keyLength; x++) {
        index += (key[x] * index);
    }
    return index % tableSize;
}

//This returns true if the username exists in the directory and the password matches the entered password.
bool Hash::search(std::string searchValue, std::string comparePW)
{
    std::string testString;
    for (int x = 0; x < tableSize; x++)
    {
        if (hashIndex(searchValue)== x){
            Node *temp = new Node;
            temp = hashTable[x]->getHead();
            while(temp != NULL){
                if (searchValue.compare(temp->GetValue()) == 0) 
                    {
                        if (comparePW.compare(temp->GetPW()) == 0)
                            return true;
                    }
                    temp = temp->GetNext();
            }
        }
    }
    return false;
}

Hash::~Hash()
{
    LinkedList* temp;
    for (int x = 0; x < tableSize; x++)
    {
        temp = hashTable[x];
        temp->~LinkedList();
        hashTable[x] = NULL;
    }
}

linked_list.hpp

#ifndef LINKED_LIST_HPP
#define LINKED_LIST_HPP
#include <string>

#include "node.hpp"

class LinkedList
{
    private:
        Node* head;
    public:
        LinkedList();
        void InsertAtHead(std::string value, std::string password);
        Node* getHead();
        ~LinkedList();

};

#endif

linked_list.cpp

#include "linked_list.hpp"
#include <iostream>

//Starts the linked list by creating a head node.
LinkedList::LinkedList()
{
    this->head = nullptr;
}

//Creates a new head for each item and places the old head as the following object.
void LinkedList::InsertAtHead(std::string value, std::string password)
{
    Node* newNode = new Node(value, password);
    newNode->SetNext(this->head);
    this->head = newNode;
}

//Returns the current head node.
Node* LinkedList::getHead()
{
    return this-> head;
}

//The destructor for the class
LinkedList::~LinkedList()
{
    Node* temp = head;
    while(temp != NULL)
    {
        Node* next = temp->GetNext();
        delete temp;
        temp = next;
    }
}

main.cpp


#include <iostream>
#include <ostream>
#include <limits>
#include <fstream>
#include <ostream>
#include <time.h>
#include <stdio.h>
#include <iomanip>
#include "node.hpp"
#include "linked_list.hpp"
#include "hash.hpp"
using namespace std;

//I know I should have passed these to the appropriate functions, but I created global containers instead of passing them around.
LinkedList* listOfNames = new LinkedList();
Hash *myHashTable = new Hash();

//Here is where I can take a string and generate a pseudo-random password from it 
std::string passGen(std::string user)
{
    char passwordArray[9];
    int achar;
    srand (time(0));    
    for (int x=0; x <= 8; x++)
    {
        achar = (user[x] * (rand()%100))%26 + 97;
        passwordArray[x] = (char)achar;
    }   
    return passwordArray;
}
        
//This reads the filename that is passed in and builds the linked list of names and uses the password generator and generates passwords for each username. 
void readFile(std::string newFile){
    ifstream inFile(newFile);
    std::string firstWord;
    
    while(inFile >> firstWord)
    {
        listOfNames->InsertAtHead(firstWord, passGen(firstWord));
        inFile.ignore(numeric_limits<streamsize>::max(), '\n');
    }
    inFile.close();
}

//Saves the plaintext username and password to a given filename.
void writeFile(std::string outFilename)
{
    Node *temp = new Node;
    temp = listOfNames->getHead();
    ofstream outFile(outFilename);
    while(temp != NULL)
    {
        outFile << std::left << setw(15) << temp->GetValue() << temp->GetPW() << std::endl;
        temp = temp->GetNext();
    }
    outFile.close();
}

//This takes a string and encrypts it using the Vigenere Cipher and jones as the key 
std::string encryptedString(std::string originalString)
{
        std::string cipher;
        std::string key = "jones";
        
        for (int x = 0; x < 9; x++)
        {
            char i = ((originalString[x] + key[x%5]) %26);
            i += 'a';
            cipher.push_back(i);
        }
        return cipher;
}

//Takes the information from one file and saves it to a new file while encrypting all of the passwords. 
void encryptFile(std::string fileName)
{
    ifstream inFile("rawData.txt");
    ofstream outFile("encrypted.txt");
    std::string userName;
    std::string passWord, encryptedPassword;
    
    while(inFile >> userName >> passWord)
    {
        encryptedPassword = encryptedString(passWord);
        listOfNames->InsertAtHead(userName, encryptedPassword);
        outFile << std::left << setw(15) << userName << encryptedPassword << std::endl;
    }
    outFile.close();
    inFile.close();
}

//Uses the information in a file to build a hash table
void fillHashTable()
{
    ifstream inFile("encrypted.txt");
    std::string username, password;
    
    while(inFile >> username >> password)
    {
        myHashTable->insert(username, password);
    }
    inFile.close();
}

//The legal test showing 5 correct password matches when compared to items in my hash table
void legalTest()
{
    ifstream inFile("rawData.txt");
    std::string userName, passWord, matchResult;
    std::cout << std::left << "Legal:\n";
    std::cout <<  std::left << setw(10) << "Userid" << setw(10) << "Password" << "Result\n";
    for (int x = 0; x < 5; x++)
    {
        inFile >> userName >> passWord;
        std::string newPass = encryptedString(passWord);
        if (myHashTable->search(userName, newPass))
            matchResult = "match";
        std::cout <<  std::left << setw(10) << userName << setw(10) << passWord  << setw(10) << matchResult << std::endl;
    }
    inFile.close();
}

//A test that pulls the first 5 entries of my hash table and compares the password to incorrect matches
void illegalTest()
{
    ifstream inFile("rawData.txt");
    std::string userName, passWord, matchResult;
    std::string key = "jones";
    std::cout << std::left << "Illegal:\n";
    std::cout <<  std::left << setw(10) << "Userid" << setw(10) << "Password" << "Result\n";
    for (int x = 0; x < 5; x++)
    {
        inFile >> userName >> passWord;
        passWord[0] = 'z';
            std::string newPass = encryptedString(passWord);
        if (myHashTable->search(userName, newPass))
            matchResult = "match";
        else
            matchResult = "no match";
        std::cout <<  std::left << setw(10) << userName << setw(10) << passWord  << setw(10) << matchResult << std::endl;
    }
    inFile.close();
}

int main(){
    readFile("lastNames.txt");
    writeFile("rawData.txt");
    encryptFile("encrypted.txt");
    fillHashTable();
    legalTest();
    std::cout << std::endl;
    illegalTest();
    listOfNames->~LinkedList();
    myHashTable->~Hash();
}

Makefile

CXX = g++
CXXFLAGS = -std=c++11 -Wall 

OBJECTS = linked_list.o node.o hash.o
HEADERS = $(shell find . -path ./test -prune -o -name "*.hpp" -print)

main: main.o $(OBJECTS)
    $(CXX) $(CXXFLAGS) -o $@ $^

$(OBJECTS): $(HEADERS)

clean:
    $(RM) *.o *.gch *.out core main test/TestCase