对字符串和基本数据类型应用大于或小于检查
Applying Greater than or Less than Checks to both Strings and Primitive Data Types?
我正在进行一个项目,该项目要求我为一个Accumulator创建一个模板类,该类返回传递给它的列表是否有序。顺序是升序的。
我可能是过度思考的问题,但我似乎无法弄清楚如何做一个大于/小于检查基本数据类型和字符串。我将澄清:这个过程是这样的:声明一个列表/向量,并将内容存储在其中。然后调用第二个累加器apply。这个Accumulator(apply)在列表中迭代,对列表中的每个值调用InOrder Accumulator的.put()方法。值可以是double、long、short等类型,也可以是string类型。
我尝试设置一个任意的下界,将其设置为列表中的第一个元素,然后根据该起点进行检查,但这提供了混合结果,因为它不适用于字符串。
我正在考虑检查类型id或其他东西,以便我可以调用。size()方法并以这种方式进行比较。对于原语,我会简单地使用>或<操作符。但是,这将破坏模板函数的意义。任何帮助都将非常感激。>
我将发布调用函数的代码,应用累加器的代码和InOrder的代码。如果还需要什么,请告诉我。
我有条不紊地进行:
template<typename T>
class InOrder
{
public:
InOrder(){}
~InOrder(){}
void put(T item)
{
_count++;
if(_count == 1)
{
_lowbound = item;
}
if(_count!=0 && _count!=1 && item<_lowbound)
{
_order = false;
}
if(_count!=0 && _count!=1 && item>_lowbound)
{
_order = true;
}
_count++;
}
bool get()
{
return _order;
}
private:
T _lowbound;
int _count = 0;
bool _order;
};
用蓄电池:
template<typename A, typename I>
void apply(A & anAccumulator, I begin, I end)
{
for (I iter = begin; iter != end; ++iter)
{
anAccumulator.put( *iter);
}
}
调用InOrder的代码:
{
// Read a list of doubles into a List and check their order
cout << "apply InOrder to a List of doublesn";
double sentinel = -1.23;
List<double> dList;
fillList(sentinel, dList);
InOrder<double> dblInOrder;
apply(dblInOrder, begin(dList), end(dList));
cout << "The doubles in dList are ";
if (!dblInOrder.get())
cout << "NOT ";
cout << "in ordernn";
}
{
// Read a list of strings into a List and check their order
cout << "apply InOrder to a List of stringsn";
string strSent = "end";
List<string> sList;
fillList(strSent, sList);
InOrder<string> strInOrder;
apply(strInOrder, begin(sList), end(sList));
cout << "The strings in sList are ";
if (!strInOrder.get())
cout << "NOT ";
cout << "in ordernn";
}
我应该注意,放入列表中的项目是按相反的顺序处理的。
例如:如果我输入我的列表为[a,b,c]或[1,2,3]要处理的第一个值/字符串将是c/3,然后依次类推到b/2和a,1
你的错误是当你发现顺序是错误的时候你没有停止:
_order = false; // here is you have to stop and skip all other items
这行不通:
if(_count!=0 && _count!=1 && item<_lowbound)
{
_order = false;
}
if(_count!=0 && _count!=1 && item>_lowbound)
{
_order = true;
}
因为应该是:
if(_count!=0 && _count!=1 && item<_lowbound)
{
_order = false;
}
删除第二部分,并添加:
InOrder() : _order(true) {}
相关文章:
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 大于65535的C++数组[size]引发不一致的溢出
- 查找最接近的大于当前数字的数字的索引
- 从值小于256的uint16到uint8的Endian安全转换
- 将stl字符串缩小到小于15个字符的容量
- 如何检查两个 std::向量在小于 O(n) 的时间复杂度内是否相等
- 如何找到大于整数的最小数字
- 如何在随机数列表中查找大于或小于的元素
- 创建一个循环,该循环将输出大于零且小于 60(不包括 60)的所有 5 的倍数
- 节点小于且大于特定节点的节点数
- 如何做比率和大于和小于C++
- 互锁。比较交换<Int> 使用大于或小于而不是相等
- 在C++中获取大于或等于一个双精度的最小浮点值(以及小于或等于一的最大浮点值)
- 如何返回小于或等于平均值的整数和大于平均值的整数
- 对字符串和基本数据类型应用大于或小于检查
- 是否有一种方法可以正确地比较一个float值是否大于/小于另一个
- 在 std::sort() 中的自定义函数中,>(大于)运算符与 <(小于运算符)的交换会导致分段错误吗?
- 大于和小于在一起
- 如何在同一个while循环中求大于和小于的数
- 如何直观地理解C++优先级队列容器比较器中的大于/小于运算符