Home > database >  read values of reference direct by std::pair<std::array<std::array<u_int16_t,2>,1>,st
read values of reference direct by std::pair<std::array<std::array<u_int16_t,2>,1>,st

Time:03-02

can someone tell me how to access the individual values directly? To really use the referent of out and not store in the temporary variable PosTextfield and val between.

#include <iostream>
#include <utility>
#include <string>
#include <cstdint>
#include <array>

using Cursor_matrix = std::array<std::array<uint16_t,2>, 1>;

void foo(const std::pair<Cursor_matrix,std::string> &out)
{
  Cursor_matrix PosTextfield;
  PosTextfield = std::get<0>(out);

  std::string val = std::get<1>(out);

  std::cout << PosTextfield[0][0] << PosTextfield[0][1] << val << "\n";
}

int main()
{
    Cursor_matrix pos;
    pos[0][0] = 1;
    pos[0][1] = 2;

    std::string str = "hello";

    std::pair<Cursor_matrix, std::string> pos_text;

    pos_text = std::make_pair(pos, str);

    return 0;
}

CodePudding user response:

std::get returns references. You can just store these references:

const auto& PosTextfield = std::get<0>(out);
const auto& val = std::get<1>(out);

or

const auto& PosTextfield = out.first;
const auto& val = out.second;

or you can replace the auto keywords with the actual types if you prefer. const can be removed as well, since auto will deduce it, but writing it explicitly makes it clear to the reader that the two references are non-modifiable.

This doesn't create any new objects. The references refer to the elements of the pair passed to the function.

Or just refer to the element directly where you want to use them with out.first and out.second or std::get<0>(out) and std::get<1>(out).

CodePudding user response:

You can access a std::pair's elements by the following:

pos_text.first; // Returns CursorMatrix
pos_text.second; // Returns std::string

So you can rewrite foo() as:

void foo(const std::pair<Cursor_matrix, std::string>& out)
{
    std::cout << out.first[0][0] << out.first[0][1] << out.second << "\n";
}
  • Related