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


ADVERTISEMENT

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++ :: 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++ :: Sort Vector Of Objects On Member Variable?

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

C++ :: Hold Vector Of Pointers In Same Class As Instances Of Those Objects?

Feb 10, 2015

Using SFML, I had a Board class which held multiple vectors of all of my object types in the game, and then it also held a vector of pointers to the memory addresses of these object instances, like this

class Board{
//...
std::vector<AbstractObject*> GetAllLevelObjects(){ return allLevelObjects; }
//so these are used to hold my object instances for each level

[Code]....

When looping through this vector and drawing the sprites of the objects, I get the runtime error 0xC0000005: Access violation reading location 0x00277000. I solved this error by storing the vector of pointers in the class that holds my Board instance, but I'm wondering why only this solution worked? Why couldn't I just have my vector of pointers in the same class that the instances of those objects were in?

View 2 Replies View Related

C++ :: Vector Of Pointers - Push Back Objects / Constant Parameters

Apr 11, 2014

I have a class called Question:

#include <string>
#include <vector>
using namespace std;
class Question {
string title;
vector<Thing*> posAns;
vector<Thing*> negAns;

[Code] ....

error: no instance of overloaded function 'std::vector::push_back()' matches the arguments list
argument types are (const Thing *)
object type is: std:: vector<Thing *, std::allocator<Thing *>>

So it cannot be constant, what if I just leave it non-constant? Will it be safe?

View 2 Replies View Related

C/C++ :: WebForms - Sort Objects In ListBox

Feb 16, 2015

This is my second hw doing C# and I'm trying to sort my objects I have in the ListBoxes,when I remove them from the ListBox on the right then get added to the original ListBox(because when i click add it removes the item and sends them to the ListBox on the right),but when i add them the go at the end of the list and they order should matter,how can i sort the list after the were added back?

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//Patricio Vargas
public partial class _default : System.Web.UI.Page {

[Code] .....

View 3 Replies View Related

C++ :: Assignment Of Objects To Pointers

Jun 6, 2013

I am using OpenCV to read and manipulate a set of images, which I need to store in an array to work with them. Here is a snippet of the code:


#define MAX_IMAGES 8
typedef Mat* MatPtr;
int main(int argc, char** argv) {
char imageName[] = "./res/imageX.tiff";
MatPtr datacube[MAX_IMAGES];

[code].....

I have an array of pointers to Mat objects (an OpenCV class used to hold info and data about an image), which I will use to store the images. The function imread reads an image and returns a Mat object loaded with the relevant data about the image.However, this gives me a nice segfault when the assignment takes place. Of course, I can swap it with the following code, but since I'm working with big images (2048x2048 and upwards), it's really inefficient:

for(unsigned int i = 0; i < MAX_IMAGES; i++) {
imageName[11] = 49 + i;
datacube[i] = new Mat(imread(imageName, -1));
}

Is there any way to do this elegantly and without much hassle?Again, excuse my rustiness and anything completely stupid I might have said. It's been a long time since I worked with C++. Managed to circumvent the problem by using a STD vector instead of an array. I'd still like to know the answer to this riddle...

View 6 Replies View Related

C++ :: Using Array Of Pointers To Objects?

Sep 27, 2013

I've created an Array of pointers to objects using:

Person ** A = new person * [arraysize];

When I intend to access a specific person do I have to do this? :

something = A->[i];

and when I want a specific object within my struct do I have to do this? :

something_else = A->[i]->random_int;

View 10 Replies View Related

C++ :: Array Of Pointers To Objects?

Dec 5, 2013

my code:

int OKCount=0;
int WaitingCount=0;
int ReservationCount=0;
Flight::Flight(int capacity, int waitingMax) {
seats=capacity;

[code].....

reservations is a data member in the class flight as:

Reservation **reservations;

OKReservation is a derived class and its abstract base class is Reservation.

My problem is that the reservations array loses its value in other function

View 8 Replies View Related

C/C++ :: How To Add Objects To A List Of Pointers

Apr 14, 2014

I have a data structure defined up here called this:

typedef list <classSpec*> ClassSpecList;

I'm trying to add stuff into the list here based on functions that return certain values of that match the same data type. In one function, I have a list pointer object defined here and I have another statement that calls a function.

ClassSpecList *answer = 0;
classSpec *thisanswer = parseClass(br);

Basically I'm trying to add the results of what thisanswer returns into my main ClassSpecList. Problem is, when I try

answer->push_back(new classSpec (*thisanswer));

It compiles but I get a seg fault

When I try somethign else like:

answer->insert(ClassSpecList.begin(), *thisanswer);

I keep getting primary expression errors and I do not know why. I even tried it with other list made without typedef and I still get those.

View 6 Replies View Related

C++ :: Selection Sort On Array Of Class Objects?

Jan 24, 2013

I have written a selection sort algorithm to go sort an array of class objects by age in ascending order, the problem is that the output being given does not match what i think the code should do. when the program runs the 3 records are added to the array and when they are sorted should be outputed in ascending order, the problem is that with my code the last 2 are sorted properly but the first element does not seem to move, it remains the same as the original unsorted value.

My code for the selection sort function and the display method are below:

void selectionSort() {
int i, minIndex, minValue;
for (i = 0; i < (arrlength - 1); i++) {
minIndex = i ;

[Code].....

View 1 Replies View Related

C++ :: Filling Vectors With Pointers To Account Objects

Jul 27, 2013

So I'm trying to fill a vector with pointers to account objects.

std::vector<account*> fill_vector() {
std::vector<account*> temp;
std::ifstream s;
std::string str;
s.open("H://account2.dat");

[Code] ....

The accounts have four different types and I am supposed to skip over ones that have an invalid account type and throw an exception:

account* factory(std::string account_code, std::string first_name,
std::string last_name, char type, double balance) {
try {
if(type == 'A') {
simple_account *a = new simple_account(account_code, first_name, last_name, balance);

[Code] .....

My problem is they program will not skip over my rejected accounts.. still adds them to the vector but I cant figure out why!

View 8 Replies View Related

C++ :: Transfer Ownerships Between Objects (passing Arguments) Using Raw Pointers?

Sep 4, 2012

Code:
void Class1::Func(shared_ptr<type1> parameter)
{
}
or
void Class1::Func(const shared_ptr<type1>& parameter)
{
}
or
Should I ever pass arguments/parameters to other objects using shared_ptr's or raw pointers?

View 3 Replies View Related

C++ :: Merge Sort Destructor - Using Delete On All Pointers On Stack

Apr 7, 2014

How can I use "delete[]" on all pointers on the stack, using a mixture of top and pop functions or variables

View 2 Replies View Related

C++ :: Using Smart Pointers To Sort And Relink Potentially Large Data Elements

Feb 20, 2014

I am trying to use smart pointers to sort and re-link potentially large data elements. I have defined a class in my code for smart pointers, as listed below:

template <typename T>
class sptr {
public:
sptr(T *_ptr=NULL) { ptr = _ptr; }

[Code] ....

The object I'm trying to sort is a singly-linked list containing class objects with personal records (i.e., names, phone numbers, etc.). The singly-linked list class has an iterator class within it, as listed below.

template <class T>
class slist {
private:
struct node {
node() { data=T(); next=NULL; }

[Code] .....

The following is my function within my list class for "sorting" using the smart pointers.

template <typename T>
void slist<T>::sort(){
vector< sptr<node> > Ap(N); // set up smart point array for list
//slist<T>::iterator iter = begin();
node *ptrtemp = head->next;

[Code] .....

I must have a bad smart pointer assignment somewhere because this code compiles, but when I run it, std::bad_alloc happens along with a core dump. Where am I leaking memory?

View 6 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++ :: 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 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++ :: 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++ :: 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







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