为什么不能使用std :: get()获得向量的成员
Why can std::get() not be used to get members of a vector?
我对std::get()
函数感到困惑。std::get()
可用于访问array
,pair
和tuple
中的成员。那么,为什么标准也不允许其访问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
具有可变大小:您可以在运行时添加或删除元素。这意味着向量的std::get
将提供比operator[]
或at
的零好处。
相关文章:
- 向量成员在管理类指针C++队列时丢失
- C++:更新类的向量成员变量
- C++ 入门 12.1:我可以在类中使用静态向量成员实现 StrBlob<string> 吗?
- 具有向量成员的基类<int>
- C++ 向量::使用类对象迭代器擦除不擦除向量成员
- 无法将类构造函数中新创建的对象复制到 C++ 中的向量成员
- 修改另一个类的向量成员时出错
- 返回对私有向量成员元素的非常量引用是否是一种不好的做法
- 如何在 C++ 中将结构类型向量数据输入到结构向量成员(嵌套结构向量)中
- std::向量成员变量 EXC_BAD_ACCESS
- 如何使用其定义附近的显式长度/值构造函数初始化向量成员变量
- "Empty"数组\向量成员 C++
- 如何使用初始值设定项列表初始化 2D 向量成员
- 如何在类定义中初始化向量成员变量
- 如何初始化结构的向量成员
- 使用向量<向量>成员实例化对象时的隔离错误<int>
- 为向量成员和更新元素指定默认值
- 保持类的向量成员与类实例连续
- C++:在类构造函数中填充向量后,向量成员被销毁
- 通过引用另一个类方法传递向量成员变量