C++编写一个函数模板,检测向量中的元素
发布网友
发布时间:2024-10-20 08:27
我来回答
共2个回答
热心网友
时间:2024-11-15 20:52
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
class CTest
{
public:
CTest(int ii = 0) { i = ii; }
bool operator<(const CTest& tst)
{
if (i < tst.i)
return true;
else
return false;
}
bool operator>(const CTest& tst)
{
if (i > tst.i)
return true;
else
return false;
}
private:
int i;
};
template<class T>
bool isAsc(vector<T>& vec)
{
vector<T>::iterator it = vec.begin();
for (; it != vec.end() - 1; ++it)
{
if ((*it) > (*(it + 1)))
return false;
}
if (it == vec.end() - 1)
return true;
return false;
}
int main()
{
vector<CTest> vec1;
vec1.push_back(CTest(0));
vec1.push_back(CTest(2));
vec1.push_back(CTest(5));
if(isAsc(vec1))
cout << "vec1's sort is ascending" << endl;
vector<CTest> vec2;
vec2.push_back(CTest(0));
vec2.push_back(CTest(2));
vec2.push_back(CTest(1));
if(!isAsc(vec2))
cout << "vec2's sort is NOT ascending" << endl;
return 0;
}
热心网友
时间:2024-11-15 20:52
#include
"stdafx.h"
#include
<iostream>
#include
<vector>
using
namespace
std;
class
CTest
{
public:
CTest(int
ii
=
0)
{
i
=
ii;
}
bool
operator<(const
CTest&
tst)
{
if
(i
<
tst.i)
return
true;
else
return
false;
}
bool
operator>(const
CTest&
tst)
{
if
(i
>
tst.i)
return
true;
else
return
false;
}
private:
int
i;
};
template<class
T>
bool
isAsc(vector<T>&
vec)
{
vector<T>::iterator
it
=
vec.begin();
for
(;
it
!=
vec.end()
-
1;
++it)
{
if
((*it)
>
(*(it
+
1)))
return
false;
}
if
(it
==
vec.end()
-
1)
return
true;
return
false;
}
int
main()
{
vector<CTest>
vec1;
vec1.push_back(CTest(0));
vec1.push_back(CTest(2));
vec1.push_back(CTest(5));
if(isAsc(vec1))
cout
<<
"vec1's
sort
is
ascending"
<<
endl;
vector<CTest>
vec2;
vec2.push_back(CTest(0));
vec2.push_back(CTest(2));
vec2.push_back(CTest(1));
if(!isAsc(vec2))
cout
<<
"vec2's
sort
is
NOT
ascending"
<<
endl;
return
0;
}