C ++:检查所有数组元素是否相等的最快方法

时间:2013-01-02 10:23:48

标签: c++ arrays

检查数组的所有元素(首选整数数组)是否相等的最快方法是什么。直到现在我一直在使用以下代码:

bool check(int array[], int n)
{   
    bool flag = 0;

    for(int i = 0; i < n - 1; i++)      
    {         
        if(array[i] != array[i + 1])
            flag = 1;
    }

    return flag;
}

12 个答案:

答案 0 :(得分:22)

int check(const int a[], int n)
{   
    while(--n>0 && a[n]==a[0]);
    return n!=0;
}

答案 1 :(得分:12)

这是一个有效的C ++ 11的可靠解决方案。 优点是您不需要手动使用索引或迭代器。

是最佳做法
  

更喜欢算法调用手写循环[Herb Sutter - C ++编码标准]

我认为这与Paul R的解决方案同样有效。

bool check(const int a[], int n)
{
      return !std::all_of(a, a+n, [a](int x){ return x==a[0]; });
}

答案 2 :(得分:10)

找到不匹配的元素后,您可以摆脱循环:

bool check(const int array[], int n)
{   
    for (int i = 0; i < n - 1; i++)      
    {         
        if (array[i] != array[i + 1])
            return true;
    }
    return false;
}

如果这对性能至关重要,那么它可以进一步优化:

bool check(const int array[], int n)
{   
    const int a0 = array[0];

    for (int i = 1; i < n; i++)      
    {         
        if (array[i] != a0)
            return true;
    }
    return false;
}

答案 3 :(得分:4)

将数组重新转换为更大的数据类型。例如,以64位整数运行,或使用SSE或AVX内在函数进行128位或256位运算。例如,SSE2内在函数是_mm_cmpeq_epi32,其结果将与_mm_or_si128一起使用。重复应用_mm_srli_si128和_mm_cvtsi128_si32检查结果。每隔几百次迭代检查一次结果,以便提前退出​​。

确保在对齐的内存上运行,检查未对齐的开始和结束为整数,并检查第一个打包的元素。

答案 4 :(得分:0)

我们基本上是一个O(n)操作,所以你不能比你拥有的更好,除了在第一次失败和return false;时放弃旗帜而只是return true;在迭代之后。

答案 5 :(得分:0)

bool check(int array[],int n)
{       
  // here 1st element is checked with others. This decreases the number of iteration by 1.
  // also it returns immediately. 
  // The requirement is to check if all the elements are equal. 
  // So if 1st element is equal to others then all elements are equal. 
  // Otherwise the  elements are not equal.
  for(int i=1;i<n;i++)      
  {         
    if(array[0]!=array[i])
      return false;
  }        
  return true;
}

答案 6 :(得分:0)

找到平台上可用的支持线程或并行for循环的库,并将计算拆分出来,以便不同的核心测试阵列的不同范围。

此处列出了一些可用的库:

http://parallel-for.sourceforge.net/parallelfor.html

或者可能,你可以利用许多GPU提供的平行主义。

答案 7 :(得分:0)

理论上,我建议这样做:

bool check_single(const int a[], int n)
{
    for (int i = 1; i < n; ++i) {
        if (a[0] != a[n]) { return false; }
    }
    return true;
}

与其他(已提出的)版本相比:

  • a[0]将在循环外被编译器提升,这意味着循环内的单个数组访问
  • 我们从0循环到n,这比加载a[0]然后从a[n]循环
  • 更好(访问方式)

显然,它仍然检查N个元素,因此是O(N)。

答案 8 :(得分:0)

对于程序员效率,您可以在一行中尝试以下所有内容。

vector<int> v{1, 1, 1, 1};
all_of(v.cbegin(), v.cend(), [&r=v[0]](int value){ return value == r; }->bool);

我没有测试运行此代码,如果有语法错误,请告诉我。

答案 9 :(得分:0)

快速哈希映射技术:

bool areSame(int a[],int n)
{
    unordered_map<int,int> m; //hash map to store the frequency od every

    for(int i=0;i<n;i++)
       m[a[i]]++;
      
    if(m.size()==1)
       return true;
    else
       return false;
}

答案 10 :(得分:0)

我认为以下内容比评分最高的答案更具可读性,我也打赌效率更高(但尚未进行基准测试)

public class MandelParalelo extends JFrame 
implements Runnable{
 private final int MAX_ITER = 100000;
 private final double ZOOM = 150;
 private static BufferedImage Imagen;
 private double zx, zy, cX, cY, tmp;
 private int nTareas = 6;
 private int linf, lsup;

 public void run()
 {
    for (int y = linf; y < lsup; y++) {
       for (int x = 0; x < getWidth(); x++) {
         zx = zy = 0;
         cX = (x - 400) / ZOOM;
         cY = (y - 300) / ZOOM;
         int iter = MAX_ITER;
         while (zx * zx + zy * zy < 4 && iter > 0) {
                 tmp = zx * zx - zy * zy + cX;
                 zy = 2.0 * zx * zy + cY;
                 zx = tmp;
                 iter--;
         }
         Imagen.setRGB(x, y, iter | (iter << 8));//setRGB es synchronized
   }
  }
 }
public MandelParalelo(int i, int s)
{
  linf = i;
  lsup = s;
}

public MandelParalelo() {
  super("Conjunto de Mandelbrot");
  setBounds(100, 100, 800, 600);
  setResizable(false);
  setDefaultCloseOperation(EXIT_ON_CLOSE);
  Imagen = new BufferedImage(getWidth(), getHeight(),
      BufferedImage.TYPE_INT_RGB);
  ExecutorService ejecutor = Executors.newFixedThreadPool(8);
  int inf = 0, tVentana = getHeight()/nTareas, sup = tVentana;
    
    for(int i = 0; i < nTareas; i++)
    {  
        ejecutor.execute(new MandelParalelo(inf, sup));
        inf = sup;
        sup += tVentana; 
    }
    
    ejecutor.shutdown();
    
    while(!ejecutor.isTerminated()){}
  

}
public void paint(Graphics g) {
  g.drawImage(Imagen, 0, 0, this);
 }
public static void main(String[] args) {
  new MandelParalelo().setVisible(true);     
 }
}

答案 11 :(得分:-2)

bool check_identity (int a[], int b[], const int size)
{
    int i;
    i = 0;
    while ((i < size-1) && (a[i] == b[i]))   i++;

    return (a[i] == b[i]);

}
相关问题