2011-10-25 4 views
1

내 프로그램은 C++로 작성되었습니다.std :: map <string, class> 키 값을 인쇄하십시오.

#include <iostream> 
#include <string> 
#include <map> 

using namespace std; 


    class Details 
    { 
     int x; 
     int y; 
    }; 

    typedef std::map<string, Details> Det; 
    Det det; 

    Details::Details(int p, int c) { 
     x = p; 
     y = c; 
    } 

    int main(){ 

     det.clear(); 

     insertNew("test", 1, 2); 

     cout << det["test"] << endl; 

     return 0; 
    } 

가장 간단한 방법으로 키 값을 인쇄하고 싶습니다. 예 : det [ "test"] 컴파일이 실패합니다. "test"키에 해당하는 (x, y) 값을 인쇄하는 방법은 무엇입니까?

+4

위의 코드는 구문 오류가 많으며 유효한 프로그램이 아닙니다. 컴파일 할 수없는 실제 코드를 입력하십시오. – ybungalobill

+1

코드 끝에 두 개의 닫는 괄호가 없습니다. – LowTechGeek

+0

@ybungalobill, 우리가 옳습니다. 내 코드를 실제 코드로 업데이트합니다. – cateof

답변

3

가장 좋은 추측은 Obj에 기본 또는 복사 생성자가 없다는 것입니다 (게시 한 코드에는 아무 것도 없지만 두 개의 정수를 사용한다고 가정합니다). 또한 catalog.insert() 행에 오타가 있습니다. 내가 조금 코드를 변경 한

for(auto ob = catalog.begin(); ob != catalog.end(); ++ob) 
{ 
    cout << ob->first << " " << ob->second.x << " " << ob->second.y; 
} 
+1

아, 닌자가 나를 편집했습니다. :) 다른 답변에 언급 된대로 연산자 <<를 만들거나 x, y 멤버에 액세스해야합니다. – JoeFish

+0

동일한 값에 대해'operator [] '를 여러 번 수행하면 성능이 심각하게 저하 될 수 있습니다. – Chad

+0

동의합니다. 동일한 C 문자열을 std :: string으로 변환하는 것이 좋습니다. 이 코드는 원래 질문과 비슷한 방식으로지도에 액세스하는 것을 설명하기위한 것입니다. – JoeFish

2

Objoperator<<을 만든 다음 std::cout << catalog["test"];과 같은 작업을 수행 할 수 있습니다 (삽입 통화에 누락 된 괄호는 복사하여 붙여 넣기 만한다고 가정합니다).

0

을 감안할 때 이러한 유형 : 채워진 catalog 목적을 감안할 때

class Obj { 
    int x; 
    int y; }; 

std::map<string, Obj> catalog; 

다음 코드를 사용하여, 나를 위해 일한 것입니다 .

#include <map> 
#include <iostream> 
#include <string> 

using namespace std; 
class Obj { 
    public: 
      Obj(int in_x, int in_y) : x(in_x), y(in_y) 
      {}; 
      int x; 
      int y; 
    }; 

int main() 
{ 
    std::map< string, Obj* > catalog; 
    catalog[ "test" ] = new Obj(1,2); 

    for(std::map<string, Obj*>::iterator i=catalog.begin(); i != catalog.end(); ++i) 
    { 
      cout << "x:" << i->second->x << " y:" << i->second->y << endl; 
    } 
} 
1

:

class Obj { 
public: 
    Obj() {} 
    Obj(int x, int y) : x(x), y(y) {} 
    int x; 
    int y; 
    }; 


int main (int argc, char ** argv) { 

    std::map<std::string, Obj> catalog; 
    catalog.insert(std::map<std::string, Obj>::value_type("test", Obj(1,2))); 

    std::cout << catalog["test"].x << " " << catalog["test"].y << std::endl; 

    return 0; 
} 
관련 문제