简体   繁体   English

填充标准向量

[英]Filling std vector

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? 当我输入-1时,循环中断,但是向量的大小为0,为什么?

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. 在输入良好的情况下,在实际调用带有向量值的push_back之前,您fillArray方法返回true

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

is never reached in your fillArray Method, because the if returns true or false 在fillArray方法中永远不会到达,因为if返回true或false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM