example4_functions.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <tuple>
#include <string>

// Function returning multiple values using tuple
std::tuple<int, int, int> parseDate(const std::string& date) {
    // Assuming date format is "YYYY-MM-DD"
    int year = std::stoi(date.substr(0, 4));
    int month = std::stoi(date.substr(5, 2));
    int day = std::stoi(date.substr(8, 2));
    return std::make_tuple(year, month, day);
}

// Function taking tuple as parameter
void printDate(const std::tuple<int, int, int>& date) {
    std::cout << "Date: " 
              << std::get<0>(date) << "-"
              << std::get<1>(date) << "-"
              << std::get<2>(date) << std::endl;
}

int main() {
    auto date = parseDate("2023-08-25");
    printDate(date);

    // Using structured binding with function return
    auto [year, month, day] = parseDate("2024-01-01");
    std::cout << "New Year: " << year << "-" << month << "-" << day << std::endl;

    return 0;
}
Back to tuple