2017-11-08 11 views
1

구조체 포인터 (st * ptr)로 인수를 취하는 루프에서 함수를 호출하고이 데이터를 STL 벡터로 push_back하고 내용을 표시해야합니다. 루프. 어떻게하면 돼? 도와주세요.stl 벡터에 구조체 포인터를 삽입하고 내용을 표시하는 방법

struct st 
{ 
    int a; 
    char c; 
}; 
typedef struct st st; 


function(st *ptr) 
{ 
    vector<st*>myvector; 
    vector<st*>:: iterator it; 
    myvector.push_back(ptr); 
    it=myvector.begin(); 
    cout<<(*it)->a<<(*it)->c<<endl; 
} 

이 정확히 맞습니까? 나는 실제 출력을 얻지 못하고있다.

코드 -----

void Temperature_sensor::temp_notification()//calling thread in a class------ 
{ 

    cout<<"Creating thread to read the temperature"<<endl; 
    pthread_create(&p1,NULL,notifyObserver_1,(void*)(this)); 
    pthread_create(&p2,NULL,notifyObserver_2,(void*)(this)); 
    pthread_join(p1,NULL); 
    pthread_join(p2,NULL); 

} 


void* Temperature_sensor::notifyObserver_1(void *data) 
{ 

    Temperature_sensor *temp_obj=static_cast<Temperature_sensor *>(data); 
    (temp_obj)->it=(temp_obj)->observers.begin(); 
    ifstream inputfile("temp.txt");//Reading a text file 

    while(getline(inputfile,(temp_obj)->line)) 
    { 
     stringstream linestream((temp_obj)->line); 
     getline(linestream,(temp_obj)->temperature,':'); 
     getline(linestream,(temp_obj)->temp_type,':'); 
     cout<<(temp_obj)->temperature<<"---"<<(temp_obj)->temp_type<<endl; 
     stringstream ss((temp_obj)->temperature); 
     stringstream sb((temp_obj)->temp_type); 
     sb>>(temp_obj)->c_type; 
     ss>>(temp_obj)->f_temp; 
     cout<<"____"<<(temp_obj)->f_temp<<endl; 
     (temp_obj)->a.temp=(temp_obj)->f_temp; 
     (temp_obj)->a.type=(temp_obj)->c_type; 
     cout<<"------------------q"<<(temp_obj)->a.type<<endl; 
     (*(temp_obj)->it)->update(&(temp_obj)->a);//Calling the function ------- 

} 
input file temp.txt 
20:F 
30:C 
40:c 
etc
void Temperature_monitor::update(st *p) {}//need to store in a vector------ 
+1

... 당신이 묘사 한 코드를 정확히 쓰면? 무엇이 효과가 없었습니까? – Quentin

+1

컴파일을 시도 했습니까? 결과? – Klaus

+0

실제 출력물을 얻지 못한다면 무엇을 얻고 있습니까? 또한 C++은 C가 아닙니다. 당신은'typedef' 라인이 필요 없다.그리고 이와 같이 벡터에 포인터를 두는 용도가 있지만 실제로는 벡터 안에 'st'를 직접 넣는 것이 좋습니다. –

답변

0

당신이 표준 : : 벡터를 사용하는 경우이 같은 수행해야합니다, 당신을 물론

std::vector<st> v; //use st as type of v 

//read 
for(auto const& i : v) { 
    std::cout << i.param1 << ' ' << i.param2; 
} 
//push_back 
v.push_back({param1, param2}); 

을 2 개 이상의 매개 변수를 가질 수 있습니다.

0

샘플 입력 데이터와 예상 출력을 공유해주십시오. 코드를 사용하면 항상 새 벡터를 만들고 거기에 1 개의 구조체를 넣습니다. 당신이 하나의 벡터 저장 모든 구조 개체를 갖고 싶어 후 "기능"의 함수를 호출에 벡터를 선언

+0

OP가 자신의 게시물을 업데이트 했으므로 대답으로 만들 수 있습니다. 너는 옳은 길을 가고있다, 조금만 대답하면 육체가 필요하다. – smac89

0
당신이 다음 malloc()와 유형 void*의 버퍼 data 또는 유사한 기능을 할당 data을 캐스팅 것처럼 보이는

~ Temperature_sensor*. Temperature_sensor은 (는) std::string 명의 회원으로 지정하고 인쇄하려고 시도하는 것으로 나타납니다.

std::stringPOD type하지 않고, 그래서 std::string 생성자가 실제로 호출되지 않습니다 때문에이 작동하지 않습니다 (이것은 비 POD의 회원을 보유하고 생성자이 때문에 호출되지 않습니다 때문에 마찬가지로, Temperature_sensor는 POD 타입이다).

은 당신이 그렇게

Temperature_sensor *tsensor = new Temperature_sensor; 
Temperature_sensor *five_tsensors = new Temperature_sensor[5]; 

그것은 std::unique_ptr 또는 대신 operator new() (및 operator delete())를 사용 std::shared_ptr 같은 스마트 포인터를 사용하는 것이 더 관용적 것 직접처럼 malloc() 대신에 operator new()를 사용할 필요가 올바르게 개체를 구성하려면 , 그리고 가장/가장 관용적 인 std::vector을 사용합니다. 이러한 메소드는 할당 된 객체를 올바르게 생성합니다.

Temperature_sensor 클래스를 크게 단순화하는 것이 좋습니다. 동일한 정보를 서로 다른 형식으로 중복 저장하는 수많은 인스턴스 변수가있는 것으로 나타나고 함수 내부의 로컬 변수로 더 적합합니다.

도 모두 std::stringstream을 만들 필요는 없습니다. std::stod()std::stoi()을 사용하여 문자열을 부동 소수점 또는 정수로 변환하고 std::to_string()을 사용하여 숫자를 문자열로 변환하는 것이 좋습니다.

+0

의견과 제안에 감사를드립니다 @ 레이 하멜 – Deepak