c++ 질문입니다. 도와주세요.

soccer0118의 이미지

#include <iostream>
#include <unordered_map>
 
class CachingCalculator
{
	class Arguments
	{
	public:
		Arguments(int firstArgument, int secondArgument)
		{
			this->firstArgument = firstArgument;
			this->secondArgument = secondArgument;
		}
 
		int firstArgument;
		int secondArgument;
	};
 
public:
	CachingCalculator(int(*func)(int, int))
	{
		this->func = func;
	}
 
	~CachingCalculator()
	{
		for (std::unordered_map<Arguments*, int>::iterator it = calculations.begin(); it != calculations.end(); ++it)
		{
			delete it->first;
		}
	}
 
	int calculate(int firstArgument, int secondArgument)
	{
		Arguments* args = new Arguments(firstArgument, secondArgument);
 
		std::unordered_map<Arguments*, int>::iterator it = calculations.find(args);
		if (it != calculations.end())
			return it->second;
 
		int calculation = func(firstArgument, secondArgument);
		calculations[args] = calculation;
		return calculation;
	}
 
private:
	std::unordered_map<Arguments*, int> calculations;
	int(*func)(int, int);
};
 
/*int modulo(int a, int b)
{
	std::cout << "Function modulo has been called.\n";
	return a % b;
}
 
int main(int argc, const char* argv[])
{
	CachingCalculator calculator(modulo);
 
	// Function modulo should be called.
	std::cout << calculator.calculate(5, 2) << '\n';
 
	// Function modulo should be called.
	std::cout << calculator.calculate(7, 4) << '\n';
 
	// Function modulo shouldn't be called because we have already made a call with arguments (5, 2)!
	// Instead, result should be pulled from the cache!
	std::cout << calculator.calculate(5, 2) << '\n';
 
	return 0;
}*/

버그를 찾고 고치는 건데 잘모르겠습니다. 도와주세요 ㅠ

shint의 이미지


보이는것만 적어봅니다.
- using namespace std;
- Arguments에 소멸자가 없슴
- endl 이 없음
- public을 지정하지 않을 경우. private 으로 지정됩니다.
- 클래스를 중복으로 사용했네요

- 개발자가 원하는 내용은 map에 저장된 내용이 있을 경우. 등록되지 않아야 하는데. 등록되어 출력된거 같습니다.
이에 대한 임시적인. 해결 방법으로는. 문자열로 입력하면 될것 같습니다.

- delete 대상이 NULL 값인 경우에 대한 처리가 필요합니다.

----------------------------------------------------------------------------
젊음'은 모든것을 가능하게 만든다.

매일 1억명이 사용하는 프로그램을 함께 만들어보고 싶습니다.
정규 근로 시간을 지키는. 야근 없는 회사와 거래합니다.

각 분야별. 좋은 책'이나 사이트' 블로그' 링크 소개 받습니다. shintx@naver.com

익명 사용자의 이미지

using namespace std;를 안 쓴 것이 에러라니... C++ 표준 라이브러리의 모든 것들은 std:: 네임스페이스 안에 들어 있기 때문에, std::cout 식으로 사용하는 것은 올바른 사용 예입니다. 이렇게 몇 줄 안 찍고 끝나는 프로그램이라면 매번 출력 때마다 버퍼를 비우는 대신 endl 대신 '\n'을 사용해도 아무런 문제가 없고요.

그리고 클래스 안에 클래스를 사용하는 것도 C++ 문법의 일부입니다. http://en.cppreference.com/w/cpp/language/nested_types 페이지를 참조하세요.

익명 사용자의 이미지

C++11 질문이라서 찾아보는 데 시간이 좀 걸렸습니다. 요점은 POD 타입이 아닌 클래스가 Key로 오면, 해시 함수 및 비교 함수를 재정의해 줘야 한다는 것입니다. 아래 코드를 보면 Arguments 클래스를 해시 및 비교하기 위한 Hasher, Comparator 함수가 새로 추가되었고, unordered_map을 선언할 때 Hasher와 Comparator를 일일이 다 쓸 수는 없기 때문에 typedef를 추가하였습니다. Hasher 안의 내용은 자유롭게 변경하셔도 되나, 같은 firstArgument와 secondArgument가 들어갔을 때 같은 값이 나오는 것이 올바른 사용법일 것입니다.

#include <iostream>
#include <unordered_map>
 
class CachingCalculator
{
	class Arguments
	{
	public:
		Arguments(int firstArgument, int secondArgument)
		{
			this->firstArgument = firstArgument;
			this->secondArgument = secondArgument;
		}
 
		int firstArgument;
		int secondArgument;
	};
 
        class Hasher {
            public:
                std::size_t operator()(Arguments* const &k) const {
                    return std::hash<int>()(k->firstArgument) ^ std::hash<int>()(k->secondArgument);
                }
        };
 
        class Comparator {
            public:
                bool operator()(Arguments* const& t1, Arguments* const& t2) const {
                    return ((t1->firstArgument == t2->firstArgument) && (t1->secondArgument == t2->secondArgument));
                }
        };
 
        typedef std::unordered_map<Arguments*, int, Hasher, Comparator> ArgumentMap;
 
public:
	CachingCalculator(int(*func)(int, int))
	{
		this->func = func;
	}
 
	~CachingCalculator()
	{
		for (ArgumentMap::iterator it = calculations.begin(); it != calculations.end(); ++it)
		{
			delete it->first;
		}
	}
 
	int calculate(int firstArgument, int secondArgument)
	{
		Arguments* args = new Arguments(firstArgument, secondArgument);
 
		ArgumentMap::iterator it = calculations.find(args);
		if (it != calculations.end())
			return it->second;
 
		int calculation = func(firstArgument, secondArgument);
		calculations[args] = calculation;
		return calculation;
	}
 
private:
	ArgumentMap calculations;
	int(*func)(int, int);
};
 
int modulo(int a, int b)
{
	std::cout << "Function modulo has been called.\n";
	return a % b;
}
 
int main(int argc, const char* argv[])
{
	CachingCalculator calculator(modulo);
 
	// Function modulo should be called.
	std::cout << calculator.calculate(5, 2) << '\n';
 
	// Function modulo should be called.
	std::cout << calculator.calculate(7, 4) << '\n';
 
	// Function modulo shouldn't be called because we have already made a call with arguments (5, 2)!
	// Instead, result should be pulled from the cache!
	std::cout << calculator.calculate(5, 2) << '\n';
 
	return 0;
}

참고:
https://stackoverflow.com/questions/17016175/c-unordered-map-using-a-custom-class-type-as-the-key
https://stackoverflow.com/questions/15810620/unordered-map-with-custom-hashing-equal-functions-functions-dont-get-called

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.