I know this can look like a rookie question already asked a thousand time. But I searched for the exact answer and I haven't found one...
I'm working on a code that, to sum up, fill an XML with different data.
I'm trying to optimize a part of it. The "naïve" code is the following:
xml << "<Node>";
for(auto& input : object.m_vec)
{
    if(input == "Something")
    {
        xml << input;
    }
}
xml << "</Node>";
for(auto& input : object.m_vec)
{
    if(input == "SomethingElse")
    {
        xml << "<OtherNode>";
        xml << input;
        xml << "</OtherNode>";
        break;
    }
}
The important thing is, while more than one input fit in <Node></Node>, only one fit in <OtherNode></OtherNode> (explaining the break;) and it may not exist either (explaining the xml << in-between the if statement).
I think I could optimize it such like:
std::vector<std::string>* VecPointer;
xml << "<Node>";
for(auto& input : object.m_vec)
{
    if(input == "Something")
    {
        xml << input;
    }
    else if(input == "SomethingElse")
    {
        VecPointer = &input;
    }
}
xml << "</Node>";
if(!VecPointer->empty())
{
    xml << "<OtherNode>"
        << *VecPointer
        << "</OtherNode>";
}
The point for me here is that there is no extra memory needed and no extra loop. But the pointer to the local variable bothers me. With my beginner's eyes I can't see a case where it can lead to something wrong.
Is this okay? Why? Do you see a better way to do it?
 
     
    