访问元组向量中的元素 C++

Ben*_*org 2 c++ c++14

我有以下代码体。

#include <iostream>
#include <vector>
#include <tuple>
int main() {
    std::vector<std::tuple<int, int>> edges(4,{1,2});

    for (auto i = std::begin (edges); i != std::end (edges); ++i) {
            std::cout << std::get<0>(i) << " "<< std::get<1>(i)<< " ";
        }
}
Run Code Online (Sandbox Code Playgroud)

在我看来这是有道理的,我有一个正在初始化的元组向量。然后,我迭代矢量,分别打印元组的两个元素。

但是代码无法返回

8:26: error: no matching function for call to 'get'
   std::cout << std::get<0>(i) << " "<< std::get<1>(i)<< " ";
                ^~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)

有人可以解释一下为什么吗?

Cor*_*mer 7

我会改为基于范围的for循环

for (auto const& edge : edges) {
    std::cout << std::get<0>(edge) << " "<< std::get<1>(edge)<< " ";
}
Run Code Online (Sandbox Code Playgroud)

否则,要访问每个边,您需要使用迭代器取消引用*以获取实际的元组本身

for (auto iter = std::begin(edges); iter != std::end(edges); ++iter) {
    std::cout << std::get<0>(*iter) << " "<< std::get<1>(*iter)<< " ";
}
Run Code Online (Sandbox Code Playgroud)