我需要一個程序,它允許陣列中的任何條目中的用戶隨機讀取訪問幫助。如果用戶試圖在有用區域之外讀取,則數據結構應該返回0.另外,它允許用戶只對有用區域進行隨機寫入訪問。如果用戶嘗試在應該爲0的數組部分寫入內容,請輸出錯誤消息。 除了程序應該具有的構造函數,取陣列參數作爲唯一的輸入並初始化所有的陣列的爲0。第二個構造應另外作爲輸入整數數組其值複製到正在製作的陣列的有用部分。稀疏矩陣和矩陣
這是數組
[ 0 0 0 0 ... 0 0 1 2 3 4 5 0 0 .... 0 0 ]
的我不知道如何創建稀疏陣,也是我不希望使用現有的庫形式。
我試圖創建一個動態數組,它採用超載運營商,但我的問題是,我甚至不知道什麼是稀疏陣以及如何創建它。
#include <iostream>
using namespace std;
class MyArray
{
friend ostream& operator<< (ostream &os, MyArray &array);
public:
MyArray (int size);
MyArray (const MyArray &rhs);
~MyArray();
MyArray& operator= (const MyArray& rhs);
int& operator[] (int index);
int read_element (int index);
void write_element (int index, int value);
private:
int *storage;
int size;
};
#include "sparse_array_1d.h"
MyArray::MyArray (int size)
{
storage = new int[size];
this->size = size;
}
MyArray::MyArray (const MyArray &rhs)
{
size = rhs.size;
storage = new int[size];
(*this) = rhs;
}
MyArray::~MyArray()
{
delete [] storage;
}
int MyArray::read_element (int index)
{
return storage[index];
}
void MyArray::write_element (int index, int value)
{
storage[index] = value;
}
MyArray& MyArray::operator= (const MyArray &rhs)
{
int i,min_size;
if (size < rhs.size)
min_size = size;
else
min_size = rhs.size;
for (i=0; i<min_size; i++)
storage[i] = rhs.storage[i];
return (*this);
}
int& MyArray::operator[] (int index)
{
if (index < size && index >=0)
return storage[index];
return storage[0];
}
ostream& operator<< (ostream &os, MyArray &array)
{
int i;
os << "[ ";
for (i=0; i<array.size; i++)
os << array[i] << " ";
os << "]" << endl;
return os;
}
#include <iostream>
#include "sparse_array_1d.h"
using namespace std;
int main()
{
int i,size;
cout << "What array sizes would you like?" << endl;
cin >> size;
MyArray p1 (size);
//int q=1;
for (i=0; i<size; i++)
{
p1[i] = 0;
//q++;
}
cout << "p1: " << endl;
cout << p1;
int x;
cout << endl;
cout << "enter numbers : " << endl;
for (i=0 ; i<size; i++)
{
cin >> p1[i];
}
cout << "This is the array" << endl;
cout << p1;
cout << endl;
return 0;
}
您的具體問題是什麼? – 2012-02-25 21:33:52
似乎你想要一個散列集。 – 2012-02-25 21:35:29
我只是不知道如何初始化所有的數組爲0。此外,我真的不明白稀疏數組是如何工作的 – toky 2012-02-25 21:37:16