迭代器返回最后一个元素上的"Junk"
Iterator Returning "Junk" on the Last Element
我正在处理一些动态分配的数组,我知道这一定是数组的某种范围问题,但我不知道它是什么。当迭代器到达最终相关的数据点时,取消引用指向元素的指针每次只会打印垃圾。m_data是保存数据的数组,并且类型为T,因为它是容器模板。如有任何建议,我们将一如既往地不胜感激。以下是一些相关的片段:
---From sorted.cpp---
template <class T>
typename sorted<T>::const_iterator sorted<T>::insert(T data){
if (m_size == m_capacity){
cout << "Resizing array." << endl;
resize();
}
cout << "Adding " << data << " to array." << endl;
m_size++;
m_data[m_size - 1] = data;
if (m_size > 10){ // This test output works fine.
cout << "Array should be: " << endl;
for (int i = 0; i < 11; i++)
cout << m_data[i] << " ";
cout << endl;
}
return const_iterator(&m_data[m_size - 1]);
}
template <class T>
void sorted<T>::resize(){
int newCapacity = (2 * m_capacity);
T *temp_array = new T[newCapacity];
for (int i = 0; i < m_capacity; i++)
temp_array[i] = m_data[i];
T *m_data = temp_array;
delete [] temp_array;
setCap(newCapacity);
}
---From test file---
int main() {
sorted<int> x;
sorted<int>::const_iterator itr;
// append some values into my_array x
for (int i = 1; i < 12 ; i++ )
x.insert( (i*i) % 19 );
// my_array does not keep items in order
cout << "my_array x:" << endl;
for (itr = x.begin(); itr != x.end(); itr++)
cout << *itr << " ";
cout << endl << endl;
return 0;
}
您的调整大小看起来可疑:
void sorted<T>::resize(){
int newCapacity = (2 * m_capacity);
T *temp_array = new T[newCapacity];
所以temp_array是一个具有新尺寸的新阵列
for (int i = 0; i < m_capacity; i++)
temp_array[i] = m_data[i];
上面您已经将旧数据复制到新阵列
T *m_data = temp_array;
delete [] temp_array;
在这里(在上面的代码中),您删除了temparray,它是您的新数组。因此,修复方法是将以上内容替换为:
delete [] m_data;
m_data = temp_array;
当您真正想要使用类的m_data时,您正在resize()中定义变量m_data。
我刚刚意识到m_data不是指向动态分配的数组的指针,而是数组本身。那是我的问题前台
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用strcpy将char数组的元素复制到另一个数组
- 使用不带参数的函数访问结构元素
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- C++如何通过用户输入删除列表元素
- lower_bound()返回最后一个元素
- 基于多个条件处理地图中的所有元素
- 调整大小后指向元素值的指针unordered_map有效?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 使用函数"remove"删除重复元素
- 具有最大子序列大小的序列,每个元素都相同
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 如何将元素添加到数组的线程安全函数?
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- 我想访问std::unique_ptr中的一个特定元素
- 如何通过 getter 函数删除矢量的元素?
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 从控制台中删除最后打印的元素
- 迭代器返回最后一个元素上的"Junk"