c++ - 从元组中提取 vector

标签 c++ vector tuples

我有int一个vector<int> , 和一个 vector<string>在元组函数中。如果运行此函数时出现错误,它将返回一个元组:{0, 0, {0}, {"0"}} . int没有错误。我已经大大简化了这段代码,但无法弄清楚为什么我不能在元组中使用 vector 。它在 { 下面放了一条红色的波浪线。 . 这是一个更简单的版本:

#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;
}

如果不能在元组中使用 vector ,还有什么其他方法可以解决这个问题?

最佳答案

您不能在右侧使用 initialiser 列表 {0},即在 == 之后。

你不能在元组中使用 vector 是一个false语句。

将您的代码更改为:

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";
}

给出了想要的结果。

通过查看编译器的输出,还值得研究为什么编译器会在您的代码下方放置一条波浪状红线。

关于c++ - 从元组中提取 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48021170/

相关文章:

c++ - 基于 vector 的二叉树遍历

c++ - 继承,提升基类成员

构建线段树时的 C++ 段错误

c++ - std::vector 如何分配对象?

C++ - 使用类参数定义 vector 大小

c# - 为什么我们不能给元组中的属性命名?

f# - 使用 "fst"从元组中提取第一个元素抛出错误 "type mismatch"

c++ - 如何在 c/c++ 中解析字符串?

actionscript-3 - AS3 : How to convert a Vector to an Array

c# - C# 方法可以定义可变数量的对象参数和可变数量的整数参数吗?