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

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

Вернуться   Форум программистов > IT форум > Помощь студентам
Регистрация

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

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

Ответ
 
Опции темы Поиск в этой теме
Старый 25.01.2015, 01:48   #1
goshek
Пользователь
 
Регистрация: 07.01.2014
Сообщений: 33
По умолчанию Создать "сумку" С++

Доброго времени суток, прошу помощи разобраться.

Есть 4 части кода

1ая

BagInterface.h

Код:
# ifndef _BAG_INTERFACE
    # define _BAG_INTERFACE
    # include < vector >
    template < class ItemType >
    class BagInterface
{
    public:
    /* Gets the current number of entries in this bag.
    @return The integer number of entries currently in the bag. */
    virtual int getCurrentSize () const = 0;

    /* Sees whether this bag is empty.
    @return True if the bag is empty, or false if not. */
    virtual bool isEmpty () const = 0;

    /* Adds a new entry to this bag.
    @post If successful, newEntry is stored in the bag and
    the count of items in the bag has increased by 1.
    @param newEntry The object to be added as a new entry.
    @return True if addition was successful, or false if not. */
    virtual bool add (const ItemType & newEntry) = 0;

    /* Removes one occurrence of a given entry from this bag,
    if possible.
    @post If successful, anEntry has been removed from the bag
    and the count of items in the bag has decreased by 1.
    @param anEntry The entry to be removed.
    @return True if removal was successful, or false if not. */
    virtual bool remove (const ItemType & anEntry) = 0;

    /* Removes all entries from this bag.
    @post Bag contains no items, and the count of items is 0. */
    virtual void clear () = 0;


    /* Counts the number of times a given entry appears in bag.
    @param anEntry The entry to be counted.
    @return The number of times anEntry appears in the bag. */
    virtual int getFrequencyOf (const ItemType & anEntry) const = 0;

    /* Tests whether this bag contains a given entry.
    @param anEntry The entry to locate.
    @return True if bag contains anEntry, or false otherwise. */
    virtual bool contains (const ItemType & anEntry) const = 0;

    /* Empties and then fi lls a given vector with all entries that
    are in this bag.
    @return A vector containing all the entries in the bag. */
    virtual vector < ItemType > toVector () const = 0;
}
;  // end BagInterface
2ая
ArrayBag.h

Код:
# ifndef _ARRAY_BAG
# define _ARRAY_BAG
# include "BagInterface.h"
template < class ItemType >
class ArrayBag:
public BagInterface < ItemType >
{
    private:
    static const int DEFAULT_CAPACITY = 6; // Small size to test for a full bag
    ItemType items [DEFAULT_CAPACITY]; // Array of bag items
    int itemCount; // Current count of bag items
    int maxItems; // Max capacity of the bag
    // Returns either the index of the element in the array items that
    // contains the given target or -1, if the array does not contain
    // the target.
    int getIndexOf (const ItemType & target) const;
    public:
    ArrayBag ();
    int getCurrentSize () const;
    bool isEmpty () const;
    bool add (const ItemType & newEntry);
    bool remove (const ItemType & anEntry);
    void clear ();
    bool contains (const ItemType & anEntry) const;
    int getFrequencyOf (const ItemType & anEntry) const;
    vector < ItemType > toVector () const;
}
;  // end ArrayBag
# endif


ArrayBag.cpp

Код:
# include < iostream >
    # include < string >
    # include "ArrayBag.h"
    using namespace std;
void displayBag (ArrayBag < string > & bag)
{
    cout << "The bag contains " << bag.getCurrentSize ()
        << " items:" << endl;
    vector < string > bagItems = bag.toVector ();
    int numberOfEntries = (int) bagItems.size ();
    for (int i = 0 ; i < numberOfEntries ; i++)
    {
        cout << bagItems [i] << " ";
    } // end for
    cout << endl << endl;
} // end displayBag

void bagTester (ArrayBag < string > & bag)
{
    cout << "isEmpty: returns " << bag.isEmpty ()
        << "; should be 1 (true)" << endl;
    displayBag (bag);
    string items [] = {"one", "two", "three", "four", "five", "one"};
    cout << "Add 6 items to the bag: " << endl;
    for (int i = 0 ; i < 6 ; i++)
    {
        bag.add (items [i]);
    } // end for


    displayBag (bag);
    cout << "isEmpty: returns " << bag.isEmpty ()
        << "; should be 0 (false)" << endl;
    cout << "getCurrentSize: returns " << bag.getCurrentSize ()
        << "; should be 6" << endl;
    cout << "Try to add another entry: add(\"extra\") returns "
        << bag.add ("extra") << endl;
} // end bagTester

