c++ - 为什么 std::get() 不能用于获取 vector 的成员?

我对 std::get() 函数感到困惑。 std::get() 可用于访问 arraypairtuple 中的成员。那么,为什么标准也不允许它访问 vector 中的成员呢?

#include <iostream>
#include <array>
#include <vector>
#include <tuple>
#include <utility> // std::pair
using namespace std;
int main()
{
    array<int, 4> a1{3,4,5,67};
    pair<int,int>  p1{5,6};
    tuple<int,float,float> t1{6,5.5,4.5};

    cout << std::get<1>(a1) <<endl;
    cout << std::get<1>(p1) <<endl;
    cout << std::get<1>(t1) <<endl;
}

以下是输出:

4
6
5.5

但是当我尝试将 std::get()vector 一起使用时,我得到了这个编译错误:

#include <iostream>
#include <array>
#include <vector>
#include <tuple>
#include <utility> // std::pair
using namespace std;
int main()
{
 vector<int> v1{4,5,6,7,9};
 cout << std::get<1>(v1) <<endl;
}

编译错误:

  main.cpp: In function 'int main()':
  main.cpp:10:27: error: no matching function for call to 'get(std::vector&)'
  cout << std::get<1>(v1) <<endl;
                       ^
  In file included from main.cpp:2:0:
 /usr/include/c++/5/array:280:5: note: candidate: template constexpr _Tp& 
  std::get(std::array<_Tp, _Nm>&)
  get(array<_Tp, _Nm>& __arr) noexcept
  ^

最佳答案

std::get 的索引作为模板参数允许它在编译时检查索引是否有效。这只有在编译时也知道容器的大小时才有可能。 std::vector 具有可变大小:您可以在运行时添加或删除元素。这意味着 vector 的 std::get 将比 operator[]at 提供零优势。

https://stackoverflow.com/questions/49516330/

相关文章:

c++ - 如何以跨平台的方式获取(几乎)唯一的系统标识符?

c++ - 如何获得 high_resolution_clock 的精度?

c++ - 对两个对应的数组进行排序

c++ - 使用 boost::graph 获取特定边缘

c++ - 如何检查 STL 迭代器是否指向任何东西?

c++ - 为什么 PRIu64 在此代码中不起作用?

c++ - 了解 double 到 int64_t 的转换

c++ - 不能在数组上使用 .begin() 或 .end()

c++ - 在 C++ 中,是否可以获取函数的返回类型以便在不调用该函数的情况下声明一个变量?

c++ - OpenCV:获取 3 channel RGB 图像,拆分 channel 并仅使用 R