创建随机迭代器(置换)

Creating A Random Iterator (Permutation)

本文关键字:置换 迭代器 随机 创建      更新时间:2023-10-16

这个项目的最后一个大障碍,我希望你们能帮助我,因为我又陷入了困境。我正在研究的是一个动态分配的模板容器,其中所有代码都是用常量迭代器从头开始编写的,还有一个随机迭代器,它以索引数组的形式生成排列。到目前为止,我已经正确地生成了索引,但我不确定如何让随机迭代器使用索引数组在索引中移动。我认为随机迭代器的++运算符有问题,但我完全不确定该怎么做才能使它正确迭代。以下是一些片段:

// Implementation of the rand_iterator method when provided a seed  by   
// the user. rand_iterator takes a pointer to a container object, and the seed // as parameters.
template <class T>
typename sorted<T>::rand_iterator sorted<T>::rndbegin(unsigned seed){
  return rand_iterator(this, seed);
}
// Implementation of the const iterator pre-incrementer.
template <class T>
typename sorted<T>::const_iterator sorted<T>::const_iterator::operator++(){ ++m_current; return *this; }

// This is what my rndbegin looks like at the moment.
// Implementation of the rand_iterator rndbegin method.
template <class T>
typename sorted<T>::rand_iterator sorted<T>::rndbegin(){
  sorted<T>::rand_iterator newrand(this);
  return newrand;
}
// Implementation of the non-default rand iterator constructor given 
// a user-defined seed.
template <class T>
sorted<T>::rand_iterator::rand_iterator(sorted<T>* srtdPtr, unsigned seed){
  int j;
  m_rsize = srtdPtr->m_size;
  // Set up the random seed.
  // Allocate memory for m_random.
  srand(seed);
  m_random = new int[m_rsize];
  // Fill the randomized array with values.
  for (int i = 0; i < srtdPtr->m_size; i++)
    m_random[i] = i;
  // Randomize the values.
  for (int i = 0; i < srtdPtr->m_size; i++){
    T temp;
    j = rand() % (srtdPtr->m_size);
    temp = m_random[i];
    m_random[i] = m_random[j];
    m_random[j] = temp;
  }
  // Just testing to make sure the random array
  // is set up properly; it is. 
  cout << "Random seed test:" << endl;
  for (int i = 0; i < srtdPtr->m_size; i++)
    cout << m_random[i] << " ";
  cout << endl;
  m_current = 0;
  m_randPtr = srtdPtr;
}
// Implementation of the dereference operator.
template <class T>
const T& sorted<T>::rand_iterator::operator*(){
  return m_randPtr->m_data[m_random[m_current]];
}
// Some code from main that's causing an issue.
// ritr3 was already created and tested.
sorted<int>::rand_iterator ritr5(ritr3);
cout << "Printing copy constructed random index array - should print: 5 16 1 7 9 17 7 4 6" << endl;
cout << "Actually prints: " << endl;
for (ritr5 = x.rndbegin(4242); ritr5 != x.rndend(); ritr5++)
  cout << *ritr5 << " ";
cout << endl;

m_currentm_crandom的索引,并使其从0变为n,则m_crandom[m_current]将成为实际数据数组的混洗索引。

下面是一个展示基本思想的例子:

http://coliru.stacked-crooked.com/a/47b28c0be0bcd027