Hi, guys. I'm writing a little game, and I want to include a high scores list.
I've got everything coded except for the sorting part. I want to use the std::sort() function, but I'm not quite sure how I could get it to work with the data in my vector.
Here is a sample high score file in which each line is inputted into a vector element. I want to sort by the score: - 2345 toefraz day time year
-
1009 toe day time year
-
8794 toejamb day time year
-
...
Any ideas?
8 3988
I sort of got it working by using - sort(v.begin(), v.end(), greater<string>());
but it is sorting the scores like this: - 975 toefraz Sun Jan 13 03:33:01 2008
-
550 toefraz Sun Jan 13 04:07:07 2008
-
440 toefraz Sun Jan 13 04:19:52 2008
-
330 toefraz Sun Jan 13 04:26:21 2008
-
323 toefraz Sun Jan 13 03:33:01 2008
-
25 toefraz Sun Jan 13 03:34:24 2008
-
220 toefraz Sun Jan 13 04:36:15 2008
-
220 toefraz Sun Jan 13 04:06:01 2008
-
1230 toefraz Sun Jan 13 03:33:01 2008
-
1090 toefraz Sun Jan 13 03:33:01 2008
whereas I need them to be sorted by numerical value. I'm pretty sure it's because i'm using strings and that's how they sort. How would I go about sorting them properly
Savage 1,764
Recognized Expert Top Contributor
You will need to create a simple struct,containi ng hi-score,name,and date(and other information you desire).After that you would create a vector of this structs and sort them by hi-score member.Offcours e you would need to write your own compare function and pass it as the third argument.
Oh ok. We haven't gotten to structs yet in class. I'll research them. Thanks for you help.
The STL (Standard Template Library) defines a group of algorithms that allow you to manipulate elements in containers through iterators. -
#include <iostream>
-
#include <vector>
-
#include <algorithm> // Added to be able to use the STL algorithms
-
-
using namespace std;
-
-
int main ()
-
{
-
// This is how you define an iterator in this case i made it constant
-
vector<int>::const_iterator iter;
-
-
cout << "Creating a list of scores.\n";
-
// declaring a vector named scores that contain integer object elements
-
vector<int> scores;
-
scores.push_back (4500);
-
scores.push_back (3500);
-
scores.push_back (234);
-
-
cout << "Printint the list of scores.\n";
-
for (iter = scores.begin(); iter != scores.end(); ++iter)
-
cout << *iter << endl;
-
-
cout << "\n\nSorting scores.\n";
-
sort (scores.begin(), scores.end());
-
for (iter = scores.begin(); iter != scores.end(); ++iter)
-
cout << *iter << endl;
-
-
system("PAUSE");
-
return (0);
-
}
-
You will need to create a simple struct,containi ng hi-score,name,and date(and other information you desire).After that you would create a vector of this structs and sort them by hi-score member.Offcours e you would need to write your own compare function and pass it as the third argument.
Hi, i think i tried to do what you mentioned but i am getting errors:
// sort algorithm example
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool myfunction (int i,int j) { return (i<j); }
class tryClass
{
public:
int a, b;
};
int main ()
{
tryClass *temp_Obj;
vector<tryClass > myvector;
vector<tryClass >::iterator it;
for(int i=1; i<= 8; i++)
{
temp_Obj = new(tryClass);
(*temp_Obj).a = 100 - i;
(*temp_Obj).b = i+10;
myvector.push_b ack(*temp_Obj);
}
// using function as comp
//sort (myvector.begin (), myvector.end(), myfunction);
// print out content:
cout << "myvector contains:" << endl;
for (it=myvector.be gin(); it!=myvector.en d(); ++it)
cout << " (" << (*it).a << ", " << (*it).b << ")" << endl;
cout << endl;
return 0;
}
Any suggestions?
sorry ... please ignore comment infront at the beginning of the sort line
phew, ok...i think i got it...(was making a lot of stupid mistakes!!)
below is what i think works....
// sort algorithm example
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class tryClass
{
public:
int a, b;
};
bool myfunction (tryClass& left, tryClass& right) { return ( left.a < right.a ); }
int main ()
{
tryClass *temp_Obj;
vector<tryClass > myvector;
vector<tryClass >::iterator it;
for(int i=1; i<= 8; i++)
{
temp_Obj = new(tryClass);
(*temp_Obj).a = 100 - i;
(*temp_Obj).b = i+10;
myvector.push_b ack(*temp_Obj);
}
// using function as comp
sort (myvector.begin (), myvector.end(), myfunction);
// print out content:
cout << "myvector contains:" << endl;
for (it=myvector.be gin(); it!=myvector.en d(); ++it)
cout << " (" << (*it).a << ", " << (*it).b << ")" << endl;
cout << endl;
return 0;
}
Laharl 849
Recognized Expert Contributor
That looks like it should work, though I have one comment: Every time you use new, get in the habit of using delete (or delete[] for arrays) to de-allocate the memory.
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: Allan Bruce |
last post by:
Hi there,
I am reading through accelerated c++, and have just finshed chapter 3.
My question is what sorting algorithm is used on vectors? e.g. if I had:
std::vector<int> scores;
// adding some values to scores
std::sort(scores.begin(), scores.end());
then what algorithm is used? or is this implementation specific?
|
by: Kitty |
last post by:
Hi, everyone.
Given a vector<int>, what is the fastest way to find out whether there is a
repeated element in it? The result is just "true" or "false". Thanks.
Kitty
|
by: asrock |
last post by:
i have prepared a code in c++ to save high scores and it is working well when i compile it in turbo c++and run the code .
but when i exit from the turbo c++ , the file to which i saved the high scores get corrupted and so when i again takes the turbo c++ , the files which i have written to the file are all missing . please help me . here is the code
#include<iostream.h>
#include<fstream.h>
#include<string.h>
#include<conio.h>
struct...
|
by: drkplaya |
last post by:
How do you push_back a vector in a vector? I have the following:
vector<string> &names, vector<vector<int> > &scores
while(fin.eof)
{
fin >> temp
names.push_back(temp)
while(fin.eof)
for(int i=0; i<scores.size(); i++)
scores.push_back(temp2)
|
by: marick66 |
last post by:
I'm trying to write a program that takes numbers from a text file and then sorts them first by name and then by the average. When I go to compile I get 3 overload errors and I can't figure out where I am going wrong, I haven't written the sorting functions yet I am just trying to get my read and write functions to work properly. Any help would be appreciated. Here is the code
#include <iostream>
using namespace std;
#include <fstream>...
| |
by: kyle christian |
last post by:
I am trying to save the high scores of a game I made. Now Im stumped on
trying to search through the file. Should I use a string, array, or one of
the STL containers to manipulate the information read from the file?
I have tried the
stringname.find("Name");
This only returns the first occurence, and doesn't look for other
occurences.
|
by: saytri |
last post by:
I am doing a game, where a user enters his name after playing the game. This name together with the percentage score are being written (stored) in a textfile called players.txt I am however trying to sort the percentage score with the highest placed on top. I have written this piece of code, but i'm stuck since altough the names and scores are being written on the file, they are not being sorted. Pls can someone help me sort them? Thanks a lot....
|
by: hamishmcgee |
last post by:
Ok, so for a project at university I have to create a High Score table in C++ with Visual Studio. Just to let you know this is my first year at university and also my first time ever learning C++.
So far I have a working menu, which lets you enter in your name, highscore and date which then gets saved to a file and is outputted via another option on the menu. I had a lot of trouble gettin the user info to save to a file in the first place, then...
|
by: makita18v |
last post by:
So my program works all right, but I can't read my information from a file into my vector, what am I doing wrong?
vector<char> grades;
grades.push_back ('A');
grades.push_back ('B');
grades.push_back ('C');
grades.push_back ('D');
grades.push_back ('E');
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
| |
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |