我正在尝试防止在功能data.frame
上添加重复项,但尚未成功。你能帮我如何做到这一点吗?预先感谢。
V1 V2 V3 V4 V5
1 0 0 0 0 0
2 0 0 223 13 9
3 0 223 0 57 28
4 0 13 57 0 82
5 0 9 28 82 0
程序的输出是;
example_data
答案 0 :(得分:0)
如评论中所述,您仅检查重复的family_name
,而不检查child_name
。您可以使用std::find
搜索std::vector
void add_child(map<string, vector<string>> &family, const string & family_name, const string & child_name)
{
auto f_it = family.find(family_name);
if (f_it != family.cend())
{
auto c_it = find(f_it->second.begin(), f_it->second.end(), child_name);
if (c_it == f_it->second.end())
{
f_it->second.insert(c_it, child_name);
}
else
{
cerr << "Error: Already has child <" << child_name << ">" << endl;
}
}
else
{
cerr << "Error: No family <" << family_name <<
"> for child <" << child_name << ">" << std::endl;
}
}
或者,您也可以使用std::map<std::string, std::set<std::string>>
来确保唯一性。此外,您可以利用insert
的返回值只查找每个名称一次。
void add_family(map<string, set<string>> &family, const string &name)
{
if (!family.insert({name, {}}).second)
{
cerr << "Error: Already has family <" << name << ">" << endl;
}
}
void add_child(map<string, set<string>> &family, const string & family_name, const string & child_name)
{
auto it = family.find(family_name);
if (it == family.cend())
{
cerr << "Error: No family <" << family_name <<
"> for child <" << child_name << ">" << std::endl;
} else if (!it->second.insert(child_name).second)
{
cerr << "Error: Already has child <" << child_name << ">" << endl;
}
}
但我认为这种设计不雅致。我完全不会理会add_family
。只需利用map
和set
的不变式即可。
void add_child(map<string, set<string>> &family, const string & family_name, const string & child_name)
{
family[family_name].insert(child_name);
}