Creating a vector of structures, reserving space, C++ - c++

Here is my structure declaration:
struct HeapEntry {
HeapEntry(int a, int b){
id = a;
key = b;
}
int id;
int key;
};
I'd like to make a vector to store HeapEntry objects, and reserve memory for it since I know how many object I'll need to store.
std::vector<HeapEntry> adjList();
adjList.reserve(200);
The adjList.reserve(200) line produces the error "expression must have class type" though. what going on here?
Thanks

use:
std::vector<HeapEntry> adjList;
instead of this:
std::vector<HeapEntry> adjList();

Did you mean to declare it like this?
std::vector<HeapEntry> adjList;

Related

Use of vector pushback with "temp" struct in one line (if possible)

I have the following code (butchered to make it small and specific):
struct myType_t
{
int a;
string str;
};
typedef vector<myType_t> dataVect_t; // Just for ease of use
...main(...)
{
dataVect_t myData;
myData.push_back((myType_t) {1, "test"}); // THIS IS THE LINE IN QUESTION!
}
EDIT: sorry, this is corrected to creating an instance of myType_t (not dataVect_t)
I want to pushback an instance of intStringPairVect_t into the vector, but I dont really want to create a variable just to do this. What I am doing seems to compile, but I am not 100% convinced it is correct... any pointers (no pun intended) here?
You want this
myData.push_back( myType_t { 1, "test" });
~~~~~~~~
It uses uniform initializer to make an object of myType_t.
If you're not using C++11, then you can define a constructor and do a same thing by ():
struct myType_t
{
myType_t(int a, string str) : a(a), str(str){}
int a;
string str;
};
myData.push_back( myType_t ( 1, "test" ));
I would do it with emplace_back instead of push_back:
struct myType_t
{
myType_t(int a, string str) : a(a), str(str) { }
int a;
string str;
};
typedef vector<myType_t> dataVect_t; // Just for ease of use
main(...)
{
dataVect_t myData;
myData.emplace_back(1, "test"); // Emplacing directly.
}
This way you don't have to create a separate variable, and using emplace_back instead of push_back is more efficient, because that way the vector does not have to copy your myType_t instance.
(And in general I find it beneficial for types to have explicit constructors with the necessary parameters.)
If emplace_back is not supported by your compiler, you can still use this approach with push_back:
main(...)
{
dataVect_t myData;
myData.push_back(myType_t(1, "test")); // Push back by creating an object.
}
The only drawback of this solution is that the object is going to be copied when inserted into the vector.

Using a list inside a struct c++

I´m starting with the programming and i speak bad english sorry for that.
I like to use a list instead of an array, inside of a struct, something like this:
#include <iostream>
#include <list>
using namespace std;
struct Market {
string b;
list <int> prices;
};
int main()
{ list <int> precios;
Market m1 = {"a",NULL};
return 0;
}
but i get this error conversion from int' to non-scalar type std::list<int, std::allocator<int> > requested|
Is this possible? maybe with malloc or free?
You should define a constructor
struct Market {
Market(string val){b=val;}
// or like this:
// Market(string val):b(val){}
string b;
list <int> prices;
};
Then you will be able to create objects like:
Market a("A");
As lists default constructor creates empty list, you dont need to pass it any parametrs.
A good read about basics of classes: http://www.cplusplus.com/doc/tutorial/classes/
NULL is not of the type std::list<int>, that's why you are getting this error.
Are you using a C++11 compiler?
If yes then try:
Market m1 = {"a", { NULL } };
Otherwise:
list<int> prices;
Market m1;
m1.b = "a";
m1.prices = prices;
You are attemping to initialize the list with a null pointer value (actually an int type). If you need to store the list by value you can initialize 'm1' like so
Market m1 = {"a", std::list<int>()};

How to return an array of structs from a class in a getter function

