大佬教程收集整理的这篇文章主要介绍了c – 如何确定字符串是否包含在std :: 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"}};
另一个包含目标主机名的向量:
std::vector<String> targets = {"Mike","Sophia"};
如果主机名矢量中的任何一行包含“MIke”或“Sophia”,请拉出其信息.在这个例子中,“MIke-Computer”将被拉掉,因为它包含来自我的目标向量的“MIke”.
我在this thread发现我可以在我的目标向量上使用std :: find,但如果它不是完全匹配则无法工作.它只会在我特意说“迈克计算机”但我不知道我查询的计算机的完整主机名时才有效.
这是一段代码:
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; } } }
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;
或者在leas使用std :: pair< std :: String,std :: String>所以代码中没有“魔术数字”.
以上是大佬教程为你收集整理的c – 如何确定字符串是否包含在std :: vector的任何字符串中?全部内容,希望文章能够帮你解决c – 如何确定字符串是否包含在std :: vector的任何字符串中?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。