std::vector crash with push_back. in VS2008 - c++

I've a structure DutPlayerArrayElement defined in following lines:
namespace Common
{
namespace Constants {
const int MaxNumberOfIPAddresses = 10;
const int NumberOFRFOutputs = 100;
const int NumberOfPlayers = 100;
const int SignalFileNameSize = 30;
}
enum AntennaType
{
Omni = 0,
Directive,
Custom,
InvalidAntenna
};
enum ModulationID
{
CW = 0,
SSB,
LSB,
AM,
FM,
WFM,
DVBT
};
enum SigFileID
{
SIG_FILE_ID_ARB12 = 1,
SIG_FILE_ID_ARB16,
SIG_FILE_ID_WAV,
SIG_FILE_ID_TXT
};
typedef struct
{
//Basic
double dLatitude;
double dLongitude;
double dAltitude;
double dHeading;
float fNorthSudVelocity;
float fEastOvestVelocity;
float fVerticalVelocity;
unsigned int uiIsValid;
bool bIsDestroyed;
bool bTxIsOn;
ModulationID xModulationID;
SigFileID xSigFileType ;
char cSigFileName[128];
bool bLoopPlayback ;
char cAntennaTableFile[128];
bool bUseAntGainFactor;
double dAntGainFactor;
double dAntennaOrientation;
double dCarrierFrequency;
bool bTxIsLOS;
double dPwr;
double dAzimuth;
double dElevation;
double dDistance;
char cEntityName[128];
//char cModulation[2];
}PlayerArrayElement;
typedef struct
{
//Basic
double dLatitude;
double dLongitude;
double dAltitude;
double dHeading;
float fNorthSudVelocity;
float fEastOvestVelocity;
float fVerticalVelocity;
bool bIsDestroyed;
unsigned int uiNumAssignedRFOut;
bool bIsSync;
unsigned int uiNumRFOutXIP;
int iAssignedRFOut[Constants::NumberOFRFOutputs];
unsigned int uiRfGenCount;
int iIpAddress[Constants::MaxNumberOfIPAddresses];
unsigned int xPort[10];
double xCarrierFrequency[10];
//AntennaType xAntennatype;
char cAntennaTableFile[128];
bool bUseAntGainFactor;
double dAntGainFactor;
double dAntennaOrientation;
unsigned int uiNumOfPlayer;
PlayerArrayElement xScenarioPlayer[Constants::NumberOfPlayers];
char cEntityName[128];
unsigned int uiIsValid;
bool simIsRunning;
} DutPlayerArrayElement;
typedef std::vector<DutPlayerArrayElement> DutPlayers;
}
I also define a typedef std::vector<DutPlayerArrayElement> DutPlayers;
In a Visual studio 2008 library, I declare a class with this vector as member:
class COM_API MyClass
{
public:
SimComintManager();
~SimComintManager() ;
bool init();
void runme();
private:
void setup();
private:
// ....
Common::DutPlayers m_xDutPlayers;
// other structures...
};
in runme method:
void MyClass::runme()
{
while(m_bScenarioIsRunning)
{
if(m_uiIterationCount == 0)
{
m_pGen->setRfOutState(0, ON);
}
else
{
//aggiornare RF scenario in base a SHM attuale
m_xDutPlayers.clear() ;
m_xShmReader.getData(m_xDutPlayers) ;
}
}
}
ShmReader is a class defined in another library, that uses the same .h file in which vector is defined:
bool Reader::getData( Common::DutPlayers& xDutVector)
{
Common::DutPlayerArrayElement xEntityArrayElement;
for(int i = 0; i < m_iNumberOfEntities; i++)
{
xEntityArrayElement = m_pxPlayerShmVector->getValue(i);
if(xEntityArrayElement.uiIsValid == 1)
m_bSimulationState = xEntityArrayElement.simIsRunning;
xDutVector.push_back(xEntityArrayElement);
}
return true;
}
When I call xDutVector.push_back(xEntityArrayElement); I've an error and program crashes. Visual studio says Microsoft Visual Studio C Runtime Library has detected a fatal error in program.exe and when I click Break button the callstack is in row 161 of vector.h, the _SCL_SECURE_VALIDATE_RANGE row of this piece of code:
_Myt& operator+=(difference_type _Off)
{ // increment by integer
_SCL_SECURE_VALIDATE(this->_Has_container());
_SCL_SECURE_VALIDATE_RANGE(
_Myptr + _Off <= ((_Myvec *)(this->_Getmycont()))->_Mylast &&
_Myptr + _Off >= ((_Myvec *)(this->_Getmycont()))->_Myfirst);
_Myptr += _Off;
return (*this);
}
I've googled a bit and I've found this error regarding iterator erasing, but nothing regarding the push_back. What I'm doing wrong and how can I use push_back correctly?

