对字符串和基本数据类型应用大于或小于检查

Applying Greater than or Less than Checks to both Strings and Primitive Data Types?

本文关键字:大于 小于 检查 应用 数据类型 字符串      更新时间:2023-10-16

我正在进行一个项目,该项目要求我为一个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) {}