c++ - 如何查看 C++ boolean 值中的数字移动?

标签 c++ boolean boolean-expression

我有一个小程序可以将随机数排序为正确的序列号。好吧,我想看到每个随机数都移动。应该添加什么?

    #include <iostream>
using namespace std;

void pindah (int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

void tukar (int arr[], int n) {
    int i, j;
    bool trade;
    for (i=0; i < n-1; i++) {
        trade = false;
        for (j=0; j < n-i-1; j++) {
            if (arr[j] > arr[j+1]) {
                pindah(&arr[j], &arr[j+1]);
                trade = true;
            }
        }
        if (trade == false)
            break;
    }
}

void cetakArray (int arr[], int n) {
    int i;
    for (i=0; i<n; i++) {
        cout << arr[i] << " "; //tampil data
    }
}

int main () {
    int arr[] = {4, 6, 7, 2, 1, 5, 8, 10, 9, 3};
    int n = sizeof(arr) / sizeof(int); //menghitung jumlah data array
    cout << "setelah diurutkan : \n";
    tukar (arr, n);
    cetakArray (arr, n);

}

请帮帮我

最佳答案

假设“进入正确的序列”是指从小到大,并且假设您愿意使用 C++11,我们可以使用 lambda 函数轻松获得它。请参阅以下示例。

  #include <vector>
  #include <algorithm>

  std::vector<int> values({4, 6, 7, 2, 1, 5, 8, 10, 9, 3});

  int number_of_moves = 0;

  std::sort(begin(values), end(values), [&](int lhs, int rhs) 
  {
    if (lhs > rhs) 
      return false; 

    ++number_of_moves;

    std::cout << "I am going to swap " << lhs << " with " << rhs << '\n'; 

    return true; 
  });

  std::cout << "I took me " << number_of_moves << " move(s) to sort the vector\n";

注意:我不清楚“c++ boolean 值中的移动”是什么意思,所以我选择打印将要交换的数字。

编辑:根据评论,我猜你想计算移动次数,所以我添加了一个计数器。请注意,bool 只能是 true/false,不能用于计数。

关于c++ - 如何查看 C++ boolean 值中的数字移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52950525/

相关文章:

C++ Card 相关程序将无法编译。 (运行时错误)

c++ - 将 cout 格式对齐为表格的列

javascript - 如何编写一个函数,通过返回 boolean 值来检查数组是否包含数字

python - 如何将德摩根定律应用于Python中的 boolean 表达式字符串?

c++ - C++ 11 原子对象的执行也是原子的吗?

c++ - 为什么大多数STL算法都需要排序后的数据作为输入?

python - 轴 1 上带有 boolean 数组的 Pandas loc() 方法

ios - 如何修复条件绑定(bind)的可选类型不是 'Bool'?

r - 检查字符串是否包含字母字符以外的字符

while 循环中的 bool (标量)上下文中的 Perl 列表