C++ :: How To Delete The Objects Within A Vector

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


ADVERTISEMENT

C++ :: Vector Delete Not Functioning

Dec 1, 2013

My delete is not working. Why?

Code:
struct MatchName{
MatchName(string& searchName) : s_(searchName) {}
bool operator()(const clsStudent* student) const {
return student->getName() == s_;

[Code] .....

View 4 Replies View Related

C++ :: Delete Pointers From Vector

Jul 25, 2013

I have something like this:

class A {
};

class B : public A {
};

class C : public A {
};

B*b1;
B*b2;
C*c1;
C*c2;

vector<A*>vec;

int main() {
vec.push_back(b1);
vec.push_back(b2);

[Code] ....

And it don't works at all. all i get (when playing with variations of this stuff until it compiles correctlly) is a memory leak.

For example, let say i have b1 address = 1234

I will effectively free the memory at 1234, but for a strange reason, the memory leak is elsewhere, for example, at 2345, and the memory value at this address is equal to... 1234, the address of the pointer i wanted to delete.

View 7 Replies View Related

C++ :: Find Object In Vector And Delete?

Dec 14, 2014

I have this class I have been working with,

Code:

// objects to hold results, row id, and name
class result_holder {
public:
// initialize class members
result_holder() : row_id(0), row_value(0.0), row_name("") { }

[Code] ....

There are cases where I need to find an object based on the value of row_id and delete the object from the vector row_results. I could find the proper object by looping through the vector and testing against each member.

Code:
// id I am looking for
unsigned int id_to_delete = 12;
for(i=0; i<row_results.size(); i++) {
if(id_to_delete == row_results[i].row_id) {
delete row_results[i];
}
}

I have used find before to find the position in a vector with a specific value, but I don't know how to use find to locate a specific value for an object member.

Also, is delete what I need to get rid of the object or should I be using erase as in,

Code:
// id I am looking for
unsigned int id_to_delete = 12;
for(i=0; i<row_results.size(); i++) {
if(id_to_delete == row_results[i].row_id) {
row_results.erase(row_results.begin()+i);
}
}

View 4 Replies View Related

C++ :: Bubble Search / Vector Delete

Apr 23, 2012

Just doing some work where i need to produce a database in C++ for DVD now I have done most of it but I'm stuck on some bits. I have split the database up into different files but I will post the files which are important. How to do a search function. I got told it's called "Bubble search" and then a delete function which i think is called "Vector delete".

My header file

Code:
#ifndef DVD_DB_H
#define DVD_DB_H
#include "dvd.h"
#include <vector>
class dvdDB {
private:
std::vector<DVD> dvds; // A container that contains an arry of DVDs

[Code] .....

View 1 Replies View Related

C++ :: Sequence Of Actions - Delete Pointer In Vector

Jul 29, 2013

I'm tying to create a program that evaluates all possible actions for a certain problem.

So what i'm basically trying to do is to create a sequence of actions, evaluate them to check if it's the best sequence, change the sequence, evaluate again and so on until all possible scenarios are exhausted, leaving the best one in the end.

My approach to this at first was to create a tree of all possible options and then evaluate each branch. Since there are a lot of possible cases i ran out of memory while the program was still creating the tree. I changed this to create just a branch, evaluate it and then modify it.

I was still getting memory problems. I declared a class tNode and declared a vector<tNode*> branch. Then i created all the nodes i needed for that branch with branch.push_back( new tNode() ). When i wanted to modify the branch i simply used branch.pop_back() and again a branch.push_back( new tNode() ). I figured i was getting the problem because although i clear the vector, i don't actually clear the reference in memory. Is this correct? If so, how can i actually delete the memory space and not just the pointer in the vector?

View 6 Replies View Related

C++ :: Delete Member Of Vector That Is Pointed By Pointer?

Apr 17, 2013

I have following:

struct Point {int* a; int b;};
vector<vector<Point> > numbers;
vector<int> example;

The numbers vector has a matrix of a sort and each of the members are pointing to one member in the example vector. A member numbers.at(2).at(3).a is pointing at example.at(3). Now, can I remotely delete a member in the example vector using the pointers? Like so:

delete (*(numbers.at(2).at(3).a));

I know there is a more convenient way to delete members, but this is a very specific case I'm working on.

View 3 Replies View Related

C++ :: The Proper Way To Do A Vector Of Objects

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

C++ :: Storing Objects Using Vector

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

C++ :: Class Objects In A Vector?

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

C++ :: Sorting A Vector Of Objects?

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

C++ :: Vector Of Int Class - How To Delete Pointer X In Destructor To Free Memory

Feb 25, 2015

An attempt to create a class which is basically a mimic of vector<int> i don't seem to know how to delete pointer x in a destructor to free memory, also on pushback and pushfront methods, i can't free y when i implement delete[] y; y=NULL; i get some NULL out put when cout 'ing the object in main, why is that happening and how do i free memory y.

#include<iostream>
using namespace std;
class vectorOfint{
int* x;
int size;
public:
vectorOfint();

[Code] .....

View 6 Replies View Related

C++ :: Sort Of Vector Of Custom Objects

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

C++ :: How To Loop Through A Vector Of Class Objects

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

C++ :: Testing Object Against All Other Objects In Vector?

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

C++ :: Sorting Vector Of Objects By One Of Their Attributes

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

C++ :: Sort Vector Of Pointers To Objects

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

C++ :: Accessing Vector Objects Via A Pointer?

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

C++ :: Class With A Vector Of Objects As Attribute

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

C/C++ :: Sort Vector Of Pointers To Objects?

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

C++ ::  Sorting Float In A Vector Of Objects

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

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 View Related

C++ :: Initializing Vector Of Objects With NULL

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

C++ :: Searching A Vector Of Objects For Pairs

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

C++ :: Loop Through A Vector Of Objects Calling A Function In Each

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

C++ :: Manipulating Set Of Containers - Vector Of Vectors Of Objects

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







Copyrights 2005-15 www.BigResource.com, All rights reserved