简体   繁体   English

向量的一个索引中的多个元素

[英]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.我正在查看 geeks for geeks 的桶排序问题,其中他们将多个元素存储在同一向量索引处。

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. vector<float> b[n] => 这是一个二维向量。 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.因此,当您编写b[bi].push_back()时,这意味着您要在bi th 向量处插入一个元素,或者您可以说bi th 行。

In bucket sort, there can be multiple buckets.在桶排序中,可以有多个桶。 So this 2D vector represents all those buckets.所以这个二维向量代表了所有这些桶。 That means, b[i] represents i th bucket.也就是说, b[i]代表第i个桶。

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.他们将元素arr[i]插入到bucket[n*array[i]]中,它本身就是一个向量。

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. vector<float>告诉编译器向量的每个元素严格来说都是一个浮点值。 However, the b[n] part that follows is the notation you use to declare an array.但是,后面的b[n]部分是用于声明数组的符号。
Ultimately, you end up with vector<float> b[n] which is basically an array but each element of the array is a vector .最终,你最终得到vector<float> b[n] ,它基本上是一个数组,但数组的每个元素都是一个 vector The vector itself stores only float values as you've instructed the compiler.向量本身仅存储您指示编译器的浮点值。
b[bi].push_back(arr[i]) is translated into: b[bi].push_back(arr[i])被翻译成:
To the vector stored in the biᵗʰ index of my array named b, append the float value which is arr[i]对于存储在名为 b 的数组的 biᵗʰ 索引中的向量,append 的浮点值是arr[i]

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

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