我將需要決議成千上萬個 C 中的簡單條目。我只用 C 編程過,所以我可能會遺漏一些更高級的函式來使這項任務更容易。
一個條目由 4 個單獨的值組成: a sender、 a receiver、 adate和 a type of mail。其中三個是string值,最后一個是integer. 我的目標(在處理完所有條目之后)是列印出輸入中收到的所有不同條目以及每個條目被接收的次數。
這意味著,如果在輸入中多次出現相同的發件人、收件人、日期和郵件型別,則輸出將顯示該條目已被接收,例如 5 次。
最好的方法是什么?我嘗試了 C map,但無法使其作業。
uj5u.com熱心網友回復:
您可以使用實作比較的結構將其存盤在集合/多集合中:
struct Entry {
friend bool operator<(const Entry& lhs, const Entry& rhs) {
if (lhs.sender < rhs.sender) return true;
if (lhs.sender > rhs.sender) return false;
if (lhs.receiver < rhs.receiver) return true;
if (lhs.receiver > rhs.receiver) return false;
if (lhs.date < rhs.date) return true;
if (lhs.date > rhs.date) return false;
if (lhs.type_of_mail < rhs.type_of_mail) return true;
return false;
}
std::string sender;
std::string receiver;
std::string date; // this should be a proper date time, otherwise DST & timezones might be a problem
int type_of_mail; // this should be enum
};
int main() {
std::set<Entry> entries;
// or
std::multiset<Entry> entries_duplications_allowed;
// you might insert elements here
// you might loop over entries using e.g. range for here
}
uj5u.com熱心網友回復:
我建議用 定義一個類,operator<這樣就可以將類的實體存盤在std::map. 可std::map用于從比較等于計數的物件映射。lhs < rhs如果兩者都不rhs < lhs為真,則認為物件相等,因此只operator<需要多載。
您還可以添加operator>>和operator<<多載以使從流中讀取和寫入物件成為可能。
它可能看起來像這樣:
#include <iostream>
#include <map>
#include <string>
#include <tuple>
struct foo {
std::string sender;
std::string receiver;
std::string date;
int type_of_mail;
// compare two foo instances:
bool operator<(const foo& rhs) const {
return std::tie(sender, receiver, date, type_of_mail) <
std::tie(rhs.sender, rhs.receiver, rhs.date, rhs.type_of_mail);
}
// read a foo from an istream:
friend std::istream& operator>>(std::istream& is, foo& f) {
return is >> f.sender >> f.receiver >> f.date >> f.type_of_mail;
}
// write a foo to an ostream:
friend std::ostream& operator<<(std::ostream& os, const foo& f) {
return os << f.sender << ' ' << f.receiver << ' ' << f.date << ' '
<< f.type_of_mail;
}
};
int main() {
std::map<foo, unsigned> counts;
foo tmp;
// read foos from any istream
while(std::cin >> tmp) {
counts[tmp]; // count
}
// print the count for each
for(const auto&[f, count] : counts) {
std::cout << count << ' ' << f << '\n';
}
}
演示
uj5u.com熱心網友回復:
對于要搜索的每個欄位,我建議使用單個資料表和索引表。(實際上這聽起來你應該使用資料庫,而不是撰寫資料庫)
將所有記錄放入std::vector<Record>. 為每個關鍵欄位
創建一個。std::map<key_text, vector_index>
要查找記錄:
- 使用鍵(字串)搜索相應的
map(索引表)。 - 如果找到,提取索引欄位。
- 使用索引歸檔為
std::vector<Record>.
多欄位鍵搜索更加困難并且可能占用更多空間(如果您使用的是索引資料結構)。
恕我直言,您最好的方法是使用資料庫。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/522824.html
標籤:C 字典
上一篇:我已經使用Python中的dict()函式為簡單的英語到德語詞典構建了一個代碼,還有改進的余地嗎?
下一篇:試圖列印出帶有索引號的字典
