【问题标题】:Pointer Array Sorting Algorithm in C++C++中的指针数组排序算法
【发布时间】:2013-08-05 05:36:46
【问题描述】:

希望我能就我所做的排序方法得到一些建议。

这只是对我正在制作的另一个程序的测试,这个测试有一个我无法弄清楚的错误。此代码的目的是创建一个 int 指针数组,并按常规 int 数组的内容对该数组中的指针进行排序。

该错误是针对我的第二个 for 循环的,它不允许我使用 j!=-1,因此不允许我对数组的第一个元素进行排序。请帮忙。谢谢!!

 //create array
 int c[8] = {3,1,5,7,8,2,6,4};
 //create pointer array
 int *newptr[8];
 for(int k = 0; k<8; k++)
 {
     newptr[k] = &c[k];
 }
//sort pointer array
for(int j = 0; j<8; j++)
{
    cout << "test1\n\n";
    cout << *newptr[j] << "and" << *newptr[j+1];
    for(;*newptr[j] < *newptr[j+1] && j!=0; j--) 
    //using j!=-1 doesn't work which causes me to not be able to sort the first element
    //in the array properly
    {
        cout<< "test2";
        int *temp;
        temp = newptr[j+1];
        newptr[j+1] = newptr[j];
        newptr[j] = temp;
    }
}**

【问题讨论】:

    标签: c++ arrays algorithm sorting pointers


    【解决方案1】:

    订单很重要。

    改变

    for(;*newptr[j] < *newptr[j+1] && j!=0; j--) 
    

    到:

    for(; j != -1 && *newptr[j] < *newptr[j+1]; j--) 
    

    据推测,该错误是导致代码崩溃的原因。发生这种情况是因为 for 循环中的表达式是从左到右计算的。所以*newptr[j] 在检查j != -1 之前 被评估。所以可以想象,在某些时候,j 等于 -1,而 *newptr[j] 被评估,这是非法的。

    更改顺序确实有第二个原因:short-circuit evaluation

    在评估两个由两个条件 AB 组成的表达式时,C++ 并不总是需要同时评估这两个条件。

    例如在语句中

    if (A && B) {
      //do something 
    }
    

    如果A 被评估为false,那么显然A &amp;&amp; B 无法评估为true,无论B 评估为什么。所以B 的值甚至从未被检查过。所以在你的情况下,在表达式中

    j != -1 && *newptr[j] < *newptr[j+1]
    

    如果j != -1 为假,C++ 将不需要计算表达式的其余部分来判断整个表达式是否为假。所以*newptr[j] 永远不会发生,你也不会得到错误。

    【讨论】:

    • 未来任何允许 j 低于 -1 的代码更改也可以通过类似 j>-1 的方式停止。
    【解决方案2】:

    正如 maditya 所指出的,问题在于表达式在检查索引本身之前尝试访问无效索引,但我看到问题被标记为 C++。你有什么明确的理由不使用 STL?

    struct sorter {
      bool operator() (const int* i, const int* j) { return (*i<*j);}
    };
    
    int c[8] = {3,1,5,7,8,2,6,4};
    int *newptr[8];
    for(int k = 0; k<8; k++)
      newptr[k] = &c[k];
    
    std::sort(newptr, newptr+8, sorter());
    

    在 C++11 中甚至更短:

    int c[8] = {3,1,5,7,8,2,6,4};
    int *newptr[8];
    for(int k = 0; k<8; k++)
      newptr[k] = &c[k];
    std::sort(newptr, newptr+8, [](const int *i, const int *j){return *i < *j;});
    

    【讨论】:

    • 我刚开始学习 c++,所以我觉得创建自己的函数比使用其他函数更有益。
    • @user2651901:如果你想通过创建函数来学习C++,那很好;出于所有其他目的,it is wrong
    • @user2651901:这是我的观点,在 C++ 中几乎需要使用 STL。忘记它没有任何意义,因此虽然学习语言的语法和语义很有用,但对于其他一切都应该避免。
    猜你喜欢
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多