矢量元素 ID 的 C++

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";
}

我已经将玩家添加到向量中,甚至 numOfElements 也能正常工作。我如何读取每个玩家的统计信息,将玩家 ID 表示为向量中的第 n 个元素? 示例:

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?
}

首先,要存储玩家列表,您应该有一个对象向量:

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

std::vector<Player> players;

要将新玩家添加到此列表,您可以 push_back 一个具有所有属性的 braced-init-list:

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

如果您随后想要找到具有给定 id(或其他 属性)的玩家,请使用 std::find_if(它会找到给定条件为真的第一个元素):

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
}

这使用 lambda expression(如 Python 中的 lambda 或 JavaScript 中的匿名函数)。如果您不熟悉迭代器的工作原理,请查阅它们;在 C++ 中,几乎总是使用它们而不是使用索引。