简体   繁体   中英

Returning two values of two different types in a C++ function

I'm writing a program that performs a simple rotation (think like rot13) on a string taken from user input. My problem is that I want to change each character in the string's ASCII value by a different amount each time - and so I'm using a for loop to go through the string, and calling a function that generates a random number each time. However, I want to be able to return this number so that I can "unscramble" the string at a later date. I also need to return the string though, obviously.

Here's my code:

int ranFunction()
{

    int number = rand() % 31;
    return number;

}

string rotFunction(string words)
{
    int upper_A = 65;
    int lower_z = 122;
    int rand_int = 0;

    for (int i = 0; i < words.length(); i++)
    {
        rand_int = ranFunction();

        if (words[i] >= upper_A && words[i] <= lower_z) {

            words[i] -= rand_int;


        }

    }
    return words; 
}

I'm hoping to get rotFunction to return words AND an integer based on whatever rand_int happens to be each time.

Just a note: the numbers I'm using RE: ascii values etc are totally arbitrary right now, just there for testing.

To return two different types use std::pair

std::pair<T1,T2> foo(){
    return std::make_pair(v1,v2);
}

Example:

std::pair<int,float> foo(){
    return std::make_pair(5,0.5f);
}

To return more than two different types use std::tuple :

std::tuple<T1,T2,...,Tn> foo(){
    return std::make_pair(v1,v2,...,Tn);
}

Example:

std::tuple<int,float,std::string> foo(){
    return std::make_tuple(5,0.5f,"sss");
}

A simple way would be to return a struct or class type.

 struct rotReturn
 {
      int ran;
      std::string str;
 };

 rotReturn rotFunction(std::string words)
 {
     // what you have, except for the return
     rotReturn retval
     retval.ran = rand_int;
     retval.str = words;
     return retval;
 }

Obviously, it is possible to optimise and use the structure to be returned within the function, rather than using separate variables for intermediate results.

Alternatives include returning an std::pair<int, std::string> or (for more values to be bundled), a std::tuple . Both of these are specialised struct or class types.

It is also possible to pass such types to functions, by reference or pointer (address), so the caller can pass an object which the function stores data into.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM