2011-10-20 2 views
-2

다음과 같이 클래스 내부에 선언 된지도가 있습니다.부스트를 사용하여 (중첩 된) 맵을 변수로 직렬화하는 방법은 무엇입니까?

class Example { 
    public: 
     Example() 
     { 
      std::map< std::string, std::string > map_data; 
      map_data["LOCATION"] = "USA"; 
      map_data["WEBSITE"] = "http://www.google.com/"; 

      custom_map["nickb"] = map_data; 
     } 
     std::map< std::string, std::map< std::string, std::string > > get_map() { return custom_map; } 
    private: 
     std::map< std::string, std::map< std::string, std::string > > custom_map; 

     friend class boost::serialization::access; 
     template<class Archive> 
     void serialize(Archive &ar, const unsigned int version) 
     { 
      ar & BOOST_SERIALIZATION_NVP(custom_map); 
     } 
}; 

그리고 boost로 변수를 매핑하기 만하면됩니다.

예제는 전체 클래스를 직렬화하는 것처럼 보입니다. 그렇게하지 않아도됩니다. 또한 파일에 쓰는 중입니다. 맵의 상태를 파일에 보관할 필요가 없으므로 나에게 비효율적 인 것처럼 보이고 나중에 복원 할 수있는 방식으로 표현할 수 있습니다.

지금지도를 저장할 수 있습니다 :

// Create an Example object 
Example obj; 

// Save the map 
std::stringstream outstream(std::stringstream::out | std::stringstream::binary); 
boost::archive::text_oarchive oa(outstream); 
oa << obj; // <-- BOOST SERIALIZATION STATIC WARNING HERE 

// Map saved to this string: 
std::string saved_map = outstream.str(); 

그리고 복원 할 :

// Now retore the map 
std::map< std::string, std::map< std::string, std::string > > restored_map; 
std::stringstream instream(saved_map, std::stringstream::in | std::stringstream::binary); 
boost::archive::text_iarchive ia(instream); 
ia >> restored_map; 

std::map< std::string, std::string > map_data = restored_map.find("nickb")->second; 
std::cout << "nickb " << map_data["LOCATION"] << " " << map_data["WEBSITE"] << std::endl; 

그러나 작동하지 않습니다. 아무도 나에게 몇 가지 팁을 주거나지도를 직렬화하고 복원하는 방법을 보여줄 수 있습니까?

감사합니다.

편집 : 예제를 더 자세하게 업데이트하고 K-ballo와 Karl Knechtel (감사합니다!)의 답변을 고려했습니다. 이것은 위의 주석 된 행에서 부스트 직렬화 정적 경고 인 1을 제외한 거의 모든 오류를 해결했습니다. 경고 :

[Warning] comparison between signed and unsigned integer expressions 

컴파일 할 수 있도록이 경고를 해결하는 방법을 알려주십시오. 감사!

편집 : 내 문제는 두 가지 : 추가 할 필요가 : BOOST_CLASS_TRACKING (예, track_never) 그리고 전체 클래스를 serialize하고 맵을 unserialize하려고했습니다.

+1

"작동하지 않음"을 정의하십시오. –

+0

더 좋은 예를 들어 질문을 업데이트하고 Karl Knechtel과 K-ballo의 의견을 포함 시켰습니다. 감사! – nickb

+0

경고는 컴파일을 방해하지 않습니다 (일반적으로). 실제로 컴파일하는 것이 아니며, 그렇다면 정말로 그 경고 하나입니까? – ssube

답변

1

두 개의 완전히 다른 stringstream 개체가있는 것 같습니다. 하나는 데이터를 받고 두 번째는 (기본 문자열 데이터없이) 데이터를 복원하려고 시도한 것입니다. 어쨌든 stringstream은 데이터 저장소가 아닙니다. string은 실제로는 fstream이 실제 저장 영역 인 디스크의 파일에 기록하는 것과 거의 같습니다.

저장하려는 스트림의 .str()을 잡고 읽은 스트림을 초기화하는 데 사용하십시오.

+0

조언을 주셔서 감사합니다 - 나는 질문을 업데이 트하고 답변을 통합했지만 여전히 컴파일되지 않습니다. – nickb

1

스트림에 대한 값은 inout입니다. 또한 입력 스트림을 비어있는 데이터로 초기화하지 않습니다.