简体   繁体   中英

Multiple Elements in one index of vector

I was looking at the bucket sort problem at geeks for geeks, in which they were storing multiple elements at same index of vector.

My question is how is this possible that we can store multiple elements at same index in vector.

The code is here

**void bucketSort(float arr[], int n)
{
      
    // 1) Create n empty buckets
    vector<float> b[n];
  
    // 2) Put array elements 
    // in different buckets
    for (int i = 0; i < n; i++) {
        int bi = n * arr[i]; // Index in bucket
        b[bi].push_back(arr[i]);
    }
  
    // 3) Sort individual buckets
    for (int i = 0; i < n; i++)
        sort(b[i].begin(), b[i].end());
  
    // 4) Concatenate all buckets into arr[]
    int index = 0;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < b[i].size(); j++)
            arr[index++] = b[i][j];
}**

vector<float> b[n] => it's a 2D vector. So when you're writing b[bi].push_back() , it means you're inserting an element at bi th vector, or you can say bi th row.

In bucket sort, there can be multiple buckets. So this 2D vector represents all those buckets. That means, b[i] represents i th bucket.

So the answer to your question is, they're not storing multiple elements at the same index in vector. They're inserting the element arr[i] into bucket[n*array[i]] , which itself is a vector.

To answer your question right off the bat, they are NOT storing multiple elements in a single index of the vector. Here is what is happening:
vector<float> tells the compiler that each element of the vector is strictly a single float value. However, the b[n] part that follows is the notation you use to declare an array.
Ultimately, you end up with vector<float> b[n] which is basically an array but each element of the array is a vector . The vector itself stores only float values as you've instructed the compiler.
b[bi].push_back(arr[i]) is translated into:
To the vector stored in the biᵗʰ index of my array named b, append the float value which is arr[i]

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