연관 컨테이너에서 map의 키로 값이 검색되지 않는데요..

dltkddyd의 이미지

map의 멤버함수인 연산자

mapped_type& operator[] (const key_type& k);

로 맵 컨테이너의 값을 반환받고자 했는데 컴파일시 다음과 같은 오류가 뜹니다.

map2.cc: 19:2: note: candidates are: Items::Items(std::string, const char*, int, int)
map2.cc: 12:2: note: Items::Items(const Items&)

그리고 해당 소스코드는 다음과 같습니다.

#include <iostream>
using namespace std;
#include <map>
#include <utility>
#include <cstring>
struct Items {
	//char* name;
	string name;
	int price;
	int damage;
	char* in_english;
	Items(const Items& it) {
		name=it.name;
		in_english=new char[strlen(it.in_english)+1];
		strcpy(in_english, it.in_english);
		price=it.price;
		damage=it.damage;
	}
	Items(/*const char* _name*/ string _name, const char* _in_english,  int _price, int _damage) {
		//name=new char[strlen(_name)+1];
		//strcpy(name,_name);
		name=_name;
		in_english=new char[strlen(_in_english)+1];
		strcpy(in_english, _in_english);
		price=_price;
		damage=_damage;
	}
};
//mapped_type& operator[] (const key_type& k);
int main() {
	map<string ,Items>  arms;
	typedef map<string ,Items>::value_type itemtype;
	Items item1("불칼","fire sword",20000,40);
	Items item2("단검" , "short sword", 5000 , 10);
	Items item3("보검", "treasure sword",100000,80);
	cout<<item1.name<<"  "<<item1.price<<"    "<<item1.damage<<endl;
	cout<<item2.name<<"  "<<item2.price<<"    "<<item2.damage<<endl;
	cout<<item3.name<<"  "<<item3.price<<"    "<<item3.damage<<endl;
	//map은 컨테이너 안 각 요소에서 동적으로 할당된 메모리는 자동으로 해제되는  것으로 추론할 수 있다. 
	pair<string,Items> armspair=make_pair("불칼",item1);
	arms.insert(armspair);
	armspair=make_pair("단검",item2);
	arms.insert(armspair);
	armspair=make_pair("보검", item3);
	arms.insert(armspair);
	map<string,Items>::iterator first, last, current;
	first=arms.begin();
	last=arms.end();
 
 
	for(current=first;current!=last;++current) {
		cout<<current->first<<"  "<<(current->second).in_english<<"  ";
		//cout<<arms[current->first].in_in_english<<endl;
		cout<<current->second.price<<"  "<<current->second.damage<<endl;
	}
	arms["불칼"];//여기서 컴파일 오류가 발생합니다.
 
 
 
	return 0;
}

위에서 return 0 직전에 arms["불칼"]에서 컴파일 오류가 발생합니다. 그래서 Items(const Items& it) 생성자를 위에서 언급된 대로 만들었는데 오류는 계속 뜹니다. 뭐가 잘못됐는지 모르겠습니다. 아시는 분 답변좀 달아주세요..

klara의 이미지

value_type에 기본생성자가 없어서 그렇습니다. []로접근하면 없는 키에대해서는 기본생성자로 값을 만들어서 키-밸류쌍을 넣고서 이렇게들어간 밸류를 반환합니다.
그리고 에러메시지를 더 주이깊게보시기 바랍니다. 적으신건 에러메시지 본문이라기보다는 힌트입니다. 에러메시지는 그앞에있습니다. 단 템플릿의 경우에는 익숙해지지않으면 에러메시지를 읽는것도 의미를 파악하는것도어렵긴 합니다.

dltkddyd의 이미지

말씀하신 대로 기본생성자를 구조체 안에 만들어놓으니, 제대로 컴파일이 됩니다. 답변 감사드립니다. 답변이 없었으면 아마 몇 일 이 문제로 고생했을지도 모를 일인데..

본인 맞습니다.
인증샷
우헤헤헤... 로 대신합니다.

dltkddyd의 이미지

참조로 객체를 받아 넘기는 생성자는 없어도 되는 거였네요. 불필요한 것은 없애서 간결하게 만드는 것이 좋겠죠?

본인 맞습니다.
인증샷
우헤헤헤... 로 대신합니다.

klara의 이미지

아마 복사 생성자를 말씀하시는 듯한데, STL의 컨테이너는 복사/대입을 자주 해야하기 때문에 필요하다면 정의해줘야합니다.
특히 tunecolor님의 경우에는 지금 클래스 객체가 직접 메모리를 관리해야하는 in_english라는 멤버변수가 존재하기 때문에 기본생성자/복사 생성자/소멸자/대입연산자 전부 정의해주는게 좋습니다.
단, in_english를 char*가 아닌 std::string으로 바꾸면 in_english에 대한 복사/대입/소멸시의 메모리 관리는 std::string이 알아서 해주므로 생략가능합니다.

댓글 달기

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
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.