可以将std :: vector看作一个数组 [英] Can std::vector be treated like an array

查看:115
本文介绍了可以将std :: vector看作一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以以此方式将 std :: vector< char> 视为数组:

Can a std::vector<char> be treated like an array in this way:

std::vector<char> v(10);
strncpy(&v[0], "hello", 9); // <-- Is this safe?


推荐答案

从C ++ 03起,向量需要具有连续存储。

Yes, that's fine. As of C++03, vector is required to have contiguous storage.

对于 std :: string 也是这样;您可以将 v.data()作为& v [0] 的同义词当 v 为空)。

As of C++11, the same is true for std::string, by the way; and you can say v.data() as a synonym for &v[0] (which is also valid when v is empty).

这篇关于可以将std :: vector看作一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