我的问题是 for 循环不会在特定情况下结束。
下面是我写的代码
我打算在 iter
遇到 arr.end()
时结束 find_period
的 for 循环
但事实并非如此。
int find_period(vector<int> arr){
vector<int>::iterator iter;
for(iter=arr.begin(); iter != arr.end(); iter++){
cout << *iter << endl;
}
}
但是当我将 for 循环移动到 main()
时,它工作正常。
int main() {
vector<int> input = {2,2,3,4,5,6,7,8,9};
vector<int>::iterator iter;
//for(iter=input.begin(); iter != input.end(); iter++){
// cout << *iter << endl;
///}
cout << find_period(input) << endl;
}
I don't know why this thing happens.
At first, I think it is related with the concept of pointer. Therefore, I modified the code that use pointer `int find_period(vector<int> *arr)`. But it didn't work too.
Could you give me a little hint?
Thanks a lot!
最佳答案
鉴于您的第一个程序只是打印了 vector
中的数字, 但现在你希望循环在一个函数中,那么你应该只调用函数:
void print_vector(const vector<int>& arr){
for(auto item: arr){
cout << item << endl;
}
}
int main() {
vector<int> input = {2,2,3,4,5,6,7,8,9};
print_vector(input);
}
起初我很困惑,当你说:I intend the for loop at find_period is ended when iter meet arr.end(). But it didn't.
现在我认为正在发生的事情是你的函数 find_period()
确实打印所有数字并在最后停止,但您的电话:cout << find_period(input) << endl;
打印额外的 0
,所以我确定您看到了:
...
7
8
9
0
关于c++ - for 循环不仅仅在声明的函数处结束,而不是在 main 处结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58776162/