gpt4 book ai didi

c++ - STL vector 使用问题——函数返回非零Iterator

转载 作者:行者123 更新时间:2023-11-30 04:38:02 26 4
gpt4 key购买 nike

我正在尝试使用 vector STL,其中我面临来自以下示例程序的奇怪响应:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

vector<int>::iterator fun();
vector<int> myvector;

bool IsOdd (int i) {
return ((i%2)==1);
}

int main()
{
vector<int>::iterator it;

it = fun();

if (it == myvector.end() )
cout << "Reached end, Global" << endl;
else
cout << "Not end" << endl;


}

vector<int>::iterator fun() {
vector<int>::iterator it;

myvector.push_back(10);
myvector.push_back(26);
myvector.push_back(40);
myvector.push_back(56);

it = find_if (myvector.begin(), myvector.end(), IsOdd);
cout << "The first odd value is " << *it << endl;

if (it == myvector.end() )
cout << "Reached end, inside the function" << endl;
else
cout << "Not end" << endl;

return it;
}

我在函数 fun() 中得到“Reached End”,而在主程序中,它显示为“Not End”。

不确定,可能是什么原因。此外,发现 myvector.end() 的地址在主程序中显示为零 [在 fun() 调用之后],而在函数 fun() 中显示非零值。

最佳答案

函数使用局部 myvector,main 使用全局 myvector。

您修改后的代码产生:

Reached end, inside the function
Reached end, Global

正如预期的那样。

编辑好吧,不像预期的那样 - 正如其他人指出的那样:

it = find_if (myvector.begin(), myvector.end(), IsOdd);
cout << "The first odd value is " << *it << endl;

将导致您的数据集出现未定义的行为,因为您没有任何奇数值。你想要:

it = find_if (myvector.begin(), myvector.end(), IsOdd);
if ( it != myvector.end() ) {
cout << "The first odd value is " << *it << endl;
}

关于c++ - STL vector 使用问题——函数返回非零Iterator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3404833/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com