lundi 14 novembre 2022

function printGraph prints too many Nodes

I'm trying to make a program that print the nodes and the edges from graph and shows the shortest path from declared node to all others. The problem is that the print function I create prints too many Nodes with name 0 and edge with weight 0 and I don't know why. Here is the function to add edge in the nodes and function that should be print the graph correctly.

`

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

void addEdge(vector<vector<pair<int, int>>>& graph, int u, int v, int w)
{
    graph[u].push_back(make_pair(v, w));
    graph[v].push_back(make_pair(u, w));
}

void printGraph(vector<vector<pair<int, int>>> adj, int V)
{
    int v, w;
    for (int u = 0; u < V; u++)
    {
        cout << "Node " << u << " makes an edge with \n";
        for (auto it = adj[u].begin(); it != adj[u].end(); it++)
        {

            v = it->first;
            w = it->second;
            cout << "\tNode " << v << " with edge weight ="
                << w << "\n";
        }
        cout << "\n";
    }
}

int main()
{
    vector<vector<pair<int, int>>> graph(9, vector<pair<int, int>>(9));
    addEdge(graph, 0, 1, 4);
    addEdge(graph, 0, 7, 8);
    printGraph(graph,1);
    return 0;
}

`

I tried to find the similar problem but without success.

g++ std=c++11 : is anything wrong in allocating/deallocating a 2d array this way

I'm using g++ -std=c++11 and this compact approach to allocate/deallocate 2d arrays :

int(*MyArray)[Ydim]=new int[Xdim][Ydim];
delete[] MyArray;

Everything seems to be working fine (compile time and run time). I know there are many ways to do the same but this is compact and seems to be doing the job. Is anything wrong with it?

Everything seems to work...but worried about subtle problems (memory leakage...)

Xdim and Ydim are compile time constants

[COVERITY][C++] Non-static class member "A._M_elems" is not initialized in this constructor nor in any functions that it calls

I am having an issue with a coverity warning that occurs in the constructor of my C++11 class.

In the class Model, I define the type Trajectory and declare it privately.

template<unsigned int T, unsigned int K>
class Model
{
public:
    typedef Eigen::Matrix<float, DEGREE, AXIS> State;
    typedef Eigen::Matrix<float, AXIS_COUNT, K> Sample;
    typedef std::array<std::array<Sample, T>, DEGREE> Trajectory;

private:
    Settings _settings;
    State _state;
    Trajectory _trajectory;

...

Later in the constructor section I define two constructors, the second one inherits from the first one. In the first one, I initialize the _trajectory variable in the double for loop.

...

public:
    Model(const Settings& settings, const State& initialState) :
     _settings(settings),
     _state(initialState)
    {
        for (unsigned int i = 0; i < DEGREE; i++)
            for (unsigned int j = 0; j < T; j++)
                _trajectory[i][j].setZero();
    };
    Model(const Settings& settings) :
     Model(settings, State::Zero()){};

    ~Model() = default;

...

This class is called by a handler which initializes Model with the second constructor. Everything works fine, however, once I run the coverity check, I receive the following error.


Non-static class member "_trajectory._M_elems" is not initialized in this constructor nor in any functions that it calls.

It is called at the line Model(settings, State::Zero()){};

I have tried many options but I cannot figure out how to initialize _trajectory properly without receiving this error.

I have tried this:

public:
    Model(const Settings& settings, const State& initialState) :
     _settings(settings),
     _state(initialState),
     _trajectory({})

this

public:
    Model(const Settings& settings, const State& initialState) :
     _settings(settings),
     _state(initialState),
     _trajectory()

this

public:
    Model(const Settings& settings, const State& initialState) :
     _settings(settings),
     _state(initialState),
     _trajectory(Trajectory)

and other combinations. None works.

Waiting for some legend to give me a hint.

What is the correct Expression to find bigger Element by pair key and the biggest of all values

What is the correct Compare Statement to find the biggest Value of a Vector full of pairs that are bigger than a specific defined int.

int x = 5;
auto pos = max_element(ownCards.begin(),
            ownCards.end(),
            [&x](pair<int, int> p1, pair<int, int> p2) 
{ return p1.first > x && p1.second > p2.second; });

From the fact that my vector is sorted, I have the upper_bound function still taken to help, this makes the code clearer and faster, still not fast enough unfortunately.

auto start = upper_bound(ownCards.begin(), ownCards.end(), ownCards[j]);

            auto pos = max_element(start,
                                   ownCards.end(),
                                   [&x](pair<int, int> p1, pair<int, int> p2) { return p1.second > p2.second; });

C++ requires a type specifier for all declarations while assigning values to array of strings [duplicate]

I am a new to C++. I have a class as follows compiling which is throwing "C++ requires a type specifier for all declarations" as the values for array of string elements are being assigned after the array of string is dynamically allocated.

#include <iostream>
#include <string>

using namespace std;

class bank {

protected:
    string* Checkperson = new string[3];
    string managerUsername = "manager";
    string managerPassword = "M@n@ger";
    Checkperson[0] = "First";    //the error is here
    Checkperson[1] = "Last";     //the error is here
    Checkperson[2] = "Manager";  //the error is here
    string* searchFiles(string username, string password) {
        string* person = new string[3];
        for(int i = 0; i < 3; i++) {
            person[i].clear();
        }
        if((username == managerUsername) && (password == managerPassword)) {
            for(int i = 0; i < 3; i++) {
                person[i] = Checkperson[i];
            }
        }
        return person;
    }
};

Compiling this I get the errors:

./bank.cpp:17:2: error: C++ requires a type specifier for all declarations
        Checkperson[0] = "First";
        ^
./bank.cpp:18:2: error: C++ requires a type specifier for all declarations
        Checkperson[1] = "Last";
        ^
./bank.cpp:19:2: error: C++ requires a type specifier for all declarations
        Checkperson[2] = "Manager";
        ^

I tried the following and it worked fine but since I am trying to learn c++ would like to know why the previous method didn't work.

string Checkperson[3] = {"First", "Last", "Manager"};

dimanche 13 novembre 2022

relaxed memory ordering for thread stop flags

The author in the video on atomic ops has the following snippet. While the load to the stop flag is not relaxed, the store cannot be relaxed. My question is if the reason for store not to be relaxed has to do with it potentially being visible after the join of threads / if there is some other reason?

Worker threads:

while (!stop.load(std::memory_order_relaxed)) {
    // do something (that's independent of stop flag)
}

Main thread:

int main() {
  launch_workers();
  stop = true; // <-- not relaxed
  join_threads();
  // do something  
}

samedi 12 novembre 2022

Expression must be a modifiable lvalue - class function [closed]

I was looking to learn some OOP concepts and i'm stuck with this error

#include <iostream>
using namespace std;

class Employee
{
private:
    string name;
    int salary;

public:
    Employee()
    {
        name = "";
        salary = 0;
    }
    int getSalary()
    {
        return salary;
    }
};

int main()
{
    Employee e1;
    e1.getSalary() = 7000;
    cout << e1.getSalary();
    return 0;
}

From what I understood, if I add & to method getSalary() it will be a setter and getter at the same time. I am confused why I need to add & to getSalary() method to work properly. What's the point of reference in this case?