矢量C++排序和打印

Vector C++ Sorting and Printing

本文关键字:打印 排序 C++ 矢量      更新时间:2023-10-16

如果元素不存在,向量是否返回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++;
    }
}

不是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;
}

最好使用迭代器迭代stl容器,这样索引就不会超出范围,因为它们使用beginend

否,如果您试图访问超出其大小的向量元素,这将是未定义的行为。

你可以简单地写

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