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

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

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

Восстановить пароль
Повторная активизация e-mail

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

Ответ
 
Опции темы Поиск в этой теме
Старый 04.07.2015, 17:56   #1
The New Guy
 
Регистрация: 01.07.2015
Сообщений: 6
По умолчанию Создание класса шаблона, ассоциативного массива

При компиляции возникают проблемы следующего характера.
1. В конструкторе IContainer компилятор пишет waring: преобразование const double в int возможна потеря данных, а потом и вовсе error: не найден оператор принимающий правый операнд хотя std::map вроде как позволяет так обращаться к элементам


Код:
IContainer<ElemType, IndexType>::IContainer(const ElemType & elem, const IndexType & index)
{
        arr[index]=elem;
}
2. В ф-ии GetElem несоответствие типов со знаком и без. строчка с return возвр. адреса локальной или временной переменной, тоже не ясно.


Код:
const ElemType& IContainer<ElemType, IndexType>::GetElem(const IndexType & index)
{
    if(index>arr.size())
        std::cout<<"exception \n";
        throw ElemNotFound<IndexType> /*err */(index);
    return arr[index];
}
3. В PutElem преобразование const double в int возможна потеря


Код:
void IContainer<ElemType, IndexType>::PutElem(const IndexType& index, const ElemType& elem)
{
    arr.at(index)=elem; //??
}
4. Последнее, самое сложное не могут состыковаться блоки throw и catch я после слова throw создаю объект и хочу передать его в блок catch по ссылке, но он туда не лезет ни в какую, пробовал как мне кажется по всякому уже.


Код:
throw ElemNotFound<IndexType> /*err */(index);
...
try
    {
    std::cout<<blablabla.GetElem(7)<<"  "<<obj.GetElem(1);
    }
    catch(/*ElemNotFound<IndexType>::*/ElemNotFound & bg/*...*/)
    {
        std::cout<<"exeption";//bg.mesg();
    }
Весь код:

Код:
#include "stdafx.h"
#include <string>
#include <iostream>
#include <map>

template<class IndexType>
class ElemNotFound
{
private:
IndexType value;
public:
ElemNotFound(IndexType index):value(index){}
void mesg();
};
template<class IndexType>
void ElemNotFound<IndexType>::mesg()
{
std::cout<<"Element #"<<value<<" not found\n";
}


template <class ElemType, class IndexType> class IContainer
{
private:
std::map<ElemType, IndexType> arr;
public:
IContainer() {};
IContainer(const ElemType & elem, const IndexType & index);
virtual const ElemType& GetElem( const IndexType& index ) /*const throw ( ElemNotFound ) = 0*/;
virtual void PutElem( const IndexType& index, const ElemType& elem ) /*throw () = 0*/; //первый это номер элемента в массиве, второй сам элемент
};
template<class ElemType, class IndexType>
IContainer<ElemType, IndexType>::IContainer(const ElemType & elem, const IndexType & index)
{
arr[index]=elem;
}
template<class ElemType, class IndexType>
void IContainer<ElemType, IndexType>::PutElem(const IndexType& index, const ElemType& elem)
{
arr.at(index)=elem; //??
}
template<class ElemType, class IndexType>
const ElemType& IContainer<ElemType, IndexType>::GetElem(const IndexType & index)
{
if(index>arr.size())
std::cout<<"exception \n";
throw ElemNotFound<IndexType> /*err */(index);
return arr[index];
}

int main()
{
IContainer<double, int> obj (5, 7);
IContainer<std::string, int> blablabla("golden joe", 6);
blablabla.PutElem(4, "duck");
/*IContainer<double, std::string> c;
c.PutElem("pi", 3.14);
c.PutElem("e", 2.71);
std::cout << c.GetElem("pi")<<"\n";*/
try
{
std::cout<<blablabla.GetElem(7)<<" "<<obj.GetElem(1);
}
catch(/*ElemNotFound<IndexType>::*/ElemNotFound & bg/*...*/)
{
std::cout<<"exeption";//bg.mesg();
}
return 0; 
}
Народ хочет разобраться что к чему, дело для нас новое, не освоенное! С СТЛ и Exception-ами сталкиваюсь впервые, строго не судите!!
The New Guy вне форума Ответить с цитированием
Старый 04.07.2015, 22:09   #2
The New Guy
 