I have a relatively simple question but I cant seem to find an answer specific for my case and I just may not be approaching this problem the right way. I have a class that looks like this:
struct tileProperties
{
int x;
int y;
};
class LoadMap
{
private:
ALLEGRO_BITMAP *mapToLoad[10][10];
tileProperties *individualMapTile[100];
public:
//Get the struct of tile properties
tileProperties *getMapTiles();
};
I have an implementation that looks like this for the getter function:
tileProperties *LoadMap::getMapTiles()
{
return individualMapTile[0];
}
I have code in the LoadMap class that will assign 100 tile properties for each struct in the array. I want to be able to access this array of structs in my main.cpp file but I just cant seem to find the right syntax or approach. My main.cpp looks like this.
struct TestStruct
{
int x;
int y;
};
int main()
{
LoadMap _loadMap;
TestStruct *_testStruct[100];
//This assignment will not work, is there
//a better way?
_testStruct = _loadMap.getMapTiles();
return 0;
}
I realize that there are many approaches to this, but I'm trying to keep this implementation as private as possible. If someone could please point me in the right direction I would greatly appreciate it. Thank you!
TestStruct *_testStruct;
_testStruct = _loadMap.getMapTiles();
This will get you a pointer to the first element in the array returned. You can then iterate through the other 99.
I would highly recommend using vectors, or another container, and writing getters that don't return pointers to bare arrays like that.
First of all, here, why do we need TestStruct, you can use "tileProperties" structure itself...
And imp thing,
tileProperties *individualMapTile[100]; is array of pointers to the structure.
Hence, individualMapTile will have pointers in it.
You have returned the first pointer, hence you can access the first structure only. What about the others????
tileProperties** LoadMap::getMapTiles()
{
return individualMapTile;
}
int main()
{
LoadMap _loadMap;
tileProperties **_tileProperties;
_tileProperties = _loadMap.getMapTiles();
for (int i=0; i<100;i++)
{
printf("\n%d", (**_tileProperties).x);
_tileProperties;
}
return 0;
}
Use vectors instead of arrays where possible. Also consider an array/vector of TestStruct directly rather than pointers to them. I can't tell if that would be appropriate for you from your code sample.
class LoadMap
{
public:
typedef vector<tileProperties *> MapTileContainer;
LoadMap()
: individualMapTile(100) // size 100
{
// populate vector..
}
//Get the struct of tile properties
const MapTileContainer& getMapTiles() const
{
return individualMapTile;
}
MapTileContainer& getMapTiles()
{
return individualMapTile;
}
private:
MapTileContainer individualMapTile;
};
int main()
{
LoadMap _loadMap;
LoadMap::MapTileContainer& _testStruct = _loadMap.getMapTiles();
}

Using member functions to deal with objects in the heap (c++)

I'm a beginner with C++, and this is a pretty basic syntax question, but i can't seem to find an answer elsewhere. Any input would be welcome. Here is a simplified version of the problem.
Say I have a class 'pair'
class pair
{
int a;
int b;
public:
pair(int x,int y)
{
a=x;
b=y;
}
int lookup()
{
return this->a+b;
}
};
Then i instanciate and copy that instance to a spot on the heap.
int func()
{
...
pair test(1,2);
pair *ptr=new pair;
*ptr=test;
}
Now here is the key. I don't destroy this memory allocation after the function ends. I want to use it later in this other function. The problem is, i would prefer to keep it in the heap and NOT have to copy it over to the stack(in the actual program it is very large). I would therefore like to do something like this:
int otherfunc()
{
...
int sum=*ptr.lookup;
}
but I get a compiler error. I end up having to do something like:
int otherfunc()
{
...
point temp=*ptr;
int sum=temp.lookup;
}
While this works, it is redundant, and when dealing with really large things it can even potentially cause an overflow. Anyone know the syntax for calling the method using the pointer while keeping it on the heap? Thanks.
I believe this is what you are trying to do:
int sum = ptr->lookup();
And as an aside, this:
return this->a+b;
Would probably be better as just this:
return a+b;
The expression *ptr.lookup will be interpreted as *(ptr.lookup), which is why you get the syntax error because ptr.lookup does not make sense. You'll need to tell the compiler dereference ptr first by using the parenthesis: (*ptr).lookup.
Because pointers are common in C (and C++), the (*a).b can be written in a simpler form: a->b.
Also, lookup is a function even if it does not take any parameters. You need to call it with ():
int sum=ptr->lookup();

Array of values within an ENUM?

I have this code
enum type {NOTHING, SOMETHING, SOMETHINGELSE}
type *x;
At the moment I use x[765] == SOMETHING for example, How would I store other values for example
x[765] == SOMETHINGELSE;
x[765].position == 43.5;
x[765].somevar == 12;
I will apologize for my poor wording within my question im just starting out in C++, I know what I want i'm just not to sure on how to ask it.
Thanks.
It looks as if you're looking for a way to structure 'knowledge'; this is done with a struct or a class:
#include <vector>
struct Info {
enum thingness { nothing, something };
// 'member' variables
thingness howMuch;
int a_counter;
float position;
};
int main(){
Info object;
object.howMuch=Info::something;
object.a_counter=1;
object.position=5.4;
You can group these kinds of objects into a container - typically an std::vector:
// a container of InterestingValues
std::vector<Info> container(300);
container[299].howMuch=Info::nothing;
container[299].a_counter=4;
container[299].position = 3.3;
// or assign rightaway:
container[2] = object;
}
You will have to make yourself a more complex type:
struct type
{
enum flag_type
{
NOTHING, SOMETHING, SOMETHINGELSE
} flag;
double position;
int somevar;
};
and later have an array of this new type.
Get yourself a good book to learn from. A list of good books is available here: The Definitive C++ Book Guide and List
In C++, you are asking how to declare an array of structures. Try this:
struct type {
double position;
int somevar;
};
type *x;
x[765].position = 43.5;
x[765].somevar = 12;
An enum is a replaceable label basically for an int. You need to define a struct or a class.
struct type
{
float position ;
};
type var;
var.position = 3.4;
Your type enum would need to be a member of a class, along with the other fields. For example,
class MyType
{
public:
type t;
double position;
int somevar;
};
With an array of MyType instances
MyType *x;
you would then be able to do what you ask expect you would need to do
x[765].t = SOMETHINGELSE;
to assign to the enum.