2014-10-26 85 views
-4

如果元素不存在,返回false吗?我试图遍历一个矢量,并且只要它们存在就打印出每个已排序的元素。这里的代码片段,我一起工作:向量C++排序和打印

typedef struct { 
    string Name; 
    map<string,string> Numbers; 
} Person 

bool ComparebyAlpha(const Person &person1, const Person &person2) { 
    return person1.Name < person2.Name; 
} 

voic print_Contacts(vector <Person> Contacts) { 
    sort(Contacts.begin(), Contacts.end(), ComparebyAlpha); 
    int num = 0; 
    while (Contacts[num]) { 
     cout << Contacts[num].Name; 
     num++; 
    } 
} 

回答

2

取而代之的是while循环,

while (Contacts[num]) { 
    cout << Contacts[num].Name; 
    num++; 
} 

你可以只使用一个for循环这个

for (auto const& person: Contacts) 
{ 
    cout << person.name; 
} 

或者

for (auto iter = Contacts.begin(); iter != Contacts.end(); ++iter) 
{ 
    auto person= *iter; 
    cout << person.name; 
} 

最好使用iterators迭代stl容器,因为它们使用的是beginend,所以您不要索引超出范围。

1

不,如果您尝试访问超出其大小的矢量元素,它将是未定义的行为。

你可以写简单

for (const Person &person : Contacts) cout << person.Name << endl;