Calculating the standard deviation of a linkedlist elements - pointers

I wanted to calculate the standard deviation of a inked list elements,so I wrote a function to calculate both the average and the sum and then claculate the standard deviation by the formula , but I am getting error " 0xC0000005: Access violation reading location 0x00000000."at the line 46 ,
sd += ((first->info)-average)*((first->info-average);
Why this problem occurs and is there any way to get rid of it ?
My code is as follows :
class Node
{
public:
int info;
Node* next;
int value;
};
class List:public Node
{
Node *first,*last;
public:
List()
{
first=NULL;
last=NULL;
}
void create();
void insert();
void delet();
void display();
void search();
void sum();
void sd();
};
void List::sd()
{
system("cls");
cout<<"The Linked List Operations Program";
cout<<"\n==========================================================="<<endl;
Node *temp=first;
int sd = 0;
int length=0;
while(temp!=NULL)
{
length++;
temp=temp->next;
}
int sum = 0;
while (first != NULL)
{
sum += first->info;
first = first->next;
}
int average;
average = (sum/length);
sd += ((first->info)-average)*((first->info-average);
first=first->next;
cout<<average;
cout<<"The standard diviation is " <<sqrt(sd)/10 ;
cin.get();
cin.get();
}
int main()
{
system("cls");
int m;
List l;
Node *first;
int ch;
l.sd();
return 0 ;
}
void List::create()
{
system("cls");
cout<<"The Linked List Operations Program";
cout<<"\n==========================================================="<<endl;
Node *temp;
temp=new Node;
int n;
cout<<"\nEnter an element to create the first node of the linkedlist:";
cin>>n;
temp->info=n;
temp->next=NULL;
if(first==NULL)
{
first=temp;
last=first;
}
else
{
last->next=temp;
last=temp;
}
}
void List::insert()
{
system("cls");
cout<<"The Linked List Operations Program";
cout<<"\n==========================================================="<<endl;
Node *prev,*cur;
prev=NULL;
cur=first;
int count=1,pos,ch,n;
Node *temp=new Node;
cout<<endl<<"ADDED";
system("cls");
temp->info=rand();
temp->next=NULL;
last->next=temp;
last=temp;
}

Related

Getting two errors E0289 and C2440 pointing at initialization of vector

I am getting these two errors when initializing vc below.
#include <iostream>
#include <complex>
#include <math>
#include <vector>
#include <limits>
#include <list>
#include <string>
class Vector {
private:
double* elem; // elem points to an array of sz doubles
int sz;
public:
Vector(int s) :elem{ new double [s] }, sz{ s } // constructor: acquire resources
{
for (int i = 0; i != s; ++i) elem[i] = 0; // initialize elements
~Vector() { delete[] elem; } // destructor: release resources
double& operator[](int i);
int size() const;
void push_back(double);
};
double& Vector::operator[](int i)
{
// TODO: insert return statement here
// added below since the funtion needs to return a double and
return elem[i];
}
int Vector::size() const
{
return sz;
}
void Vector::push_back(double)
{
}
class Container {
public:
virtual double& operator[](int) = 0; // pure virtual function
virtual int size() const = 0; // const member function (§3.2.1.1)
virtual ~Container() {} // destructor (§3.2.1.2)
};
// use function uses Container interface.
void use(Container& c)
{
const int sz = c.size();
for (int i=0; i!=sz; ++i)
cout << c[i] << '\n';
}
class Vector_container : public Container { // List_container implements Container
Vector v;
public:
Vector_container(int s) : v(s) {} // Vector of s elements
void ˜Vector_container() {}
double& operator[](int i) { return v[i]; }
int size() const { return v.size(); }
};
void main()
{
Vector_container vc = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
use(vc)
}
I receive both errors pointing at this line Vector_container vc = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }
Error E0289 is - no instance of constructor "Vector_container::Vector_container" matches the argument list
Error C2440 'initializing': cannot convert from 'initializer list' to 'Vector_container'
I was able to solve the issue by modifying the Vector_container and initializing using Initializer-list constructor below:
class Vector_container : public Container {
std::list<double> ld;
public:
Vector_container() { }
Vector_container(initializer_list<double> il) : ld{ il } {}
~Vector_container() {}
double& operator[](int i);
int size() const { return ld.size(); }
};
double& Vector_container::operator[](int i)
{
for (auto& x : ld) {
if (i == 0) return x;
--i;
}
}

the count of subsequence of aray where arr[i]-arr[i-1] is constant for the array

we are given an array and its size and a interger k we need to find all/count of all subsequence that has constant arr[i]-arr[i-1] diff for all element and it size should be k
i have tryed my approach and it is clear to understand also but it just printing count i.e cnt as 0 why any one
#include<bits/stdc++.h>
#include
using namespace std;
void subseq(vector<int>&arr,int idx,int n,int k,int& cnt,vector<int>&nums){
if(idx==n-1){
if(nums.size()==k){
bool flag=1;
int dist=nums[1]-nums[0];
for(int i=2;i<n;i++){
if(nums[i]-nums[i-1]==dist){
continue;
}else{
flag=0;
}
}
if(flag)
cnt+=1;
}
return;
}
nums.push_back(arr[idx]);
subseq(arr,idx+1,n,k,cnt,nums);
nums.pop_back();
subseq(arr,idx+1,n,k,cnt,nums);
}
int main(){
int t;
cin>>t;
while(t--){
int n,m;
cin>>n>>m;
vector<int>v(n);
// cout<<1<<endl;
for(int i=0;i<n;i++)
cin>>v[i];
vector<int>x;
int cnt=0;
// cout<<1<<endl;
subseq(v,0,n,m,cnt,x);
cout<<cnt<<endl;
}
return 0;
}

Tree returning the maximum value

50
/ \
30 70 (( which should return 50+70=120 ))
int MyFunction(struct node *root){
struct node *ptr=root;
int leftsum=0;
int rightsum=0;
if(ptr==NULL){
return;
}
else{
MyFunction(ptr->left);
leftsum=leftsum+ptr->key;
MyFunctipn(ptr->right);
rightsum=rightsum+ptr->key;
return (root->key+max(leftsum,rightsum));
}
}
for that, I've written this code. Maybe it is wrong so please help me as I'm new in this field. I want to write a recursive code such a way that it compares two leaf node(left and right) and returns the maximum to the parent nood.
The recursive function should look something like this:
int getMaxPath(Node* root){
// base case, We traveled beyond a leaf
if(root == NULL){
// 0 doesn't contribute anything to our answer
return 0;
}
// get the max current nodes left and right children
int lsum = getMaxPath(root->left);
int rsum = getMaxPath(root->right);
// return sum of current node value and the maximum from two paths starting with its two child nodes
return root->value + std::max(lsum,rsum);
}
Full code:
#include <iostream>
struct Node{
int value;
Node* left;
Node* right;
Node(int val){
value = val;
left = NULL;
right = NULL;
}
};
// make a tree and return a pointer to it's root
Node* buildTree1(){
/* Build tree like this:
50
/ \
30 70
*/
Node* root= new Node(50);
root->left = new Node(30);
root->right = new Node(70);
}
int getMaxPath(Node* root){
if(root == NULL){
// 0 doesn't contribute anything to our answer
return 0;
}
int lsum = getMaxPath(root->left);
int rsum = getMaxPath(root->right);
return root->value + std::max(lsum,rsum);
}
int main() {
using namespace std;
Node* root = buildTree1();
int ans = getMaxPath(root);
cout<< ans <<endl;
return 0;
}
int Sum(struct node *root)
{
if(root->left == NULL && root->right== NULL)
return root->key;
int lvalue,rvalue;
lvalue=Sum(root->left);
rvalue=Sum(root->right);
return root->key+max(lvalue,rvalue);
}
int max(int r,int j)
{
if(r>j)
return r;
else
return j;
}

QDoubleSpinBox with leading zeros (always 4 digits)

I have a QDoubleSpinBox in range 0-7000, but want the value always displayed as 4 digits
(0-> 0000, 1 -> 0001 , 30 -> 0030, 3333 -> 3333).
I understand I can add a prefix, but a prefix is always added.
What are my options?
If you use integers, then QSpinBox will be enough.
You can simply inherit from QSpinBox and re-implement the textFromValue function:
class MySpinBox: public QSpinBox
{
Q_OBJECT
public:
MySpinBox( QWidget * parent = 0) :
QSpinBox(parent)
{
}
virtual QString textFromValue ( int value ) const
{
/* 4 - number of digits, 10 - base of number, '0' - pad character*/
return QString("%1").arg(value, 4 , 10, QChar('0'));
}
};
Filling QString this way does the trick.
Since prefix is not an option solution if you consider negative values, in my opinion the best and most elegant solution is defining your own custom spin box by deriving QAbstractSpinBox. Here is a small example:
Note that it is far from perfection and it serves just as an example on what could be done:
q4digitspinbox.h:
#ifndef Q4DIGITSPINBOX_H
#define Q4DIGITSPINBOX_H
#include <QAbstractSpinBox>
#include <QLineEdit>
class Q4DigitSpinBox : public QAbstractSpinBox
{
Q_OBJECT
public:
explicit Q4DigitSpinBox(QWidget *parent = 0);
StepEnabled stepEnabled() const;
double maximum() const;
double minimum() const;
void setMaximum(double max);
void setMinimum(double min);
void setRange(double minimum, double maximum);
double value() const;
public slots:
virtual void stepBy(int steps);
void setValue(double val);
signals:
void valueChanged(double i);
void valueChanged(const QString & text);
private:
double m_value;
double m_minimum;
double m_maximum;
QLineEdit m_lineEdit;
};
#endif // Q4DIGITSPINBOX_H
q4digitspinbox.h:
#include "q4digitspinbox.h"
Q4DigitSpinBox::Q4DigitSpinBox(QWidget *parent) :
QAbstractSpinBox(parent),
m_value(0),
m_minimum(-99),
m_maximum(99)
{
setLineEdit(&m_lineEdit);
setValue(0.0);
}
QAbstractSpinBox::StepEnabled Q4DigitSpinBox::stepEnabled() const
{
return StepUpEnabled | StepDownEnabled;
}
double Q4DigitSpinBox::maximum() const
{
return m_maximum;
}
double Q4DigitSpinBox::minimum() const
{
return m_minimum;
}
void Q4DigitSpinBox::setMaximum(double max)
{
m_maximum = max;
}
void Q4DigitSpinBox::setMinimum(double min)
{
m_minimum = min;
}
void Q4DigitSpinBox::setRange(double minimum, double maximum)
{
m_minimum = minimum;
m_maximum = maximum;
}
double Q4DigitSpinBox::value() const
{
return m_value;
}
void Q4DigitSpinBox::stepBy(int steps)
{
m_value += (double)steps / 10;
if (fabs(m_value - 0) < 0.00001)
{
m_value = 0;
}
if(m_value < m_minimum || m_value > m_maximum)
{
return;
}
int prefixNumberOfDigits = 4;
QString valueAsString = QString("%1").arg((int)m_value);
int numberOfDigits = valueAsString.length();
QString prefix;
prefixNumberOfDigits -= numberOfDigits;
if(prefixNumberOfDigits > 0)
{
while(prefixNumberOfDigits--)
{
prefix += "0";
}
}
QString value;
if(m_value < 0)
{
value = QString("-%1%2").arg(prefix).arg(-m_value);
}
else
{
value = QString("%1%2").arg(prefix).arg(m_value);
}
m_lineEdit.setText(value);
emit valueChanged(m_value);
emit valueChanged(value);
}
void Q4DigitSpinBox::setValue(double val)
{
if(val < m_minimum || val > m_maximum)
{
return;
}
int prefixNumberOfDigits = 4;
QString valueAsString = QString("%1").arg((int)val);
int numberOfDigits = valueAsString.length();
QString prefix;
prefixNumberOfDigits -= numberOfDigits;
if(prefixNumberOfDigits > 0)
{
while(prefixNumberOfDigits--)
{
prefix += "0";
}
}
QString value;
if(val < 0)
{
value = QString("-%1%2").arg(prefix).arg(-val);
}
else
{
value = QString("%1%2").arg(prefix).arg(val);
}
m_lineEdit.setText(value);
emit valueChanged(val);
emit valueChanged(value);
}
I didn't provide any commentary since I considered it pretty straight forward, but if needed I can add a few more explanations.
I hope this helps.

error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'Car' (or there is no acceptable conversion)

Queue class
#ifndef Queue_H
#define Queue_H
#include "Car.h"
#include <iostream>
#include <string>
using namespace std;
const int Q_MAX_SIZE = 20;
class Queue {
private:
int size; // size of the queue
Car carQueue[Q_MAX_SIZE];
int front, rear;
public:
Queue();
~Queue();
bool isEmpty();
bool isFull();
void enqueue(Car c);
void dequeue(); // just dequeue the last car in the queue
void dequeue(Car c); // if a certain car wants to go out of the queue midway.
// Condition: Car is not in washing. Meaning is not the 1st item in the queue
void dequeue(int index); // same as the previous comment
Car getFront();
void getCarQueue(Queue);
int length();
Car get(int);
};
Queue::Queue() {
size = 0;
front = 0;
rear = Q_MAX_SIZE -1;
}
Queue::~Queue() {
while(!isEmpty()) {
dequeue();
}
}
void Queue::enqueue(Car c) {
if (!isFull()) {
rear = (rear + 1) % Q_MAX_SIZE; // circular array
carQueue[rear] = c;
size++;
} else {
cout << "Queue is currently full.\n";
}
}
void Queue::dequeue() {
}
void Queue::dequeue(int index) {
if(!isEmpty()) {
front = (front + 1) % Q_MAX_SIZE;
if(front != index) {
carQueue[index-1] = carQueue[index];
rear--;
size--;
} else {
cout << "Not allowed to dequeue the first car in the queue.\n";
}
} else {
cout << "There are no cars to dequeue.\n";
}
}
bool Queue::isEmpty() {
return size == 0;
}
bool Queue::isFull() {
return (size == Q_MAX_SIZE);
}
Car Queue::getFront() {
return carQueue[front];
}
int Queue::length() {
return size;
}
Car Queue::get(int index) {
return carQueue[index-1];
}
void Queue::getCarQueue(Queue q) {
for(int i = 0; i< q.length(); i++)
cout << q.get(i) << endl; // Error here
}
#endif
error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'Car' (or there is no acceptable conversion)
I get this error which is kind of odd. so is there anything wrong? Thanks!
cout has no idea how to process a car object; it has never seen a car object and doesn't know how you output a car as text. cout can only process types it knows about, string, char, int, etc. The specific error is because there is version of operator << that takes an ostream and a car.
There are two options:
Creation an overload for operator<< that takes an ostream and a car. That will show cout how to output a car. This isn't usually done becuase there is usually more than one way your would want to display a car.
Write the output statement so that it manually prints out car properties like
cout << c.getMake() << " " << c.getModel()

Resources