I want to declare a pointer in my .h and initialize it in .cpp. For example an int pointer:
My .h class file:
#pragma once
#include <iostream>
#include <stdio.h>
#include <stdint.h>
using namespace std;
class Calc_ToF_low
{
private:
int telo[3];
public:
Calc_ToF_low(void);
~Calc_ToF_low(void);
double * CalcToF(int16_t * señal, int fs);
long double * filter(long double *ganancias, long double *coeficientes, double *señal,int lensignal, int L, int control);
void signal_p1_lowf(void);
void avg_p1_lowf(void);
void time_est();
};
My .cpp class file:
#include "Calc_ToF_low.h"
Calc_ToF_low::Calc_ToF_low(void)
{
telo[3]={0,1,2};
}
How can I do this?
Like this:
Calc_ToF_low::Calc_ToF_low() // note no need to say void in C++
{
telo[0]=0;
telo[1]=1;
telo[2]=2;
}
Or if you can use C++11, something like this might work:
Calc_ToF_low::Calc_ToF_low()
: telo{{0,1,2}} // initializer list, will not work in "old" C++98
{}
You could just assign values to it by typing:
telo[0] = 0;
telo[1] = 1;
telo[2] = 2;
in your .cpp.
It may not be perfect for huge arrays but then you probably should assign the values from a file instead.
If you're initializing large arrays with a constant value for all item, you can use this approach:
Calc_ToF_low::Calc_ToF_low(){
memset(telo, 0, sizeof(telo)); //0 is the constant value
}
If you want to initialize your large array to some set of values that has no patterns:
int defaultTeloData[TELO_NUMITEM] = {2,4,1,5,6,1,7,82,41,6,134,88,1};
Calc_ToF_low::Calc_ToF_low(){
memcpy(telo, defaultTeloData, sizeof(telo));
}
If your array values has pattern, use a loop and some formulas or constructors.
Calc_ToF_low::Calc_ToF_low(){
for(int a = 0; a sizeof(telo)/sizeof(telo[0]); a++){
telo[a] = dataFormulaForTelo(a);
}
}
This is one way you could do it:
#include <array>
class Calc_ToF_low
{
private:
std::array<int, 3> telo;
public:
Calc_ToF_low();
};
Calc_ToF_low::Calc_ToF_low()
: telo()
{
for(unsigned i = 0; i<telo.size(); ++i)
telo[i] = i;
}
Related
I am trying to create an array in my UnsortedList class. I specified to create an array in the header file, and I also specified the MAX_SIZE, which is equal to 10. However, whenever I create my object of the class, the default constructor does not create that array with the MAX_SIZE. I am unsure what I am doing wrong. I also get an error saying "stack around the variable 'myList' was corrupted". Also, just as a side note, can I initialize the array values when the default constructor is called, instead of creating a function to do it?
"UnsortedList.h" header file:
#pragma once
class UnsortedList {
public:
UnsortedList();
bool IsFull(); //Determines whether the list is full or not (returns T or F)
int GetLength(); //Gets the length of the list
void SetListValues();
private:
int length;
const int MAX_ITEMS = 10;
int numbers[];
};
"UnsortedList.cpp" file:
#pragma once
#include "UnsortedList.h"
#include <fstream>
#include <iostream>
using namespace std;
UnsortedList::UnsortedList() {
length = 0; //sets length to 0
numbers[MAX_ITEMS]; //sets array maximum size to MAX_ITEMS (10 as indicated in UnsortedList.h)
}
bool UnsortedList::IsFull() {
return (length == MAX_ITEMS);
}
int UnsortedList::GetLength() {
return length;
}
void UnsortedList::SetListValues() {
ifstream inFile;
inFile.open("values.txt");
int x = 0;
while (!inFile.eof()) {
inFile >> numbers[x];
x++;
}
}
"main.cpp" file:
#include <iostream>
#include <string>
#include "UnsortedList.h"
using namespace std;
int main() {
UnsortedList myList;
myList.SetListValues();
return 0;
}
I recommend you use std::array or std::vector, but if you must use C arrays, then your definition in the header needs correcting:
class UnsortedList {
// ...
const static int MAX_ITEMS = 10;
int numbers[MAX_ITEMS];
};
You can remove the corresponding line in the constructor. The file reading method also needs correcting:
void UnsortedList::SetListValues() {
ifstream inFile;
inFile.open("values.txt");
int x = 0;
int read_value;
// x < MAX_ITEMS to avoid out of bounds access
while (x != MAX_ITEMS && inFile >> read_value)
{
numbers[x++] = read_value;
length++; // I assume you also want to increment the length at this point?
}
}
Edit: As noted by #πάνταῥεῖ, there is no good reason to use C style arrays when the standard provides std::array. Not much changes, it is declared as:
std::array<int, MAX_ITEMS> numbers;
You can use operator[] as with the C array. This is preferable as it provides a richer API and can be used like other C++ containers, i.e. with STL algorithms.
I've been trying to use arrays in a class constructor. Here is my code:
struct Motor_Group{
int Motors[3];
int Encoder;
};
int main()
{
Motor_Group Left_Drive {{2,3},3};
Motor_Group Right_Drive {{2,3},3};
cout<< sizeof(Left_Drive.Motors)/sizeof(int);
return 0;
}
But, the problem is that i want to make the length of the array motors to be undefined untill its contents is declared. How can i do that?
Thanks for your kind help!
If you do not need MotorGroups to be of the same type,
then you could template the array size.
Using std::array
#include <array>
#include <iostream>
template<size_t motor_count>
struct Motor_Group{
std::array<int,motor_count> Motors;
int Encoder;
};
int main()
{
Motor_Group<2> Left_Drive {{2,3},3};
Motor_Group<3> Right_Drive {{2,3,4},3};
std::cout<< Left_Drive.size();
// Left_Drive = Right_Drive; // Error at compile time, since Motor_Group<2> != Motor_Group<3>
return 0;
}
class1.cpp
int a=10; int b=5; int c=2;
//for this array[a][b][c]
int*** array=new int**[a];
for(int i =0; i<a; i++)
{
array[i] = new int*[b];
for(int k =0; k<b; k++)
{
array[i][k] = new int[c];
}
}
how can i use this array in other .cpp files ?
Instead of manually allocating an array you should at least use a std::vector. What you would do is have a header file that contains
extern std::vector<std::vector<std::vector<int>>> data;
that you will include in all the cpp files you wish to share the vector with and then in a single cpp file have
std::vector<std::vector<std::vector<int>>> data = std::vector<std::vector<std::vector<int>(a, std::vector<std::vector<int>>(b, std::vector<int>(c)));
and now you will have a global object that is shared and it has a managed lifetime.
You shouldn't really use a nested vector though. It can scatter the data in memory so it isn't very cache friendly. You should use a class with a single dimension vector and pretend that it has multiple dimensions using math. A very basic example of that would look like
class matrix
{
std::vector<int> data;
int row; // this really isn't needed as data.size() will give you rows
int col;
int depth;
public:
matrix(int x, int y, int z) : data(x * y * z), row(x), col(y), depth(z) {}
int& operator()(int x, int y, int z) { return data[x + (y * col) + (z * col * depth)]; }
};
and then the header file would be
extern matrix data;
and a single cpp file would contain
matrix data(a, b, c);
Prefer std::array or std::vector to raw arrays. You had constant dimensions so use std::array.
Declare it in header file:
// header.h
#pragma once // or use multiple inclusion guards with preprocessor
#include <array>
const int a = 10;
const int b = 5;
const int c = 2;
using Array3D = std::array<std::array<std::array<int,c>,b>,a>;
extern Array3D array3d; // extern indicates it is global
Define it in cpp file:
// class1.cpp
#include "header.h"
Array3D array3d;
Then include the header wherever you want to use it.
// main.cpp
#include "header.h"
int main()
{
array3d[3][2][1] = 42;
}
I am not sure I have understood what exactly you mean but simply :
class1 obj1;
obj1.array[i][j][k] // assuming you make the array public and already initialized in the constructor(and dont forget to delete it in the destructor)
im new in c++ (and not to old in programming...) and i have problem with handling vectors and strucs in class.
basically i have a vector and a array of pointers to struct members in the class and i want work on the in my methos but im doing something worng/
here is my movement.h
#pragma once
using namespace std;
class movement
{
private:
static const int MAX_ROW_PER_TRACKER = 100;
static const int MIN_TO_START_CALC = 30;
static const int MAX_TRACKERS = 20;
struct tracker
{
int id;
double a[MAX_ROW_PER_TRACKER];
double b[MAX_ROW_PER_TRACKER];
double c;
};
vector<int> trackersOrder[MAX_TRACKERS] = {};
tracker* trackersArr[MAX_TRACKERS];
public:
movement();
void addRow(int a, int b, int c);
~movement();
};
and my movement.cpp
#include "stdafx.h"
#include "movement.h"
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
movement::movement()
{
}
void movement::addRow(int id, int a, int b)
{
int index;
vector<int>::iterator searchID = find(trackersOrder.begin(), trackersOrder.end(), ID);
if (searchID == trackersOrder.end())
{
vector<int>::iterator freeLocation = find(trackersOrder.begin(), trackersOrder.end(), 0);
index = freeLocation - trackersOrder.begin();
trackersOrder.insert(trackersOrder.begin + index, id);
structArr[index] = new tracker;
structArr[index]->id = id;
structArr[index]->a[0] = a;
structArr[index]->b[0] = b;
structArr[index]->c = 0;
}
}
movement::~movement()
{
}
so when i send to method "addRow" id, and b i want to first check if i allready have this id in my vector (the vector just give me the index for the structs array) and if not then if put the id in the first empty place in the vector and on the structs array/
but from some reasin its look to me that the methid dont reconized the vector and the structs. can you help me understand why?
p.s - i can bet that i have more mistakes in my code, its my firs try with pointers and ect. (im comming from the good life in Matlab) so i will be happy to learn on them also
thank you very much!
The main problem
The problem is that in your code, trackersOrder is not a vector but an array of vectors:
vector<int> trackersOrder[MAX_TRACKERS] = {}; // array of MAXTRACKERS vectors !!
The solution
If you define it as simple vector, it should work better:
vector<int> trackersOrder;
If you want to set its size do it in the movement constructor:
movement::movement() : trackersOrder(MAX_TRACKERS)
{
}
Other issues
There is a case typo with an ID that should be id.
auto searchID = find(trackersOrder.begin(), trackersOrder.end(), id); // by the way auto is easier + ID corrected
There are a missing () after a begin whicn transforms unfortunately your iterator arithmetic into function pointer arithmetic (sic!!):
trackersOrder.insert(trackersOrder.begin() + index, id); // corrected
Finally, there are a couple of structArr that should be replaced by trackersArr.
The result does finally compile (online demo)
I have to make a class that will make arrays act like vectors. When I try and pass the class into the method into my main I get an error telling me that "[" and "]" are incorrect operators. I was wondering if I'm just completely doing this wrong or if it's just a simple mistake. Help is greatly appreciated. Here is my header file:
#ifndef PROGRAM5HEADER_H
#ifndef PROGRAM5HEADER_H
#define PROGRAM5HEADER_H
#include <string>
using namespace std;
class FloatArray
{
int *rep;
int _size;
public:
FloatArray(int sz=100):_size(sz)
{
rep=new int[sz];
}
~FloatArray()
{
delete [] rep;
}
int size() const
{
return _size;
}
FloatArray(const FloatArray& x)
{
copy(x);
}
void copy(const FloatArray& x)
{
_size == x.size();
rep=new int[_size];
for(int k=0;k<_size;k++)
rep[k]=x.rep[k];
}
};
#endif
and here is my main program
#include <iostream>
#include <string>
#include <cstdlib>
#include "program5header.h"
#include <cmath>
using namespace std;
int meanstd(FloatArray x, int& std)
{
int sx=0,sx2=0,mean;
for(int i=0;i<x.size();i++)
{
sx+=x[i];
sx2+=x[i]*x[i];
}
mean=sx/x.size();
std=sqrt(sx2/x.size()-mean*mean);
return mean;
}
int main()
{ int f;
cout<<"How big of an array would you like: "<<endl;
cin>>f;
FloatArray x(f);
}
There are a lot of issues with a lot of your implementation, I'd suggest doing some research on the subject. I'll touch on a few.
Firstly, you should make your FloatArray a templated class and allow for different types other than just int.
When you initialize a FloatArray x and then try to access it's underlying array through "[]" you are actually invoking the following:
x.operator[](...)
You haven't defined the '[]' operator on your FloatArray class so you are getting an error.
You need something similar to this:
int FloatArray.operator[](int index) {
assert(index < _size);
return _rep[index]
}
Your copy isn't doing what you want, it's not copying the size over to "this". It should look something similar to this:
void copy(const FloatArray& x)
{
_size = x._size;
rep=new int[_size];
for(int k=0;k<_size;k++)
rep[k]=x.rep[k];
}
However I would suggest not having a copy method and instead implement everything in your copy constructor.