C++ Create an object with array simultaneously with the constructor - c++

So, I've been exploring on how to create a dynamical array with a custom template class that I made.
#include <iostream>
#include <vector>
//HOW TO SET CLASS INTO DYNAMICAL ARRAY WITH VECTOR
//CREATE A CLASS
class User{
std::string name;
public:
User(){
}
User(std::string name){
this->name = name;
}
void set_name(std::string name){
this->name = name;
}
std::string get_name(){
return name;
}
};
int main(){
//SET A NORMAL ARRAY THAT CAN CONTAIN AN OBJECT
User user[1];
//DO WHATEVER WITH THE USER[0] TO SET EVERYTHING THAT LATER WILL BE PUT IN VECTOR
user[0].set_name("Meilianto");
std::cout << "user[0]: " << user[0].get_name() << std::endl;
//CREATE A DYNAMICAL ARRAY WHICH IS VECTOR
std::vector<User> vuser;
//PUSHBACK TO THE VECTOR AS "FIRST ELEMENT" BY PUTTING "USER[0]" AS AN ARGUMENT
vuser.push_back(user[0]);
std::cout << "vuser[0]: " << vuser[0].get_name() << std::endl;
//YOU CAN "MODIFIED" THE "USER[0]" AND ADD AGAIN AS THE "SECOND ELEMENT" OF VECTOR
user[0].set_name("Meilianto1");
vuser.push_back(user[0]);
std::cout << "vuser[1]: " << vuser[1].get_name() << std::endl;
//YOU CAN EVEN "MODIFIED" THE "FIRST ELEMENT" BY CALLING THE "METHOD" OF IT
vuser[0].set_name("Hantu");
std::cout << "vuser[0]: " << vuser[0].get_name() << std::endl;
//THE QUESTION HERE, CAN I DECLARE ARRAY TOGETHER WITH THE CONSTRUCTOR?
User user1[1]("Bebek");
//AND AFTER THAT I CAN ADD THAT OBJECT STRAIGHT AWAY TO VECTOR WITHOUT ASSIGNING ALL THE
//MEMBERS ONE BY ONE
return 0;
}
If you have read my comments in my code, what I am trying to do is maybe it will be faster if I just construct right away when I create the object instead of assigning all the members one by one that will cost more code. I imagine if in the future there will be an object with a lot of members and need to assign it one by one. It won't be efficient.
EDIT: I edit the User user[0] into User user[1], Thanks

If you're using a modern standard of C++, then you can do this
std::vector<User> vuser {
{"Meilianto1"},
{"Hantu"},
{"Bebek"}
};
Where each pair of inner brackets with a string calls User constructor, and outer pair of brackets calls std::vector<User> constructor with a sequence of Users

THE QUESTION HERE, CAN I DECLARE ARRAY TOGETHER WITH THE CONSTRUCTOR ?
User user1[1]("Bebek");
You can use list initialization for that, for arrays as well as for vectors:
User users[] { std::string("Herbert"), std::string("Anton") };
std::vector<User> vusers { std::string("Herbert"), std::string("Anton") };
CAN I ADD THAT OBJECT STRAIGHT AWAY TO VECTOR WITHOUT ASSIGNING ALL THE MEMBERS ONE BY ONE
You can initialize a vector with the elements of an previously defined array like this:
std::vector<User> v2users(std::cbegin(users), std::cend(users));
BTW: note that User user[0]; in your code defines an array without elements, i.e. of size 0, which rarely makes sense. Accessing user[0] leads to undefined behaviour

Yes, you can!
User users[]{ User{ "one" }, User{ "two" } };
// Construct vector from iterator-pair:
std::vector<User> users_vector{ std::cbegin(users), std::cend(users) };

You can use emplace_back method or push_back with temporary object to add the vector. For example;
vuser.emplace_back("Meilianto1"); // 1
vuser.push_back(User{"Meilianto1"}); // 2
The first one passes the arguments to the constructor. The second one will move the variable to vector. To be honest, there will be copy elision that's why there will be no move or copy. Just it will construct the variable.

Related

C++ Member Function That Returns A Value of Two other member functions

