std::vector: vec.data() 或 &vec[0] [英] std::vector: vec.data() or &vec[0]

查看:50
本文介绍了std::vector: vec.data() 或 &vec[0]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您希望将 std::vector 作为 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].我认为它是最不优雅的,所以......为什么它是最常用的?它是更高效还是更兼容?我找不到很多关于 data() 的文档.

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().

推荐答案

data() 是 C++11 的全新内容,这就是您不常看到它的原因.我从来没有想过使用 &vec.front() 的想法,可能是因为我使用 operator[] 的频率比 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::vector: vec.data() 或 &amp;vec[0]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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