Values from vector differ from the original value - c++

I am confused with C++ vector and ask for help.
I declare a class CBoundaryPoint:
class CBoundaryPoint:
{
public:
double m_param;
int m_index;
}
And then I define a vector:
vector<CBoundaryPoint> vBoundPoints;
CBoundaryPoint bp;
double param;
// other codes
bp.m_param = param;
vBoundPoints.push_back( bp );
It surprises me that for every element in vBoundPoints, the value of m_param is totally different from the given value param. I just don't know why.
For Example:
param = 0.3356;
bp.m_param = param; // so bp.param equals to 0.3356;
vBoundPoints.push_back( bp ); // while (*(vBoundPoints.end()-1)).m_param = -6.22774385622041925e+066; same case to other elements
So what happened and why? I'm using VS2010.

You probably get garbage when you resize the vector or create a vector of a certain size using the size_type constructor. You get default-constructed objects in your vector, and these contain primmitive types. Since you have no user defined default constructor, the values are essentially random, or "garbage".
You can fix this by adding a default constructor to your class:
class CBoundaryPoint:
{
public:
CBoundaryPoint : m_param(), m_index() {} // initializes members to 0. and 0
double m_param;
int m_index;
}

Related

Declare size of a vector inside class

I am trying to declare the size of a vector inside a class. I want the vector size equal to another attribute of this same class. Vector "table" is inside the class Hashtable. "bucket_count" is the intended size for the vector "table". the error given is "member is not a type name". Please let me know what another way I can declare the size of a vector inside the class. If not, then what is the way out? Thanks.
Please refer to the code below.
class HashTable {
public:
int bucket_count;
vector<list<string>> table(bucket_count);
//bool isEmpty(list<string> &cell) const;
int hashFunction(const string& s);
void insertItem(string value);
void removeItem(string value);
bool searchTable(string s);
void printTable();
void processQueries();
void processQuery(const Query& query);
};
I tried making a constructor which worked for me, but I am not sure why it worked.
Here is my code:
HashTable::HashTable(int bc)
: bucket_count(bc)
, table(bucket_count)
{}
In this, the bucket_count is initialized to bc in this constructor which is agreeable. But by that logic table should be initialized to bc. But that is not what happened. Instead the size of table vector got initialized (which is what I wanted).
If anyone could explain, why the constructor initialization worked this way it would be of great help.
The easiest solution would be
vector<list<string>> table{(size_t)bucket_count};
This depends largely on how, where and when you set the actual value of bucket_count. For example, you could set the size of the table vector in the initializer list of your class constructor. The following code lets you do this by setting the size in the constructor call, either by passing a size explicitly when you construct a class object, or by using a default value (42 in the code I've shown):
class HashTable {
public:
int bucket_count;
vector<list<string>> table;
HashTable(int bc = 42) : bucket_count(bc), table(bucket_count) { }
//...
Alternatively, if bucket_size is to remain constant and universal, you could make it a static constexpr member:
class HashTable {
public:
static constexpr auto bucket_count = 42;
vector<list<string>> table;
HashTable() : table(bucket_count) { }
//...

Reference changes value when used to create object

I'm getting some strange error while running some C++ code that uses references. Basically I have three classes, the first contains an object of the second one while the second contains a vector of objects of the third class. This is the example code:
class MainClass {
public:
SecondaryClass myClass;
private:
void myFunction() {
int temp = 0;
const int& newValue = myClass.getFinalClassByIndex(temp).getInt();
// I add another FinalClass with the same value
myClass.addClassToVector(newValue);
// I try to add another one but the variabile "newValue" has another value
myClass.addClassToVector(newValue);
}
};
class SecondaryClass {
public:
SecondaryClass() {
myVector.push_back(FinalClass(0));
}
private:
std::vector<FinalClass> myVector;
void addClassToVector(const int& value) {
myVector.push_back(FinalClass(value));
}
FinalClass& getFinalClassByIndex(const int& index) {
return myVector.at(index);
}
};
class FinalClass {
public:
FinalClass(const int& value) : myInt(value){}
FinalClass(const int&& value) : myInt(value){}
const int& getInt(){ return myInt; }
private:
int myInt;
};
This is what happens when I run "myFunction": I get the integer value from the first object in the vector myVector and I put it in the newValue variable. Then I try to create two new FinalClass objects with the addClassToVector method, and these two will have the same integer value as the first one.
The first new object (that will be the second object in the vector) is created correctly; when I try to create the second object (the third one in the vector) the newValue variable does not have the value 0 as it should be, but it has a totally different one. It seems like the value has been moved instead of copied into the new class.
The second constructor in the class FinalClass is used when I create the class like ' FinalClass(0) ', it gives me an error if I don't use the "&&" notation.
What could the problem be in this case? I think it has something to do with the way I handle the references, but I don't understand why.
You return everything by reference. Which is fine until your vector needs to be resized, which reallocates your vector's memory and invalidates all references to that memory. Including your newValue reference. As a result your const int& newValue points to memory, which contains random data and it's a miracle your program doesn't crash at all.
Stop using references when you don't need them:
newValue = myClass.getFinalClassByIndex(temp).getInt();
and
int getInt(){ return myInt; }
even better:
auto getInt(){ return myInt; }

Assign a point to the class member

i trying to implement the following link http://in.mathworks.com/help/vision/examples/motion-based-multiple-object-tracking.html in opencv and c++.
I have created a class say ex:
class assign
{
vector <int> id;
vector <int> area;
vector<Point> centroid;
};
After this i have created an object
assign id;
Now i want to assign the centroid value and other values too. what i tried is
id.centroid (p);
where p is a "point" But i'm getting error for this. I don't know where i'm going wrong.
centroid is a private member of class assign. If you want to access it directly, you should make it public
class assign
{
public:
vector<Point> centroid;
//...
};
And if you want to add a Point into centroid, you should
id.centroid.push_back(p);
The main answer is already given by songyuanyao. What I want to add is a possible solution which allows you to use the member variables like you already tried it.
If you want to get and set the member centroid with id.centroid(p) you could go with the following class declaration:
class Assign
{
public:
vector<Point> centroid();
void centroid(vector<Point> c);
private:
vector<Point> m_centroid;
};
The definition might then look like this:
// getter
vector<Point> Assign::centroid() {
return m_centroid;
}
// setter
void Assign::centroid(vector<Point> c) {
m_centroid = c;
}
Now if you use id.centroid(p) to set the member the overloaded setter will be called and will set the variable. If you call p = id.centroid() (empty parameter list) the overloaded getter will be called and will return the current m_centroid.
To add to the previous answers; if you want to expand on your class this can be done for you during construction of your object.
class Assign {
private:
std::vector<int> m_vIds;
std::vector<int> m_vAreas;
std::vector<Vec2> m_vCentroids;
public:
Assign(); // Default Constructor Same As What You Have But Not Declared.
Assign( int* pIds, int* pAreas, int* pCentroids ); // Create By Using Pointers
// Create By Passing In Either Pre Filled Vectors Or Even An Empty
// Vectors To Be Filled Out Later. Passes By Reference. This Will
// Also Set The Variables That Are Passed In From The Caller.
Assign( std::vector<int>& vIds, std::vector<int>& vAreas, std::vector<Vec2>& vCentroids );
// Since You Are Using Vectors Within This Class It Is Also Good To
// Have A Destructor To Clear These Out Once The Object Is Done And
// Ready To Be Destroyed Or Removed From Memory
~Assign();
};
// The Destructor Would Look Like This
Assign::~Asign() {
if ( !m_vIds.empty() ) {
m_vIds.clear();
}
if ( !m_vAreas.empty() ) {
m_vAreas.clear();
}
if ( !m_vCentroids.empty() ) {
m_vCentroids.empty();
}
} // ~Assign
// NOTE: I used Vec2 instead of point due to my use of programming
// 2D & 3D Graphics Rendering Engines; Most Graphics APIs and Libraries
// along with Most Math Libraries Will Not Have A Point Class; Most Will
// Use Vec2 or Vec3 - Vector2 or Vector3 & Vector4 Since in terms of
// memory they are exactly the same thing. It is up to you to know which
// objects are points or locations, and which are vectors as in forces,
// velocities, accelerations, directions, normals etc. The only major
// difference between a discrete Point Class or Structure versus a Vector
// Class is that the Vector Class usually has operations defined with it
// to do vector mathematics such as addition, subtraction, multiplication by
// value, multiplication by vector, division by value, division by vector,
// cross & dot product, comparisons, testing if vector is 0, setting it to
// be a normal vector, returning the magnitude or length and a few others.
// The general point class or object is usually just data values or
// simply coordinates without operations.

Passing integer by reference to a class in c++

I have a thread-class Buffer (own made class), and many derived classes such as BufferTypeA, BufferTypeB...
Since I have to synchronize them in a certain order, I'm giving any of them an integer which represents the order to run certain task. I also have to know inside each thread Buffer which one is next to run the task, so I'm passing every BufferType a reference to an integer which all of them must share and I didn't want to make it Global.
I got lost at any point and I don't see where.
First I create all the BufferTypes from a class where I also define that shared integer as:
int currentThreadOrder;
And when creating the BufferTypes:
int position = 0;
if (NULL == bufferA) {
bufferA = new BufferTypeA(&currentThreadOrder, ++position,
waitCondition);
}
if (NULL == bufferB) {
bufferB = new BufferPos(&currentThreadOrder, ++position,
waitCondition);
}
if (NULL == bufferC) {
bufferC = new BufferRtk(&currentThreadOrder, ++position,
waitCondition);
}
Then, in BufferTypeA header:
class BufferTypeA: public Buffer {
public:
BufferTypeA(int currentThreadOrder,
int threadConnectionOrder = 0,
QWaitCondition *waitCondition = NULL);
//..
}
And in cpp file:
BufferTypeA::BufferTypeA(int currentThreadOrder, int threadConnectionOrder, QWaitCondition *waitCondition):
Buffer(currentThreadOrder, threadConnectionOrder, waitCondition) { }
Now I'll show Buffer header:
class Buffer: public QThread {
public:
Buffer(int &currentThreadOrder,
int threadConnectionOrder = 0,
QWaitCondition *waitCondition = NULL);
//...
protected:
QWaitCondition *waitCondition;
int threadConnectionOrder;
int &currentThreadOrder; // Shared address
}
And finally the cpp:
Buffer::Buffer(int &currentThreadOrder, int threadConnectionOrder, QWaitCondition *waitCondition) {
this->threadConnectionOrder = threadConnectionOrder;
this->waitCondition = waitCondition;
this->currentThreadOrder = currentThreadOrder;
}
And the error I'm getting is error: uninitialized reference member Buffer::currentThreadOrder.
I'm embarrased to ask, because it's going to be a simple problem with pointers and addresses, but I can't see where the problem is, so please help.
When you create a class with a data-member that is a reference, the reference needs to be assigned a value in the constructor initializer list.
References have to be given a value when they are created, they are not pointers. They have to start with a value and that value cannot be changed (while the contents that is pointed to by that value can be changed).
Essentially you can think of a reference as an alias for an existing variable. You can't give a friend a nickname if you don't have a friend :)
RESPONSE TO COMMENT:
You don't "share a reference" between objects. Each object will have its own reference to the same variable. When you "pass by reference" you are telling the compiler that you want the variable in your function to actually be the variable in your outer scope, rather than creating a new variable by value. This means that you only have one variable at one memory location. The reference is just memory in some other place that forwards you to that same memory location.
Think of this as call forwarding... I can have 15 phone numbers in 15 different countries. I can set them all up to forward calls to my cell in the US. So, people are calling me no matter which number they call.
Each of your classes just has another reference to forward the "phone calls" or variable reads/writes to that same memory location. So, you're not sharing a reference between classes, you're making sure that each class HAS a reference to the same underlying memory location.
Back to the metaphore, each class won't have the same phone, but each class' phone will forward to the same number (variable) none-the-less which lets them all set/get the same value in the end.
RESPONSE II:
Here's a simple example to get your head going, it's pretty easy to apply to your classes. I didn't compile it but it should work minus a typo or two possibly.
class A
{
public:
A(int& shared) : m_shared(shared)
{
//No actions needed, initializer list initializes
//reference above. We'll just increment the variable
//so you can see it's shared in main.
m_shared += 7;
}
void DoSomethingWithIt()
{
//Will always reflect value in main no matter which object
//we are talking about.
std::cout << m_shared << std::endl;
}
private:
//Reference variable, must be initialized in
//initializer list of constructor or you'll get the same
//compiler error again.
int& m_shared;
};
int main()
{
int my_shared_integer = 0;
//Create two A instances that share my_shared_integer.
//Both A's will initialize their internal reference to
//my_shared_integer as they will take it into their
//constructors "by reference" (see & in constructor
//signature) and save it in their initializer list.
A myFirstA(my_shared_integer);
A mySecondA(my_shared_integer);
//Prints 14 as both A's incremented it by 7 in constructors.
std::cout << my_shared_integer << std::endl;
}
you pass a pointer int* as 1st argument to BufferTypeA, which expects and int, while you said in your question you meant to use a int&. To do this, the ctor of BufferTypeA should take a int& and initialise it in an initialisation list (i.e. not within the { } part of the ctor) like
class BufferType {
int &Ref;
public:
BufferTypeA(int& ref) : Ref(ref) { /* ... */ }
};
and in your construction of BufferA you must not pass an address, but the reference, i.e.
int counter;
Buffer = new BufferType(counter);
You want code like this:
Buffer::Buffer(
int &currentThreadOrder0,
const int threadConnectionOrder0,
QWaitCondition *const waitCondition0
) :
threadConnectionOrder(threadConnectionOrder0),
waitCondition(waitCondition0),
currentThreadOrder(currentThreadOrder0)
{}
The reason is related to the reason you cannot write
const double pi;
pi = 3.14;
but can write
const double pi = 3.14;
A reference is typically implemented as a constant pointer, to which one cannot assign an address after one has initialized the pointer. Your version of the code assigns, as in the first pi example. My version of the code initializes, as in the second pi example.

Class C++ trace this value!

#include <iostream>
using namespace std;
class t
{ public:
int health; //its members
int speed;
int power;
void attack() // its methods
{ cout<<"I'm attacking"<<endl;
};
};
int main()
{ t A,B,C,D;
A.power = 100;
B.health = 87;
C.speed = 92;
cout<<"A= "<<A.power<<"B= "<<A.health<<"C= "<<A.speed<<endl; // <---
cout<< "My health is "<<C.health<<" My speed is "<<A.speed<<endl;
cout<<"My power is "<<B.power<<endl;
D.attack();
system("pause");
return 0;}
The output result was ::
A= 100 B= 96 C=6234392 <--- From where these values come
A.health and A.speed are just junk values on the stack because you didn't explicitly set them. If you want to initialize all fields of A to zero, you can use memset:
memset(&A, 0, sizeof(A));
You should create a constructor to initialize those values to some default value in the initializer list.
class t {
public:
t() : health(100),power(100),speed(100) {}
// ...
};
This will guarantee that those values are all set to 100, or some default, or even an input parameter, rather than garbage. It's considered much better design since otherwise the initialization of those values would be handled in the constructor that the compiler generates for you behind the scenes.
Uninitialized memory?
Uninitialized variable won't be zero setted at the creation of the class/struct. You need to manualy do it. Otherwise, you will get whatever_is_in_memory_at_that_time.