History of Idiom 20 > diff from v53 to v54
Edit summary for version 54 by archi:
[Cpp] fixed small grammar mistake
[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.
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
The elements can be accessed via returnValue.first and returnValue.second.
Comments bubble
The elements can be accessed via returnValue.first and returnValue.second.