mardi 27 mars 2018

Why can std::get() not be used to get members of a vector?

I am confused about the std::get() function. std::get() can be used to access members in array, pair, and tuple. So, why does the Standard not also allow it to access the members in 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;
}

Following is the output:

4
6
5.5

But when I try to use std::get() with vector, I get this compilation error:

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

Compilation error:

  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
  ^

Aucun commentaire:

Enregistrer un commentaire