Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > C/C++ программирование > Общие вопросы C/C++
Регистрация

Восстановить пароль

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 27.03.2011, 21:48   #1
Alex1911
 
Регистрация: 27.03.2011
Сообщений: 3
По умолчанию найти ошибку

Не обращайте внимание на много букв, значение имеет только оператор ++ и итераторы начала и конца.
помогите пожалуйста найти причину, почему программа выдает ошибку на пустых списках хэш-таблицы? и если не сложно, способ исправления..
спасибо

Код:
#include <algorithm>
#include <iostream>
#include <list>
#include <numeric>
#include <string>
#include <vector>

using namespace std;

int hash_function (string str, int size)
{
	int sum = 0;
	int length = str.length ();
	for (int i=0; i < length; i++)
		sum += str [i];
	return (sum % size);
}

class CHash
{   
public:

    class  CHash_iterator
    {
        const vector <list <string> >&     lists;        
        vector <list <string> >::iterator  it_Vector;
        list <string>::iterator   it_List;

    public:
        CHash_iterator
            (const vector <list <string> > & lists_, vector <list <string> >::iterator  it_Vector_, list <string>::iterator   it_List_ )
            : lists (lists_), it_Vector  (it_Vector_), it_List   (it_List_) {}

        void  operator++()
        {            
            if(it_List == it_Vector->end())
			{
				if (it_Vector + 1 != lists.end ())
				{
					++ it_Vector;
					it_List = it_Vector->begin ();
				}
			}
			else 
			{
				it_List ++;
				if(it_List == it_Vector->end())
				{
					operator ++ ();
				}
			}
                
        }
        string  operator*()
        {
            return  *it_List;
        }

        bool  operator == (const CHash_iterator&  it)
        {
            return    lists     == it.lists                   
                   && it_Vector  == it.it_Vector
                   && it_List   == it.it_List;
        }

        bool  operator != (const CHash_iterator&  it)
        {
            return !(*this == it);
        }
    };

    typedef CHash_iterator  iterator;    

    CHash();
    size_t  size();

    CHash_iterator  begin()
    {
        return   CHash_iterator
                     (
                        table,                        
                        table.begin(),
                        table.begin()->begin()
                     );
    }

    CHash_iterator  end()
    {
        return   CHash_iterator
                     (
                        table,                        
                        table.end()-1,
                        table.back().end()
                     );
    }

	
	void add (string str);

    void  test_fill()
    {
        for(size_t  i = 0; i < table.size(); ++i)
        {
            for(size_t  j = 1; j <= i + 1; ++j)
            {
                table[i].push_back(string(j, 'a' + i));
            }
        }
    }

private:
    int num_of_elem;
    vector <list <string> >  table;    
};

CHash::CHash()
{
    table.resize(3);
    num_of_elem = 0;
}

void CHash::add (string str)
{
	int num = hash_function (str, table.size ());
	bool flag = true;
	
	if (table[num].empty ())
		table[num].push_front (str);
	else
		for (list <string>::iterator it = table[num].begin (); it != table[num].end (); it++)
			if  (!str.compare (*it))
			{
				cout << "Already exist"<< endl;
				break;
			}
	num_of_elem ++;
}

int main()
{
    CHash  hash;
	hash.add ("123");
	hash.add ("123");
	hash.add ("125");
    for(CHash::iterator  it = hash.begin(); it != hash.end(); ++it)
    {
         cout << *it <<"\n";
    }    
    
     cout <<  endl;
}

Последний раз редактировалось Alex1911; 27.03.2011 в 22:15.
Alex1911 вне форума Ответить с цитированием
Старый 27.03.2011, 23:02   #2
onewho
Форумчанин
 
Регистрация: 29.09.2010
Сообщений: 636
По умолчанию

я думал operator++ возвращает *this...
onewho вне форума Ответить с цитированием
Старый 28.03.2011, 00:43   #3
Alex1911
 
Регистрация: 27.03.2011
Сообщений: 3
По умолчанию

Все! Сделал сам, промучавшись немного!!
Код:
#include <iostream>
#include <list>
#include <numeric>
#include <string>
#include <vector>

using namespace std;

int hash_function (string str, int size)
{
	int sum = 0;
	int length = str.length ();
	for (int i=0; i < length; i++)
		sum += str [i];
	return (sum % size);
}

class CHash
{   
public:

    class  CHash_iterator
    {
        const vector <list <string> >&     lists;        
        vector <list <string> >::iterator  it_Vector;
        list <string>::iterator   it_List;

    public:
        CHash_iterator
            (const vector <list <string> > & lists_, vector <list <string> >::iterator  it_Vector_, list <string>::iterator   it_List_ )
            : lists (lists_), it_Vector  (it_Vector_), it_List   (it_List_) {}

