2015-07-12 151 views
-4

我有問題打印出載有我的人信息的矢量。如何打印矢量類的內容

struct PersonInfo{ 

    string name; 
    vector<string> phones; 
}; 

int main(){ 

    string line, word; 
    vector<PersonInfo> people; 
    while(getline(cin, line)){ 
     PersonInfo info; 
     istringstream record(line); 
     record >> info.name; 
     while(record >> word) 
      info.phones.push_back(word); 
     people.push_back(info); 

    } 
    for(auto i = people.begin(); i != people.end(); i++) 
     cout << people << endl; 
    return 0; 
} 
+0

您是否嘗試搜索所有如何在C++中打印對象?並看看你的'聲明'。如果你從不在循環體內使用它,那麼爲'vector'創建一個迭代器有什麼意義呢? – Praetorian

回答

0

有幾種選擇:

  1. 使用迭代器

    for(auto i = people.begin(); i != people.end(); i++) 
    { 
        cout << i->name<< endl; 
        for (auto l= i->phones.begin(); l != i->phones.end(); ++l) 
         std::cout<< *l<<"\n"; 
    } 
    
  2. 使用範圍循環

    for (auto & val: people) 
    { 
        std::cout<<val.name<<"\n"; 
        for (auto & phone: val.phones) 
         std::cout<<phone; 
    } 
    
  3. 您可以使用矢量指數,留給你的在家工作

+0

您的示例錯誤標記。 – celticminstrel

+0

迭代器錯誤的運算符 – 2015-07-12 09:15:42

0
for(int i = 0 ; i < people.size(); i++){ 
     cout << people[i].name<< endl; 

     for(int j = 0 ;j<people[i].phones.size() ; j++) 
      cout<< people[i].phones[j]<<" "; 

     cout<<endl;  
} 

在這裏,在使用第一循環我們遍歷直到矢量人的大小和每個矢量人的內容有另一個手機載體命名的,所以我們需要遍歷一個了。我們在第二個循環中做了這個。

因此,如果人[0]有手機尺寸爲10,然後我們會遍歷

人[0] .phones [10]等..

+1

給答案添加一點解釋會使它更好的回答。 – NathanOliver

+0

謝謝Nathan :) –

1
error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&' 
      cout << people << endl; 
       ^

您需要定義<<運營商你的自定義結構。這樣

ostream & operator<<(ostream & out, const PersonInfo & p) { 
    out << p.name << endl; 
    copy(p.phones.begin(), p.phones.end(), ostream_iterator<string>(out, " ")); 
    return out; 
} 

的結構後,將其定義和糾正你的打印語句

for (auto i : people) 
    cout << i << endl; 

看到http://ideone.com/uLSLHY工作演示。