矢量C++排序和打印
Vector C++ Sorting and Printing
如果元素不存在,向量是否返回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容器,这样索引就不会超出范围,因为它们使用begin
和end
。
否,如果您试图访问超出其大小的向量元素,这将是未定义的行为。
你可以简单地写
for ( const Person &person : Contacts ) cout << person.Name << endl;
相关文章:
- 读取一组用户输入,按升序排序,然后打印结果
- 如何基于一个数组对多个数组进行排序并打印出来
- 插入排序打印错误的输出
- 如何按姓氏排序并打印新数组
- 队列快速排序不排序和打印随机字符串[C ]
- 每次交换后,如何使用任何排序算法打印到控制台
- 排序向量不断修改数据并打印不正确的结果
- 尝试使用 cout 打印矢量中包含的对象列表并排序是错误的
- 根据用户输入对二维数组进行排序和打印
- C++链表-按排序顺序打印
- 除了显示平均,最高和最低温度之外,有没有办法打印出整个排序列表
- 打印排序的整数数组元素
- C++:使用 map 对文本文件中出现的字符串值进行排序和打印
- 在C++中对列(数组)中的平均值进行排序和打印
- 矢量C++排序和打印
- 按字母顺序降序对列表进行排序,然后打印列表
- C++链表排序、拆分和打印问题
- 快速排序后打印出数组的元素
- C++按升序对数组进行排序打印
- 如何在C++中打印按行排序的矩阵