c++ - for 循环不仅仅在声明的函数处结束,而不是在 main 处结束

标签 c++ c++11 vector iterator

我的问题是 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/

相关文章:

c++ - 如果只有 *ptr,如何移动 unique_ptr

c++ - 是否可以在 O(1) 时间内为 C++ vector 分配新值?

c++ - 在用户定义的类中清空 std::vector 时未释放内存

c++ - 循环中奇怪的指针行为

c++ - 如何创建一个 unordered_set 的 shared_ptr 对象?

c++ - 一次覆盖两个方法

c++ - "layout-compatible with C"是什么意思?

c++ - 应用程序无法正确启动 (0*0150002) - OpenCv

c++ - 如何在 Eclipse 中禁用警告 "No break at the end of case"?

c++ - 将字节序列转换为 ASCII 表示形式,反之亦然