填充标准向量
我不明白为什么向量在填充后会变空。
代码是:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这些行是您的问题:
在输入良好的情况下,您将在使用
push_back
实际调用push_back
之前从fillArray
方法返回true
向量上的值。These lines are your problem:
In the case of good input, you're returning
true
from yourfillArray
method before you actually callpush_back
with the value on your vector.在 fillArray 方法中永远不会达到,因为 if 返回 true 或 false
is never reached in your fillArray Method, because the if returns true or false