int main ()
{
    ArrayBag < string > bag;
    cout << "Testing the Array-Based Bag:" << endl;
    cout << "The initial bag is empty." << endl;
    bagTester (bag);
    cout << "All done!" << endl;
    return 0;
} // end main

Последний раз редактировалось goshek; 25.01.2015 в 02:52.
goshek вне форума Ответить с цитированием
Старый 25.01.2015, 01:48   #2
goshek
Пользователь
 
Регистрация: 07.01.2014
Сообщений: 33
По умолчанию

4ая

Код:
#include <cstddef>

template<class ItemType>

Bag<ItemType>::Bag() : itemCount(0), maxItems(DEFAULT_BAG_SIZE)
{
	
	//itemCount=0;
	//maxItems=DEFAULT_BAG_SIZE;
}  // end default constructor

template<class ItemType>
int Bag<ItemType>::getCurrentSize() const
{
	return itemCount;
}  // end getCurrentSize

template<class ItemType>
bool Bag<ItemType>::isEmpty() const
{
	return itemCount == 0;
}  // end isEmpty

template<class ItemType>
bool Bag<ItemType>::add(const ItemType& newEntry)
{
	bool hasRoomToAdd = (itemCount < maxItems);
	if (hasRoomToAdd)
	{
		items[itemCount] = newEntry;
		itemCount++;
	}  // end if
    
	return hasRoomToAdd;
}  // end add
// private
template<class ItemType>
int Bag<ItemType>::getIndexOf(const ItemType& target) const
{
	bool found = false;
   int result = -1;
   int searchIndex = 0;
   // if the bag is empty, itemCount is zero, so loop is skipped
   while (!found && (searchIndex < itemCount))
   {
      if (items[searchIndex] == target)
      {
         found = true;
         result = searchIndex;
      } 
      else
      {
         searchIndex++;
      }  // end if
   }  // end while
   
   return result;
}  // end getIndexOf

template<class ItemType>
bool Bag<ItemType>::remove(const ItemType& anEntry)
{
   int locatedIndex = getIndexOf(anEntry);
	bool canRemoveItem = !isEmpty() && (locatedIndex > -1);
	if (canRemoveItem)
	{
		itemCount--;
		items[locatedIndex] = items[itemCount];
	}  // end if
    
	return canRemoveItem;
}  // end remove

template<class ItemType>
void Bag<ItemType>::clear()
{
	itemCount = 0;
}  // end clear


template<class ItemType>
vector<ItemType> Bag<ItemType>::toVector() const
{
	vector<ItemType> bagContents;
	for (int i = 0; i < itemCount; i++)
		bagContents.push_back(items[i]);
   return bagContents;
}  // end toVector

Уже исправил несколько ошибок в начальном коде, вопрос такой. Куда вставить 4ую часть? Я понимаю, что это описание виртуальных функции из заголовочного файла Интерфейса, но я запутался. Еще почему то компилятор выдает странные ошибки, типа в 1ом файле я забыл ";" . И не могу решить последний вопрос, написать функцию для проверки дублирования "предметов в сумке"

Большое Спасибо, заранее
goshek вне форума Ответить с цитированием
Ответ


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



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Постоянно слетает галочка "автоматически" в "Параметры Excel", "Формулы", "Вычисления в книге" Alexsandrr Microsoft Office Excel 4 19.10.2013 14:22
Нужно создать "батник", вырезать из "2.txt" первых n строк и вставить их в "1.txt" temphard Помощь студентам 2 03.09.2013 16:03
создать файл формата ".dwg" или "dxf" Sergey_gorobets Помощь студентам 2 26.03.2013 03:03
Создать класс "Фигура", от него наследованием создать 3 класса ("треугольник", "четырехугольник", "окружность") funnyy Помощь студентам 3 17.10.2012 17:40
при вводе на листе "магазин"- код товара появлялось "описание" товара из "склада" с "продажной ценой" aleksei78 Microsoft Office Excel 13 25.08.2009 12:04