什么List [i] ++;应该怎么做?

时间:2012-12-04 09:52:42

标签: c++ algorithm list sorting

我需要了解称为珠子排序的算法。我找到了算法的c ++实现,但我还没有完全理解它。 令我困惑的是这一行发生的事情:

    List[i]++;

请帮帮我

这里是完整的代码:

#include <iostream>
#include <vector>

using std::cout;
using std::vector;

void distribute(int dist, vector<int> &List) {
    //*beads* go down into different buckets using gravity (addition).
    if (dist > List.size() )
        List.resize(dist); //resize if too big for current vector

    for (int i=0; i < dist; i++)
        List[i]++;
}

vector<int> beadSort(int *myints, int n) {
    vector<int> list, list2, fifth (myints, myints + n);

    cout << "#1 Beads falling down: ";
    for (int i=0; i < fifth.size(); i++)
        distribute (fifth[i], list);
    cout << '\n';

    cout << "\nBeads on their sides: ";
    for (int i=0; i < list.size(); i++)
        cout << " " << list[i];
    cout << '\n';

    //second part

    cout << "#2 Beads right side up: ";
    for (int i=0; i < list.size(); i++)
        distribute (list[i], list2);
    cout << '\n';

    return list2;
}

int main() {
    int myints[] = {734,3,1,24,324,324,32,432,42,3,4,1,1};
    vector<int> sorted = beadSort(myints, sizeof(myints)/sizeof(int));
    cout << "Sorted list/array: ";
    for(unsigned int i=0; i<sorted.size(); i++)
        cout << sorted[i] << ' ';
}

3 个答案:

答案 0 :(得分:3)

它将列表中 i th 元素的值递增1.

答案 1 :(得分:1)

它只是在索引vector<int>访问函数的List参数中的元素(称为i)并将其值递增1

答案 2 :(得分:0)

C中的++运算符会增加变量。请参阅此处以获取快速参考: http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Arithmetic_operators

在这种情况下,变量是名为i的数组的位置List中的数组元素,在C中表示为List[i]