2015-10-14 53 views
0

我正在研究一個項目,該項目要求我爲累積器創建一個模板類,以返回天氣或不是傳遞給它的列表。訂單正在上升。將大於或小於檢查應用於字符串和基元數據類型?

我得太多可能的問題,但我似乎無法弄清楚如何做一個大於/小於檢查兩個基本數據類型和字符串。我將澄清: 進程如下所示: 聲明瞭一個列表/向量,並在其中存儲了內容。 然後調用一個名爲apply的輔助累加器。 此累加器(應用)遍歷列表中每個值調用InOrder累加器的.put()方法的列表。值可以是double類型,long類型,short類型或者string類型。

我已經嘗試設置任意的下限,將其設置等於在列表中的第一個元素,然後做基於該起點檢查,但此提供混合的結果,因爲它不會在弦上工作。

我想檢查的typeid或東西,這樣的字符串然後我可以調用.size()方法和比較的方式。至於基元,我會簡單地使用>或<運算符。但是,這將打敗模板功能的重點。任何幫助將不勝感激。

我會後的代碼是函數被調用時,應用累加器的代碼,我的序碼。讓我知道是否需要其他東西。

我的序:

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

代碼,其中序叫做:

{ 
    // 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]中鍵入我的列表,第一個要處理的值/字符串將是c/3,然後等到那裏爲b/2並且一,1

+0

這似乎像要對這個奇怪的方式。你有什麼要求? – NathanOliver

+0

「您的第一個任務是爲累加器InOrder編寫一個模板,它通過.put(item)方法接受一系列項目,並通過指示序列是否正確的.get()方法返回true或false。「 – Scymantic

+0

這是沒有任何限制或要求的方向,除了我不能有超過1個放置功能或獲得功能的事實,這是一種非常奇怪的做事方式,而不是我的第一選擇 – Scymantic

回答

0

你的錯誤是,當您發現該命令有錯誤不停止:

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

美好的謝謝我知道這是簡單的事情,我一直沒有考慮過直! – Scymantic

0

這是行不通的:

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

給你的構造函數。

+0

謝謝你回答我的問題。是絕對正確的 – Scymantic