Регистрация: 01.07.2015
Сообщений: 6
По умолчанию

Сейчас код немного видоизменился:

Код:
#include "stdafx.h"
#include <string>
#include <iostream>
#include <map>

template<class IndexType>
class ElemNotFound
{
private:
    IndexType value;
public:
    ElemNotFound(IndexType index):value(index){}
    void mesg();
};
template<class IndexType>
void ElemNotFound<IndexType>::mesg()
{
    std::cout<<"Element #"<<value<<" not found\n";
}


template <class IndexType, class ElemType> class IContainer
{
private:
    std::map<IndexType, ElemType> arr;
public:
    IContainer() {};
    IContainer(const IndexType & index, const ElemType & elem);
   virtual const ElemType/*&*/ GetElem( const IndexType& index) /*const throw ( ElemNotFound ) = 0*/;
   virtual void PutElem( const IndexType& index, const ElemType& elem ) /*throw () = 0*/;
};
template<class IndexType, class ElemType>
IContainer<IndexType, ElemType>::IContainer(const IndexType & index, const ElemType & elem)
{
        arr[index]=elem;
}
template<class IndexType, class ElemType>
void IContainer<IndexType, ElemType>::PutElem(const IndexType& index, const ElemType& elem)
{
    arr.at(index)=elem;
}
template<class IndexType, class ElemType>
const ElemType/*&*/ IContainer<IndexType, ElemType>::GetElem(const IndexType & index)
{
    arr.find(index);
    //if(index>arr.size())
        //std::cout<<"exception \n";
        //throw ElemNotFound<IndexType> /*err */(index);
    return arr[index];
//return 0;
}

int main()
{
    IContainer<double, int> obj (5, 7);
    IContainer<std::string, int> blablabla("golden joe", 6);
    blablabla.PutElem("golden joe", 4);
    /*IContainer<std::string, double> c;
   c.PutElem("pi", 3.14);
   c.PutElem("e", 2.71);
   std::cout << c.GetElem("pi")<<"\n";*/
    //try
    //{
    //std::cout<<blablabla.GetElem("golden joe")<<"  "<<obj.GetElem(1);
    //}
    //catch(/*ElemNotFound<IndexType>::ElemNotFound & bg*/)
    //{
    //  std::cout<<"exeption";//bg.mesg();
    //}
    return 0;
}

Не могу наладить эксепшн по человечьи, наверно я не понимаю как обращаться к созданному объекту. И функции в GetElem я написал find, думаю что с ним делать, и еще возник вопрос в PutElem если он обращается по неправильному индексу, надо по идее тоже эксепшен, но в задании его нет:

Необходимо разработать класс контейнера, реализующий приведенный ниже интерфейс. При разработке приветствуется использование STL.

Код:
class ElemNotFound {};
template < class ElemType, class IndexType > class IContainer
{
public:
   virtual const ElemType& GetElem( const IndexType& index ) const throw ( ElemNotFound ) = 0;
   virtual void PutElem( const IndexType& index, const ElemType& elem ) throw () = 0;
};
The New Guy вне форума Ответить с цитированием
Старый 05.07.2015, 00:02   #3
waleri
Старожил
 
Регистрация: 13.07.2012
Сообщений: 6,330
По умолчанию

А зачем методы шаблона виртуальны?
Зачем нужен IContainer - что мешает использовать std::map напрямую?
В чем именно проблема с эксепшн ?
waleri вне форума Ответить с цитированием
Ответ


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



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
(С++) Шаблонный класс ассоциативного массива с использованием вектора Алексеева Евгения Помощь студентам 0 12.05.2015 20:34
Пример глобального ассоциативного массива ? AlienNation C# (си шарп) 4 12.07.2012 12:21
получение ссылки на функцию из класса шаблона и передача ее как параметр шаблона pror0ck Общие вопросы C/C++ 7 17.06.2012 15:06
Создание двумерного массива объектов класса (С#) Fiamma Помощь студентам 2 17.03.2012 10:43
Вывод двумерного ассоциативного массива через цикл фор Syltan PHP 2 26.11.2010 18:59