问题描述
当你想访问一个std ::向量作为C数组你可以从至少四个不同的方式选择,你可以在这个例子中看到:
When you want access a std::vector as a C array you can choose from at least four different ways, as you can see in this example:
#include <iostream>
#include <vector>
using namespace std;
int main() {
std::vector<int> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(42);
vec.push_back(24024);
{
int* arr = vec.data();
cout << arr << endl; /* output: 0x9bca028 */
cout << arr[3] << endl; /* output : 24024 */
}
{
int* arr = &vec.front();
cout << arr << endl; /* output: 0x9bca028 */
cout << arr[3] << endl; /* output : 24024 */
}
{
int* arr = &vec[0];
cout << arr << endl; /* output: 0x9bca028 */
cout << arr[3] << endl; /* output : 24024 */
}
{
int* arr = &vec.at(0);
cout << arr << endl; /* output: 0x9bca028 */
cout << arr[3] << endl; /* output : 24024 */
}
}
我在大多数情况下,找到的一个是&放大器; VEC [0]
。我认为这是最优雅,所以...为什么这是最常用的?是的更有效或更兼容?我无法找到大量的文档资料约数据()
。
The one I've found in most cases is the &vec[0]
. I think it's the least elegant, so... why is it the most used? Is it more efficient or more compatible? I can't find lot of documentation about data()
.
推荐答案
数据()
是全新的,以C ++ 11,这就是为什么你没有看到它经常。使用&放的想法; vec.front()
甚至从来没有想过我,可能是因为我用运算符[]
很多比更经常前()
(几乎没有)。我想这对其他人是一样的。
data()
is brand new to C++11, that's why you don't see it as often. The idea of using &vec.front()
never even occurred to me, probably because I use operator[]
alot more often than front()
(almost never). I imagine it's the same for other people.
这篇关于的std ::向量:vec.data()或放大器; VEC [0]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!