I've not used std::tuple
much in C++ and I have the following tuple:
std::tuple<int, int> range {0, 100};
This is the range for my mysql query:
prestmt_ = con_ -> prepareStatement("SELECT example_value FROM example_table WHERE example_column = '0' LIMIT ?, ?");
prestmt_ -> setInt(1, std::get<0>(range));
prestmt_ -> setInt(2, std::get<1>(range));
I'm using a tuple structure to make it clear that the two integers are coupled together in the operation of the function.
I need to increment both tuple integers after each query:
range = std::tuple<int, int>(std::get<0>(range) + 100, std::get<0>(range) + 100);
This re-assignment looks really poor and isn't very readable. Is there a better way of editing these tuple values?
Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called. But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.
Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets. tup1 = (50,); Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.
Tuple is stored in a single block of memory. Creating a tuple is faster than creating a list. Creating a list is slower because two memory blocks need to be accessed. An element in a tuple cannot be removed or replaced.
The key takeaways are: The key difference between the tuples and lists is that while the tuples are immutable objects the lists are mutable. This means that tuples cannot be changed while the lists can be modified. Tuples are more memory efficient than the lists.
std::get<N>(x)
returns an lvalue reference to the N
th tuple element if x
is an lvalue. You can therefore say:
std::get<0>(range) += 100;
std::get<1>(range) += 100;
wandbox example
For readability, use a function or lambda:
const auto increaseRange = [](auto& x, auto increment)
{
std::get<0>(x) += increment;
std::get<1>(x) += increment;
};
Usage:
increaseRange(range, 100);
wandbox example
Alternatively, consider creating your own integer_range
class instead of using std::tuple
. It could support an extend
method that does what you want and have named fields which would be easier to read compared to std::get<N>(...)
:
template <typename T>
struct integer_range
{
T _begin, _end;
constexpr integer_range(T begin, T end) noexcept
: _begin{begin}, _end{end}
{
assert(_end >= _begin); // additional safety
}
void extend(T increment) noexcept
{
_begin += increment;
_end += increment;
}
};
wandbox example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With