수다닷컴

  • 해외여행
    • 괌
    • 태국
    • 유럽
    • 일본
    • 필리핀
    • 미국
    • 중국
    • 기타여행
    • 싱가폴
  • 건강
    • 다이어트
    • 당뇨
    • 헬스
    • 건강음식
    • 건강기타
  • 컴퓨터
    • 프로그램 개발일반
    • C언어
    • 비주얼베이직
  • 결혼생활
    • 출산/육아
    • 결혼준비
    • 엄마이야기방
  • 일상생활
    • 면접
    • 취업
    • 진로선택
  • 교육
    • 교육일반
    • 아이교육
    • 토익
    • 해외연수
    • 영어
  • 취미생활
    • 음악
    • 자전거
    • 수영
    • 바이크
    • 축구
  • 기타
    • 강아지
    • 제주도여행
    • 국내여행
    • 기타일상
    • 애플
    • 휴대폰관련
  • 프로그램 개발일반
  • C언어
  • 비주얼베이직

c++ 질문드립니다...

가랑비

2023.04.01

1번코드대신 2번코드를 사용하면 왜 더 간단한지 자세히 설명좀 부탁드리겠습니다ㅜㅜ=====================================================1번 코드=====================================================#include iostreamusing namespace std;
struct word{ char* str; // 각 단어의 내용 int count; // 각 단어의 사용 빈도};
int max_of_words = 10; // 전체 words 배열의 크기int num_of_words =0; //입력된 words의 개수word *words = null; //동적 메모리 배열의 주소
int findwords (const char *s);void increase () ;void countwords (char *s);voidshowword();void removeall();
int main (){words = new word[max_of_words];memset(words, 0 ,sizeof (word)*max_of_words);
cout 문자열을 입력하세요 . 종료하려면 ctrl +z을 입력하세요. \n;while(true){ char buffer[128];cin. getline(buffer, 128);countwords (buffer);if(cin.eof)())break;}showwords();removeall();
return 0;}
void countwords(char *s){const char * delimiter = ,.?!\t\n;char *token = strtok(s, delimiter);while(token != null){int index = findwords (token);if (index == -1){if (num_of_words = max _of_words)increase ();else{words[num_of_words].str = new char [strlen (token)+1];strcpy(words[num_of_words].str, token);words[num_of_words]. count=1;num_of_words++;}}else{words [index].count++;}token = strtok (null, delimiter);}}
int findwords(const char *s){for (int i = 0 ; i num_of_words ; i++)if (strcmp(words[i].str,s)==0)return i ;return -1; //단어 검색 실패}
void increase (){max_of_words += 10;
word *tmp = words;words = new word [max_of_words]; //증가된 크기로 배열 생성memcpy(words, tmp, sizeof (word)* num_of_words);delete [] tmp;}
void showwords(){for (int i=0; i num_of_words; i++)cout words [i].str : words[i]. count 번 사용 \n;}
void removeall(){for(int i = 0;i num_of_words ; i++)delete [] words [i].str;delete [] words;}
=====================================================2번 코드=====================================================#include iostream#include string#include vectorusing namespace std;
struct WORD{string str; // 각 단어의 내용int count; // 각 단어의 사용빈도};
vector WORD* words; // WORD 구조체 포인터를 저장하는 벡터 객체
int FindWords(const string& s); // 동일 문자열 검색void CountWords(const string& s); // 문자열 카운트void ShowWords(); // 해당 문자열을 보여줌void RemoveAll(); // 할당된 메모리 해제
int main(){cout 문자열을 입력하세요. 종료하려면 Ctrl+Z를 입력하세요.\n; string buffer;while( cin buffer ) CountWords(buffer);ShowWords () ;RemoveAll () ;
return 0;}
void CountWords(const string& s){int index = FindWords(s);if ( index == -1){ WORD *pWord = new WORD; // 구조체 포인터(동적 메모리 할당) pWord-str = s; pWord-count = 1; words.push_back(pWord); // 배열 원소 추가}else{ words[index]-count++;}}
int FindWords(const string& s) //같은 문자열이 있는지 검색{for(int i = 0 ; i words.size() ; i++) if ( words[i]-str == s) return i;return -1; // 동일한 단어 검색 실패}
void ShowWords() //해당 문자열을 보여줌{for(int i = 0 ; i words.size() ; i++) cout words[i]-str : words[i]-count 번\n;}
void RemoveAll () // 할당된 메모리 해제(반납){for(int i = 0 ; i words.size() ; i++) delete words[i];}

신청하기





COMMENT

댓글을 입력해주세요. 비속어와 욕설은 삼가해주세요.

번호 제 목 글쓴이 날짜
2699024 C언어 공부하려는데 도와주세요!!! (2) 달님 2025-06-22
2698994 날짜 계산하는 C 코드 짜고 있는데 꽉 막혀서 질문드립니다.. (6) 별 2025-06-22
2698967 파일삭제 윈도우 폴더까지 접근하게하는 함수가 뭔가요 (2) 샤인 2025-06-21
2698938 c언어 메모리질문 (3) 나래 2025-06-21
2698909 서비스 요청 고객 관리 프로그램 짜는것좀 도와주세요ㅜㅜ (4) 궁수자리 2025-06-21
2698882 프로그래밍좀 짜주세요 (3) 황예 2025-06-21
2698855 카프-라빈 알고리즘 코딩 분석좀 도와주세요.. 꽃봄 2025-06-20
2698829 학점계산기 (7) MyWay 2025-06-20
2698782 기초적인 함수 질문이요ㅠㅠㅠㅠ 내담 2025-06-20
2698749 프로그램 짜던 도중 패닉입니다...ㅜ 파랑 2025-06-19
2698719 조건부컴파일 질문입니다.~ (2) 큐트 2025-06-19
2698693 재귀 함수 에러 바닐라 2025-06-19
2698673 고민이있는데 들어좀주세요!! (1) 초코맛캔디 2025-06-19
2698644 1부터 n까지의 합을 구하는데 엄청긴숫자의 합을 구할때는 어떻게 해야하나요? (4) 슬우 2025-06-18
2698616 다른 함수로 안넘어갑니다..;;; 도1도캣 2025-06-18
2698587 배열하다 막혀서... (3) WhiteCat 2025-06-18
2698559 문자열을 비우는방법 (2) 하늘 2025-06-18
2698528 착하고 친절한 선생씌구해염~ㅋㅋ (4) 옆집언니야 2025-06-17
2698502 자료구조 큐 캔서 2025-06-17
2698477 실행화면 배경문의요 선아 2025-06-17
<<  이전  1 2 3 4 5 6 7 8 9 10  다음  >>

수다닷컴 | 여러분과 함께하는 수다토크 커뮤니티 수다닷컴에 오신것을 환영합니다.
사업자등록번호 : 117-07-92748 상호 : 진달래여행사 대표자 : 명현재 서울시 강서구 방화동 890번지 푸르지오 107동 306호
copyright 2011 게시글 삭제 및 기타 문의 : clairacademy@naver.com