I had this question on a test about a month ago and I still can't seem to understand it completely and quite frankly it's driving me crazy. I will include the question at the bottom. But, it's asking to create a single parameter constructor that creates a new "Vector" (the name of the class) which is the sum of two others. The vector class I made has a function set/get x and set/get y. My hang up is I can't seem to figure out how to make a function that adds the two x's and y's together from vector and vector1 to create a new Vector...call it vector2. I'll include everything I got so far. Thanks to anyone willing to make it through the wall of text as confusing as it must be haha.
Write a class Vertor with the following properties and place the class in a separate header file :
Add member function with a single parameter of another vector and returns a new vector that is the sum of the two (to add vectors you sum the components, for example, Cx = Ax + Bx and Cy = Ay + By).
Write a program that includes the Vector header file, constructs two different vectors and demonstrates the magnitude, angle, and add functions.
Data Members
vector
x component
y component
Member Functions
Set and Get functions for all data members
Magnitude member function
Angle member function (angle = inverse tangent(y / x))
ps I hope I am not doing anything wrong by uploading this and asking I have waited this entire time because I didn't want to break some sort of rule in the community....that I am honestly desperate to become a part of. I've dreamed of doing this my whole life and finally....ahh i digress sorry thanks guys
Oh...my code
#include "Vertor.h"
#include <iostream>
int main()
{
// creates a vector class
Vector vector;
vector.setXcom(4); // sets X
vector.setYcom(12); // sets Y
Vector vector1; // Creates another vector
vector1.setXcom(3);
vector1.setYcom(52);
Vector vector2; // constructs another vector that returns the sum of two other vectors
cout << vector.getXcom() << endl;
cout << vector.getYcom() << endl;
cout << vector.getMag() << endl;
cout << vector.getAng() << endl;
cout << vector1.getXcom() << endl;
cout << vector1.getYcom() << endl;
cout << vector1.getMag() << endl;
cout << vector1.getAng() << endl;
}
#include<iostream>
using namespace std;
// initalize variables
double xcomponent, ycomponent;
double ans, anns, annns;
class Vector // creates Vector class
{
public:
void setXcom(double x) // setX function
{
xcomponent = x;
}
void setYcom(double y) // setY function
{
ycomponent = y;
}
double getXcom() // getX function
{
return xcomponent;
}
double getYcom() // getY function
{
return ycomponent;
}
double getMag() // get magnitude function
{
double ans = sqrt((xcomponent * xcomponent) + (ycomponent * ycomponent));
return ans;
}
double getAng() // get angle function
{
double annns = atan(xcomponent / ycomponent);
return annns;
}
// setnewvec function to make a new vector from two others
void setNewVec(int a, int b)
{
xcomponent = a;
ycomponent = b;
}
// NOT SURE
Vector getNewVec(int a, int b)
{
return a + a;
return b + b;
}
};
So you have an absolutely fundamental misunderstanding or gap in your knowledge about how objects work, and this task will be impossible until you sort that out.
To illustrate here's a simpler example written in the style of your code above. I'll follow that with the same example written as it should be. This example is a simple Person class which has an age 'component'.
int age;
class Person
{
public:
void setAge(int a) { age = a; }
int getAge() { return age; }
};
int main()
{
Person fred;
fred.setAge(22);
Person mary;
mary.setAge(33);
cout << "Fred is " << fred.getAge() << " and Mary is " << mary.getAge() << endl;
}
If you run this program the output will be Fred is 33 and Mary is 33. Both the people have the same age even though you set them as different in the program.
The problem is that although this program has two people it only has one age. So it's literally impossible for the two people to have different ages.
Here's the program written correctly. The crucial difference is that the age variable is inside the class. This means that each Person object gets it's own age.
class Person
{
public:
void setAge(int a) { age = a; }
int getAge() { return age; }
private:
int age;
};
int main()
{
Person fred;
fred.setAge(22);
Person mary;
mary.setAge(33);
cout << "Fred is " << fred.getAge() << " and Mary is " << mary.getAge() << endl;
}
Now the output is Fred is 22 and Mary is 33 as it should be.
First thing you need to do, is to move xcomponent and ycomponent to inside the object. Right now they are global variables which means they share values in all objects you create (and outside object too).
I'm gonna assume you've learned about structures before moving to objects. It's pretty hard to understand object without knowing structures first.
Structures and classes are very similar. They both are containers for variables. Classes are a little more advanced version that usually hides the raw data and instead provides member functions (sometimes called methods) that allow to manipulate the data inside in a more convenient way.
Anyway, when you create a new object of a class, you create it with a new copy all member variables (fields) inside. This way, they can have different values for each object.
Your code is pretty easy to fix in that regard. Just move definition of these variables inside your class.
Old code:
double xcomponent, ycomponent;
double ans, anns, annns;
class Vector // creates Vector class
{
public:
//...
};
New code:
class Vector // creates Vector class
{
double xcomponent, ycomponent;
double ans, anns, annns;
public:
//...
};
Now we can work on the return value.
Your return value of getNewVec is all right. You've declared that you want to return an object of type Vector and this is exactly what you want.
However, the function should also take a single vector as an argument. Right now you have tho arguments int a and int b, none of which is a Vector. We need to change that to Vector otherVector to do what your assignment said.
The call of the function looks like this: someVector.getNewVec(someOtherVector).
When it runs, you have two vectors accessible inside of it. The first of them is the one on which the function was called. You have direct access to its fields. The second one is of course the argument otherVector. You can access its fields through its member functions. (Or you can access directly its private fields because you're in a member function of its class.)
Now you need to construct the new vector.
The simplest way is to just create it and assign the values one by one:
Vector getNewVec(Vector otherVector)
{
Vector newVector;
newVector.setXcom(xcomponent + otherVector.getXcom());
newVector.setYcom(ycomponent + otherVector.getYcom());
return newVector;
}
or:
Vector getNewVec(Vector otherVector)
{
Vector newVector;
newVector.setXcom(xcomponent + otherVector.xcomponent);
newVector.setYcom(ycomponent + otherVector.ycomponent);
return newVector;
}
or if you really want:
Vector getNewVec(Vector otherVector)
{
Vector newVector;
newVector.setXcom(this->getXcom() + otherVector.getXcom());
newVector.setYcom(this->getYcom() + otherVector.getYcom());
return newVector;
}
(this is a pointer the object your inside of. You have access to it from each member function.)
I recommend the second option.
Some additional stuff you can read about if your interested...
(I'm not gonna go into any details here.)
Constructors
You can have a special member function that is called when object it's created that is supposed to set initial values to the fields.
It is written similar to a function, except is doesn't have a return value and it's name is always the same as the name of the class.
Vector(int x, int y)
{
xcomponent = x;
ycomponent = y;
}
That allows to create an abject and assign the values in one line so instead of:
Vector newVector;
newVector.setXcom(12);
newVector.setYcom(42);
you can have:
Vector newVector(12, 42);
You can have more than one constructor with different list of arguments.
You can create an operator instead of a normal function. An operator is a function with specific name and arguments that can be called similarly to built-in mathematical operations.
Operator for addition looks like this:
Vector operator+(Vector otherVector)
//the body is the same as getNewVec
You could call it like a normal member function:
someVector.operator+(someOtherVector)
but a better way of writing it is:
someVector + someOtherVector

C++: How to make some class access it's member by default in its object?

Lets take the example some of the codes like the following use objects but can access their members directly without using any '.' operator
Eg-1
#include <iostream>
#include <string>
using namespace std;
int main () {
string mystr;
cout << "What's your name? ";
getline (cin, mystr);
cout << "Hello " << mystr << ".\n";
cout << "What is your favorite team? ";
getline (cin, mystr);
cout << "I like " << mystr << " too!\n";
return 0;
}
Here mystr is an object of std::string but it can access the group of characters inside it without using the '.' operator it should be
getline(cin,mystr.(member_name)); //Here member name is the name of the member which is there inside the class std::string and stores the data
But the actual working code is
getline(cin,mystr);
Second thing what is indirection
Edit 1:
Ok let me put this in a more simpler way if i have some class which has some data members and if i want to use any data member then i need to refer it from the object like
Eg-2
class reff{
public:
int a;
int b;
}
reff per;
per.a=36;
This statement tells that to access any class' members we need to refer it from the object but the same is not happening in the example of std:: string which i have mentioned above mystr is an object so it must be having some data member to store the data if i want to display the data inside a std::string object then i should mention the data member's name along with the objects name but in Eg-1 only object's name is mentioned.
The reason the call to getline(cin,mystr); does not directly specify any of the members of mystr is because the getline() function requires a string object, not one of its member variables. The actual implementation will access the individual members, but as a user of the string class, you don't need to (or want to) know those details. This concept is known as encapsulation, and allows you to seperate what a thing does (stores and allows access to a string of characters) from how it does it (pointers and length counters, static buffers, or whatever).
In your example:
class reff{
public:
int a;
int b;
};
reff per;
per.a=36;
you directly access the a member, but we could write a function which requires a reference to a reff object to set the value of its member variable:
void setValueA(reff& obj, int value)
{
obj.a = value;
}
and then use similar syntax to the getline() method on it:
setValueA(per, 36);
to achieve the same thing as per.a = 36, but with the benefits of encapsulation: if you later need to change the details of how reff stores its data (e.g. changing a and b to meaningful names), you only need to change the function implementation to use the new data members; all user code using this class will continue to work. If user code directly accessed the members, it would also need to be changed to use the new name.
Notice that setValueA() is accessing the member variables of the object it is passed; so calling it with per.a directly is not only unnecessary, but impossible:
setValueA(per.a, 36); // invalid: setValueA() requires a reff&, not an int
since the function itself tries to utilise the member a of the object it is passed, and an int does not have any members.
For the getline() call using a std::string, it has the same issue: for this function to work, it needs at the minimum:
read/write access to a pointer to the memory to store the data it reads (it may need to reallocate this if there's not enough space already allocated); and
the amount of memory pointed to the above, so it knows how much additional data it can store before it needs to allocate additional space.
So, given that getline() requires more than just a single intrinsic type in order to function, it should be clear why the parameter includes a string object rather than one of its specific member variable.
For additional examples, you should look up operator overloading, which can even let you do things like have per = 36; assign a value to per.a.
Here's a self-contained example using overloaded operators on a slightly modified version of your reff class. The comments try to explain what's going on, and should give you terms you can search for - this stuff is all pretty basic C++ and should be covered in any tutorial series.
#include <iostream>
class Reff
{
public:
int a;
float b; // changed the data type to illustrate overloading the = operator
// operator= will be called if we try to assign to a an object of this class;
// this version of the function accepts an integer value
Reff& operator= (int intval)
{
a = intval;
return *this;
}
// another operator=, this one accepting a float value as the parameter
Reff& operator= (float floatval)
{
b = floatval;
return *this;
}
};
// operator+ will be called if we try to add a value to this object;
// I'm only defining this one which accepts an int value
int operator+ (Reff const& reff, int intval)
{
return reff.a + intval;
}
// an overload of the operator<< function, which accepts a reference to
// an instance of a Reff, along with the output stream parameter.
std::ostream& operator<< (std::ostream& stream, Reff const& reff)
{
return stream << "[a:" << reff.a << " b:" << reff.b << "]";
}
int main()
{
// create an instance of our class
Reff per;
// assign the instance 42 (an integer value) - this will use the integer
// overload of the operator= we defined
per = 42;
// assign it a floating point value - this will use the float overload
// of the operator=. Note that if we didn't define a float-specific overload,
// the compiler would probably truncate the value to an integer and use our
// integer version instead - possibly with a warning, possibly silently,
// depending on your compiler settings.
per = 3.14159f;
// output the object; this will use the overload of the operator<< function
// that we created, which accepts our Reff object
std::cout << per << std::endl;
// output the result of adding 58 to our object; this will use the operator+
// overload which accepts an integer
std::cout << "per + 58 = " << (per + 58) << std::endl;
}
Here you can get output directly through
cout << "I like " << mystr << " too!\n";
because operator << is overridden in string Class.
like:
ostream& operator << (ostream& OS, MyString & S)
{
OS << S.get_string();
return OS;
}
Check whole implementation : http://www.cplusplus.com/forum/beginner/15396/

initializing an passing a string array as a parameter

Can I initiate a string array and pass it as a function that initializes it. I know this sounds redundant, but basically I want to initiate a string array and then pass it to a variable so that I can use it later? Something like this:
This is the .h:
class ScreenBasics{
void setupAnswers(int &_numberOfAnswers, string *_answersText);
string *answersText;
{
This will be the implementation .cpp
void ScreenBasics::setupAnswers(int &_numberOfAnswers, string *_answersText){
answersText = _answersText; // this is where I get confused cause I don't know if I should initiate my string pointer using new like answersText = new string(_numberOfAnswers);
{
so in the main.cpp I can do something like this:
int main( ) {
ScreenBasics basics;
int numberOfAnswers = 4;
string newAnswers [] = { "Good", "Superb", "Great", "Perfect"};
basics.setupAnswers(numberOfAnswers, newAnswers);
// let's say I want to call some of those answers later
for ( int i = 0; i < numberOfAnswers; i++){
cout << basics.answersText[i] << endl;
}
}
Thanks!
Have you thougt about using structs? Both classes and structs can have a mixture of public and private members, can use inheritance, and can have member functions. I would recommend using structs as plain-old-data structures without any class-like features, and using classes as aggregate data structures with private data and member functions.
Your code would look like the following:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
struct movies_t {
string title;
int year;
} mine, yours;
int main ()
{
string mystr;
mine.title = "2001 A Space Odyssey";
mine.year = 1968;
cout << "Enter title: ";
getline (cin,yours.title);
cout << "Enter year: ";
getline (cin,mystr);
stringstream(mystr) >> yours.year;
cout << "My favorite movie is:\n ";
printmovie (mine);
cout << "And yours is:\n ";
printmovie (yours);
return 0;
}
void printmovie (movies_t movie)
{
cout << movie.title;
cout << " (" << movie.year << ")\n";
}
Please let me know if you have any questions!
It sounds like your class should use a constructor to initialize the pointer.
class ScreenBasics
{
ScreenBasics(std::string* _answersText, std::size_t size)
: answersText(new std::string[size])
{
// copy values from _answersText to answersText
}
};
Note that since you are allocating a resource dynamically, you will need to implement The Rule of Three: that is, you need to create a copy-constructor, copy-assignment operator and destructor. This is because their default implementations do not semantocally conform to our requirements. For instance, the default copy-constructor and copy-assignment operator perform shallow copies (that is, they copy the pointer but not what it points to). Also, the destructor doesn't free the memory allocated my new[]. You will need to provide your own definition of the destructor that calls delete[].
Fortunately, all this can be avoided by using the standard library container std::vector, which is a dynamic array class that handles the memory allocation for you. The default implementations of the aforementioned constructors will correctly copy/copy-assign a vector if the need be:
class ScreenBasics
{
ScreenBasics(std:vector<std::string> _answersText)
: answersText(_answersText)
{
}
};
Notice that the size also didn't have to be passed as a parameter. A vector maintains its size internally.

using a constructor to initialise a string pointer

i am having trouble with my code. I am abit stumped.
I have a data member which is a pointer to a string type.
I use the constructor as a defualt initialer to this pointer, then when I call an object in the main function the intialised pointer to points to the memory address where the string is stored and prints the contents. That is what is supposed to happen, but I can't get the program to work. May somebody please tell me where I am going wrong?
#include<iostream>
#include<string>
using namespace std;
class NoName{
public:
NoName(string &sName("Alice In Wonderland") ){};
private:
string *pstring;
};
int main(){
//the constructor will be automatically called here once a object is created
// and the string "Alice in Wonderland" will appear on the screen
return 0;
}
Just simply use a std::string member and initialize it in Member initializer list:
private:
string mstring;
public:
NoName():mstring("Alice In Wonderland"){}
You could also let the constructor take in a parameter instead of hardcoding the string and let the user pass the string at run-time:
NoName(std::string str):mstring(str){}
You do not need a pointer. By using a pointer to std::string You nullify the advantages of implicit manual memory management offered by std::string.
If you really need to store a pointer for some reason, then there are some points to remember:
Pointers are initialized like new Class
Prefer to initialize class members in the member initializer list
Any time you write the word new think about where you're going to write delete. (In this case it goes in the destructor.
Rule of Three: If you need a destructor (you do, because of delete), then you also need a copy constructor and copy assignment operator.
This is one way your code could look: http://ideone.com/21yGgC
#include<iostream>
#include<string>
using std::cout; using std::endl;
using std::string;
class NoName
{
public:
NoName(string sName = "Alice In Wonderland") :
pstring(new string(sName))
{
cout << "ctor - " << *pstring << endl;
}
NoName(const NoName& rhs) :
pstring(new string(*rhs.pstring))
{
cout << "Copy ctor - " << *pstring << endl;
}
NoName& operator=(const NoName& rhs)
{
*pstring = *rhs.pstring;
cout << "Copy assignment operator - " << *pstring << endl;
return *this;
}
~NoName()
{
cout << "dtor, my name was " << *pstring << endl;
delete pstring;
}
private:
string *pstring;
};
.
int main()
{
NoName m, n("Another name");
NoName o(m);
o = n;
return 0;
}
Notice how much easier it is if you don't use the unnecessary pointer:
class Better
{
public:
Better(string sName = "Alice In Wonderland") :
m_string(sName)
{
}
private:
string m_string;
};
Because you don't need the custom destructor, you also don't need the copy constructor or copy assigment operator either. Much easier!
You're not using the constructor properly. First of all, you create this reference parameter and try to initialize it to a string object (that's asking for problems). Second, your constructor never actually does anything.
You need to call new on your pointer, dereference it and give the data pointed to a value, output the dereferenced value with std::cout and then clean the memory up with delete in the destructor (or in this case, you can do it after you use cout if you're not planning on using that string again. But do it in the destructor if you need it still).
Assuming you're doing this for a class, your textbook should tell you how to do these things.
EDIT: this is also not the default-constructor. I changed your tag to match appropriately.

C++ constructor problem, values not being set

I'm new to C++ and I'm trying to figure out this problem I'm having with my constructor for one of my classes. What happens is... all my variables are initialized properly except two (health and type).
#pragma once
#include <irrlicht.h>
#include <vector>
#include <cassert>
using namespace irr;
using namespace core;
using namespace scene;
enum
{
PLAYER = 0,
NPC = 1,
SOLDIER = 2,
CHAINGUNNER = 3
};
class Model
{
public:
Model(void);
Model(int id, std::vector<ISceneNode*> modelVec, int modType);
~Model(void);
std::vector<int> path;
std::vector<ISceneNode*> model;
int endNode;
int type;
int animate;
int health;
u32 lastAnimation;
private:
int mId;
};
#include "Model.h"
Model::Model(void)
{
//assert(false);
}
Model::Model(int id, std::vector<ISceneNode*> modelVec, int modType)
{
path = std::vector<int>();
model = modelVec;
endNode = 0;
type = modType;
animate = 0;
health = 100;
lastAnimation = 0;
mId = id;
}
Model::~Model(void)
{}
I create a model with Model soldier(id, model, SOLDIER)
Everything is set properly except type and health. I've tried many different things, but I cannot figure out my problem. I'm not sure but the default constructor is being called. It doesn't make sense because I make no called to that constructor.
Thanks,
vector<ISceneNode*> model;
model.push_back(soldierBody);
model.push_back(soldierHead);
model.push_back(soldierWeapon);
cout << "Id of char: " << id << endl;
Model soldier(id, model, SOLDIER);
modelMap[id] = soldier;
This lines:
modelMap[id] = soldier;
First default constructs the Model inside the map.
The returned reference is then used with the assignment operator to copy the value of soldier into the value contained inside the map.
To test if it is working try:
Model soldier(id, model, SOLDIER);
std::cout << "TYPE(" << soldier.type << ") HEALTH(" << soldier.health << ")" std::endl;
modelMap[id] = soldier;
std::cout << "TYPE(" << modelMap[id].type << " HEALTH(" << modelMap[id].health << ")" std::endl;
If your class is not designed to be default constructible.
Then do not have a default constructor (this will just lead to problems).
Declare a default constructor in the private part of the class (no need for a body).
Without a default constructor you will not be able to use the operator[] on map. But you can get around this by using insert:
modelMap.insert(std::map<XX, Model>::value_type(id, soldier));
From the comments, you say that you are inserting these into a map like so:
modelMap[id] = Model(id, model, SOLDIER);
std::map::operator[] requires that the mapped type be default constructible. When you call operator[] on a map, if there is no mapped value with the given key, the map default constructs a new object, maps it to the given key, and returns a reference to that object.
You can get around this by using std::map::insert():
modelMap.insert(std::make_pair(id, Model(id, model, SOLDIER));
You do:
Model soldier(id, model, SOLDIER); //1
modelMap[id] = soldier; //2
What happens here?
1. New object is created, using consructor you have provided.
2. The so-called copy-constructor copy assignment operator is called to copy soldier to modelMap[id]. You haven't defined your own copy-constructor copy assignment operator so one default is created for you by compiler, it is in most cases just copying byte-by-byte whole data-structure to the new memory address. However you have vector of pointers in your class, so compiler should call copy-constructor of vector... And I don't know (maybe someone with greater experience would know exactly what happens now) what is the result copy-constructor, I don't know if standard clearly defines 'default copy-constructor'.
So it is possible, that the whole structure is copied to the modelMap[] but with some random data.
If you create a copy-constructor (its declaration in your case will look something like Model::Model(const Model& myModel);, copy-constructor always takes reference to object of its type as an argument) If you override copy assignment operator (best, if you make both things), you have control over everything that is done while copying your object to another variable/object.
Download eg. Bruce Eckel's Thinking in C++, V. 1 [1], or search somewhere on the Net how to do it (probably this will be good, didn't read whole article, http://www.learncpp.com/cpp-tutorial/911-the-copy-constructor-and-overloading-the-assignment-operator/).
[1] Downloadable on his website, mindview.net, as a new user I can paste only one link, so cannot link it here myself :P.