std::set<std::string> &uniq_email_list;
我有一组很多email元素,例如:
('foo@bar.com', 'foo2@bar.com', 'foo@bazz.com', 'foo2@bazz.com','zfoo@bar.com')
然后将这些元素写入文件
for(iter = uniq_email_list.begin() ; iter!=uniq_email_list.end(); ++iter){
output_file<< *iter << std::endl;
}
在我将这些元素写入文件之前,我想按下一个域名"@"排序我想让它在文件
中看起来像这样foo@bar.com
foo2@bar.com
zfoo@bar.com
foo@bazz.com
foo2@bazz.com
And I know
不能使用集合,它如何排序是特定集合类型的一部分。给定的集合有固定的集合顺序,不能更改。
您可以相对容易地使用相同的数据创建一个新集。只需创建一个基于新标准
进行排序的新集合我读了那篇文章,排序集使用std::sort但是我找不到问题的答案。
作为我研究的结果,我发现了类似
的东西std::set<string>::iterator ⁢
it=myset.find('@');
我可以用这个结构按返回地址排序吗?或者如果有其他适合这个问题的解决方案,提前谢谢你,我已经准备好听取有关c++解决方案的问题的建议。
如果您要单独使用域名和名称部分,我建议您将它们分开并将它们放在email
类中,您为其提供满足创建std::set<email>
所需的比较要求的operator<
:
#include <tuple> // std::tie
struct email {
std::string name;
std::string domain;
// The compare operator used by default by a std::set<email>:
bool operator<(const email& rhs) const {
// using std::tie makes creating an operator< that does
// strict weak ordering relatively easy:
return std::tie(domain, name) < std::tie(rhs.domain, rhs.name);
}
};
std::ostream& operator<<(std::ostream& os, const email& e) {
os << e.name;
if(not e.domain.empty()) os << '@' << e.domain;
return os;
}
std::istream& operator>>(std::istream& is, email& e) {
if(std::string tmp; is >> tmp) {
auto at_pos = tmp.find('@');
e.name = tmp.substr(0, at_pos);
if(at_pos != std::string::npos) {
e.domain = tmp.substr(at_pos + 1);
} else {
e.domain.clear();
}
}
return is;
}
现在可以将它们放入std::set<email>
或std::vector<email>
(以及std::sort
)中,并按照成员operator<
指定的顺序将它们流式输出。首先是域名,最后是名称,并从流中读取:
email tmp;
while(instream >> tmp) {
std::cout << "read address: " << tmp << 'n';
}
演示class EmailCompare
{
public:
bool operator()(const std::string& a, const std::string& b) const {
// your code here
return ... ;
}
};
using EmailSet = std::set<std::string, EmailCompare>;