Dean Hampson Dean Hampson - 11 days ago 6
C++ Question

Vector element ID's C++

UserFile.open(cname + ".txt");
int numOfElements = name.size();

if (UserFile.is_open())
{
name.push_back(cname);
pass.push_back(cpass);
posx.push_back(0);
posy.push_back(0);
id.push_back(numOfElements);

std::cout << "Your player name has been registered successfully." << std::endl;
UserFile << cname << ";" << cpass << ";" << "0" << ";" << "0";
}


I've gotten this far with adding players to vectors and even the numOfElements works correctly.. How can I read statistics of each player representing the player id as the nth element in the vector?
Example:

else if (userInput == "stats") // Ignore the else
{
// Name is Allura. ID is stored too. Increments from 0 to work with the vector
// What can I do to make a way of showing information only in that nth element (like element 0 if player id is 0) etc?
}

qxz qxz
Answer

First of all, to store a list of players, you should have a single vector of objects:

struct Player {
    std::string name, pass;
    int posx, posy;
    int id;
    // etc.
};

std::vector<Player> players;

To add a new player to this list, you can push_back a braced-init-list with all the properties:

players.push_back({cname, cpass, 0, 0, numOfElements /*, etc. */});

If you then want to find a player with a given id (or other property), use std::find_if (which finds the first element for which the given condition is true):

int id_to_find = ...;
auto iterator = std::find_if(players.begin(), players.end(), [&](const Player& p) {
    return p.id == id_to_find;
});
if (iterator == players.end()) {
    // the id wasn't found
} else {
    // the id was found
    // (*iterator) is a reference to the Player object in the vector
}

This uses a lambda expression (like a lambda in Python or an anonymous function in JavaScript). If you're unfamiliar with how iterators work, look those up; in C++, they're almost always used instead of working with indices.

Comments