Q:

Can I return a selected reference in c++?

Please see following sudo code.
Object& getObjectDependingOnMonth(std::string& month, std::vector<Object>& vec) {

    if (month == "January") {
        auto& ref = vec.at(1);
    } else {
        auto& ref = vec.at(2);
    }

    ref.do_something();  // error because ref is local in block above.

    return ref;  // error because ref is local in block above.
}

The above code shows what I want to do. I would like to get a reference of element of a vector. It depends on an input, month. I would like to use its reference outside the function, getObjectDependingOnMonth(...). However I could not think of how to return valid reference of a selected element in vector without duplicated code in blocks. auto& ref = ... is defined in a if block. The ref are invalid outside its block.
Could I return a selected reference from a function?
Thank you very much.

A:

Just change the code:
if (month == "January") {
    auto& ref = vec.at(1);
} else {
    auto& ref = vec.at(2);
}

to the following so that you have one reference
auto& ref = vec.at(month == "January" ? 1 : 2);

