这个项目的最后一大障碍,我希望你们能帮助我,因为我再次陷入困境。我正在研究的是一个动态分配的模板化容器,所有代码都是从头开始使用常量迭代器编写的,以及一个随机迭代器,它以索引数组的形式生成排列。到目前为止,我已经得到它来正确生成索引,但我不确定如何让随机迭代器使用索引数组移动它们。对于随机迭代器,我认为我的++运算符存在问题,但我完全不确定该怎么做才能使它正确迭代。以下是一些片段:
// 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;
答案 0 :(得分:1)
让m_current
成为m_crandom
的索引,让它从0
更改为n
,然后m_crandom[m_current]
将成为改组后的索引实际的数据数组。
这是一个显示基本想法的例子: