有人可以告訴我如何直接訪問各個值嗎?要真正使用 out 的所指物件而不是存盤在臨時變數 PosTextfield 和 val 之間。
#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;
}
uj5u.com熱心網友回復:
std::get回傳參考。您可以只存盤這些參考:
const auto& PosTextfield = std::get<0>(out);
const auto& val = std::get<1>(out);
要么
const auto& PosTextfield = out.first;
const auto& val = out.second;
或者,auto如果您愿意,可以將關鍵字替換為實際型別。const也可以洗掉,因為auto會推斷它,但是明確地撰寫它可以讓讀者清楚地知道這兩個參考是不可修改的。
這不會創建任何新物件。參考是指傳遞給函式的對的元素。
out.first或者直接使用andout.second或std::get<0>(out)and參考要使用它們的元素std::get<1>(out)。
uj5u.com熱心網友回復:
您可以std::pair通過以下方式訪問 a 的元素:
pos_text.first; // Returns CursorMatrix
pos_text.second; // Returns std::string
所以你可以重寫foo()為:
void foo(const std::pair<Cursor_matrix, std::string>& out)
{
std::cout << out.first[0][0] << out.first[0][1] << out.second << "\n";
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/436229.html
