473,786 Members | 2,462 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

vector sort for high scores

19 New Member
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:

Expand|Select|Wrap|Line Numbers
  1. 2345     toefraz     day time year
  2. 1009     toe           day time year
  3. 8794     toejamb    day time year
  4. ...
Any ideas?
Jan 13 '08 #1
8 3988
toefraz
19 New Member
I sort of got it working by using
Expand|Select|Wrap|Line Numbers
  1. sort(v.begin(), v.end(), greater<string>());
but it is sorting the scores like this:

Expand|Select|Wrap|Line Numbers
  1. 975       toefraz   Sun Jan 13 03:33:01 2008
  2. 550       toefraz   Sun Jan 13 04:07:07 2008
  3. 440       toefraz   Sun Jan 13 04:19:52 2008
  4. 330       toefraz   Sun Jan 13 04:26:21 2008
  5. 323       toefraz   Sun Jan 13 03:33:01 2008
  6. 25        toefraz   Sun Jan 13 03:34:24 2008
  7. 220       toefraz   Sun Jan 13 04:36:15 2008
  8. 220       toefraz   Sun Jan 13 04:06:01 2008
  9. 1230      toefraz   Sun Jan 13 03:33:01 2008
  10. 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
Jan 13 '08 #2
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.
Jan 13 '08 #3
toefraz
19 New Member
Oh ok. We haven't gotten to structs yet in class. I'll research them. Thanks for you help.
Jan 13 '08 #4
intOwnsVoid
11 New Member
The STL (Standard Template Library) defines a group of algorithms that allow you to manipulate elements in containers through iterators.

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm> // Added to be able to use the STL algorithms
  4.  
  5. using namespace std;
  6.  
  7. int main ()
  8. {
  9.     // This is how you define an iterator in this case i made it constant
  10.     vector<int>::const_iterator iter; 
  11.  
  12.     cout << "Creating a list of scores.\n";
  13.     // declaring a vector named scores that contain integer object elements
  14.     vector<int> scores; 
  15.     scores.push_back (4500);
  16.     scores.push_back (3500);
  17.     scores.push_back (234);
  18.  
  19.     cout << "Printint the list of scores.\n";
  20.     for (iter = scores.begin(); iter != scores.end(); ++iter)
  21.         cout << *iter << endl;
  22.  
  23.     cout << "\n\nSorting scores.\n";
  24.     sort (scores.begin(), scores.end());
  25.     for (iter = scores.begin(); iter != scores.end(); ++iter)
  26.         cout << *iter << endl;
  27.  
  28.     system("PAUSE");
  29.     return (0);
  30. }
  31.  
Jan 13 '08 #5
amalestale
3 New Member
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?
Jan 29 '08 #6
amalestale
3 New Member
sorry ... please ignore comment infront at the beginning of the sort line
Jan 29 '08 #7
amalestale
3 New Member
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;
}
Jan 29 '08 #8
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.
Jan 29 '08 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

3
5651
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?
16
2742
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
0
2229
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...
0
1075
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)
0
2633
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>...
4
5421
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.
1
1166
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....
3
8902
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...
2
2050
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');
0
9647
marktang
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...
0
10164
jinu1996
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...
1
10110
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,...
0
9961
tracyyun
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...
0
8989
agi2029
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...
1
7512
isladogs
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...
0
5397
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...
2
3669
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
bsmnconsultancy
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...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.