gpt4 book ai didi

c++ - 使用 iter_swap 方法 c++ 我做错了什么?

转载 作者:行者123 更新时间:2023-11-30 02:17:47 33 4
gpt4 key购买 nike

实现基本的冒泡排序以按名称对 Student 结构的 vector 进行排序。

#include <vector>
#include <string>

void sortStudents(std::vector<Student>& students) {

typedef std::vector<Student>::iterator iter;

for (iter i = students.begin(); i != students.end()-1; ++i) {
for (iter j = i; j != students.end() - 1; ++j) {

Student current = *i;
Student next = *(i + 1);

bool shouldSwap = ((next.name).compare(current.name)) < 0; // if next is before current in the alphabet

if (shouldSwap) {
std::iter_swap(*i, *(i + 1));
}
}
}
}

我是完全错误地使用这种方法还是缺少一些基本的东西?

注意:我知道冒泡排序的低效,我只是想了解迭代器。

最佳答案

std::iter_swap是一个特殊版本(不同于交换实际元素的 std::swap),它交换迭代器指向的元素。但是您尝试将实际元素传递给它。所以它是:

std::swap(*i, *(i + 1));

std::iter_swap(i, i + 1);

关于c++ - 使用 iter_swap 方法 c++ 我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53227068/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com