Related

Kattis annoyed coworkers problem (self-sorting data structures and a min heap )

Okay so am trying to make a data structure that maintains a heap of data in order to solve within the compile-time limit. https://open.kattis.com/problems/annoyedcoworkers
I might be in over my head since I just started coding in the last year or so and I just learned about sorting and vectors last week and heap data structures yesterday. But I am really interested in solving this problem.
Anyway here goes I first started to solve this problem with selection sort... needless to say it took way too long.
Then I started looking into making a heap data structure that yields values sorted order,
which brought me to priority_queue
After about 9 hours of trying different methods, this is the closest I've gotten to solving the problem.
does anyone have any suggestions as to why after 25/27 test cases my code returns a wrong answer?
Here is my code :
// C++ program to use priority_queue to implement Min Heap
// for user defined class
#include <algorithm>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
// User defined class, coworker
class CoworkerT
{
private:
int a;
int d;
public:
CoworkerT(int _a, int _d)
{
a = _a;
d = _d;
}
int SimAddAD() const
{
int aD;
aD = a + d;
return aD;
}
int AddAD()
{
a = a + d;
return a;
}
int getA() const {
return a;
}
int getD() const {
return d;
}
};
// To compare two coworkers possible a value
class Min
{
public:
int operator() (const CoworkerT& p1, const CoworkerT& p2)
{
return p1.SimAddAD() > p2.SimAddAD();
}
};
//compare two a values between coworkers
class Max
{
public:
int operator() (const CoworkerT& p1, const CoworkerT& p2)
{
return p1.getA() < p2.getA();
}
};
int AskForA() {
int a;
cin >> a;
return a;
}
int AskForD() {
int d;
cin >> d;
return d;
}
priority_queue <CoworkerT, vector<CoworkerT>, Max >
PopulateMax(priority_queue <CoworkerT, vector<CoworkerT>, Max > max,
priority_queue <CoworkerT, vector<CoworkerT>, Min > min) {
while (min.empty() == false)
{
CoworkerT e = min.top();
max.push(CoworkerT(e.getA(), e.getD()));
min.pop();
}
return max;
}
// Driver code
int main()
{
int h, c, i, a, d;
cin >> h >> c;
// Creates a Min heap of points (order by possible a +d combination )
priority_queue <CoworkerT, vector<CoworkerT>, Min > pq;
// Creates a Max heap of points (order by actual a value )
priority_queue <CoworkerT, vector<CoworkerT>, Max > max;
// Insert points into the min heap
for (int i = 0; i < c; i++) {
a = AskForA();
d = AskForD();
pq.push(CoworkerT(a, d));
}
i = 0;
while (i < h) {
CoworkerT e = pq.top();
a = e.AddAD();
d = e.getD();
pq.pop();
pq.push(CoworkerT(a, d));
i++;
}
max = PopulateMax(max, pq);
CoworkerT eMax = max.top();
cout << eMax.getA() << endl;
return 0;
}
I just want to say that I ended up using something similar to my original algorithm using the heap. The problem was my use of int I switched to an unsigned long long int ~(though that might have been overkill?) and it worked like a charm.
// C++ program to use priority_queue to implement Min Heap
// for user defined class
#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
// User defined class, coworker
class CoworkerT {
private:
unsigned long long int a;
unsigned long long int d;
public:
CoworkerT(unsigned long long int _a, unsigned long long int _d){
a = _a;
d = _d;
}
unsigned long long int SimAddAD() const{
return a + d;
}
unsigned long long int AddAD(){
return a + d;;
}
unsigned long long int getA() const {
return a;
}
unsigned long long int getD() const {
return d;
}
};
//compare two coworkers possible a + d values
struct MinSort {
bool operator()(const CoworkerT& p1, const CoworkerT& p2) const {
return p1.SimAddAD() < p2.SimAddAD();
}
};
//compare two coworkers possible a + d values ~for some reason heap lesser than or greater need to be reverse of operator for sort???
struct Min {
bool operator()(const CoworkerT& p1, const CoworkerT& p2) const {
return p1.SimAddAD() > p2.SimAddAD();
}
};
//compare two a values between coworkers
struct MaxSort {
bool operator()(const CoworkerT& p1, const CoworkerT& p2) const {
return p1.getA() > p2.getA();
}
};
void FindAndPrintMax(vector<CoworkerT>& max) {
sort(max.begin(), max.end(), MaxSort());
CoworkerT minMax = max.front();
cout << minMax.getA();
}
void InputCoworkersAD(vector<CoworkerT>& min, unsigned long long int& h, unsigned long long int& c) {
int a, d, i;
cin >> h >> c;
// Insert a and d into the vector
if (h <= 100000 && h >= 1 && c <= 100000 && c >= 1) {
for (i = 0; i < c; i++) {
cin >> a >> d;
min.push_back(CoworkerT(a, d));
}
}
make_heap(min.begin(), min.end(), Min());
}
void AskForHelp(vector<CoworkerT>& min, unsigned long long int h) {
int i = 0;
while (i < h) {
push_heap(min.begin(), min.end(), Min());
CoworkerT e = min.front();
pop_heap(min.begin(), min.end(), Min());
min.pop_back();
min.push_back(CoworkerT(e.AddAD(), e.getD()));
i++;
}
}
// Driver code
int main()
{
unsigned long long int h, c;
vector<CoworkerT> min;
InputCoworkersAD(min, h, c);
AskForHelp(min, h);
FindAndPrintMax(min);
return 0;
}

