如果元素不存在,向量是否返回false?我试图迭代一个向量并打印出每个已排序的元素,只要它们存在。这是我正在使用的代码的片段:
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++;
}
}
答案 0 :(得分: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容器,这样就不会超出范围,因为它们使用begin
和end
。
答案 1 :(得分:1)
不,如果你试图访问超出其大小的向量元素,它将是未定义的行为。
你可以写简单
for ( const Person &person : Contacts ) cout << person.Name << endl;