所以你的T
對象是一個公司ntainer,你還沒有給我們提供很多關於它的信息,但是如果你在對象內部使用vector
來包含對象,那麼你將會前進。
其次,如果您要使用pair
來包含您的vector
,您可以利用get
來選擇正確的成員。
所以,寫答案的目的,我TransactionList
對象將是這樣的:
typedef pair<vector<string>, vector<double>> TransactionList;
然後我們可以重寫你的函數:
template <typename T>
TransactionList getTransactionsForSearchCriteria(TransactionList result, T criteria) {
auto& attribute = get<vector<T>>(result);
auto it = find(attribute.begin(), attribute.end(), criteria);
//check that criteria matches transaction attribute
if(it != attribute.end()) {
//flag as match
}
//guessing what you want to do with this: attribute.insert(it, criteria); return result;
}
如果你能保證名單已維護排序,該標準提供二進制搜索功能,這將顯着提高您的大型收藏的性能:
template <typename T>
transactionList getTransactionsForSearchCriteria(transactionList result, T criteria) {
auto& attribute = get<vector<T>>(result);
auto it = lower_bound(attribute.begin(), attribute.end(), criteria);
//check that criteria matches transaction attribute
if(it != attribute.end() && *it == criteria) {
//flag as match
}
//guessing what you want to do with this: attribute.insert(it, criteria); return result;
}
至於確定你的輸入值使用TransactionList result
時,採取所有輸入作爲string
然後看你是否能成功地消耗整個string
成double
是string
或double
:Forcing String to int Function to Consume Entire String
size_t size;
double num;
string i;
cin >> i;
if(sscanf(i.c_str(), "%lf%n", &num, &size) == 1 && size == i.size()) {
result = getTransactionsForSearchCriteria(result, num);
} else {
result = getTransaztionsForSearchCriteria(result, i);
}
Live Example
嗨,謝謝你。使用你的例子,如果我想使用這些函數來返回它們各自的int/double/T值並將它們存儲在一個變量中,我該怎麼去做呢? – marcuthh
@marcuthh:我剛剛包括那 – purpletentacle
這已完美運行。謝謝你的時間! – marcuthh