I'm trying to create an array or vector of objects. Most other stuff that I've found online has been about dynamically creating this, but I know the size that I need. I say vector or arrays because I believe either one will work for my situation (I'm comparing start and stop points) but any input onto which one will work better would be gladly welcomed as I'm pretty new to C++. My code below is my header followed by my main where I attempt to declare an array of objects, then I get this error: Variable length array of non-POD element type "Window." posWsize is a const int declared
#ifndef __Compare_Data_C____comp_fns__
#define __Compare_Data_C____comp_fns__
#include <iostream>
using namespace std;
class Window {
int start, stop, length;
double average;
string strandID;
public:
void setValues(int a, int b, string strand, int length, double avg);
};
#endif
int main()
{
int posWsize = getSize(fwdWindowInput, "+", windowHeader);
Window posWindow[posWsize];
return 0;
}
getSize gets the size of my array. Any help would be greatly appreciated! If I can't do it this specific way that's ok, I just want to know how to properly create this array (or vector if appropriate) of objects. Thanks
Use an std::vector:
std::vector<Window> posWindow(posWsize);
As a general rule in C++, unless you have a compelling reason not to, use a vector.
Related
I need to return an array of class objects from a function. I understand from research that the best way to do this is with a pointer, but is this the best way given my program design, and the need to access this from multiple CPP files?
main.cpp
#include <class.h>
#include <functions.h>
int main(){
Class Object[2][]; //define second dimension here?
some_function(); //should return / create the array with filled in elements.
int var = arr[2][3]; // want to be able to do something like this in main
}
functions.cpp
void some_function(){
// assign values
arr[2][3] = 1;
}
You should really use std::vector<std::vector<Object> > for your multi-dimensional array. Using raw arrays is error prone, and since you're using C++ anyways, why not make use of something as useful as the std::vector which automatically resizes when needed.
You can even return the vector from your function like so:
std::vector<std::vector<Object> > my_function() { /* do something */ return some_vector; }
I need a tip in creating a C++ utility.
I'm implementening an optimization algorithm, and at a certain step, I would need to create as much new variables as the iterations of a cycle.
There's some code that would explain it better:
for(int i=1;i<112;i++){
struct nodo n_2i[111-i];
}
The structure nodo is defined as:
struct nodo{
int last_prod;
int last_slot;
float Z_L;
float Z_U;
float g;
bool fathomed;
};
I would like the names of the new variables (arrays of structures) to be n_21,n_22,n_23,...etc.
How can I handle that?
Why do you need the name to be n_21. you can use a vector of vector.
#include <vector>
using namespace std;
int main() {
vector<vector<struct nodo> > n;
for(int i=1;i<112;i++){
n.push_back(vector<struct nodo>(111-i));
}
// you can use n[0] ... n[111] now
}
You can't declare new variable names during run-time. You're best off creating a std::vector of the variables.
Once the code is compiled, variable names are no longer present. At compile time the loop is a single construct (unless/until it is unrolled), and at that point it does not make sense to have different names referring to the same compile time element (the variable). The whole question makes little sense, I would advise you to provide a single variable with a good name that need not change for each iteration.
Also, c++ has no variable sized arrays, that is a C99 construct that only some compilers accept, so you might want to get rid of that and use a single array of the greatest size you will need together with a constant initialized in each iteration that will control how many of the positions of the array are valid. If you don't have an upper bound on the size, you can dynamically allocate the memory before entering the loop and release after completing the last iteration. (to avoid the expense of reallocating with each iteration.
That is, unless you need to check the previous step results...
You might want to use a std::map<string,struct nodo*>, and hold your elements in it.
also note you cannot declare a static variable which length depends on i, as your example shows, you are going to need a std::vector or to dynamically allocate memory.
If you decide to use a vector, your map will be of type map<string,vector<struct node> >
A map should do that for you:
std::map<string, struct nodo*> n_2i;
I believe that an std::map will help here:
std::map< int , std::vector< struct nodo > > n;
for(int i=1;i<112;i++){
n.insert(std::make_pair(i, std::vector<struct nodo>(111-i)));
}
you could access you values after with using the index:
n[0].SomeProperty;
The sample code below shows what I am trying to do:
template<int NX, int NY>
class Array
{
public:
float v[NX][NY];
};
void main()
{
Array<10,20> grid;
}
The above code won't compile, but it shows what I want to do. We have a class that contains an array, and the array class doesn't know its size until compile time. Is there a simple way to do this?
Edit: I want to write a simple reusable array class. That means I need to find a good way to separate the array size from the class.
I also want the class to be fast (and simple) so it must not be dynamically allocated. That means the size can't be given during run time.
I also don't want to use the preprocesser to define the size because that means I will have to go through the hassle of changing a number somewhere. That isn't convenient enough.
Basically, the class doesn't know its own size until compile time, because that is when the main function tells the class its size.
Edit: The above code is good.
Other than main not returning an int, this is legal code and should compile. In fact, on some compilers this will compile without main returning an int, such as VC++ but this is non-standard behaviour.
You can also store the size at compile time so that you don't have to calculate it manually.
#include <iostream>
template<int NX, int NY>
class Array
{
public:
float v[NX][NY];
int size() const { return ArraySize; }
private:
enum { ArraySize = NX * NY }; // You can also store rows/cols individually
};
int main()
{
Array<10,20> grid;
std::cout << grid.size();
return 0;
}
Boost.MultiArray might fit your needs.
I'm trying to create an array and pass it to functions, which then return it, but I don't know the correct way of returning.
I've been looking around tutorials and trying stuff out, but haven't managed to solve this.
I'm new to C++ and thought it would be similar to Java, but apparently it isn't.
This is where I've gotten:
class MainClass {
public:
static int countLetterCombinations(string array[], int numberOfWords) {
// Code
return totalCombos;
}
// This is the function I'm having trouble with.
static string** sortCombos(string combinations[][3]) {
// Do something
return combinations; // This gives converting error.
}
};
int main() {
// Code
int numberOfCombinations = MainClass::countLetterCombinations(words, numberOfWords);
string combinations[numberOfCombinations][3];
combinations = MainClass::sortCombos(combinations);
// Further code
}
Anyone know how to fix this?
You need to use a vector. C++ stack-based arrays cannot be dynamically sized- oh, and you can't convert [][] to **, the conversion only works for the first dimension. Oh, and you can't assign to arrays, either.
The simple rule is, in C++, never use primitive arrays- they're just a headache. They're inherited from C, which actually defined a lot of it's array behaviour for source compatibility with B, which is insanely old. Use classes that manage dynamic memory for you, like std::vector, for dynamically sizable arrays.
std::vector<std::array<std::string, 3>> combinations(numberOfCombinations);
static void sortCombos(std::vector<std::array<std::string, 3>>& combinations) {
// Do something
} // This function modifies combinations in-place and doesn't require a return.
Oh, and you really don't have to make functions static class members- they can just go in the global namespace.
Your sortCombos method can modify the array parameter in-place, and the caller will see those changes directly. Because you doesn't need to return anything, you should change the return type to void.
Even if you could return input array, you can't assign to combinations.
i want to know if there is a way to take size of a dimentional array from user?
for example for size of a matrix i have tried to definition a pointer,and after takeing size of matrix make memory.
this is: `
void getMatrixSize(&int,&int);
void makeMatrix(int **mat,int,int);
void getMatrixData(int **mat,int,int);
int matrixRow,matrixColumn;
int **A=NULL;
int main()
{
int row,column;
getMatrixSize(row,column);
makeMatrix(A,row,column);
getMatrixData(A,row,column);
}
getMatrixSize(int &row,int &column)
{
cout<<"Enter matrix row:";
cin>>matrixRow;
row=matrixRow;
cout<<"Enter matrix column:";
cin>>matrixColumn;
column=matrixColumn;
}
makeMatrix(int**mat,int row,int column)
{
int i=0;
mat=(int**)malloc(sizeof(int)*row);
if(mat==NULL)
{
cout<<"Error in getting memory";
exit(1);
}
for(i=0;i<row;i++)
{
mat[i]=(int*)malloc(sizeof(int))*column);
if(mat[i]==NULL)
{
cout<<"Error in getting memory";
exit(1);
}
}
}
void makeMatrixData(int**mat,int row,int column)
{
int i,j;
for(i=0;row>i;i++)
{
for(j=0;column>j;j++)
{
printf("m[%d][%d]=",i+1,j+1)
cin>>mat[i][j];
}
}
}
the program don't give any error but when i run it, it don't work. when i checked the debuge i realized that it take memory for mat not for A.
this was my idea and didn't find anyway to make it work.do we have any way for take size of a dimentional array from user?
Other than your use of cin and cout, your code reads like C, not C++.
There is no notion of the size of an array in C++. The way that you're doing it, you'll have to keep track of it manually, so if you plan to write matrix code in C++, I would suggest that you implement Matrix as a class, that you seriously consider using a prepackaged container for your values (vector of vectors is fine, but you can also use a single vector, a single valarray, a single scoped array from boost) instead of managing memory on your own (unless this is the objective of the exercise, and then I'd suggest that you use new and delete instead of malloc and release).
The reason that I'm suggesting that you use prepackaged containers is because today, you should not have to worry about manual memory management in C++ anymore (a lot of people who complain about memory leaks being too easy to create in C++ don't realize this). That is what containers and smart pointers exist for.
If you're wondering about how to use a single array, a single valarray or vector, read up on valarray and slices. That will point you in the right direction.
Finally, if you're writing C++, don't do an exit(1); you should throw an exception (which by the way, is what you'll get by using prepackaged containers or the new operator).
Happy learning.
Have you considered using a vector of vectors and passing that around by reference?
std::vector<std::vector<int> > mat(rows, std::vector(cols, 0)); ought to initialize a matrix to all zeroes.
mat is a local variable on stack. You better use return value to pass the allocated pointer, but if you want to pass it through parameters - you need to use references:
void makeMatrix(int **&mat,int,int);
or
'void makeMatrix(int ***mat,int,int);' and pass &A (and do *mat = inside).
i just have found a way with memory allocation.
only need that make a type and then address it's variable in the function.like this:
typedef int mymatrix;
void makeMatrix(mymatrix &mat,int,int);
and in main need to definition a pointer and put the pointer in function:
int **A;
makeMatrix(A,row,column);
so it's possible to take size of dimetional array from user.