2014-10-30 99 views
0

我在遍历vectorstruct s,然后尝试对迭代器进行解引用。我想我错过了一些逻辑并做错了,或者只是没有正确的语法。对结构向量进行迭代并对迭代器解引用

的代码如下,并含有大量的调试输出:

#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 
    } 

什么可能我是做错了什么?

+0

什么问题?请在代码中不要描述问题。请缩进你的代码。 – sfrehse 2014-10-30 08:19:31

+0

'iterator-> name'保持不变。但预计会发生变化,因为'find_if'预计会找到相应的“人员”。 – Chiffa 2014-10-30 08:23:31

+1

没有必要提供ifstream/ofstream的修饰符。 – 2014-10-30 08:33:13

回答

2

如果你想找到与给定值的向量的元素,那么你必须使用等于运算符

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; 
    //... 

看起来可疑地。

+0

改变了它,它似乎是这样工作的。这应该意味着我的迭代器是好的,但我的比较不是? – Chiffa 2014-10-30 08:30:45

+0

@Chiffa据我所知,你需要找到给定值的元素。在这种情况下,元素将在条件为真时找到,然后相应的elemnt的数据成员等于给定值。 – 2014-10-30 08:32:54

+0

没错,就是这样。谢谢。我现在正在解决其他部分代码的逻辑问题,这个问题没有提到。 – Chiffa 2014-10-30 08:38:13