Logo

Programming-Idioms

History of Idiom 20 > diff from v53 to v54

Edit summary for version 54 by archi:
[Cpp] fixed small grammar mistake

Version 53

2019-09-26, 15:56:08

Version 54

2019-09-26, 15:56:49

Idiom #20 Return two values

Implement a function search which looks for item x in a 2D matrix m.
Return indices i, j of the matching cell.
Think of the most idiomatic way in the language to return the two values at the same time.

Idiom #20 Return two values

Implement a function search which looks for item x in a 2D matrix m.
Return indices i, j of the matching cell.
Think of the most idiomatic way in the language to return the two values at the same time.

Imports
#include <utility>
Imports
#include <utility>
Code
template<typename T, size_t len_x, size_t len_y>
std::pair<size_t, size_t> search (const T (&m)[len_x][len_y], const T &x) {
    for(size_t pos_x = 0; pos_x < len_x; ++pos_x) {
        for(size_t pos_y = 0; pos_y < len_y; ++pos_y) {
            if(m[pos_x][pos_y] == x) {
                return std::pair<size_t, size_t>(pos_x, pos_y);
            }
        }
    }

    // return an invalid value if not found
    return std::pair<size_t, size_t>(len_x, len_y);
}
Code
template<typename T, size_t len_x, size_t len_y>
std::pair<size_t, size_t> search (const T (&m)[len_x][len_y], const T &x) {
    for(size_t pos_x = 0; pos_x < len_x; ++pos_x) {
        for(size_t pos_y = 0; pos_y < len_y; ++pos_y) {
            if(m[pos_x][pos_y] == x) {
                return std::pair<size_t, size_t>(pos_x, pos_y);
            }
        }
    }

    // return an invalid value if not found
    return std::pair<size_t, size_t>(len_x, len_y);
}
Comments bubble
This tries to be similar to the C variant. In a real world program the 2D matrix should offer a iterator.

The elements can be accessed via returnValue.first and returnValue.second.
Comments bubble
This tries to be similar to the C variant. In a real world program the 2D matrix should offer an iterator.

The elements can be accessed via returnValue.first and returnValue.second.
Demo URL
https://repl.it/repls/SereneWearyApplet
Demo URL
https://repl.it/repls/SereneWearyApplet