C++ 클래스 타입의 벡터와 .erase()

조회수 606회

ShoppingCart.cpp 의 update_quantity() 에서 listOfItem.erase(p) 를 사용하여 이름이 같은데 newQuantity가 1 이하면 listOfItem 이라는 벡터에서 class Item 타입의 element를 지우려고 합니다. 벡터는 erase 로 지울 수 있다고 아는데 왜 안되는지 막막하네요. 답변 주시면 정말 감사하겠습니다.

아래에 에러 메세지와 코드입니다. cart_test.cpp 라는 파일도 있지만 연관성이 없어보여 올리지 않았습니다.

이미지

ShoppingCart.h

#ifndef SHOPPINGCART_H
#define SHOPPINGCART_H
#include <vector>

#include "Item.h"
class ShoppingCart
{
    public:
        void add(Item newItem);
        bool update_quantity(std::string name, int newQuantity);
        bool remove(std::string name);
        void write();
        double total_value();

    private:
        std::vector<Item> listOfItem;
};

#endif

ShoppingCart.cpp

#include "ShoppingCart.h"
#include <iostream>
#include <vector>

void ShoppingCart::add(Item newItem)
{
    bool trueFalse = false;

    if (newItem.get_quantity() > 0)    
    {
        for (auto& p : listOfItem)
        {
            if (p.get_name() == newItem.get_name())
            {
                p.set_quantity(p.get_quantity() + newItem.get_quantity());

                if (p.get_price() != newItem.get_price())
                {
                    p.set_price(newItem.get_price());
                };

                trueFalse = true;
            };
        };

        if (trueFalse == false)
            listOfItem.push_back(newItem);
    };

}
bool ShoppingCart::update_quantity(std::string name, int newQuantity)
{
    bool trueFalse;
    int position = 0;
    for (auto& p : listOfItem)
    {
        if (p.get_name() == name)
        {
            if (newQuantity < 1)
                {
                    listOfItem.erase(p);
                    trueFalse = false;
                }
            else
            {
                p.set_quantity(newQuantity);
                trueFalse = true;
            };


        };
    };
}

bool ShoppingCart::remove(std::string name)
{

}

void ShoppingCart::write()
{

}

double ShoppingCart::total_value()
{

}

Item.h

//file Item.h
#ifndef ITEM_H
#define ITEM_H
#include <string>

class Item {
public:
    // constructors
    Item(std::string name, double price, int quantity);
    // accessors
    std::string get_name()     const;
    double      get_price()    const;
    int         get_quantity() const;
    // mutators
    void set_price(double new_price);
    void set_quantity(int new_quantity);
    // other methods
    void print() const; 

private:
    std::string name;     /// name of the item
    double      price;    /// price for one item
    int         quantity; /// how many are you buying?
};


#endif

Item.cpp

// @file Item.cpp
#include "Item.h"
#include <iomanip>
#include <iostream>

Item::Item( std::string name, double price, int quantity ) {
    this->name     = name;  // `this->` means "self"
    this->price    = price;
    this->quantity = quantity;
}

std::string Item::get_name( ) const {
    return name;
}

double Item::get_price( ) const {
    return price;
}

int Item::get_quantity( ) const {
    return quantity;
}

void Item::set_price( double new_price ) {
    price = new_price;
}

void Item::set_quantity( int new_quantity ) {
    quantity = new_quantity;
}

void Item::print( ) const {
    std::cout << std::fixed << std::setprecision( 2 );
    std::cout << name << '\n';
    std::cout << "\tPrice: $  " << price << '\n';
    std::cout << "\tQuantity: " << quantity << '\n';
}

  • (•́ ✖ •̀)
    알 수 없는 사용자

1 답변

  • 올려주신 코드에 보면 erase 함수에 벡터의 요소인 p를 직접 넣었는데, erase 함수는 요소를 직접 넣는 것이 아니고 요소의 위치를 넣어줘야 합니다.

    아래의 코드를 보시면 감이 오실거에요.

    • 코드
    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    int main()
    {
        vector<int> numbers{ 1,2,3,4 };
    
        cout << "삭제 전\n";
        for (int num : numbers)
            cout << num << '\n';
    
        for (int i = 0; i < (int)numbers.size(); ++i) {
            if (numbers[i] == 3) {
                numbers.erase(numbers.begin() + i);
                --i;
            }
        }
    
        cout << "\n삭제 후\n";
        for (int num : numbers)
            cout << num << '\n';
    
    
        return 0;
    }
    

    -결과

    이미지

    • (•́ ✖ •̀)
      알 수 없는 사용자

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)