- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在尝试用 C++ 为类创建一个基本的 ArrayList 实现。该类(class)的要求非常严格,并且需要数据成员和函数。但是,当我运行它时,当它试图删除 deepCopy 中的列表指针时,我得到“无法访问内存位置”。我似乎无法弄清楚为什么。请帮忙。谢谢!
我已经缩小了代码范围。不过,我仍然想为您提供足够的信息以便能够提供帮助。
美国要求完整的代码,所以我把它加回来了。
#ifndef LIST_H
#define LIST_H
/**
* This implentation of list is a pseudo ArrayList. Since we don't guarantee that a class has a hashCode in C++
* this will only work for objects which have an id field.
*
*/
template <class T>
class List{
private:
// If you want the max size of the list (100), then you should probably create a const. Example:
// const int MAX_SIZE;
// T[] list = new T[MAX_SIZE];
// But really, that is not much better. This is just bad, overall. It's like we're implementing a very poor ArrayList.
T * list; // This is our array for our elements.
int numberInList; //
int listSize; // Getter method will be getMaxSize. This seems unnecessary if we're initializing it to 100...
int nextIndex; // this is a number of the index for the next element. Really, this should be inside a private class (who has the pointer to its next).
double loadFactor; // We need to determine when we need to allocate additional slots so we don't run out if they try to add more than they have allocated.
void deepCopy(const List<T> & toBeCopied ); // We need a method to perform a deepCopy. Abstracts the implementation from each method. Private because we don't want it exposed to clients.
bool isAboveThreshold(); // Check if the list is above the loadFactor.
// Publicly available API
public:
List();
List(int size); // Overloaded constructor to initialize the List to a runtime size
List(const List<T> & toBeCopied); // Copy constructor
~List(); // Destructor -- Get rid of the dynamically allocated member.
T next(); // Gets the next element in the list, and increments next
bool add( T & element ); // Adds an element to the list. Also checks to make sure the element hasn't already been added.
bool contains(T & element); // Checks the list to see if the element exists in the list already.
int getSize(); // return the number of elements in the list.
List<T> & List<T>::operator =( const List<T> & toBeCopied );
};
template <class T>
List<T>::List(){
listSize = 100;
list = new T[listSize];
numberInList = 0;
nextIndex = 0; // Initialize the next element to 0.
loadFactor = 0.75;
};
template <class T>
List<T>::List(int size){
list = new T[size];
numberInList = 0;
nextIndex = 0; // Initialize the next element to 0.
listSize = size;
loadFactor = 0.75;
};
template <class T>
List<T>::List(const List<T> & toBeCopied){
deepCopy(toBeCopied);
};
/****
*
* We need to release the allocated heap memory. Non-pointer members will be deallocated when they are out of scope.
*
*/
template <class T>
List<T>::~List(){
delete [] list;
};
/**
* Return the number of elements in the list.
*/
template <class T>
int List<T>::getSize(){
return numberInList;
}
/**
* Return the number of elements in the list.
*/
template <class T>
T List<T>::next(){
return list[nextIndex++];
}
/**
* Check if the element is already in the list
*/
template <class T>
bool List<T>::contains( T & element){
// Now, to check if the item already exists, we could just iterate over the array, but that gives us linear execution time.
// It seems sub-optimal to work in linear time here, when it feels like we shouldn't have to, but honestly, I'm too tired
// to care at this point.
for(int i = 0; i < (numberInList); i++){
if(element != list[i]) // We do this so that if the first item is not equal, we don't even bother checking the second condition.
{
// The element isn't matched. We have to finish iterating, though, before we can add it.
}
else{ // The element matched. Return false.
element = list[i];
return true;
}
}
return false;
}
/**
* The implementation for this is very bad. But, the requirements in the homework documentation are very restrictive.
*
* Ideally, we would have a companion class named Entry which kept the reference to the element via composition.
*
* Obviously, this is a list, so we only want unique entries.
*
* if successful, we return a true. Else, we're returning false.
*
*/
template<class T>
bool List<T>::add( T & element ){
// If we've exceeded the loadFactor, we want to expand our array before we add.
if( isAboveThreshold() ){
int newSize = listSize*2;
List<T> tempPtr = List<T>(newSize);
for(int i = 0; i < numberInList; i++){
tempPtr.add(list[i]);
}
deepCopy(tempPtr);
}
if(!contains( element )){
list[numberInList] = element; // if there are 4 in the list, the next empty index is 4, so this works. We get our element, then post-increment.
numberInList++;
return true;
}
return false;
}
/**
* Deep copy mechanism
*/
template<class T>
void List<T>::deepCopy(const List<T> & toBeCopied){
// Take care of shallow copying first.
numberInList = toBeCopied.numberInList;
listSize = toBeCopied.listSize;
nextIndex = 0; // We're getting a new list, so our iterator should start over.
// Now, to initialize the new list
T *tempList = new T[listSize];
for(int i = 0; i < toBeCopied.numberInList; i++){
// We can do this because we're in the List class. We have access to private members.
tempList[i] = toBeCopied.list[i];
}
delete [] list;
list = tempList;
}
/**
* boolean for if we've exceeded the loadFactor threshold.
*/
template<class T>
bool List<T>::isAboveThreshold(){
if(numberInList != 0){
double division = (double)numberInList/listSize;
return (division >= loadFactor)? true : false;
}else
return false;
}
/***
* Overloaded assignment operator
*/
template <class T>
List<T> & List<T>::operator =( const List<T> & assigner ){
if(*this == &assigner)
return *this;
delete[] list;
deepCopy(assigner);
return *this;
}
#endif
#include "List.h"
#include <string>
#include<iomanip>
#include <iostream>
#include <fstream>
#include <stdlib.h>
using namespace std;
struct Customer{
int id;
string name;
string city;
string address;
float amount;
Customer(){id=0; city="Default"; name="N/A"; address="N/A", amount = 0;}
bool operator==( const Customer & assign){
if(assign.id == id)
return true;
else
return false;
}
bool operator!=( const Customer & assign){
if(assign.id != id)
return true;
else
return false;
}
};
List<Customer> readCustomers();
void printCustomers();
int main(){
cout.setf(std::ios::fixed);
printCustomers();
return 0;
}
// Definitions
List<Customer> readCustomers(){
List<Customer> WebsterCommunications(50);
ifstream custFile;
custFile.open("Customers.csv");
// This could be abstracted out into another method, where we took the struct, a struct name, and the inFile, and spit back a
// customer from the file. But, for now, we'll just settle with the code duplication.
if(!custFile){
cout << "There was a problem reading the Customer File..." << endl;
exit(99);
}
while(!custFile.eof()){
Customer tempCust;
custFile>>tempCust.id;
if(tempCust.id == 0)
break;
custFile.ignore();
getline(custFile, tempCust.name, ',');
getline(custFile, tempCust.address, ',');
getline(custFile, tempCust.city, ',');
custFile>>tempCust.amount;
custFile.ignore();
WebsterCommunications.add(tempCust);
}
custFile.close();
return WebsterCommunications;
}
void printCustomers(){
List<Customer> customers = readCustomers();
double addCalc = 0.0;
cout << string( 100, '\n' );
for(int i = 0; i < customers.getSize(); i++){
Customer cust;
cust = customers.next();
cout << "id: " << cust.id << " name: " << cust.name << " address: " << cust.address << " balance: " << cust.amount << endl;
addCalc += cust.amount;
}
cout.precision(2);
cout << "average: " << (addCalc / customers.getSize()) << endl;
int isActive = 1;
cout << "Please enter a customer's id to find them (0 to exit):" << endl;
while(isActive){
cin >> isActive;
if(!isActive){
return;
}
Customer tempCust;
tempCust.id = isActive;
if(customers.contains(tempCust)){
cout << "id: " << tempCust.id << " name: " << tempCust.name << " address: " << tempCust.address << " balance: " << tempCust.amount << endl;
}
else{
cout << "That customer is not found" << endl;
}
cout << "Please enter a customer's id to find them (0 to exit):" << endl;
}
}
最佳答案
在 operator=
中,您尝试删除当前附加到对象的内部列表,但实际上您所做的是删除要复制的 list
- 在复制构造函数中,list
命名参数而不是类成员。
通过为类成员和参数赋予不同的名称来解决此问题。 C++ 中有明确定义的名称隐藏规则,但依赖它们几乎总是会导致混淆。
而且你还在重复删除 list
!一旦进入你的 deepCopy
并且一旦进入你的 operator=
!您需要重新考虑您的设计以及应该清理哪些资源。一个快速修复方法是在 deepCopy
中不删除,但我还没有想过这会如何泄漏。我会留给您寻找更好的解决方案。
关于C++编程练习--深拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14674844/
K&R 前。 4.2 要求您修改给定的(非标准)atof 函数,该函数缺少处理指数的指数处理机制(如 123e6 或 456e-7)。我添加了一个最小的更改来处理正确输入的、无空格的个位数指数。为了检
我正在学习计算机科学入门类(class)的考试,我对“常规”算法和递归算法中的复杂性主题有疑问(通常我们将这些问题写成 C 代码). 我想知道 Internet 和/或书籍中是否有涵盖该主题的基础级别
console.log( ‘blah’.repeatMe( 3 ) ); 使用 Javascript 编写代码,使前面的函数打印: 输出:blahblahblah 最佳答案 噢,放弃函数式解决方案太有
我正在准备 Java SE 7 认证考试,并且正在做一些关于继承和访问修饰符的无聊练习。 但是现在我在应用继承时遇到了意外的行为。在我的基础包 com.testpkg 中,我有一个抽象类: packa
我刚刚开始了 C 语言队列的第一课,我得到了创建队列、向队列添加元素和删除元素的练习。但是,我在检查队列是满还是空时遇到了麻烦。 #include typedef struct FloatQueue
请问我从昨天开始就被困在下面这个问题中了。下面是问题: Write a program that uses console.log to print all the numbers from 1 to
我最近尝试了一些 Java,希望对我的风格进行一些评论。如果你喜欢看这个放在图像中的练习,并告诉我我的风格是否足够好?或者是做的还不够好,可以告诉我应该在哪方面多下工夫,帮我改进一下? exercis
我对手动编写 SQL 查询还很陌生,而且我有一个我似乎无法解决的练习。 我了解解决此问题所需的工具,但我就是想不出解决方案。 你能帮助我理解如何以一种能让我在未来解决类似练习的方式解决这个问题吗? 我
好吧,这就是练习: Define a class named student, containing three grades of students. The class will have a f
我是一个 JS 菜鸟,试图制作这个“你好,先生/小姐 你的名字!”干净的。我看不到在 if/else 中重构警报的方法,因为那样我就失去了 var b 的值。 JS: "use strict
很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visit the help center . 关闭 1
反转二维数组的值,可以扩展 n 次。 [1, [2, [3, ... [n, null]]]] 给定: 所有数组的长度始终为 2 列表中的最后一个数组将包含一个 null 索引 1 示例: [1, [
我试图通过 Jason Hickey 笔记自学 OCaml,下面的练习让我难住了。 问题:编写一个函数 sum 给定两个整数边界 m,n 和函数 f 计算求和。 我正在尝试这个: let r
这是一个生成斐波那契数列的程序,这里是引用:http://sicp.org.ua/sicp/Exercise1-19 据说我们可以将程序视为“a <- bq + aq + ap and b <- bp
所以,我正在努力通过 SICP。 第 4 章的第一个练习是: Exercise 4.1. Notice that we cannot tell whether the metacircular eva
这个问题已经有答案了: Count the number of occurrences of a character in a string in Javascript (39 个回答) 已关闭 6
已关闭。这个问题是 off-topic 。目前不接受答案。 想要改进这个问题吗? Update the question所以它是on-topic用于堆栈溢出。 已关闭10 年前。 Improve th
我目前正在学习 JS,并且正在尝试进行编码练习。到目前为止,我已经成功地使用离线和在线部分代码的大量资源拼凑了以下代码。我已经非常接近了 - 只是结果中的数字无法正确。 一些背景:在函数中输入一个对象
我需要创建一个回收器 View 练习,这是一个带有简单的单个回收器的应用程序加载大小为 20 的页面,并且可以容纳无限数量的项目。 现在我不想做出重新加载越来越多的项目的幼稚解决方案,而是一个优雅的解
下面的实现正确吗? 输入:Oldrecords(GameRecord 对象数组)和 newRecords (GameRecord) 我将检查 oldRecords 数组中的 newRecord 值。如
我是一名优秀的程序员,十分优秀!