C++ :: Storing Objects Of Hierarchy In A Vector
Jun 6, 2012
I have a hierarchy of Actions (NonMovingActions and MovinActions each with sub-hierarchies). Actions class has an abstract function.
Code:
class Action {
public:
Action(Agent& agent, ...):agent(agent),..{}
virtual ~Action(void);
virtual bool run()=0;
[Code]...
It appears that C++ does not allow this (in Java it was possible). Compiler objects that Action class is abstract (and cannot be instantiated?!)
Code: error C2259: 'Action' : cannot instantiate abstract class
1- May I know what do I not understand here? We cannot refer to sub-class instances with a reference of parent class type?
2- Should I use vector of pointers instead or what?
View 6 Replies
ADVERTISEMENT
Oct 31, 2014
I have two classes, Parent and Child, where Parent contains a vector that is used to store instances of Child. When I create an instance of Parent, three instances of Child are also created in Parent's constructor and stored in the vector. I understand that push_back() creates a shallow copy of each Child instance and that Child's destructor is called each time the loop (inside Parent's constructor) iterates. The problem is that because Child's destructor is called each time the local variable child goes out of scope, the memory previously allocated in Child's constructor is destroyed and when Child's destructor is called again later on in the program to get rid of the copy stored in vector, the program crashes. I can fix this by overriding the default copy function or by storing pointers to objects instead of copies of objects. I don't really need to use vectors in this case since I always have three children in one parent but I'm doing this as a learning exercise and would prefer to use vectors.
#include <iostream>
#include <vector>
class Child {
public:
Child() {
std::cout << "child constructor called" << std::endl;
[Code] .....
View 3 Replies
View Related
Apr 25, 2014
How do we design a container of objects all of which belong to some subclass which directly/indirectly inherits from a given parent class? Moreover, I would like to have functions that enable me to pick only objects of a certain class type from the container.
For example if the parent class is A and I have a hierarchy of classes that derive from it, we must have a container that can contain any class that exists in this hierarchy. Also, get_B() must be able to let me examine only those objects in this container that inherit (directly/indirectly) from class B (class B exists in the hierarchy rooted at A).
Preferably, we would like to avoid downcasting. Or even explicit typechecking of any sort.
View 8 Replies
View Related
Aug 18, 2013
I've a text file : Random.txt which comprises of
Jade
12MS234
Male
18
Rocky
12MS324
Male
18
Marx
12MS632
Male
18
Now in my program i've a class
class stud
{
char name[10];
char reg[10];
char gender[10];
int age;
};
Now I've to write a code in c++, where i've to read the given data and store this into 3 objects of stud class(array of objects) ...then further i've to manipulate the above stored data. I think i'm getting error while storing...variables are showing random characters... give me the code.for this program..in C++
View 2 Replies
View Related
Jul 13, 2014
I'm having trouble storing a string in a vector.
I keep getting the errors in lines 51-54: no suitable constructor exist to convert from
#include <iostream>
#include <string>
#include <vector>
#include "Movie.h"
using namespace std;
vector <string> movieActors;
void promptForMovie(Movie & myMovie);
[code]....
View 6 Replies
View Related
Jan 10, 2013
I'm trying out the code below; it runs and produces the output I'd expect, but could it lead to undefined behavior?
To test with, I show the key and wait for user input; if the input doesn't match the value, the iterator is stored in the vector.
map<string, string> test;
map<string, string>::iterator it;
vector<map<string, string>::iterator> bad_input;
string input;
test["key 1"] = "value 1";
[Code] ....
I am also interested in knowing if I can use an iterator to walk through the vector? I tried
vector<map<string, string>::iterator>::iterator v_it;
for(v_it = bad_input.begin(); v_it != bad_input.end(); ++v_it)
cout << v_it-> ??
However, I couldn't figure out how to access "first" and "second" using this method. Is it possible to do so?
View 2 Replies
View Related
Feb 3, 2014
I've got something I'm trying to accomplish, but crashes my program.
I've got my server and client code.
Having the client send a message they type (char Chat[1024]) And the server receiving the chat (char recv_chat[1024]) only to send it to all connected clients again. Which the server sends the recv_chat.
The client receives it (char recv_chat[1024]). This works, and the client gets the right info. However, I'm trying to store it using a vector. I'm sure I've tried any way possible.
Client storing vector pseudo-code:
vector<char*> SaveChat;
int main () {
while (true) {
if (newClientConnected) {
[Code]....
This doesn't work, and crashes my application. I've tried changing the vector to string, const char*, basically anything I can with no avail.
View 8 Replies
View Related
Oct 20, 2014
I've been really busy but managed to get in enough down time to learn somewhat decent info about vectors. Anyways originally my program created a dynamic array of pointers to class objects and I came across a few problems because of this. Apparently an array of pointers is now outta of the question and I will now be switching to a vector of objects instead.
Why I want a list of objects instead of pointers this little comment should clear things up.
tiles[i]->show() dereferences tiles[i] (i.e. accesses whatever it points at) before calling the show() method.
That is undefined behaviour. Once undefined behaviour occurs, there is no recovery, and there is nothing the show() method (or any subsequently called function for that matter) can do to recover (short of invoking their own forms of undefined behaviour - compiler specific hacks, etc).
Even if the show() method initialises the object correctly, it cannot change the pointer tiles[i] which is in a different scope (within main()).
What I'm trying to do is create a vector of already intialized objects so that I can use a conditional statement of every single element to properly layer my games art resources. This should also automatically fix a mild unrelated collision dectection problem too but first thing first layering.
View 9 Replies
View Related
Nov 10, 2013
here's the problem. I want to delete the objects within a vector, although I'm not sure whether I should clear the vector afterwards. Is it really necessary?
Code:
for (i = 0; i < allSales.size(); i++)
delete allSales[i];
allSales.clear(); //Is this step necessary?
View 5 Replies
View Related
Mar 16, 2013
So I'm trying to store class objects in a vector:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
[Code]....
1. Am I storing it correctly?
2. How would I access the stored data, say, if I wanted to compare it to other stored data or COUT it?
View 1 Replies
View Related
Feb 11, 2012
I'm implementing kruskal's algorithm and ran into some troubles compiling. I need to sort a vector of objects by value. Here is my code and the error I'm getting.
Code:
These are the two functions in graph.cpp (there are more but are unrelated)
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
#include "graph.h"
#include "edge.h"
using std::vector;
void graph::sort_edgesArray() {
[code].....
//This is the error I'm getting.
graph.cpp: In member function "void graph::sort_edgesArray()":
graph.cpp:39:33: error: no matching function for call to sort
(std::vector<edge>::iterator&, std::vector<edge>::iterator&, <unresolved overloaded function type>)
/usr/include/c++/4.5/bits/stl_algo.h:5236:18: note: candidate is:
void std::sort(_RAIter, _RAIter, _Compare)
[with _RAIter = __gnu_cxx::__normal_iterator<edge*, std::vector<edge> >, _Compare = bool (graph::*)(edge&, edge&)]
View 3 Replies
View Related
Feb 23, 2014
I'm working on a code for ascertaining the minimum penalty of an assignment problem. The basic complication of my code is this: I have a vector of objects of a custom struct. The struct has a member, which is an integer. I need to keep the vector sorted according to that member, even when objects are added to or deleted from the vector. To illustrate the problem, I'll give an example.
Code:
typedef struct examplestruct{int i;
char c;
...} es;
int function(void)
{vector<es> ObjectTable;
//insert an object so that the vector remains sorted according to i
insertobject( newobject, &ObjectTable);
//deleting the top element of the vector
deleteobject(&ObjectTable);
return 0;}
I have tried to do it using bubblesort. But it's too slow. How to make a heap out of it.
The detailed premises of the problem is this: There are a number of jobs, and with each job a completion time and a cost coefficient. We are to ascertain the optimal sequence of jobs for which the penalty is minimum. Now, suppose we are given jobs A, B, C, D and E. We find out the lower bound of penalties for all the jobs.
Suppose we find B has the lowest penalty. Then we find out the lower bound of penalties for BA, BC, BD and BE. We continue this until we have the best value and a complete sequence. The way I have implemented this in a code: I have created two structs. One is Job, with the completion time and cost coefficient as members. The other is Node. Nodes have a Job Array and a Penalty as members. Now, we have a vector of Nodes which we need to keep sorted according to the penalty. We need to insert new Nodes and delete the expanded Nodes.
I have included my code. The pushInTable function inserts the new Nodes in a sorted vector. But it slows down remarkably when we give more than 20 jobs as input.
View 9 Replies
View Related
Mar 22, 2013
For a beginners C++ lab, I have a base class Employee and two derived classes HourlyEmployee and SalaryEmployee. In main, I have a vector defined as vector <Employee *> VEmp; It's then passed to a function to get the input, which works fine. But what I'm struggling with is another function with the header "printList(const vector <Employee *> & Ve)". It's supposed to loop through the vector and call the appropriate printPay function, which is a seperate print function inside each derived class. How do I loop through the vector and print it out? I was trying to do a for loop and something like "Ve[i].printPay();", but that doesn't work. So how would I do it?
Here's some snippets of the relevant code.
class Employee {
....
virtual void printPay() = 0;
};
class HourlyEmployee : public Employee {
[Code] ....
View 4 Replies
View Related
Jan 28, 2015
I'm working on collision detection for a game in SFML. I successfully designed a Spatial Partition grid to speed up the collision test, in the following of this tutorial: [URL] ....
But now I have an issue with one aspect of it: Going through a vector of objects and testing all the OTHER objects in the vector against said object. The author puts it into psueudocode here:
For each tick of the clock
For every object in the game
Get all the other objects in the same grid square
For each other object in the same grid square
I have trouble with the last line, because in iterating through a vector I am not sure how to skip over the current object. Here is my own code (a couple of sysntax errors but this is a c++ question not an SFML question):
//for every moveable object
for(int i = 0; i < rects_.size(); i++){
std::vector<sf::RectangleShape> posibleObjects_; //this will be a vector of WorldObjects in a real game
//for every object in that object's gridsquare
for(int j = 0; j < rects_.size(); j++){
if(rects_[i].intersects(rects_[j])){
//collision
} } }
The problem is, a collision will always be reported because somewhere in the vector the object will eventually check against itself which is always a true collision. What is the correct way to do this?
View 11 Replies
View Related
May 1, 2013
I have a vector of Car* objects - vector<Car*> cars
Each object in the vector has an integer attribute called passengers, which can be returned using the function getPassengers().
How do I sort the vector by the objects' passenger int? I know I need to use sort() and presumably a comparison function but I'm not quite sure how.
View 2 Replies
View Related
Nov 5, 2014
Im creating a program for a race. The Race class has a vector of results and each element of that vector is a pointer to a result. The Result class has a Time and a pointer to a Participant. So in each race there are various results and it is a result for each participant.The Time is a class that has hours, minutes and seconds. How can I sort the vector of results from the result of the participant with the fastest time to the result of the participant with the slowest time?My code is like this:
//.h file:
class Time {
unsigned int hours;
unsigned int minutes;
unsigned int seconds;
[code]....
What am I missing to get my code to work?
View 9 Replies
View Related
May 9, 2013
I have a pointer to a vector of objects, each object has an array and a couple of strings. how to access the data in the objects via the pointer.
Best tree::chooseSplit(vector <pgm> *ptr)
{
Best splits;
cout<<ptr[1].filePath; //not working!!!
}
filepath is a string in the pgm object. i also need to be able to access elements in an array that also exists in pgm.
View 2 Replies
View Related
Dec 9, 2013
I'm having the same problem : [URL] .....
Though, my vector isn't one of int, it is a vector of objects from another class and NetBeans won't compile it.
#include <cstdlib>
#include<vector>
#include <string>
#include<iostream>
using namespace std;
class estoque{
[Code] .....
View 3 Replies
View Related
Nov 5, 2014
Im creating a program for a race. The Race class has a vector of results and each element of that vector is a pointer to a result. The Result class has a Time and a pointer to a Participant. So in each race there are various results and it is a result for each participant. The Time is a class that has hours, minutes and seconds. How can I sort the vector of results from the result of the participant with the fastest time to the result of the participant with the slowest time?
Im getting some errors in my code. I put the error as comments in the code. Each error is after the line where it occurs. My code is like this:
//.h file:
class Time
{
unsigned int hours;
[Code]....
View 8 Replies
View Related
Nov 2, 2014
I've a vector of objects that I can get my float value from by accessing it through a method.It's not a pointer of vector of objects though.
Meaning it's something like vector[i].getFloatValue().
However,how do I sort the float values by descending order since I access it through a method?
View 6 Replies
View Related
Feb 27, 2014
class A; //forward defined in class B.h
class B
{
private:
[Code]....
I get error message forward Declaration of class A;
What is going on here. Is there a way I could initialize all the vectors of type B to be set to NULL in the constructor?
View 6 Replies
View Related
May 16, 2013
Say I have a vector of objects and I want to return an object based on a pair of strings. The strings can be in either order Ie; A B==B A.
In general, what do you think is the best way to do this?
View 5 Replies
View Related
Apr 18, 2013
I am having a problem with a program. I have a bunch of classes all derived from the same base class. I want to loop through a vector of objects, calling a function in each. The problem is that it doesn't matter which class the objects are, only the function defined in the base class is called.
I simplified the code as far as possible to replicate the problem. As you see, I would like a mix of numbers 1,2,3 as the output, however using the vector the only number output is 1. Here is a copy of the output by the way:
base->num() : 1
a->num() : 2
b->num() : 3
(*it)->num() : 1
(*it)->num() : 1
(*it)->num() : 1
I suspect this is the "slice" problem, because the vector is defined with pointers to the base class so it uses the base class functions? The question is how to get around it? How can I loop through a vector of objects sharing the same base class but calling each by their correct member functions?
Code:
#include <iostream>
#include <vector>
class Base {
public:
int num() { return 1;}
[Code] .....
View 5 Replies
View Related
Mar 5, 2013
I need manipulating a set of containers. I created a vector that contained vectors of objects:
std::vector< std::vector<Terrain> > mapArray(num1, std::vector<Terrain>(num2));
where num1 and num2 are arbitrary numbers. and Terrain is the class of objects I'm trying to store.
I want to be able to use push_back on both the main vector and the vectors within the mapArray vector but I'm unsure of how to target the inner vectors with push_back. How to dynamically store a 2D array of objects.
View 10 Replies
View Related
Oct 13, 2013
I just created an object who store a vector of size 7 with random numbers between 1 and 36. If i declare two objects i get different vector, but running many times the program i always get the same vectors . For example, if i declare one object, even if i run any time the program, i always get the same numbers.
I am using the function
num= rand()%36+1,
wasn't it supposed to generate randoms numbers?
View 7 Replies
View Related
Dec 10, 2014
I have a small class and a vector to hold the objects.
Code:
class result_holder {
public:
// initialize class members
[Code]....
The purpose is to keep results and be able to sort the results on row_value while keeping the id and name values in registration with the row_value. I am running allot of tests and keeping the top n results. The idea is to sort the vector so that I can just examine the object in the last element to see if it should be replaced by a better result.
I know that this kind of thing is often done with an overloaded operator or a functor, but I am a bit out of my depth with that, especially determining what class variable will be used for the sort. sorting the above objects on the row_value variable?
View 14 Replies
View Related