Problems Initializing Vector - c++

I'm new to c++ so I'm kind of consfused
I wanted to do something like that:
`
int max = 30;
class MyClass{
vector<int> data(max);
};
but it wasn't working, because it was not recognizing that "max" was that int I had just initialized.
so i changed to that:
class MyClass{
MyClass();
int max;
vector<int> data(max);
}
MyClass::MyClass(){
max = 40;}
Don't work unless I initialize the vector in the constructor, but I don't know the correct sintax.
How can I make this work? All I want is to initialize "max" and then use it as the initial size of the vector.

You prof/teacher should have told you about initializer lists. The syntax looks something like this:
class MyClass {
std::vector<int> data;
public:
MyClass(int max) : data(max) { }
};

Related

How to use () initializers for vector in class?

This code gives an error
class Board {
vector<vector<int>> sudoku(9, vector<int>(9));
// Error; Expected a parameter declarator
};
How can I fix it?
You can't use parentheses to directly initialize a member when you do in class initialization. You have to either brace ({}) or equal (= ...;) initialize the member. That means you need to refactor it to have the form of
vector<vector<int>> sudoku = vector<vector<int>>(9, vector<int>(9));
// or
vector<vector<int>> sudoku{9, vector<int>(9)};
One way:
class Board {
vector<vector<int>> sudoku = vector<vector<int>>(9, vector<int>(9));
};
Second way:
class Board {
public:
Board() : sudoku(9, vector<int>(9)) {}
private:
vector<vector<int>> sudoku;
};

Inheritance and array of types

I have a probably very simple question in C++.
Let's say I have class defined as:
class PS
{
private:
int value;
int m;
public:
PS();
PS(int value, int m);
PS(int m);
};
Now I want to define an array with elements of this type. For example,
PS t[3];
However, I want all of the elements in this array to have m=2. How would I do that? I am assuming I have to use inheritance some how, right?
So for example I don't want to do something like this:
>PS t[3];
>t[0].PS(2);
>t[1].PS(2);
>t[2].PS(2);
I want to do it one show for all elements of t.
Using your constructor, you can simply use brace initialization :
PS t[] = { PS(2) , PS(2), PS(2) };
Or as suggested by #0x499602D2, since PS has a non explicit constructor, simply :
PS t[] = { 2, 2, 2 };
I would also suggest you to use std::array<> instead of C-style arrays.
It is not really safe not to initialize a value but you can use the C++11 feature that allows you to initialize variable directly in your class definition :
class PS {
private:
int value;
int m = 2;
public:
PS() {};
};
If you are using an older version of C++ you can consider overloading the default constructor
class PS {
private:
int value;
int m;
public:
PS(int _m = 2) : m(_m) {};
};
The STL Vector class is preferred to c-arrays. Using one, you could do:
std::vector<PS> t(3, PS(2));

initializing a vector of vectors of a user defined

I have this struct
struct myStruct {
int a;
int b;
}
I want to create a vector <vector<myStruct> > V and initialize it to n empty vectors of type vector<myStruct>
I'm trying to use the the fill constructor
like this:
vector<edge> temp;
vector<vector<edge> > V(n, temp);
This code works fine in main, but when I have V inside a class how can I do that inside the class constructor.
EDIT:
when I do it in my class constructor I get the following error:
no match for call to '(std::vector<std::vector<edge> >) (int&, std::vector<edge>&)'
the code generating the error is:
vector<myStruct> temp;
V(n, temp); // n is a parameter for the constructor
First, note that temp is not necessary: your code is identical to
vector<vector<edge> > V(n);
Now to your main question: When your vector is inside a class, use initializer list if the member is non-static, or initialize the member in the declaration part if it is static.
class MyClass {
vector<vector<edge> > V;
public:
MyClass(int n) : V(n) {}
};
or like this:
// In the header
class MyClass {
static vector<vector<edge> > V;
...
};
// In a cpp file; n must be defined for this to work
vector<vector<edge> > MyClass::V(n);
Just omit temp. The constructor for the class that V is inside should look like:
MyClass(size_t n) : V(n) {}
class A
{
private:
std::vector<std::vector<myStruct>> _v;
public:
A() : _v(10) {} // if you just want 10 empty vectors, you don't need to supply the 2nd parameter
A(std::size_t n) : _v(n) {}
// ...
};
You use initializer lists for this kind of initialization.

Creating 2-dimensional vector in class C++

I need to create a vector of vectors full of integers. However, I continuously get the errors:
error: expected identifier before numeric constant
error: expected ',' or '...' before numeric constant
using namespace std;
class Grid {
public:
Grid();
void display_grid();
void output_grid();
private:
vector<int> row(5, 0);
vector<vector<int> > puzzle(9, row);
int rows_;
int columns_;
};
You cannot initialize the member variables at the point where you declare them. Use an initialization list in the constructor for that:
Grid::Grid()
: row(5,0), puzzle(9, row),
rows_(5), columns_(9)
{
}
C++ class definitions are limited in that you cannot initialise members in-line where you declare them. It's a shame, but it's being fixed to some extent in C++0x.
Anyway, you can still provide constructor parameters with the ctor-initializer syntax. You may not have seen it before, but:
struct T {
T() : x(42) {
// ...
}
int x;
};
is how you initialise a member, when you might have previously tried (and failed) with int x = 42;.
So:
class Grid {
public:
Grid();
void display_grid();
void output_grid();
private:
vector<int> row;
vector<vector<int> > puzzle;
int rows_;
int columns_;
};
Grid::Grid()
: row(5, 0)
, puzzle(9, row)
{
// ...
};
Hope that helps.
You can't initialize a member in a class declaration unless it's const static, because in C++ no code is being run/generated when you are declaring a class. You'll have to initialize them in your constructor.
You should initialize members in the class constructor, not the declaration. The following doesn't seem to be right in any way:
vector<int> row(5, 0);
vector<vector<int> > puzzle(9, row);
If row and puzzle are functions - the parameters should be types. If they're member variables - initialize them in the class constructor.
You cannot initialize mutable members as a part of class definition itself. Instead do assign it in in the constructor.
// ....
Grid()
{
row.resize(5,0) ;
puzzle.resize(9,row) ;
}
private:
vector<int> row;
vector<vector<int> > puzzle ;
// ..

C++ / Arduino: dynamic int array

I'm writing a class for the Arduino. It's been going well so far, but I'm sort of stuck now...
I have declared an int array in my class
class myClass
{
public: MyClass(int size);
private:
int _intArray[];
};
When I initialize the class MyClass myClass1(5) I need the array to look like this {0,0,0,0,0}.
My question: what do I need to do so that the array contains 'size' amount of zeros?
MyClass::MyClass(int size)
{
//what goes here to dynamically initialize the array
for(int i=0; i < size; i++) _intArray[i] = 0;
}
Edit: Following up on various replies below, Arduino does not include the standard library so unfortunately std::vector is not an option
Your code as I'm writing this:
class myClass
{
public: MyClass(int size);
private:
int _intArray[];
};
The declaration of _intArray is not valid C++: a raw array needs to have a size specified at compile time.
You can instead instead use a std::vector:
class myClass
{
public:
MyClass( int size )
: intArray_( size ) // Vector of given size with zero-valued elements.
{}
private:
std::vector<int> intArray_;
};
Note 1: some compilers may allow your original code as a language extension, in order to support the "struct hack" (that's a C technique that's not necessary in C++).
Note 2: I've changed the name of your member. Generally underscores at the start of names can be problematic because they may conflict with names from the C++ implementation.
Cheers & hth.,
You should use a std::vector.
class myCLass {
public:
myClass(int size)
: intarray(size) {
for(int i = 0; i < size; i++) intarray[i] = 0;
}
private:
std::vector<int> intarray;
};
You should really use vectors as others have suggested. A work-around could be as shown (in case you do not want to use memcpy or a loop).
This would be useful if you have a really huge array. Note that it would add a level of indirection to access the array.
class myClass
{
public:
myClass(){
mt = T(); // value initialize.
}
private:
struct T{
int _intArray[10];
} mt;
};
int main(){
myClass m;
}
I'll try the following:
class myClass
{
public:
MyClass(int size);
~MyClass();
private:
int* _intArray;
};
MyClass::MyClass(int size) {
_intArray = new int[size];
for (int i=0; i<size; ++i) _intArray[i] =0; // or use memset ...
}
MyClass::~MyClass() {
delete[] _intArray;
}
Or, even better, use a STL vector instead ...
you can use another hack basing on a string value and then populate a limited size array
check this :
https://github.com/Riadam/ViewPort-Array-Shifter-for-Arduino-Uno.git