尝试自定义一个函数来对不同种类元素的向量进行排序
Trying to self-define a function to sort a vector of different kinds of elements
我想写一个有点像stl中的排序的函数。这是我主要功能的一部分
inline bool myCmp(const int & a, const int & b) {
return a > b;
}
int main() {
int n, * s, i;
std::vector<int> v;
std::list<int> l;
std::cin >> n;
s = new int[n];
for (i = 0; i < n; ++i) {
std::cin >> s[i];
v.push_back(s[i]);
l.push_back(s[i]);
}
mySort(v.begin(), v.end(), myCmp);
mySort(l.begin(), l.end());
我在这里实现了我的排序功能
template <typename T>
typedef bool (*pf)(const T& ,const T&);
template <typename T>
void mySort(T a, T b, pf = nullptr)
{
for(auto i = a; i != b; i++)
{
for(auto j = a + 1; j != b; j++)
{
if(i > j)
{
T temp = i;
i = j;
j = temp;
}
}
}
}
不幸的是,我遇到了一些错误,
sort.h: In instantiation of 'void mySort(T, T, pf) [with T = std::_List_iterator<int>; pf = bool (*)(const int&, const int&)]':
main.cpp:22:30: required from here
sort.h:8:20: error: no match for 'operator+' (operand types are 'std::_List_iterator<int>' and 'int')
for(auto j = a + 1; j != b; j++)
^
In file included from /usr/include/c++/5/bits/stl_algobase.h:67:0,
from /usr/include/c++/5/vector:60,
from main.cpp:1:
/usr/include/c++/5/bits/stl_iterator.h:334:5: note: candidate: template<class _Iterator> std::reverse_iterator<_Iterator> std::operator+(typename std::reverse_iterator<_Iterator>::difference_type, const std::reverse_iterator<_Iterator>&)
operator+(typename reverse_iterator<_Iterator>::difference_type __n,
^
/usr/include/c++/5/bits/stl_iterator.h:334:5: note: template argument deduction/substitution failed:
In file included from main.cpp:4:0:
那么运算符"+"有什么问题呢?我怎样才能成功地编写这个 mySort 函数?提前感谢!
问题是,在行中:
mySort(l.begin(), l.end());
而在里面,
for(auto j = a + 1; j != b; j++)
^^^^^
您正在尝试访问列表迭代器operator+
。但是 std::list<T>::begin/end
返回的迭代器是一个双向迭代器。双向迭代器未定义operator+
。不过,您可以使用operator++
。
另一方面,std::vector
按 std::vector<T>::begin/end
返回随机访问迭代器。随机访问迭代器确实定义了operator+
。
因此,请尝试以下操作:
for(auto i = a; i != b; i++)
{
auto c = a;
for(auto j = ++c; j != b; j++)
{
...
相关文章:
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 如何为 c++ 的不同变量类型的结构元素创建动态数组?
- 如何创建一个所有行大小不同的 2D 数组,并且用户将指定每行将有多少个元素?
- 为什么 std::p air 的大小与其元素的大小之和不同?
- 是否需要 mutex() 来安全地同时访问具有 2 个线程的数组的不同元素?
- C++:是否可以编写一个函数,将不同类型的元素附加到变体数组中?
- 访问数组中的不同元素
- 将函数应用于元组中的每个元素,将每个元素强制转换为类型包中的不同类型,然后作为参数包传递
- C++ 如何以特定模式遍历矢量的不同集合元素
- 如何检查所有随机数组元素是否不同
- 生成所有可能的元素选择,每个元素都来自不同的集合
- 我创建了deque<CObject*>并添加了不同类型的元素。如何更改此元素的属性?
- 我如何使用Qsort对结构(由几个不同元素组成)进行排序
- C++ 比较 2 个不同向量的元素
- 如何在 c++ 中计算 2 个不同向量的相等元素
- 我如何将std ::数组作为模板参数传递,其中C 中的元素数量不同
- 尝试自定义一个函数来对不同种类元素的向量进行排序
- 输入元素与文件C 的输出元素不同
- 如何在CUDA中将不同种类的纹理绑定到纹理引用