使用c ++中的第二个索引数组对数组进行排序

时间:2015-11-04 03:05:36

标签: c++ arrays sorting indexing

我有一个自定义对象的arr1,但其中一个成员是arr1.percentChanged 我需要一个第二个数组来存储arr1的索引值,这些索引值按percentChanged排序但是保持第一个数组不变。

变化的百分比是双倍[8.67,-9.64,14.83,0.99,5.33] 我将arr2初始化为[0,1,2,3,4],但我无法弄清楚如何对它进行排序。即它应该是[2,0,3,4,1]。任何有关如何做到这一点的帮助将不胜感激。

我认为我的问题是我的第一个数组不是双精度数组,而是一个stockObjects数组。所以arr1实际上是[obj1,obj2 ...]但是每个obj都有一个obj.percentChanged成员。它们按照obj.name在arr1中排序。我有一个名为stockListType的第二个自定义对象需要sortPercentageIndex。 stockList对象有一个数组,它按照从文件中读取的顺序存储所有stockObject。它还包含sortPercentageIndex数组。我需要一个sortByPercentage方法来按降序对索引数组进行排序。我可以发布一些代码,如果它有帮助,但它是一个更大的程序的一部分,一些类是子类,所以我担心没有看到它就没有意义。

1 个答案:

答案 0 :(得分:1)

将比较器仿函数传递给sort函数:

std::sort( begin(arr2), end(arr2), [const &arr1]( int index1, int index2 ) -> bool
{
  return arr1[index1] < arr1[index2];
} );

或者,您可以使用lambda:

in = new Scanner(file);
while(in.hasNextLine()) {
  // count the lines
  lines++;
  String line = in.nextLine();

  // chars in the line, plus one for the newline
  chars  += line.length() + 1;

  // count words.  Are there other word terminators, such as . ? ! -
  words += new StringTokenizer(line, " ,").countTokens();
}

(这都假设arr2是一个int索引数组。)