I have got int
s, a vector<int>
, and a vector<string>
in a tuple function. If there is an error when running this function, it will return a tuple of: {0, 0, {0}, {"0"}}
. The int
s have no errors. I have simplified this code a lot, and can't figure out why I can't use a vector in a tuple. It puts a red squiggly line under the {
. Here is a much simpler version:
#include <iostream>
#include <vector>
using namespace std;
tuple<vector<int>, vector<string>> tuples()
{
return { {0}, {"0"} };
}
int main()
{
tuple<vector<int>, vector<string>> result = tuples();
if (get<0>(result) == {0} && get<1>(result) == {"0"})
{
cout << "It worked!\n";
}
return 0;
}
If you can't use vectors in tuples, what is the other way around this?
You can't use initialiser
lists {0}
on the right hand side ie after the ==
.
You can't use vectors in tuples
is a false
statement.
Changing your code to:
tuple<vector<int>, vector<string>> result = tuples();
vector<int> v = {0};
vector<string> v2 = {"0"};
if (get<0>(result) == v && get<1>(result) == v2)
{
cout << "It worked!\n";
}
Gives the desired results.
It is also worth investigating why the compiler put a squiggly
red line under your code by looking at the output from the compiler.
Check this one :) As far as you simply can't return initializer lists(implicit constructor of vector), you can return created tuple with vector constructors(explicit).
#include <iostream>
#include <tuple>
#include <vector>
using namespace std;
std::tuple<std::vector<int>, std::vector<string>> tuples()
{
return std::make_tuple(std::vector<int>({0}), std::vector<std::string>({"0"}));
}
int main()
{
tuple<vector<int>, vector<string>> result = tuples();
if (get<0>(result) == std::vector<int>{0} && get<1>(result) == std::vector<std::string>{"0"})
{
cout << "It worked!\n";
}
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.