简体   繁体   中英

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

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.

The arguments are iterators. These iterators define a range of elements:

  • arr : iterator to the first element of the range to be copied.
  • arr + sizeof(arr) / sizeof(arr[0]) : iterator pointing the past-the-end element of the range to be copied.

The C++11 way would be to use the function templates std::cbegin() and std::cend() for C-style arrays:

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

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 is constructed via copying all elements of arr .

it uses the following constructor of the vector:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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