Why am I getting a Link error when I try to overload an operator?

I'm doing a project exercise, where I'm revising a previous project of a class I created called Polynomial to use a link list (the original used arrays). The link list uses a template so that any type can be passed into it.
One of the problems I ran into with this project exercise is that I am trying to pass an object of type PolyNumber (from a class I made), and the link list bag I made has a function that compares any item (using ==) that is passed to it.
It works fine with regular types, such as int and string, but runs into problems with custom made object types. So I figured out how to overload the == operator in the PolyNumber class. By itself, it works when I test this class, but when I use this type with the Polynomial class with the Link List implementation, I get errors such as the following for each method in the Polynomial class:
Error LNK2005 "public: __thiscall PolyNumber::PolyNumber(int,int)" (??0PolyNumber##QAE#HH#Z) already defined in Polynomial.obj Project11
Here's my code for those files, but as you can see in the code, there are other files that go with this code, such as the LinkedBag for the link list object, but for space I just include these:
PolyNumber.h
#pragma once
class PolyNumber
{
public:
PolyNumber();
PolyNumber(int set_coefficent, int set_degree);
void setDegree(int set);
void setCoefficient(int set);
int getDegree();
int getCoefficient();
friend bool operator== (const PolyNumber& p1, const PolyNumber& p2);
friend bool operator!= (const PolyNumber& p1, const PolyNumber& p2);
private:
int degree;
int coefficient;
};
PolyNumber.cpp
#include "PolyNumber.h"
PolyNumber::PolyNumber()
{
coefficient = 0;
degree = 0;
}
PolyNumber::PolyNumber(int set_coefficent, int set_degree)
{
coefficient = set_coefficent;
degree = set_degree;
}
void PolyNumber::setDegree(int set)
{
degree = set;
}
void PolyNumber::setCoefficient(int set)
{
coefficient = set;
}
inline int PolyNumber::getDegree()
{
return degree;
}
inline int PolyNumber::getCoefficient()
{
return coefficient;
}
bool operator== (const PolyNumber& p1, const PolyNumber& p2)
{
return (p1.coefficient == p2.coefficient && p1.degree == p2.degree);
}
bool operator!= (const PolyNumber& p1, const PolyNumber& p2)
{
return !(p1 == p2);
}
Polynomial.h
#pragma once
#include "PolynomialInterface.h"
#include "LinkedBag.cpp"
#include "PolyNumber.cpp"
static const int POLYNOMIAL_SIZE = 10;
class Polynomial : public Polynomoal_Interface
{
public:
//Cunstructs am empty Polynomial
Polynomial();
//Copy constructor
Polynomial(Polynomial& copy);
/** Cunstructs a Polynomial with a client defined Polynomial
#param an array of non-negative integer coeffient that does not exceed POLYNOMIAL_SIZE, each coeffient in the array has a power that correspounds
to the respective value of the location of the ceffient in that array. */
Polynomial(int coeffient[POLYNOMIAL_SIZE], int size);
int degree();
int coefficient(int power);
bool changeCoefficient(int newCoefficient, int power);
private:
//static const int POLYNOMIAL_SIZE = 10;
//int polynomial[POLYNOMIAL_SIZE];
LinkedBag<PolyNumber> bag;
};
Polynomial.cpp
#include "Polynomial.h"
Polynomial::Polynomial()
{
}
Polynomial::Polynomial(Polynomial& copy)
{
std::vector<PolyNumber> copyFrom = copy.bag.toVector();
for (int i = 0; i < copyFrom.size(); i++)
{
bag.add(copyFrom[i]);
}
}
Polynomial::Polynomial(int coeffient[POLYNOMIAL_SIZE], int size)
{
for (int i = 0; i <= size; i++)
{
PolyNumber number = { coeffient[i], i + 1 };
bag.add(number);
}
}
int Polynomial::degree()
{
int max = 0;
std::vector<PolyNumber> result = bag.toVector();
for (int i = 0; i < result.size(); i++)
{
if (result[i].getDegree() > max)
{
max = result[i].getDegree();
}
}
return max;
}
int Polynomial::coefficient(int power)
{
int result = 0;
std::vector<PolyNumber> powerOf = bag.toVector();
for (int i = 0; i < powerOf.size(); i++)
{
if (powerOf[i].getDegree() == power)
{
result = powerOf[i].getCoefficient();
}
}
return result;
}
bool Polynomial::changeCoefficient(int newCoefficient, int power)
{
PolyNumber number = { newCoefficient, power };
int result = coefficient(power) + newCoefficient;
bag.remove(number);
number.setCoefficient(result);
bag.add(number);
return true;
}
You have #include "PolyNumber.cpp" instead of #include "PolyNumber.h".
That makes all the methods defined in PolyNumber.cpp to be included (and re-defined) in Polynomial.cpp.
The same will happen with LinkedBag.
Why are you including cpps?

How to fix class function "prototype does not match" and "cadidate is" errors

I'm desperately trying to finish this last assignment, and I'm at a complete loss for what these errors are trying to tell me to do. The errors are as such:
"prototype for 'double Rectangle::calculateArea()' does not match any in class 'Rectangle'" (line 40)
"candidate is: int Rectangle::calculateArea()" (line 11)
"prototype for 'double Rectangle::calculatePerimeter()' does not match any in class 'Rectangle'" (line 45)
"candidate is: int Rectangle::calculatePerimeter()" (line 12)
This is my first post on this forum, so I apologize in advance for it being ill-formatted
I haven't tried anything because none of the solutions I've found on forums relate directly to my problem (or so I think).
Thank you
// Rectangle.cpp
using namespace std;
class Rectangle
{
public:
void setLength(double length);
void setWidth(double width);
double getLength();
double getWidth();
int calculateArea() {return width*length;}
int calculatePerimeter() {return (width*2) + (length*2);}
private:
double length;
double width;
};
void Rectangle::setLength(double len)
{
len = length;
}
void Rectangle::setWidth(double wid)
{
wid = width;
}
double Rectangle::getLength()
{
return length;
}
double Rectangle::getWidth()
{
return width;
}
double Rectangle::calculateArea()
{
return (width*length)
}
double Rectangle::calculatePerimeter()
{
return ((width*2) + (length*2))
}
You already defined the functions in the class definition with a wrong return type (int instead of double)
class Rectangle
{
//...
int calculateArea() {return width*length;}
int calculatePerimeter() {return (width*2) + (length*2);}
//..
};
And then you redefined them outside the class
double Rectangle::calculateArea()
{
return (width*length)
}
double Rectangle::calculatePerimeter()
{
return ((width*2) + (length*2))
}
Also these functions are defined incorrectly
void Rectangle::setLength(double len)
{
len = length;
^^^^^^^^^^^^
}
void Rectangle::setWidth(double wid)
{
wid = width;
^^^^^^^^^^^
}
They must be defined like
void Rectangle::setLength(double len)
{
length = len;
}
void Rectangle::setWidth(double wid)
{
width = wid;
}
And all these functions
double getLength();
double getWidth();
int calculateArea() {return width*length;}
int calculatePerimeter() {return (width*2) + (length*2);}
should be declared with the qualifier const
double getLength() const;
double getWidth() const;
double calculateArea() const {return width*length;}
^^^^^^
double calculatePerimeter() const {return (width*2) + (length*2);}
^^^^^^
The compiler literally tells you!
It says that these two things don't match:
int Rectangle::calculateArea()
double Rectangle::calculateArea()
And, well, that's true. Your return types differ.
Pick one and use it consistently.

matrix in a class in C++

the following code is for three classes , class One, class Two, class Three.
class Three takes tow vectors, the first vector contains instances of One , the second vector contains instances of Two.
I want to get a 2D matrix via a method in Three , this matrix will have two equal indices each one is the size of the vector of One instances.
I don't know where to declare this matrix , and how to initialize it.
i will present a code is working fine before i declare the matrix , then i will present one example of my many tries which is not working and producing error messages.
here is the code before declaring the matrix(it works fine)
#include<iostream>
#include<vector>
#include <stdlib.h>
using namespace std;
const unsigned int N = 5;
class One
{
private:
unsigned int id;
public:
unsigned int get_id(){return id;};
void set_id(unsigned int value) {id = value;};
One(unsigned int init_val = 0): id(init_val) {}; // constructor
~One() {}; // destructor
};
class Two
{
private:
One first_one;
One second_one;
unsigned int rank;
public:
unsigned int get_rank() {return rank;};
void set_rank(unsigned int value) {rank = value;};
unsigned int get_One_1(){return first_one.get_id();};
unsigned int get_One_2(){return second_one.get_id();};
Two(const One& One_1 = 0, const One& One_2 =0 , unsigned int init_rank = 0)
: first_one(One_1), second_one(One_2), rank(init_rank)
{
}
~Two() {} ; // destructor
};
class Three
{
private:
std::vector<One> ones;
std::vector<Two> twos;
public:
Three(vector<One>& one_vector, vector<Two>& two_vector)
: ones(one_vector), twos(two_vector)
{
}
~Three() {};
vector<One> get_ones(){return ones;};
vector<Two> get_twos(){return twos;};
void set_ones(vector<One> vector_1_value) {ones = vector_1_value;};
void set_twos(vector<Two> vector_2_value) {twos = vector_2_value;};
};
int main()
{
cout<< "Hello, This is a draft for classes"<< endl;
vector<One> elements(5);
cout<<elements[1].get_id()<<endl;
vector<Two> members(10);
cout<<members[8].get_One_1()<<endl;
Three item(elements, members);
cout<<item.get_ones()[3].get_id() << endl;
return 0;
}
now i declared a method to produce a matrix in Three , the method's name is get_Mat() here is the code :
#include<iostream>
#include<vector>
#include <stdlib.h>
using namespace std;
const unsigned int N = 5;
class One
{
private:
unsigned int id;
public:
unsigned int get_id(){return id;};
void set_id(unsigned int value) {id = value;};
One(unsigned int init_val = 0): id(init_val) {}; // constructor
~One() {}; // destructor
};
class Two
{
private:
One first_one;
One second_one;
unsigned int rank;
public:
unsigned int get_rank() {return rank;};
void set_rank(unsigned int value) {rank = value;};
unsigned int get_One_1(){return first_one.get_id();};
unsigned int get_One_2(){return second_one.get_id();};
Two(const One& One_1 = 0, const One& One_2 =0 , unsigned int init_rank = 0)
: first_one(One_1), second_one(One_2), rank(init_rank)
{
}
~Two() {} ; // destructor
};
class Three
{
private:
std::vector<One> ones;
std::vector<Two> twos;
public:
Three(vector<One>& one_vector, vector<Two>& two_vector)
: ones(one_vector), twos(two_vector)
{
}
~Three() {};
vector<One> get_ones(){return ones;};
vector<Two> get_twos(){return twos;};
void set_ones(vector<One> vector_1_value) {ones = vector_1_value;};
void set_twos(vector<Two> vector_2_value) {twos = vector_2_value;};
unsigned int get_Mat() {
unsigned int mat[ones.size()][ones.size()];
for(unsigned int i = 0; i < ones.size(); ++i)
for(unsigned int j = 0; j < ones.size(); ++j)
mat[i][j] = 1;
return mat;}
};
int main()
{
cout<< "Hello, This is a draft for classes"<< endl;
vector<One> elements(5);
cout<<elements[1].get_id()<<endl;
vector<Two> members(10);
cout<<members[8].get_One_1()<<endl;
Three item(elements, members);
cout<<item.get_ones()[3].get_id() << endl;
return 0;
}
I will be very thankful if you can help me to find a way to produce this matrix via a method in class Three.
Thanks.
get_Mat returns an integer, not a matrix. It is better to use vector<vector<unsigned int> >, that will avoid a lot of troubles later on.
Or have a look here (c++):
Return a 2d array from a function
or here (C):
Return a 2d array from a function

expected an identifier c++

I am trying to write a class and I finally got it to compile, but visual studio still shows there are errors (with a red line).
The problem is at (I wrote #problem here# around the places where visual studio draws a red line):
1. const priority_queue<int,vector<int>,greater<int> #># * CM::getHeavyHitters() {
2. return & #heavyHitters# ;
3. }
And it says:
"Error: expected an identifier" (at the first line)
"Error: identifier "heavyHitters" is undefined" (at the second line)
The first problem I don't understand at all. The second one I don't understand because heavyHitters is a a member of CM and I included CM.
BTW, I tried to build. It didn't fix the problem.
Thanks!!!
The whole code is here:
Count-Min Sketch.cpp
#include "Count-Min Sketch.h"
CM::CM(double eps, double del) {
}
void CM::update(int i, int long unsigned c) {
}
int long unsigned CM::point(int i) {
int min = count[0][calcHash(0,i)];
return min;
}
const priority_queue<int,vector<int>,greater<int>>* CM::getHeavyHitters() {
return &heavyHitters;
}
CM::CM(const CM &) {
}
CM::~CM() {
}
int CM::calcHash(int hashNum, int inpt) {
int a = hashFunc[hashNum][0];
int b = hashFunc[hashNum][1];
return ((a*inpt+b) %p) %w;
}
bool CM::isPrime(int a) {
bool boo = true;
return boo;
}
int CM::gePrime(int n) {
int ge = 2;
return ge;
}
Count-Min Sketch.h
#pragma once
#ifndef _CM_H
#define _CM_H
using namespace std;
#include <queue>
class CM {
private:
// d = ceiling(log(3,1/del)), w = ceiling(3/eps)
int d,w,p;
// [d][w]
int long unsigned *(*count);
// [d][2]
int *(hashFunc[2]);
// initialized to 0. norm = sum(ci)
int long unsigned norm;
// Min heap
priority_queue<int,vector<int>,greater<int>> heavyHitters;
// ((ax+b)mod p)mod w
int calcHash(int hashNum, int inpt);
// Is a a prime number
bool isPrime(int a);
// Find a prime >= n
int gePrime(int n);
public:
// Constructor
CM(double eps, double del);
// count[j,hj(i)]+=c for 0<=j<d, norm+=c, heap update & check
void update(int i, int long unsigned c);
// Point query ai = minjcount[j,hj(i)]
int long unsigned point(int i);
const priority_queue<int,vector<int>,greater<int>>* getHeavyHitters();
// Copy constructor
CM(const CM &);
// Destructor
~CM();
};
#endif // _CM_H
>> is a single token, the right-shift (or extraction) operator. Some compilers don't recognize it correctly in nested template specialization. You have to put a space between the two angle brackets like this:
Type<specType<nestedSpecType> > ident;
^^^