【发布时间】:2017-10-21 19:58:06
【问题描述】:
背景: 这是一个将 1 加 1 到存储在向量中的数字的程序。
前面有 0 的数字可以作为输入,但不能作为输出。 eg: 0123 & 123 都是有效输入 但 0124 是无效的输出 而 124 是一个有效的输出
问题:
我想使用erase() 删除输出向量前面的 0,直到使用代码底部的 while 循环找到非零值。
但是编译器返回一个垃圾值。另一个在线编译器给出了分段错误。
其余代码在没有 while 循环的情况下编译时可以正常工作。
#include <iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> A = { 9, 9, 9 };
A.insert(A.begin(), 0); /*--last carry may nonzero so new digit -*/
vector<int>::reverse_iterator it;
int c = 1;
for (it = A.rbegin(); it != A.rend(); it++) /*----finds and adds carry---*/
{
int d = *it;
d = d + c;
c = d / 10;
if (c == 0)
*it = d;
else
{
d = d % 10;
*it = d;
}
}
vector<int>::iterator iss;
iss = A.begin();
问题循环开始
while (*iss == 0) /*----------------problem----------------*/
{
iss = A.erase(iss);
}
循环结束
for (int i = 0; i < A.size(); i++)
{
cout << A[i];
}
}
【问题讨论】:
-
这个程序对我来说是正确的,并且对我有用。您在粘贴在这里的程序上得到意外的输出或崩溃?你能更具体地谈谈“垃圾价值”吗?
-
不相关:研究 Erase-remove 成语
标签: c++