对字符串和原始数据类型应用大于或小于检查?

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

我正在做一个项目,该项目要求我为一个累加器创建一个模板 class,无论天气与否,传递给它的列表都是有序的。顺序是升序的。

我可能想多了这个问题,但我似乎无法弄清楚如何对原始数据类型和字符串进行大于/小于检查。我会澄清: 这个过程是这样的: 声明了一个 list/vector 并在其中存储了东西。 然后调用一个名为 apply 的辅助累加器。 此 Accumulator(apply) 遍历列表,对列表中的每个值调用 InOrder Accumulator 的 .put() 方法。这些值可以是 double、long、short 等类型或字符串。

我试过设置任意下限,将其设置为列表中的第一个元素,然后根据该起点进行检查,但这提供了混合结果,因为它不适用于字符串。

我正在考虑检查 typeid 或其他东西,以便对于字符串我可以调用 .size() 方法并以这种方式进行比较。至于基元,我会简单地使用 > 或 < 运算符。但这会破坏模板函数的意义。任何帮助将不胜感激。

我将 post 调用函数的代码、应用累加器的代码和我的 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 doubles\n";
    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 order\n\n";
}
{
    // Read a list of strings into a List and check their order
    cout << "apply InOrder to a List of strings\n";
    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 order\n\n";
}

我要注意,放入列表的项目是按相反顺序处理的。
例如:如果我将我的列表输入 [a,b,c] 或 [1,2,3],第一个要处理的 value/string 将是 c/3,然后依此类推 b/2 和 a,1

这行不通:

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) {}

给你的构造函数。

你的错误在于你发现顺序错误时没有停止:

 _order = false; // here is you have to stop and skip all other items