gpt4 book ai didi

c++ - 迭代结构 vector 并取消引用迭代器

转载 作者:行者123 更新时间:2023-11-28 02:38:56 25 4
gpt4 key购买 nike

我正在迭代 structvector,然后尝试取消引用迭代器。我认为我缺少一些逻辑并且做错了,或者只是语法不正确。

代码如下,包含大量调试输出:

#include <fstream>
#include <map>
#include <string>
#include <vector>
#include <algorithm>


using namespace std;


int main()
{
ifstream fin("gift1.in", ios::in);
ofstream fout("gift1.out", ios::out);

unsigned short NP;

struct person
{
string name;
unsigned int gave;
unsigned int received;
};

vector<person> accounts;

string tmp_name;

fin >> NP;
accounts.resize(NP);
for (auto& i : accounts)
{
fin >> tmp_name;
//fout << "Just read this name: " << tmp_name << "\n";
i.name = tmp_name;
i.gave = 0;
i.received = 0;

}

fout << "\n";

for (unsigned int j = 1; j <= NP; j++)
{
string giver_name;
fin >> giver_name;
fout << "Read a name #" << j << ": " << giver_name << "\n";

auto vpit = find_if(accounts.begin(), accounts.end(), [&giver_name](const person& pers) -> bool {return pers.name != giver_name; });
if (vpit == accounts.end())
{
fout << "Couldn't find this giver in accounts\n";
}
else
{
person& found = *vpit; // the logic is probably wrong here
fout << "\nDebug info: \n\t Giver#" << j << "; \n\t iterator->name ==" << vpit->name << "; \n\t iterator->gave == " << vpit->gave << "; \n\t iterator->received == " << vpit ->received << "\n";
fout << "Found " << found.name << " in accounts; proceeding\n";
//further code
}

我可能做错了什么?

最佳答案

如果要查找具有给定值的 vector 元素,则必须使用相等运算符

auto vpit = find_if( accounts.begin(), accounts.end(), 
[&giver_name] (const person& pers) { return pers.name == giver_name; } );

至于我然后是第二个循环

for (unsigned int j = 1; j <= NP; j++)
{
string giver_name;
fin >> giver_name;
//...

看起来很可疑。

关于c++ - 迭代结构 vector 并取消引用迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26647986/

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