有了一个主机名 vector ,我想从另一个 vector 中提取包含任何字符串的任何主机名。
假设我有一个包含主机名和 IP 地址的 2D vector :
std::vector<std::vector<string>> hostnames = {{"Mike-computer","1.2.3.4"},
{"John-computer","5.6.7.8"},
{"Monica-computer","9.10.11.12"}};
另一个包含目标主机名的 vector :
std::vector<string> targets = {"Mike", "Sophia"};
如果hostnames
vector 中的任何行包含“Mike”
或“Sophia”
,则提取其信息。在此示例中,“Mike-Computer”
将被取消,因为它包含来 self 的 targets
vector 的 “Mike”
。
我在 this thread 上找到我可以在我的 targets
vector 上使用 std::find
,但如果它不完全匹配,它将不起作用。仅当我明确地说“Mike-computer”时它才有效,但我不知道我查询的计算机的完整主机名。
这是一段代码:
for (std::vector<std::vector<std::string>>::iterator row = hostnames.begin(); row != hostnames.end(); ++row)
{
for (std::vector<std::string>::iterator col = row->begin(); col != row->end(); ++col)
{
if ((std::find(targetsList.begin(), targetsList.end(), *col) != targetsList.end()))
{
std::cout << *col << " is a match" << std::endl;
}
}
}
最佳答案
std::string
有一个 find
成员函数将查找一个字符串是否存在于另一个字符串中。您可以使用它来查看主机名是否包含目标名称,例如
for (const auto& host : hostnames)
{
for (const auto& target : tagets)
{
if (host[0].find(target) != std::string::npos)
std::cout << "Found: " << host[0] << " with IP: " << host[1];
}
}
我还想建议,如果您总是只有一个主机名和 IP 对,那么您可以使用像这样的实际数据结构
struct Computer
{
std::string name;
std::string IP;
};
所以
if (host[0].find(target) != std::string::npos)
std::cout << "Found: " << host[0] << " with IP: " << host[1];
看起来像
if (host.name.find(target) != std::string::npos)
std::cout << "Found: " << host.name << " with IP: " << host.IP;
或者至少使用std::pair<std::string, std::string>
所以代码中没有“魔数(Magic Number)”。
关于c++ - 如何查明某个字符串是否包含在 std::vector 的任何字符串中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49182027/