increment an instance of structure - c++

I'm new in C++; here is my problem.
DataInterface is a struct defined.
I would like to create Datainterface_1, Datainterface_2, Datainterface_3 as an instance of existing DataInterface. How to do that.
I wrote the following :
for (int i = 0; i < 3; ++i)
{
DataInterface* Datainterface_$i = .....;
}
It doesn't work.
Any ideas?

Use a container - like std::vector or std::array - to hold multiple instances.

Related

Is it possible to create an array of IloModel objects in C++?

I've been unsuccessfully trying to create an array of IloModel object. Is there an easy way to do it ?
This is what I've tried so far:
IloModel* models = new(env) IloModel[S];
The code compiles but whenever I try to add constraints to each one of the models, the following error message is displayed:
Error:trying to add to an empty handle IloModel
I've removed the argumento from the new operator and added the following lines to code I'm wrinting:
cout << "0" << endl;
for(int i=0; i < S; S++)
models[i] = IloModel(env);
But now the computer freezes when I run the code.
You are creating an array of empty model objects (i.e. objects without handle). After creating the array of empty models you have to initialize each of the models:
for (int i = 0; i < 5; ++i) models[i] = IloModel(env);
I am not sure about the placement-new syntax for allocating the array. Unless there is a very good reason not to use the default operator new, it is probably easier to read to just us that or even allocate the array on the stack.
EDIT: Here is a full code snippet that works for me:
IloEnv env;
int S = 5;
IloModel *models = new IloModel[S];
for (int i = 0; i < S; ++i)
models[i] = IloModel(env);

c++ 2d array of class pointers

i am trying to create a 2d array holding pointers of my class. first, i'd like to assign all of them NULL:
Timetable::Timetable(int hours) : TimetableBase(hours){
scheduledLectures = new Lecture**[5];
for (int i = 0; i < 5; i++) {
scheduledLectures[i] = new Lecture*[hours];
for (int j = 0; j < hours; j++)
scheduledLectures[i][j] = NULL;
};
}
this is for a timetable generator application. i have a function to set these pointers to a specific object.
void Timetable::setLecture(Lecture& lecture){
while ((lecture.getDuration()) -1 > 0){
scheduledLectures[lecture.getDayScheduled()][(lecture.getHourScheduled())+1] = &lecture;
}
}
the compiler returns no errors for this, but when its running, it seems that the pointers remain NULLs.
i am sure the error is inside the setter function (and almost sure that its a grammar mistake) but i cannot find the solution for that.
whats wrong in here?
thank you
Use a vector (or std::array) of pointers or shared_ptrs (or unique_ptrs depending on how your lifetimes are arranged) instead of a 2D array of pointers that you manage yourself. Save yourself the trouble of managing the memory and lifetimes of your objects manually.
class TimeTable {
vector<vector<shared_ptr<Lecture>>> scheduledLectures;
};
Timetable::Timetable(int hours)
: TimetableBase(hours),
scheduledLectures(5, vector<shared_ptr<Lecture>>(5)) {}
void Timetable::setLecture(std::shared_ptr<Lecture> lecture){
while ((lecture->getDuration()) -1 > 0) { // not sure what this does
scheduledLectures[lecture->getDayScheduled()][(lecture->getHourScheduled())+1] = lecture;
}
}
You can test whether a shared_ptr is null like follows
auto s_ptr = std::shared_ptr<int>{}; // null
// either assign it to a value or keep it null
if (s_ptr) {
// not null
}
If you are managing the memory of the Lecture objects elsewhere then just use a 2D vector of pointers and trust your code
class TimeTable {
vector<vector<Lecture*>> scheduledLectures;
};
Timetable::Timetable(int hours)
: TimetableBase(hours),
scheduledLectures(5, vector<Lecture*>(5)) {}
void Timetable::setLecture(Lecture& lecture){
while ((lecture.getDuration()) -1 > 0) { // not sure what this does
scheduledLectures[lecture.getDayScheduled()][(lecture.getHourScheduled())+1] = &lecture;
}
}

Trying to fill a 2d array of structures in C++

