【发布时间】:2016-05-02 03:28:59
【问题描述】:
这个项目的最后一个大障碍,我希望你们能帮助我,因为我再次陷入困境。我正在处理的是一个动态分配的模板化容器,所有代码都是从头开始编写的,带有一个常量迭代器,以及一个随机迭代器,它以索引数组的形式生成排列。到目前为止,我已经让它正确地生成索引,但是我不确定如何让随机迭代器使用该索引数组在它们中移动。我认为随机迭代器的 ++ 运算符存在问题,但我完全不确定该怎么做才能使其正确迭代。以下是一些sn-ps:
// 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;
【问题讨论】:
标签: c++ random iterator permutation