【问题标题】:Vector C++ Sorting and Printing矢量 C++ 排序和打印
【发布时间】:2014-10-26 20:07:35
【问题描述】:

如果元素不存在,向量是否返回 false?我试图遍历一个向量并打印出每个排序的元素,只要它们存在。这是我正在使用的代码的 sn-p:

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++;
    }
}

【问题讨论】:

    标签: c++ vector boolean cout


    【解决方案1】:

    而不是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

    【讨论】:

      【解决方案2】:

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

      你可以简单地写

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多