1

I have some code that is part of a larger function that is working. However, in order to optimize it and eliminate the unnecessary need for string copying I want to rewrite this code with references. My code relies on largerStr being a longer string than smallerStr. I want to rewrite this with references but I can't seem to get it to work. If I try and make largerStr and smallerStr references without explicitly initializing them the compiler tells me need to initialize it at declaration. If I try and put it as a temporary variable in the if statement I end up having both variables referencing the same string.

What is the best solution?

//str1 and str2 are std::strings
std::string largerStr, smallerStr;

if(str1.length() > str2.length()) {
    largerStr = str1;
    smallerStr = str2;
} else {
    largerStr = str2;
    smallerStr = str1;
}
user2771729
  • 448
  • 1
  • 7
  • 13
  • "in order to optimize it and eliminate the unnecessary need for string copying"--> why do you have to create references, use pass by reference or pass by const ref – Tejendra May 30 '19 at 05:22
  • You might utilize `std::string_view` if you don't modify `largerStr`/`smallerStr` – R2RT May 30 '19 at 05:27
  • Reference cannot be "assigned", only can be "initialized". So the ternary operator in Kamil's answer works. – Chen OT May 30 '19 at 06:44

2 Answers2

5

You can use ternary operator to initialize them.

#include <string>    
int main() {
    std::string str1, str2;
    const bool str1_longer = str1.length() > str2.length();
    std::string& largerStr  = str1_longer ? str1 : str2;
    std::string& smallerStr = str1_longer ? str2 : str1;
}
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
4

You can use C++17's structured binding declaration to unpack a std::tie'd tuple of references.

auto [largerStr, smallerStr] = str1.length() > str2.length() ?
                               std::tie(str1, str2)          :
                               std::tie(str2, str1)          ;

The structured bindings aren't variables or references per-se, but they avoid the copies and act like references in every way that seems important to you.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458