Manipulate tuple values ​​efficiently?

I have not used std::tuple lot 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 use the tuple structure to make it clear that two integers are associated with the operation of the function.

I need to increment tuple integers after each query:

 range = std::tuple<int, int>(std::get<0>(range) + 100, std::get<0>(range) + 100); 

This redistribution looks very bad and not very readable. Is there a better way to edit these tuple values?

+5
source share
1 answer

std::get<N>(x) returns an lvalue reference to the N th tuple element if x is an lvalue. Therefore you can say:

 std::get<0>(range) += 100; std::get<1>(range) += 100; 

wandbox example


For readability, use the function or lambda:

 const auto increaseRange = [](auto& x, auto increment) { std::get<0>(x) += increment; std::get<1>(x) += increment; }; 

Using:

 increaseRange(range, 100); 

wandbox example


Alternatively, consider creating your own integer_range class instead of using std::tuple . It can support the extend method, which does what you want, and has fields with names that are easier to read than 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

+2
source

Source: https://habr.com/ru/post/1264130/


All Articles