Effective STL:Item 16: Know how to pass vector and string data to

 

Since C++was standardized in 1998,the C++elite haven¡¯tbeenterri-bly
subtle in their attempt to nudge programmers away from arrays
and towards vectors. They¡¯ve been similarly overt in trying to get devel-opers
to shift from char* pointers to string objects. There are good rea-sons
for making these changes, including the elimination of common
programming errors (see Item 13) and the ability to take full advan-tage
of the power of the STL algorithms (see, e.g., Item 31).
Still, obstacles remain, and one of the most common is the existence
of legacy C APIs that traffic in arrays and char* pointers instead of vec-tor
and string objects. Such APIs will exist for a long time, so we must
makepeace with them if we aretouse theSTL effectively.
Fortunately, it¡¯s easy. If you have a vector v and you need to get a
pointer to the data in v thatcan be viewedasan array,just use&v[0].
For a string s, the corresponding incantation is simply s.c_str().But
read on. As the fine print in advertising often points out, certain
restrictions apply.
Given
vector<int> v;
the expression v[0] yields a reference to the first element in the vector,
so &v[0] is a pointer to that first element. The elements in a vector are
constrained by the C++ Standard to be stored in contiguous memory,
just like an array, so if we wish to pass v to a C API that looks some-thing
like this,
void doSomething(const int* pInts, size_t numInts);
we can do it like this:
doSomething(&v[0], v.size());
Maybe. Probably. The only sticking point is if v is empty. If it is, v.si ze()
is zero, and &v[0] attempts to produce a pointer to something that
does not exist. Not good. Undefined results. A safer way t
阅读终点,创作起航,您可以撰写心得或摘录文章要点写篇博文。去创作
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

copy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值