以数字形式访问 C++ 向量

Accessing C++ Vector as number

所以基本上我是想获得一个游戏列表,并让用户选择删除它。它看起来像这样:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
//setup
vector<string> games;
games.push_back("Team Fortress 2");
games.push_back("Skyrim");
games.push_back("Portal");
vector<string>::iterator myIterator

//main
int delItem;
cin >> delItem; // Consumes a number to represent the game to be deleted

while (iter != games.end()) // Displays all the games
{
    cout << j << ") " << *iter << endl;
    iter++;
    j++;
}

while ((delItem <= games.begin()) || (delItem > games.end())) // can only be 1, 2, or 3
{
    cout << "\nThat input is incorrect. Please try again: ";
    getline (cin, delItem);
}
myIterator = (games.begin() + (delItem - 1);
games.erase(myIterator); // Deletes the item
cout << "\nThe game has been deleted.";

return 0;
}

所以当我显示列表时,它看起来像这样:
1) 军团要塞 2
2) 天际
3) 传送门

用户可以键入游戏之前的数字,然后将选择该数字以将其删除。我想做的是防止用户输入高于或低于这三个数字的数字。我在第二个 while 循环中尝试这样做,但看起来 games.begin() 不是数字。我知道这可能是一个我几乎没有错过的愚蠢错误,但任何帮助都会很棒。

你说得对 games.begin() 不是数字。这是一个 iterator。但是,您可以使用 games.size() 来确定 games 向量中的元素数。您可以将其用于用户可以键入的最大数量。据我所知,最小数量将始终相同。我把它留作 reader 的练习以确定它是什么。

你的代码有几个问题。

在打印出可供用户选择的可用选项之前,您正在阅读用户的输入。您需要撤消这些操作。

您正在使用尚未声明的变量。

当用户输入无效号码时,您正在调用 std::getline() 以获取新号码,但 std::getline() 输出到 std::string,而不是 int .

尝试更像这样的东西:

#include <iostream>
#include <string>
#include <vector>
#include <limits>

using namespace std;

int main()
{
    //setup
    vector<string> games;
    games.push_back("Team Fortress 2");
    games.push_back("Skyrim");
    games.push_back("Portal");
    vector<string>::iterator myIterator;

    //main

    int j = 1;
    for (myIterator = games.begin(); myIterator != games.end(); ++myIterator) // Displays all the games
    {
        cout << j << ") " << *myIterator << endl;
        ++j;
    }

    cout << "\nPick an item to delete: ";

    int delItem;
    do
    {
        if (cin >> delItem) // Consumes a number to represent the game to be deleted
        {
            if ((delItem >= 1) && (delItem <= games.size())) // can only be 1, 2, or 3
                break;
        }

        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cin.clear();

        cout << "\nThat input is incorrect. Please try again: ";
    }
    while (true);

    /*
    alternatively:

    int delItem;
    do
    {
        string line;
        if (!getline(cin, line)) {
            // error!
            return 0;
        }

        istringstream iss(line);
        if (iss >> delItem) // Consumes a number to represent the game to be deleted
        {
            if ((delItem >= 1) && (delItem <= games.size())) // can only be 1, 2, or 3
                break;
        }

        cout << "\nThat input is incorrect. Please try again: ";
    }
    while (true);
    */

    myIterator = games.begin() + (delItem - 1);
    games.erase(myIterator); // Deletes the item
    cout << "\nThe game has been deleted.";

    return 0;
}