填充标准向量

发布于 2024-09-12 23:48:55 字数 616 浏览 4 评论 0原文

我不明白为什么向量在填充后会变空。

代码是:

bool fillArray (vector<int> &array)
{        
    string temp;
    getline(cin, temp);

    if (temp  == "-1")
       return false
    else
       return true;

    int res = atoi(temp.c_str());
    array.push_back(res);
}

void showArray(const vector<int> array)
{
    for (int i = 0; i < array.size(); i ++)
        cout << array[i] << " ";
}


int main(int argc, char** argv)
{
    vector<int> array;

    while (fullArray (array))
    {}

    showArray(array);
    return 0;
}

当我输入-1时,循环中断,但向量的大小为0,为什么?

I can't understand why does vector empty after it's filling.

The code is:

bool fillArray (vector<int> &array)
{        
    string temp;
    getline(cin, temp);

    if (temp  == "-1")
       return false
    else
       return true;

    int res = atoi(temp.c_str());
    array.push_back(res);
}

void showArray(const vector<int> array)
{
    for (int i = 0; i < array.size(); i ++)
        cout << array[i] << " ";
}


int main(int argc, char** argv)
{
    vector<int> array;

    while (fullArray (array))
    {}

    showArray(array);
    return 0;
}

When I input -1 the cycle breaks but the size of vector is 0, why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不再让梦枯萎 2024-09-19 23:48:55

这些行是您的问题:

    if (temp  == "-1")
       return false
    else
       return true;

    int res = atoi(temp.c_str());
    array.push_back(res);

在输入良好的情况下,您将在使用 push_back 实际调用 push_back 之前从 fillArray 方法返回 true向量上的值。

These lines are your problem:

    if (temp  == "-1")
       return false
    else
       return true;

    int res = atoi(temp.c_str());
    array.push_back(res);

In the case of good input, you're returning true from your fillArray method before you actually call push_back with the value on your vector.

滥情哥ㄟ 2024-09-19 23:48:55
int res = atoi(temp.c_str());
array.push_back(res);

在 fillArray 方法中永远不会达到,因为 if 返回 true 或 false

int res = atoi(temp.c_str());
array.push_back(res);

is never reached in your fillArray Method, because the if returns true or false

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文