2

Having a vector of hostnames, I want to pull off any hostname that contains any string from another vector.

Let's say that I have a 2D vector containing hostnames and IP addresses:

std::vector<std::vector<string>> hostnames = {{"Mike-computer","1.2.3.4"}, 
                                         {"John-computer","5.6.7.8"}, 
                                         {"Monica-computer","9.10.11.12"}};

And another vector containing target hostnames:

std::vector<string> targets = {"Mike", "Sophia"};

If any line in hostnames vector contains "Mike" or "Sophia", pull off its info. In this example, "Mike-Computer" would be pulled off since it contains "Mike" from my targets vector.

I found on this thread that I can use std::find on my targets vector but it will not work if it is not an exact match. It would only work if I specifically says "Mike-computer" but I don't know the full hostnames of computers I query.

Here is the piece of code:

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;
        }
    }
}
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
Jim P.
  • 303
  • 1
  • 5
  • 15

1 Answers1

5

std::string has a find member function that will find if a string exists in another string. You can use that to see if the host name contains the target name like

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];
    }
}

I would also like to suggest that if you are always going to just have a host name and IP pair that you use a an actual data structure like

struct Computer
{
    std::string name;
    std::string IP;
};

So that

if (host[0].find(target) != std::string::npos)
    std::cout << "Found: " << host[0] << " with IP: " << host[1];

Would look like

if (host.name.find(target) != std::string::npos)
    std::cout << "Found: " << host.name << " with IP: " << host.IP;

Or at leas use a std::pair<std::string, std::string> so the code doesn't have "magic numbers" in it.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402