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


ADVERTISEMENT

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++ :: 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++ :: Sorting Vector Of Complex Objects Using Custom Function

Mar 6, 2014

I am trying to use std::sort to sort a vector of complex objects using a custom function. However, it keeps erroring "Unresolved overloaded function type".

encounter::encounter(){
// ... cut
std::sort (allpeople.begin(), allpeople.end(), sortByInit);}
bool encounter::sortByInit (character& a, character& b) {
if (a.getinit () == b.getinit ()) {

[Code] ....

View 6 Replies View Related

C++ :: Sorting Array Of Mixed Float?

Oct 25, 2014

I should sort an array of mixed float and integer numbers by merge method, and using the pointers to sort that mix array. how to use pointers to sort those different type of data.

View 19 Replies View Related

C++ :: Two Vectors Of Float - Sorting In Reverse Order?

Jul 15, 2013

I have two vectors of float that I need to sort in reverse order. reverse() seems to work for one of them, but not the other. I have toggled between sort() and reverse(). for one vector, the expected behavior is seen and the order reverses. For the other, there is no change in order.

This is very simple code, so it's hard to imagine what is going wrong.

Code:
vector<float> vec1, vec2;
vec1[0] = 14.1102; vec1[1] = 14.1145;
vec2[0] = 15.8508; vec2[1] = 26.0842;
sort( vec1.begin(), vec1.end() );
sort( vec2.begin(), vec2.end() );

[Code] ......

Printout is,

Code:
vector 1 sort
14.1102
14.1145
vector 2 sort
15.8508
26.0842

vector 1 reverse
14.1102
14.1145
vector 2 reverse
26.0842
15.8508

You can see that the order of the first vector did not change. Am I right in suspecting that the numbers are too similar for what ever method reverse() uses to determine the difference between values?

View 8 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 Of Object In A Vector

Oct 24, 2013

I'm new to C++ especially vectors.. I've a question regarding sorting of object in a vector.. My object consists of x,y and civ. so I would like to know how do I sort the value of the civ in an descending order but at the same time retaining the value of x and y attached to it..

original
X: 4 Y: 5 CIV: 10
X: 3 Y: 2 CIV: 30
X: 3 Y: 3 CIV: 05

sorted
X: 3 Y: 2 CIV: 30
X: 4 Y: 5 CIV: 10
X: 3 Y: 3 CIV: 05

missionplan.cpp
void MissionPlan::topfives() {
stable_sort (topfive.begin(), topfive.end());
pointtwoD = topfive.at(i);
pointtwoD.displayPointdata();
}

View 2 Replies View Related

C++ :: Sorting On Two-dimensional Vector

Oct 30, 2012

Suppose I have a two-dimensional stl vector (a vector of vectors), for example:

Code : vector<vector<int> > x;

And then I want to sort the outer vectors in order of the size of their inner vectors. How do I do this?

Usually, with a one-dimensional vector, I can just create a comparison function and use the sort function. For example, if my vector is defined as:

Code:
vector<int> y;

And I want to sort if in terms of the int values of each vector element, then I can sort by using the stl::sort function, with the comparison function defined as:

Code:
static bool SortFunction(int val1, int val2) {
if (val1 > val2) {
return true;
} else {
return false;
}
};

However, with my two-dimensional vector, I use the following comparison function:

Code:
static bool SortFunction(vector<int> vec1, vector<int> vec2) {
if (vector1.size() > vector2.size()) {
return true;
} else {
return false;
}
};

I get a runtime error:

"Debug Assertion Failed!
File: c:Program Files (x86)Microsoft Visual Studio 10.0VCincludealgorithm
Line 3686
Expression: invalid operator<"

Why is this?

View 2 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++ :: 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++ :: 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++ :: Sorting Vector Of Strings Alphabetically

Aug 30, 2014

I'm trying to write a program that reads in from a .txt file the movie title, rating, director, actors etc. All I want to do is to just sort movie titles alphabetically and print all its attributes(director, actors). I tried using sort( movies.begin(), movies.end()) method, but it doesn't work.

here's my code btw:

#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <algorithm>
#include <iterator>
#include "Movie.h"

[Code]...

View 2 Replies View Related

C++ :: Sorting Function - Vector Swap

Jun 26, 2013

writing a sorting function that has an argument for a vector of ints rather than an array; it should use a selection sort algorithm.Here is what I have:

#include <iostream>
#include <vector>
#include <conio.h>
using namespace std;
void fillVector(vector<int> &aVector);
// PRECONDITION: number declared size of array a.
// POSTCONDITION: number_used is the number of values stored in a
//a[0] through a[number_used-1] have been filled with nonnegative int.

[code].....

View 7 Replies View Related

C++ :: Vector Int Sorting In Ascending Order

Feb 17, 2015

I want to sort a vector int in ascending order, but when I test, the output isn't correct - the vector is still unsorted. Am I calling it incorrectly?

int sorted (vector <int> a) {
int size = a.size();
sort(a.begin(), a.end());

View 2 Replies View Related

C++ :: Sorting And Calculating Median Of A Vector?

Dec 1, 2014

I am trying to to pull data from a file into a vector, then calculate different statistics from said vector. I've got everything working great except for one part. The program requires the median be calculated, which means I need to sort the data in the vector. However I can't do a quick easy sort, I'm required to use the functions swap(double, double), sort(vector), and index_of_smallest.

how to get these all working in sync to calculate the median(not to mention my algorithms appear to be wrong as I return nothing but 0's for the median value.)

I'm either not sorting right, or the index_of_smallest function is supposed to be doing something I don't realize.

#include <iostream> // for screen and kbd io
#include <iomanip>
#include <fstream> // file io
#include <cstdlib> // for exit()
#include <cmath> // for sqrt
#include <string>
#include <vector>
using namespace std;
void fill_vector(ifstream& in_file,vector<double>& v);

[code]...

View 1 Replies View Related







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