I'm learning C++ and I'm trying to figure out a method that involves switching out a card in the list below.
for example:
ace of spades
king of hearts
four of clubs
two of hearts
two of clubs
How would I go about exchanging 2, 3, and 5 each for a new card.
Ok so here is my code, i have other header files that it also uses but I think that you guys should be able to understand stand where I going with it.
#ifndef POKERGAME_H
#define POKERGAME_H//guard code
#include <iostream>
#include <iomanip>
//don't need to add .cpp files
#include "Card.h"
#include "Deck.h"
#include "Hand.h"
class PokerGame
{
public:
void playGame()
{
PokerGame play;
Deck myCard;
Hand hand;
Hand list;
cout << "***Simple 5-card Poker***" << endl;
//get a brand new card and places it in position
hand.setCard(0, myCard.getNextCard());
hand.setCard(1, myCard.getNextCard());
hand.setCard(2, myCard.getNextCard());
hand.setCard(3, myCard.getNextCard());
hand.setCard(4, myCard.getNextCard());
cout << "The cards have been shuffled and you are dealt " << endl
<<"1."<< hand.getCard(0).printName() << endl//then i ask what is the name of the card in that position
<<"2."<< hand.getCard(1).printName() << endl
<<"3."<< hand.getCard(2).printName() << endl
<<"4."<< hand.getCard(3).printName() << endl
<<"5."<< hand.getCard(4).printName() << endl;
//ask for users input and store them in an array
int stop = 0;
int user_input[6];
int counter = 0;
while((stop != -1) && counter < 6 )
{
cout << "Indicate the cards that you would like to exchange (-1 to end): ";
cin >> user_input[counter];
if(user_input[counter] > 5 || user_input[counter] < 0 || user_input[counter - 1] == user_input[counter])
{
cout << "Invalid input" << endl;
if(user_input[counter] == -1)
{
stop = -1;
cout << "...Oh nevermind...ended" << endl;
}
}
counter++;
}
This is where I'm having trouble, I'm only getting #1 on the list to change. When only the user inputs numbers should be changed. How do I change the code to make this happen?
//now remove the desired card from the player's hand
for(int i = 0; i < sizeof(user_input); i++ )
{
if(user_input[i] = 1)
{
hand.setCard(0, myCard.getNextCard());//change #1 on the list
}else if(user_input[i] = 2)
{
hand.setCard(1, myCard.getNextCard());//#2
}
else if(user_input[i] = 3)
{
hand.setCard(2, myCard.getNextCard());//#3
}
else if(user_input[i] = 4)
{
hand.setCard(3, myCard.getNextCard());//#4
}
else if(user_input[i] = 5)
{
hand.setCard(4, myCard.getNextCard());//#5
}
}
cout << "You new hand is: " << endl
<<"1."<< hand.getCard(0).printName() << endl//then i ask what is the name of //the card in that position
<<"2."<< hand.getCard(1).printName() << endl
<<"3."<< hand.getCard(2).printName() << endl
<<"4."<< hand.getCard(3).printName() << endl
<<"5."<< hand.getCard(4).printName() << endl;
2 problems:
1) You don't initialize user_input. Do:
int user_input[6] = {};
to set all elements to 0.
2) Your conditions in the are all assigning instead of comparing...
if(user_input[i] = 1)
should be:
if(user_input[i] == 1)
// ^ - missing equal sign
Related
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string getItemName(int k) {
if(k == 0) {
return "Sunkist Orange";
} else if(k == 1) {
return "Strawberry";
} else if(k == 2) {
return "papaya";
} else if(k == 3) {
return "Star Fruit";
} else if(k == 4) {
return "Kiwi";
}
return "";
}
int main() {
double prices[] = {2.00, 22.00, 5.00, 6.00, 10.00};
double total = 0.0;
string cart[50];
int key = 0;
int weight = 0;
int index = 0;
cout << "Welcome to Only Fresh Fruit Shop\n\nToday's fresh fruit <Price per Kg>\n";
cout << "0-Sunkist Orange RM2\n";
cout << "1-Strawberry RM22\n";
cout << "2-Papaya RM5\n";
cout << "3-Star Fruit RM6\n";
cout << "4-Kiwi RM10\n";
while (key != -1) {
double current = 0.0;
cout << "Enter fruit code <-1 to stop>: " << endl;
cin >> key;
if (key == -1) {
break;
}
cout << getItemName(key) << endl;
cout << "Enter weight <kg> : " << endl;
cin >> weight;
current = prices[key] + weight;
total = total + current;
}
cout << "-------------------------------------------------------\nReciept\n";
for(int i = 0; i < index; i++) {
cout << cart[i] << "\n";
}
cout << "TOTAL = RM" << total << endl;
return 0;
}
This is my code so far. The system have to display what fruit the user have chosen at in the receipt. My code is not working on the receipt part. Is there any other way on how to improvise the code to make it simpler? How can I improvise?
At very first you can re-organise your data better:
struct Product
{
std::string name;
double price;
};
This struct keeps the data closely related to a single product (fruit in this case) together locally.
You might organise these in an array (preferrably std::array, alternatively raw) making access to simpler – making your getItemName function obsolete entirely. Instead of a static array a std::vector would allow to manage your products dynamically (adding new ones, removing obsolete ones, ...).
You can even use this array to output your data (and here note that your condition in the while loop is redundant; if the inner check catches, the outer one cannot any more as you break before; if the inner one doesn't, the outer one won't either, so prefer a – seeming – endless loop):
std::vector<Product> products({ {"Apple", 2.0 }, { "Orange", 3.0 } });
for(;;)
{
std::cout << "Welcome ... \n";
for(auto i = products.begin(); i != products.end(); ++i)
{
std::cout << i - products.begin() << " - " << i->name
<< " RM " << i-> price << '\n';
}
// getting key, exiting on -1
if(0 <= key && key < products.size()
{
// only now get weight!
}
else
{
std::cout << "error: invalid product number" << std::endl;
}
}
Now for your cart you might just add indices into the vector or pointers to products – note, though, that these will invalidate if you modify the vector in the mean-time – if you do so you need to consider ways to correctly update the cart as well – alternatively you might just empty it. Inconvenient for the user, but easy to implement…
In any case, such a vector of pointers to products would easily allow to add arbitrary number of elements, not only 50 (at least as much as your hardware's memory can hold...) and would allow for simple deletion as well.
Calculating the full price then might occur only after the user has completed the cart:
// a map allows to hold the weights at the same time...
std::map<Product*, weight> cart;
for(;;)
{
// ...
if(0 <= key && key < products.size()
{
double weight;
std::cin >> weight;
// TODO: check for negative input!
// (always count with the dumbness of the user...)
cart[&products[key]] += weight;
// note: map's operator[] adds a new entry automatically,
// if not existing
}
}
Finally you might iterate over the cart, printing some information and calculating total price for the shopping cart:
double total = 0.0;
for(auto& entry : cart) // value type of a map always is a std::pair
{
std::cout << entry.first->name << "..." << entry.second << " kg\n";
total += entry.first->price * entry.second;
// note: you need MULTIPLICATION here, not
// addition as in your code!
}
std::cout << "Total price: RM " << total << std::endl;
This should do it whilst staying close to original code, I also improved you're method of gathering price/name a bit, try to catch the out of index exceptions or check if current index is NULL. Good luck!
#include <iostream>
#include <string>
#include <sstream>
#include <vector>;
using namespace std;
std::vector<std::string> itemList = {"Sunkist Orange", "Strawberry", "Papaya", "Star Fruit", "Kiwi"};
//If you dont want this to be global put it in the getItemName function
string getItemName(int k) {
return itemList.at(k);
}
int main() {
std::vector<double> prices = { 2.00, 22.00, 5.00, 6.00, 10.00 };
double total = 0.0;
int key = 0, weight = 0;
cout << "Welcome to Only Fresh Fruit Shop\n\nToday's fresh fruit <Price per Kg>\n";
cout << "0-Sunkist Orange RM2\n";
cout << "1-Strawberry RM22\n";
cout << "2-Papaya RM5\n";
cout << "3-Star Fruit RM6\n";
cout << "4-Kiwi RM10\n";
while (key != -1) {
double current = 0.0;
cout << "Enter fruit code <-1 to stop>: " << endl;
cin >> key;
if (key == -1) {
break;
}
cout << getItemName(key) << endl;
cout << "Enter weight <kg> : " << endl;
cin >> weight;
current += prices.at(key) + weight;
total += total + current;
cout << "-------------------------------------------------------\nReciept\n";
cout << "Purchased: " << getItemName(key) <<" "<< "TOTAL = RM" << total << "\n" << endl;
}
return 0;
}
I noticed there is a string cart[50] and int index = 0which you did not use throuoght the whole code except printing it at the end of the code. I am guessing that you want to add the fruit into the cart but it seems like you have not done so.
double price[50];
while (key != -1) {
double current = 0.0;
cout << "Enter fruit code (<-1> to stop): ";
cin >> key;
if (key == -1) break;
cout << getItemName(key) << endl;
cout << "Enter weight <kg> : ";
cin >> weight;
cart[index] = getItemName(key);
price[index] = prices[key] * weight;
total += price[index];
index++;
}
for (int i = 0; i < index; i++) {
cout << cart[i] << " " << price[i] << endl;
}
I have added some code so that cart[index] = getItemName(key). When you print each element of cart, it will now work. Also, current = prices[key] * weight is the correct one, not addition (unless your rules are different).
on a side note are you malaysian
I am trying to practice my C++ in order to grasp a better understanding in class, as I am a beginner and a little behind, and I came across a zombie game that someone posted online.
Anyways, I understand most of the code, however I do not understand "if(rand() & 67 < 10)".
I can interpret "rand() % 10 + 1", in which the code will generate a number, or in this case zombies, between 1 and 10.
Thinking at first that the zombies would cap at 67, given the player had chosen a high number, but I don't believe that is its function, but again, I'm not entirely sure...
Here is an example of the code I am looking at:
I'm sure its something simple, however I am still confused on its purpose. Even after trying to learn its function my running the game
Here is the whole code just in case:
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
using namespace std;
int createZombie() { // createZombie function OPEN
if(rand() % 67 < 10)
return 11;
else
return rand() % 10 + 1;
} // createZombie fuction CLOSED
// #################### MAIN FUNCTION ############################
int main() { // main function OPEN
srand(time(NULL));
char enter;
// game stats
int playerAlive = true;
int playerSkill = 9;
int playerScore = 1;
string playerName = "";
int zombieCount = 0;
int zombiesKILLed = 0;
// title
cout << "Welcome to Zombie War." << endl << "Press [ENTER] to start ";
cin.get();
// player name
cout << "Please enter your name: ";
cin >> playerName;
// ask how many zombies
cout << "How many zombies do you wish to fight? ";
cin >> zombieCount;
cout <<"Get ready to fight for you life, " << playerName << "!" << endl;
// main game loop
while(playerAlive && zombiesKILLed < zombieCount) { // while loop OPEN
// create a random zombie
int zombieSkill = createZombie();
// battle sequence
if(zombieSkill > 10) { // if statment OPEN
cout << endl << "Here comes a huge zombie! " << endl;
} // if statement CLOSED
else { // else statement OPEN
cout << endl << "Here comes Zombie " << zombiesKILLed + 1 << endl;
} // else statement CLOSED
cout << "Fighting... " << endl;
sleep(2);
// zombies killed the player
if(playerSkill < zombieSkill) { // if statement OPEN
playerAlive = false;
cout << "You have died." << endl;
} // if statement CLOSED
else { // else statment OPEN
// PLAYER KILLED THE ZOMBIE
if(playerSkill - zombieSkill > 7) { // if statement OPEN
cout << "You wasted the Zombie! " << endl;
playerScore = playerScore * 2;
} // if statment CLOSED
else if (playerSkill - zombieSkill > 5) { // else if statement OPEN
cout << "You decapitated the Zombie!" << endl;
playerScore = playerScore * 2;
} // else if statement CLOSED
else if (playerSkill - zombieSkill > 0) { // else
if statement OPEN
cout << "You Killed the Zombie!" << endl;
playerScore = playerScore * 2;
} // else if statment CLOSED
else { // else statment OPEN
cout << "You killed the zombie, but suffered injuries." << endl;
} // else statment CLOSED
zombiesKILLed++;
} // else statment CLOSE
cout << endl;
sleep(1);
} // while loop CLOSED
if(zombiesKILLed == zombieCount) { // if statement OPEN
// victory
cout <<"Your have survived the onslaught!" << endl;
} // if statement CLOSED
else { // else statement OPEN
// LOST
cout << "You did not survive the zombie war" << endl;
} // else statement CLOSED
cout << "Zombies killed: " << zombiesKILLed << endl;
cout << "Final score: " << playerScore << endl << endl;
} // main function CLOSED
Splitting the command into two parts for easy understanding:
Part I-
rand() % 67
= generate any random number from 0-66
= remainder of division of any number by 67
= N (say)
Part II
if( rand() % 67 < 10)
= if( N < 10)
I am facing difficulties in my C++ code. I am a beginner. Like, only with very basic knowledge of C++. So, I really can't figure a way to do this. I thought of making an RPG game using C++ commands and am close to finishing it. But somehow, I couldn't make a constant health for the hero. Taking a look at the code,
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
class player
{ public:
int health = 100;
};
int battle();
void death();
int main()
{
int abc;
player hero;
hero.health = abc;
int a;
int replay = 1;
cout << "You have 100 Hp. \n";
while (replay == 1)
{
srand(time(0));
cout << "\n Press 1 to move forward; 2 To stay. \n";
cin >> a;
if (a == 2)
{
if (rand() % 4 + 1 != 1)
{
cout << "You stay at your place. \n";
}
else
{
cout << "Enemy Attacks! (20 Hp) \n";
//battle(hero.health);
//cout << "\n Press 1 to continue. \n";
cout << "\n Do you want to play again? Press 1 to replay and 0 to quit.\n";
cin >> replay;
}
}
else if (a == 1)
{
if (rand() % 2 + 1 != 1)
{
cout << "You moved forward. No one around. \n";
}
else
{
cout << "You move forward. Enemy attacks! (20 Hp) \n";
battle(abc);
cout << "\n Do you want to play again? Press 1 to replay and 0 to quit.\n";
cin >> replay;
}
}
else
{
cout << "Sorry. Please enter a valid move. \n";
}
}
return 0;
}
int battle(int x)
{
player enemy;
enemy.health = 20;
player hero;
int y;
while (enemy.health >= 0)
{
int eattack = rand() % 15 + 7;
int attack = rand() % 10 + 1;
int escape = rand() % 4 + 1;
cout << "\n Press 1 to attack. 2 to flee \n";
cin >> y;
if (y == 2)
{
if (escape != 1)
{
cout << "Can't escape! \n";
cout << "Enemy attacked! Dealing a damage of: " << eattack << " Hp. \n";
hero.health = hero.health - eattack;
cout << "Your Hp is: " << hero.health;
}
else
{
goto Aftermath;
}
}
else if (y != 1)
{
cout << "Sorry. Please enter a valid response. \n";
}
else
{
cout << "You attack the enemy. \n";
cout << "You deal a damage of: " << attack;
enemy.health = enemy.health - attack;
if (enemy.health >= 0)
{
cout << "\n Enemy attacks you, dealing: " << eattack << " Hp damage.";
hero.health = hero.health - eattack;
cout << "\n You have: " << hero.health << " Hp left.";
}
}
if ((hero.health <= 0) || (hero.health == 0))
{
death();
enemy.health = -1;
}
}
if (hero.health > 0)
{
cout << "\n Enemy fainted!";
//cout << "You found Hp Potion! Your Hp was refilled.";
}
Aftermath:
if ((hero.health > 0) && (enemy.health > 0))
{
cout << "Escaped Successfully! \n";
}
return x;
}
void death()
{
cout << "You died!";
}
As you see, I have called for battle(abc) and battle(hero.health) [which I have commented for now] but the problem is, it says "Too many arguments to function int battle(). Previously, I simply avoided parameters and created object "hero" in the battle method itself. But every time you get through a battle sequence, it comes back and declares it again, thus making its health refill. [Look at if (hero.health > 0) ]
I really don't know about global variables and all that. I just want to know if there is a workaround or a way to solve this parameter problem. Any other suggestions to have health as a 'constant' and not declared every time is also warmly accepted. Thank you so much!
P.S. Suggestions for shortening the code also accepted but please, I am a beginner. So advanced strategies are beyond my skills right now. I take time to grasp concepts.
You declare the function before the main method, and then you implement the function after the main method.
The problem is, you implement the function as:
int battle(int x)
but this doesn't match your declaration:
int battle();
Just change your function declaration block so the battle function matches the expected signature:
int battle(int x);
void death();
That will get your code compiling, but you are still a number of steps from getting this to work.
I'll give you one starter: instead of passing in the hitpoints into battle, pass the entire player.
void battle(Player &player)
{
// ...
}
Then you can modify the player's hitpoints directly in the battle function.
You would then call this with:
battle(hero);
Attempting a basic C++ challenge, (beginner at C++) and I produced this code. I understand that calling a value in an array starts from zero but I wanted the user to type from 1-5 instead of 0-4 because I didn't want to go the easy route and wanted to see if I could do it.
Here is my problem, I made a basic function to subtract 1 from the int choice to allow the user to enter 1-5 but the array see the value as 1-4. However as shown in this image it seems to ignore my function and skip to the next part of the code. I have included my code below.
#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;
string drink[5] = { "Coke", "Water", "Sprite", "Monster", "Diet Coke" };
int choice;
int correct = 0;
void AdjArray()
{
choice--;
};
int main()
{
while (correct != 1)
{
cout << "Enter the number of the beverage you would like." << endl;
cout
<< " Coke = 1\n Water = 2\n Sprite = 3\n Monster = 4\n Diet Coke = 5"
<< endl;
cin >> choice;
AdjArray;
if (choice >= 0 && choice <= 4)
{
cout << "You have chosen " << drink[choice] << "." << endl;
correct = 1;
}
else
{
system("cls");
cout << "Error, you entered: " << choice
<< ". Please enter a number between 1 and 5.\n" << endl;
}
}
return 0;
}
You're not calling your function. Change AdjArray; to AdjArray();
score is an array of 10 scores in ascending order.
scoreName is an array of names associated with with each score.
I need to check if a new score is good enough to enter the the high score table and if so, insert it into the correct position and make sure scoreName is also updated to reflect any changes.
I am having problems with my current code:
//Table
for (int i = 0; i < leaderBoardSize; i++)
{
cout << scoreName[i] << "\t\t" << score[i] << endl;
}
system("pause");
//Check to see if you made the highScore
if (diceTotal >= score[9])
{
cout << "Congrats, you have made the HighScore Table !\nEnter Your Name.";
cin >> playerName;
for (int i = 9; i < leaderBoardSize; i--)
{
if (diceTotal <= score[i])
{
scoreName[i = i + 1] = scoreName[i];
score[i = i + 1] = score[i];
scoreName[i] = playerName;
score[i] = diceTotal;
break;
}
scoreName[i = i + 1] = scoreName[i];
score[i = i + 1] = score[i];
}
}
Here is the entire code:
#include <iostream>
#include <string>
#include <time.h>
using namespace std;
int main()
{
//dice game variables
int dice1 = 0;
int dice2 = 0;
int diceTotal = 0;
int round = 0;
string choice;
bool isDone = true;
//Scoreboard
const int leaderBoardSize = 10;
int score[10] = { 40, 33, 29, 24, 22, 19, 15, 12, 11, 9 };
string scoreName[leaderBoardSize] = { "Jason", "Steve", "Bob", "Timberduck", "Eric", "Susan", "Tyler", "Nick", "NinjaDave", "RaidenGunfire" };
string playerName;
//random number seeder
srand((unsigned int)time(NULL));
//Game instructions
cout << "dice game\n---------\nCreated By: Darcy Tellier\n--------------------------\nInstructions:\nRoll 2 dices. Try to get as close to 50 without going over." << endl;
//The Game loop
do
{
//resets game variables
diceTotal = 0;
round = 1;
//in game match loop
do
{
// display round #, current dice total, ask user to quit or re-roll.
cout << "Round\n-----\n " << round << endl;
cout << "current total:" << diceTotal << endl;
cout << "Roll dice (y/n)?";
cin >> choice;
//Checks the users imput for invalid characters
while (choice != "Y" && choice != "y" && choice != "N" && choice != "n")
{
cout << "invalid option. Choose y/n:" << endl;
cin >> choice;
}
if (choice == "Y" || choice == "y")
{
//roll dice
round += 1;
dice1 = rand() % 6 + 1;
dice2 = rand() % 6 + 1;
diceTotal = diceTotal + dice1 + dice2;
cout << "you have rolled a " << dice1 << " and a " << dice2 << endl;
if (diceTotal > 50)
{
isDone = false;
}
}
else
{
//break was used because "isDone = false" does not work here. The debugger shows that when the variable is set to false, it still ignores it and skips to the next round.
break;
}
} while (isDone == true || diceTotal < 50);
//end of round
if (diceTotal > 50)
{
cout << "\nGameOver" << endl;
cout << "You went over in " << round << " turns. You Lose!!! " << endl;
}
else
{
cout << "You stopped at " << round << " turns. Final score: " << diceTotal << "." << endl;
system("pause");
system("cls");
}
//Table
for (int i = 0; i < leaderBoardSize; i++)
{
cout << scoreName[i] << "\t\t" << score[i] << endl;
}
system("pause");
//Check to see if you made the highScore
if (diceTotal >= score[9])
{
cout << "Congrats, you have made the HighScore Table !\nEnter Your Name.";
cin >> playerName;
for (int i = 9; i < leaderBoardSize; i--)
{
if (diceTotal <= score[i])
{
scoreName[i] = playerName;
score[i] = diceTotal;
break;
}
}
}
//board display #2
for (int i = 0; i < leaderBoardSize; i++)
{
cout << scoreName[i] << "\t\t" << score[i] << endl;
}
system("pause");
//do you want to play again?
cout << "Do you want to play again";
cin >> choice;
while (choice != "Y" && choice != "y" && choice != "N" && choice != "n")
{
cout << "invalid option. Choose y/n:" << endl;
cin >> choice;
}
if (choice == "Y" || choice == "y")
{
system("cls");
isDone = true;
}
else
{
cout << "game over" << endl;
isDone = false;
}
} while (isDone);
system("pause");
return 0;
}
This is a copy of the assignment.
Note: I am not asking for you guys to do my work. I just want to figure out the highScore sorting thing.
The problem: arrays are not a good way to achieve what you want
You are trying to see if a score beat another score, and if so, replace that and move the rest of the scores down. I assume your scores are sorted, and that score is a int[10], but you have several problems:
1.
for (int i = 9; i < leaderBoardSize; i--)
You are attempting to iterate through your scores backwards, so you start at 9 (which I assume is the last index) and work your way down. Assuming leaderBoardSize is the total size of the leaderboard, and likely 10, i will always be less than leaderBoardSize and your for loop will go for a loooong time. You probably meant to say:
for (int i = 9; i >= 0; i--)
2.
scoreName[i = i + 1] = scoreName[i];
score[i = i + 1] = score[i];
This is assigning i to a new value, which will also ruin your for loop. You should only be doing
scoreName[i + 1] = scorename[i];
Trying to swap all the values in an array in cumbersome, and you are trying to do everything manually, so I give you:
The solution: use the standard library!
C++ is a great language, if for no other reason than containing a standard library: a library of functions and classes that solve many basic problems for you.
It is far easier to sort, insert and remove elements by using a standard container. Let's use std::vector:
// Simple class to handle a player score: a name and score
struct PlayerScore
{
std::string name;
unsigned int score;
};
// Create some test scores. I assume you have another means of storing high scores, perhaps in a file, but for this small purpose I am just hard-coding some scores:
std::vector<PlayerScore> hiScores = { {"ABC", 5000}, {"XJK", 10000}, {"FOO", 20000}, {"EGG", 4000}, {"HI", 50000} };
You may keep your scores sorted, but if, like mine they aren't sorted, you can sort them easily with std::sort:
std::sort(hiScores.begin(), hiScores.end(), [](PlayerScore ps1, PlayerScore ps2){ return ps1.score > ps2.score; });
With that out the way, you can proceed to play your game and obtain a name for the player and their score. I haven't bothered, and will just create a value for the score:
auto score = 10123u;
// Check if this score beats any of the current high scores:
auto it = std::find_if(hiScores.begin(), hiScores.end(), [score](PlayerScore ps){ return score > ps.score; });
if (it != hiScores.end())
{
// Yes! We beat a score!
std::cout << "Found score: " << it->score << std::endl;
// Insert this score before the other score
hiScores.insert(it, {"NewScore", score});
// Remove the last score:
hiScores.pop_back();
}
You no longer need to iterate and manually try to manipulate the positions of scores. Standard containers with random access such as std::vector allow you to just insert and access elements as you need to. Your 10 lines of code simply becomes 2 lines. std::vector also manages the size for you, so if you only have 3 high scores initially, it can grow easily to contain 10, 100 or many more scores.
std::find_if can find an element in your container without the need to manually iterate over every element. A predicate is passed in which acts as a find condition, which in our case we pass our score and check if it's greater than any PlayerScore in the container. The first element it's greater than is returned to us, and then we can insert our score in front of it, then remove the last score via pop_back
and if so, insert it into the correct position and make sure scoreName is also updated
This is a poor design. If scores and names need to stay together, you should make them a single entity. Define a struct or class to hold a name and associated score, and then store instances of that entity in a single array.