[英]Creating A Random Iterator (Permutation)
这个项目的最后一个大障碍,希望你们能帮助我,因为我再次陷入困境。 我正在研究的是一个动态分配的模板容器,其中所有代码都是使用常量迭代器从头开始编写的,并且是一个随机迭代器,它以索引数组的形式生成排列。 到目前为止,我已经知道它可以正确生成索引了,但是我不确定如何使用该索引数组使随机迭代器遍历它们。 我认为随机迭代器的++运算符存在问题,但我完全不确定该如何进行正确的迭代。 以下是一些摘要:
// 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_current
是索引m_crandom
,并让它从改变0
至n
,然后m_crandom[m_current]
将是混洗索引到实际的数据数组。
这是一个显示基本思想的示例:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.