简体   繁体   English

如何理解“矢量 <int> avector(arr,arr + sizeof(arr)/ sizeof(arr [0]))”?

[英]How to understand “vector<int> avector (arr, arr + sizeof(arr) / sizeof(arr[0]) )”?

In the code below, what's the meaning of 在下面的代码中,什么是

vector<int> avector (arr, arr + sizeof(arr) / sizeof(arr[0]) );

in main() ? main()

vector<int> bubbleSort(vector<int> avector) { //the vector for bubble sort
  for (int passnum = avector.size()-1; passnum > 0; passnum -= 1) {
      for (int i = 0; i < passnum; i++) {
          if (avector[i] > avector[i+1]) {
              int temp = avector[i];
              avector[i] = avector[i+1];
              avector[i+1] = temp;
          }
      }
  }
  return avector;
}

int main() {
    // Vector initialized using a static array
    static const int arr[] = {54,26,93,17,77,31,44,55,20};
    vector<int> avector (arr, arr + sizeof(arr) / sizeof(arr[0]) );

    vector<int> bvector = bubbleSort(avector);
    for (unsigned int i = 0; i < bvector.size(); i++) {
        cout<<bvector[i]<< " ";
    }
    return 0;
}

Thank you! 谢谢!

Jeff 杰夫

vector<int> avector (arr, arr + sizeof(arr) / sizeof(arr[0]) );

initializes an std::vector , avector , from the arr C-style array. arr C样式数组中初始化std::vectoravector

The arguments are iterators. 参数是迭代器。 These iterators define a range of elements: 这些迭代器定义了一系列元素:

  • arr : iterator to the first element of the range to be copied. arr :迭代器到要复制范围的第一个元素。
  • arr + sizeof(arr) / sizeof(arr[0]) : iterator pointing the past-the-end element of the range to be copied. arr + sizeof(arr) / sizeof(arr[0]) :迭代器,指向要复制范围的过去-结束元素

The C++11 way would be to use the function templates std::cbegin() and std::cend() for C-style arrays: C ++ 11的方式是将函数模板std::cbegin()std::cend() std::cbegin() std::cend()用于C型数组:

vector<int> avector(std::cbegin(arr), std::cend(arr));

This approach takes advantage of template argument deduction for inferring the size of the C-style array. 这种方法利用模板自变量推导来推断C样式数组的大小。 This way is less error-prone since it requires less typing. 这种方式不太容易出错,因为它需要更少的键入。

n = sizeof(arr) / sizeof(arr[0]) is the number of elements stored by the array. n = sizeof(arr) / sizeof(arr[0])是数组存储的元素数。

avector(arr, arr + sizeof(arr) / sizeof(arr[0]) means copy the elements of the array arr to the vector avector from index 0 to n-1 (inclusive) avector(arr, arr + sizeof(arr) / sizeof(arr[0])表示将数组arr的元素复制到向量avector从索引0n-1 (含)

avector is constructed via copying all elements of arr . 通过复制arr所有元素来构造avector

it uses the following constructor of the vector: 它使用向量的以下构造函数

 template< class InputIt > vector( InputIt first, InputIt last, const Allocator& alloc = Allocator() ); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM