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();
}
this is for my list class to find the index and i want to return a int, double or a string but i dont know how plz help.
CodePudding user response:
See your question is not clear, but assuming you have three vectors of nodes of different types (int, float, std::string), and you want to return a value based on index. In that case you can use std::variant if you are using C 17 or above.
using MyVariant = std::variant<int,double,std::string>;
MyVariant list::at(int index)
{
...
}
For C 14 or below, you can look for union
(better to wrap it in a class) or use void*
(not recommended). Or use boost::variant
for C 11 and C 14.
CodePudding user response:
It's hard to give a solid answer to your question which lacks details. But I still want to suggest a potential solution. Keep in mind that this is only a suggestion.
You might return a std::tuple
containing 3 std::optional
values:
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;
}
But without knowing your circumstances, I can't say if this will be a nice way of doing it or not.