2014-10-30 57 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