auto list::at(int index)
{
for (auto node : VECTOR_OF_INT)
if (node.getIndex() == index)
return node.getValue();
for (auto node : VECTOR_OF_DOUBLE)
if (node.getIndex() == index)
return node.getValue();
for (auto node : VECTOR_OF_STRING)
if (node.getIndex() == index)
return node.getValue();
}
這是讓我的串列類找到索引,我想回傳一個 int、double 或 string,但我不知道如何幫助。
uj5u.com熱心網友回復:
看到您的問題不清楚,但假設您有三個不同型別(int、float、std::string)節點的向量,并且您想根據索引回傳一個值。在這種情況下,如果您使用的是 C 17 或更高版本,則可以使用 std::variant。
using MyVariant = std::variant<int,double,std::string>;
MyVariant list::at(int index)
{
...
}
對于 C 14 或以下,可以查找union(最好將其包裝在一個類中)或使用void*(不推薦)。或boost::variant用于 C 11 和 C 14。
uj5u.com熱心網友回復:
您的問題缺乏細節,很難給出可靠的答案。但我仍然想提出一個潛在的解決方案。請記住,這只是一個建議。
您可能會回傳std::tuple包含 3 個std::optional值的一個:
auto list::at(const int index)
{
std::tuple< std::optional<int>, std::optional<double>,
std::optional<std::string> > returnValue;
for (auto node : VECTOR_OF_INT)
{
if (node.getIndex() == index)
{
std::get<0>(returnValue) = node.getValue();
std::get<1>(returnValue) = { };
std::get<2>(returnValue) = { };
return returnValue;
}
}
if ( !std::get<0>(returnValue).has_value( ) )
{
std::get<0>(returnValue) = { };
}
for (auto node : VECTOR_OF_DOUBLE)
{
if (node.getIndex() == index)
{
std::get<1>(returnValue) = node.getValue();
std::get<2>(returnValue) = { };
return returnValue;
}
}
if ( !std::get<1>(returnValue).has_value( ) )
{
std::get<1>(returnValue) = { };
}
for (auto node : VECTOR_OF_STRING)
{
if (node.getIndex() == index)
{
std::get<2>(returnValue) = node.getValue();
return returnValue;
}
}
if ( !std::get<2>(returnValue).has_value( ) )
{
std::get<2>(returnValue) = { };
}
return returnValue;
}
但是在不了解您的情況的情況下,我不能說這是否是一種很好的方式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/389656.html
標籤:C
上一篇:轉發參考:參考引數來源
