纠结的问题
C++ Primer 中文版,
第81页: “v[n] 返回v中位置为n的元素” //表3-5 vector操作
第279页:“c[n] 返回下标为n的元素的引用” //表9-9 访问顺序容器内元素的操作
1.vector容器是顺序容器中的一种,那下标返回的是元素还是元素的引用?
2.vec[1]是可以接收常量值的,如vec[1]=10; //vector<int> vec(10,1);
如果vec[1]返回的是引用,vec[1]=10应该是错误的(需要const引用接收10),说明“c[n] 返回下标为n的元素的引用”是错误的!
如果书上写的没错,那应该怎么理解81,279页写的这两句?
[解决办法]
[解决办法]
const容器,返回const 引用.
const_reference operator[](size_type _Pos) const
{// subscript nonmutable sequence
#if _HAS_ITERATOR_DEBUGGING
if (size() <= _Pos)
{
_DEBUG_ERROR("vector subscript out of range");
_SCL_SECURE_OUT_OF_RANGE;
}
#endif /* _HAS_ITERATOR_DEBUGGING */
_SCL_SECURE_VALIDATE_RANGE(_Pos < size());
return (*(_Myfirst + _Pos));
}
非const容器直接返回引用:
reference operator[](size_type _Pos)
{// subscript mutable sequence
#if _HAS_ITERATOR_DEBUGGING
if (size() <= _Pos)
{
_DEBUG_ERROR("vector subscript out of range");
_SCL_SECURE_OUT_OF_RANGE;
}
#endif /* _HAS_ITERATOR_DEBUGGING */
_SCL_SECURE_VALIDATE_RANGE(_Pos < size());
return (*(_Myfirst + _Pos));
}
[解决办法]
非const容器返回的是 元素的引用.
const容器返回的是 元素的const引用
vc2008的stl:
---
- C/C++ code
//const 成员 const_reference operator[](size_type _Pos) const { // subscript nonmutable sequence #if _HAS_ITERATOR_DEBUGGING if (size() <= _Pos) { _DEBUG_ERROR("vector subscript out of range"); _SCL_SECURE_OUT_OF_RANGE; } #endif /* _HAS_ITERATOR_DEBUGGING */ _SCL_SECURE_VALIDATE_RANGE(_Pos < size()); return (*(_Myfirst + _Pos)); }//非const成员 reference operator[](size_type _Pos) { // subscript mutable sequence #if _HAS_ITERATOR_DEBUGGING if (size() <= _Pos) { _DEBUG_ERROR("vector subscript out of range"); _SCL_SECURE_OUT_OF_RANGE; } #endif /* _HAS_ITERATOR_DEBUGGING */ _SCL_SECURE_VALIDATE_RANGE(_Pos < size()); return (*(_Myfirst + _Pos)); }