        void  operator++()
        {            
			if( it_List == it_Vector->end() )
			{
				if (it_Vector + 1 != lists.end ())
				{
					++it_Vector;
					while (it_Vector->empty ())
						++it_Vector;
					it_List = it_Vector->begin ();
				}
			}
			else 
			{
				it_List ++;
				if(it_List == it_Vector->end())
				{
					operator ++ ();
				}
			}
                
        }
        string  operator*()
        {
            return  *it_List;
        }

        bool  operator == (const CHash_iterator&  it)
        {
            return    lists     == it.lists                   
                   && it_Vector  == it.it_Vector
                   && it_List   == it.it_List;
        }

        bool  operator != (const CHash_iterator&  it)
        {
            return !(*this == it);
        }
    };

    typedef CHash_iterator  iterator;    

    CHash();

    CHash_iterator  begin()
    {
		vector <list <string> >::iterator  it_Vector1 = table.begin();
        list <string>::iterator it_List1;

		while (it_Vector1-> empty ())
			++it_Vector1;
		
        return CHash_iterator
			( table, it_Vector1, it_Vector1->begin() );
    }

    CHash_iterator  end()
    {
		vector <list <string> >::iterator  flag;
        list <string>::iterator   it_List1;
		if (table.back().empty ())
		{
			for (vector <list <string> >::iterator  it_Vector1 = table.begin(); it_Vector1 != table.end (); it_Vector1++)
				if (!it_Vector1->empty ())
					flag = it_Vector1;
			return CHash_iterator
				( table, flag, flag->begin() );
		}
		else return CHash_iterator
			( table, table.end() -1 , table.back().end () );
    }

	
	void add (string str);
	void delete_str (string str);
	bool find (string str);
	void print_hash ();
	void reallocate ();
   
private:
    int num_of_elem;
    vector <list <string> >  table;    
};

CHash::CHash()
{
    table.resize(3);
	num_of_elem = 0;
}

void CHash::add (string str)
{
	int num = hash_function (str, table.size ());
	bool flag = true;

	if (((2*table.size ()) <= num_of_elem) && (num_of_elem > 3))
		reallocate ();
	
	if (table[num].empty ())
	{
		table[num].push_front (str);
		flag = false;
	}
	else
		for (list <string>::iterator it = table[num].begin (); it != table[num].end (); it++)
			if  (!str.compare (*it))
			{
				cout << "Already exist"<< endl;
				flag = false;
				break;
			};
	if (flag) table[num].push_front (str);
	num_of_elem ++;
}

bool CHash::find (string str)
{
	int num = hash_function (str, table.size ());
	bool flag = false;
	if (table[num].empty ())
	{
		cout << "Not Found!"<<endl;
		return false;
	}
	else 
	{
		for (list <string>::iterator it = table[num].begin (); it != table[num].end (); it++)
			if (!str.compare (*it))
			{
				cout << "Found";
				flag = true;
				return true;
			};
	}
	if (!flag )
	{
		cout << "Not Found!"<<endl;
		return false;
	}	
}

void CHash::delete_str (string str)
{
	if (find (str)==true)
	{
		int num = hash_function (str, table.size ());
		table[num].remove (str);
		cout << " and Deleted!\n";
		num_of_elem --;
	}
}

void CHash::print_hash ()
{
	if (num_of_elem > 0)
	{
		bool flag = false;
		for (vector <list <string> >::iterator it = table.begin(); it!= table.end (); it++)
			if (! it->empty ())
				flag = true;

		for(iterator it = CHash::begin(); it != CHash::end(); ++it)
		{
			cout << *it <<endl;
		}
	}
	else cout<<"Hash table is empty!"<<endl;
}

void CHash::reallocate()
{
	vector <string> temp;
	for(iterator it = CHash::begin(); it != CHash::end(); ++it)
    {
		temp.push_back (*it);
    }
	int size = table.size (), length = temp.size ();
	for (vector <list <string> >::iterator it = table.begin(); it!= table.end (); it++)
		it -> clear ();
	table.clear ();
	num_of_elem = 0;
	table.resize (size*2);
	for (int i = 0; i<length; i++)
		add (temp[i]);
}

int main()
{
    CHash hash;
	hash.add ("129");
	hash.add ("123");
	hash.add ("126");
	hash.add ("125");

	hash.print_hash ();

	hash.reallocate ();

	cout << endl;
}
Alex1911 вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
найти ошибку pufystyj PHP 11 16.02.2011 12:57
найти ошибку IceFlame1292 Помощь студентам 4 11.01.2011 20:14
С++ Найти ошибку! sir.andrey Помощь студентам 5 20.10.2010 13:06
найти ошибку sergio11 Общие вопросы C/C++ 2 03.09.2010 19:29
найти ошибку sergio11 Паскаль, Turbo Pascal, PascalABC.NET 2 19.05.2010 01:22