I am trying to initialize the dynamic array in the constructor using initialize_list in C++. How can I achieve this?
#include <cstdlib>
#include <initializer_list>
#include <iostream>
#include <utility>
using namespace std;
class vec {
private:
// Variable to store the number of elements contained in this vec.
size_t elements;
// Pointer to store the address of the dynamically allocated memory.
double *data;
public:
/*
* Constructor to create a vec variable with the contents of 'ilist'.
*/
vec(initializer_list<double> ilist);
}
int main() {
vec x = { 1, 2, 3 }; // should call to the constructor
return 0;
}
initializer_list has size method, it gives you information how many elements must be allocated by new, so it could be:
vec(initializer_list<double> ilist)
{
elements = ilist.size();
data = new double[ ilist.size() ];
std::copy(ilist.begin(),ilist.end(),data);
}
Use a standard std::vector container instead of a raw pointer. std::vector is a wrapper for a dynamic array, and it has a constructor that accepts a std::initializer_list as input.
#include <initializer_list>
#include <iostream>
#include <vector>
using namespace std;
class vec {
private:
vector<double> data;
public:
vec(initializer_list<double> ilist) : data(ilist) {}
};
Related
When an object is placed inside a vector, the vector makes a copy of the object, this means that any changes to the object does not change the object inside the vector. How do i make so any changes to the object also change the object inside the vector.
#include <iostream>
#include <vector>
using namespace std;
class objectClass {
public:
int x = 0;
};
vector<int> my_vector;
int main()
{
objectClass testObject;
vector<objectClass> my_vector = {testObject};
testObject.x = 5;
cout << my_vector[0].x;
}
//outputs 0
You can do this in two way
change the object from the vector like :
#include <iostream>
#include <vector>
using namespace std;
class objectClass {
public:
int x = 0;
};
vector<int> my_vector;
int main()
{
objectClass testObject;
vector<objectClass> my_vector = {testObject};
my_vector[0].x = 5;
cout << my_vector[0].x;
}
or you can do this by using pointers or reference, use a vector of pointers, where the vector will have the collections of objects references and thus changing the object from outside the vector also will change from inside the vector.
#include <iostream>
#include <vector>
using namespace std;
class objectClass {
public:
int x = 0;
};
int main()
{
objectClass testObject;
vector<objectClass*> my_vector = {&testObject};
testObject.x = 5;
cout << my_vector[0]->x;
}
One way of doing it would be having a vector of pointers instead, where each pointer points to some instance of objectClass:
#include <iostream>
#include <vector>
using namespace std;
class objectClass {
public:
int x = 0;
};
int main()
{
objectClass testObject;
vector<objectClass*> my_vector = {&testObject};
testObject.x = 5;
cout << my_vector[0]->x;
}
Is it possible to initialize a vector member with the initialization list of the constructor. I give some incorrect codes below.
#ifndef _CLASSA_H_
#define _CLASSA_H_
#include <iostream>
#include <vector>
#include <string>
class CA{
public:
CA();
~CA();
private:
std::vector<int> mCount;
std::vector<string> mTitle;
};
The implementation of the constructor in .cpp file
// I want to do it this way
#pragma once
#include "classa.h"
// Constructor
CA::CA(int pCount, std::string pTitle) :mCount(pCount), mTitle(pTitle)
{
}
// Destructor
CA::~CA()
{
}
in main file
#include "classa.h"
int main()
{
CA A1(25, "abcd");
return 0;
}
If you want to initialize the vector members with the the parameters passed to CA::CA as elements, you can use list initialization (since C++11), for which the constructor of std::vector taking std::initializer_list will be used for initialization. e.g.
CA::CA(int pCount, std::string pTitle) :mCount{pCount}, mTitle{pTitle}
// ~ ~ ~ ~
{
// now mCount contains 1 element with value 25,
// mTitle consains 1 element with value "abcd"
}
I'm trying to use arrays with unique_ptr with no success.
What is the correct way to declare a unique_ptr of some size?
(size is some paramter).
unique_ptr<A[]> ptr = make_unique<A[]>(size);
Here's an example:
#include <iostream>
#include <string>
#include <vector>
#include <functional>
#include <memory>
using namespace std;
class A {
string str;
public:
A(string _str): str(_str) {}
string getStr() {
return str;
}
};
int main()
{
unique_ptr<A[]> ptr = make_unique<A[]>(3);
}
This is not working, however, if I delete the constructor of A, it works.
I want the 3 to represent the size of the array, and not an argument to A's constructor, how do I make that happen?
This is not working, however, if I delete the constructor of A, it
works.
When you removed the user defined constructor, the compiler implicitly generates a default one. When you provide a user defined constructor, the compiler doesn't implicitly generate a default constructor.
std::make_unique<T[]> requires the use of default constructors...
So, provide one, and all should work well
#include <iostream>
#include <string>
#include <vector>
#include <functional>
#include <memory>
using namespace std;
class A {
string str;
public:
A() = default;
A(string _str): str(_str) {}
string getStr() {
return str;
}
};
int main()
{
unique_ptr<A[]> ptr = make_unique<A[]>(3);
}
This is the code I am using:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Vector
{
// Use user defined template class for vector handling
template <class V,class D>
void vec_add(V &vec, D data)
{
vec.push_back(data);
}
};
int main ()
{
vector<int> v; // v is vecor of int elements
Vector.vec_add(&v,222);
}
Goal: Define a generic add of item to any kind of vector.
Problem: I am getting a compilation error.
There are many issues:
First, make the member functions public:
class Vector
{
public:
Second,
Vector.vec_add(&v,222);
should be something like
Vector foo;
foo.vec_add(v,222);
as you are passing a reference, not a pointer, and you must invoke the member function on an instance, in this case foo, as the member function is not static (think whether you want to make it static, in which case you invoke it as Vector::vec_add). Full working code below:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Vector
{
public:
// Use user defined template class for vector handling
template <class V, class D>
void vec_add(V &vec, D data)
{
vec.push_back(data);
}
};
int main ()
{
vector<int> v; // v is vecor of int elements
Vector foo;
foo.vec_add(v, 222);
std::cout << v.front(); // test it
}
Live on Coliru
A good advice is to pick up a book from here and learn the basic features of the language.
Why bother making a class? It would have to be static member function, because you didn't make any Vector objects. Better use normal functions, if you don't have any plans with the class alone:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
template <class V,class D>
void vec_add(V &vec, D data)
{
vec.push_back(data);
}
int main ()
{
vector<int> v; // v is vecor of int elements
vec_add(v,222);
}
You have a several problems with your code: your vec_add is private, it is non static, also you call it with pointer to std::vector - while your method accepts a reference. Below is an example with fixed errors, hopefully this is what you want:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Vector
{
// Use user defined template class for vector handling
public:
template <class V,class D>
static void vec_add(V &vec, D data)
{
vec.push_back(data);
}
};
int main ()
{
vector<int> v; // v is vecor of int elements
Vector::vec_add(v,222);
}
Here is my code
main.cpp
#include <iostream>
#include "header.h"
#include "source.cpp"
using namespace std;
int main()
{
cout << "Hello world!" << endl;
int testarray[]={1,3,5,7};
mymatrix* first=new mymatrix(testarray,2,2);
return 0;
}
and header.h
using namespace std;
#include <iostream>
#include <string>
class mymatrix{
public:
int i;
int j;
int marray[];
mymatrix(int m[],int rows,int cols ) : marray(m),i(rows),j(cols)
{
cout<<"this is for testings ";
}
mymatrix()
{};
~mymatrix(){
// delete[] marray;
};
};
I get this error :Invalid use of non static data member mymatrix::i
what I wanna do is make a object of my
matrix class and pass an array
Convert it from
int marray[];
to
int *marray;
In addition, either use C paradigm or use C++ one but not the mixture.
Instead of
mymatrix* first=new mymatrix(testarray,2,2);
use
mymatrix first(testarray,2,2);
Let the compiler allocate and release the memory instead of you.
If you have no restriction about the C++ libraries that you use, consider std::vector library to manage your dynamic arrays.
Instad of managing memory out of the object, manage it inside the object specially inside constructor and destructor.