As above, I'm trying to create and then fill an array of structures with some starting data to then write to/read from.
I'm still writing the cache simulator as per my previous question:
Any way to get rid of the null character at the end of an istream get?
Here's how I'm making the array:
struct cacheline
{
string data;
string tag;
bool valid;
bool dirty;
};
cacheline **AllocateDynamicArray( int nRows, int nCols)
{
cacheline **dynamicArray;
dynamicArray = new cacheline*[nRows];
for( int i = 0 ; i < nRows ; i++ )
dynamicArray[i] = new cacheline [nCols];
return dynamicArray;
}
I'm calling this from main:
cacheline **cache = AllocateDynamicArray(nooflines,noofways);
It seems to create the array ok, but when I try to fill it I get memory errors, here's how I'm trying to do it:
int fillcache(cacheline **cache, int cachesize, int cachelinelength, int ways)
{
for (int j = 0; j < ways; j++)
{
for (int i = 0; i < cachesize/(cachelinelength*4); i++)
{
cache[i][ways].data = "EMPTY";
cache[i][ways].tag = "";
cache[i][ways].valid = 0;
cache[i][ways].dirty = 0;
}
}
return(1);
}
Calling it with:
fillcache(cache, cachesize, cachelinelength, noofways);
Now, this is the first time I've really tried to use dynamic arrays, so it's entirely possible I'm doing that completely wrong, let alone when trying to make it 2d, any ideas would be greatly appreciated :)
Also, is there an easier way to do write to/read from the array? At the moment (I think) I'm having to pass lots of variables to and from functions, including the array (or a pointer to the array?) each time which doesn't seem efficient?
Something else I'm unsure of, when I pass the array (pointer?) and edit the array, when I go back out of the function, will the array still be edited?
Thanks
Edit:
Just noticed a monumentally stupid error, it should ofcourse be:
cache[i][j].data = "EMPTY";
You should find your happiness. You just need the time to check it out (:
The way to happiness

boost:python passing an pointer to pointer as parameter

First, i'm not a python programmer, so excuse my silly mistakes.
In C++ I have this public method from MyClass that creates a image dynamically and returns its size.
int MyClass::getImg(uchar *uimg[])
{
int size = variable_size;
*_uimg = new uchar[size];
memcpy(*_uimg, imageOrigin->data(), size);
uimg = _uimg;
return size;
}
And the boost:python:
BOOST_PYTHON_MODULE(mymodule)
{
class_<MyClass>("MyClass")
.def("getImg", &MyClass::getImg)
;
}
and when i try to use it in python:
def getImg():
img = c_char_p()
size = mymodule.MyClass.getImg(byref(img))
I'm getting this error:
Boost.Python.ArgumentError: Python argument types in
MyClass.getImg(MyClass, CArgObject, CArgObject)
did not match C++ signature:
getImg(class MyClass {lvalue}, unsigned char * *)
In python I also tried declaring
img = POINTER(c_ubyte)()
but that did'nt help either.
I googled it around for hours and i didn't came up with any good solution.
I just need access to that image in python, how can i get this done?
Revised and working version, exposing the data as a python list.
I am not sure how to implement this, but there may be a better way of implementing it, if you can choose your python interface freely. I think creating a list may be a better way to expose it. What do you expect from the return value? Maybe you can also wrap it a s a numpy array for better performance (there are also some questions on stackoverflow if you search for boost python and numphy)
class TestPtr
{
public:
int getImg(uchar **uimg)
{
int size = 9045;
uchar *_uimg = new uchar[size];
for( int i = 0; i < size; ++i )
_uimg[i] = i;
*uimg = _uimg;
return size;
}
};
boost::python::list getImgList( TestPtr &p )
{
uchar *uimg;
int rv = p.getImg(&uimg);
boost::python::list l;
for ( int i = 0; i < rv; ++i)
l.append( uimg[i] );
return l;
}
BOOST_PYTHON_MODULE(mymodule)
{
class_<TestPtr>("TestPtr")
.def("getImg",&getImgList)
;
}
Another hint, in your question, you have used the following line to call the method:
mymodule.MyClass.getImg()
This will make a class call (more or less equivalent to a static call) to your object. This is a mor ecorrect way to do it:
img = mymodule.MyClass()
data = img.getImg()

C++ multidimensional dynamic array

Let's say I have this to create a multidimensional array dynamically:
int* *grid = new int*[gridSizeX];
for (int i=0; i<gridSizeX; i++) {
grid[i] = new int[gridSizeY];
}
Shouldn't be possible now to access elements like grid[x][y] = 20?
Yes, this should work fine.
But... you might want to consider using standard containers instead of manually managing memory:
typedef std::vector<int> IntVec;
typedef std::vector<IntVec> IntGrid;
IntGrid grid(gridSizeX, IntVec(gridSizeY));
grid[0][0] = 20;
Yes - but in C/C++ it will be laid out as grid[y][x].