CPP module 01
ex00
- zombie ๊ฐ์ฒด๋ฅผ ๋๊ฐ์ง ๋ฐฉ์์ผ๋ก ์์ฑ.
- ์คํ์ zombie ๊ฐ์ฒด ์์ฑ (randomChump())
- ํ์ ๊ฐ์ฒด๋ฅผ ๋ง๋ค์ด๋ณด๊ธฐ(newZombie())
heap์ ๋ง๋ค๊ธฐ : new ํค์๋๋ฅผ ์ฌ์ฉํ๋ค. ์๋์ผ๋ก ์๋ฉธ๋์ง ์์ผ๋ฏ๋ก ๋ค ์ฐ๋ฉด delete๋ฅผ ํด์ฃผ์ด์ผํจ
ex01
๊ฐ์ฒด ๋ฐฐ์ด ์์ฑํ๊ธฐ๋ ํ ๋น ํด์ ํ๊ธฐ
//zombie ๊ฐ์ฒด n๊ฐ๋ฅผ ๋ฅผ ํ๋ฒ์ ํ ๋น
Zombie *z = new Zombie[N];
delete [] z;
ex02
pointer ์ reference ํ์ ์ ์ฐจ์ด ์ดํดํ๊ธฐ
int n = 0;
int *ptr = &n;
int &ref = n;
- ptr ์์๋ n์ด ์ ์ฅ๋์ด์๋ ๊ณณ์ ์ฃผ์๊ฐ์ด ์์. ptr์ ํตํด n์ ์ ๊ทผํ ์ ์์ ๋ฟ ptr๊ณผ n์ ์ ํ ๋ค๋ฅธ ๋ณ์
- ref๋ n๊ณผ ๊ฐ์ ๋ฉ๋ชจ๋ฆฌ ๊ณต๊ฐ์ ๋ํ๋ธ๋ค๊ณ ๋ณด๋ฉด๋ ๋ฏ? ๋ณ์ n์ ref๋ผ๋ ๋ค๋ฅธ ์ด๋ฆ์ด ์๊ฒผ์ ๋ฟ ๋์ด๋ ๊ฐ๋ค !
ex03
ref type์ผ๋ก ๋ฐํํ๊ฑฐ๋ ์ธ์๋ฅผ refํ์ ์ผ๋ก ๋ฃ๋ ๊ฒ์ ์ด์ ์ด ๋ญ๊น?
์ฐธ์กฐ ์ ๋ฌ์ ๋ณต์ฌ๋ณธ ์์ฑ์ ์ํด์ ๋น ๋ฆ
ex04
- s1์ด null์ผ ๊ฒฝ์ฐ์๋ ์์ธ์ฒ๋ฆฌ๋ฅผ ํด์ฃผ์๋ค. s2๋ null์ด ์ค๋ฉด ๊ทธ ๋ฌธ์๋ฅผ ์ง์์ฃผ๋ ๊ฑธ๋ก!
int main(int argc, char **argv) {
if (argc != 4) {
std::cout << "[Usage]: ./SedIsForLosers <file_name> <s1> <s2>" << std::endl;
return 0;
}
std::string s1 = argv[2];
std::string s2 = argv[3];
if (s1.empty()) {
std::cout << "String1 must NOT be empty." << std::endl;
return 0;
}
Constructs an ifstream object, initially associated with the file identified by its first argument (filename), open with the mode specified by mode.Internally, its istream base constructor is passed a pointer to a newly constructed filebuf object (the internal file stream buffer). Then, filebuf::open is called with filename and mode as arguments.If the file cannot be opened, the stream's failbit flag is set.
cplusplus ๋ ํผ๋ฐ์ค๋ฅผ ๋ณด๋ฉด โฆ! ifstream์ ์์ฑํ๋ฉด์ ๋์์ ์ธ์๋ก filename์ ๋ฃ์ผ๋ฉด open์ด ํธ์ถ๋จ. ์๋ง ofstream๋ ๋ง์ฐฌ๊ฐ์ง
- file์ open ํ๋ ค๋๋ฐ c++98์ file name์ ๋ฃ์ ๋ char * ๋ง์ ์ธ์๋ก ๋ฐ๋ ๊ฒ์ ํ์ธํจโฆใ ใ std::string์ ์ธ์๋ก ๋ฃ๋ ๊ฒ์ c++11๋ถํฐ๋ผ๊ณ ๋์ด์๋คโฆ.! ๊ทธ๋์ ์ด์ฉ์ ์์ดโฆ. char * ํ์ ์ธ์๋ก ๋ฃ๊ธฐ๋ก!
std::ifstream ifs_src(argv[1]);
if (ifs_src.fail()) {
std::cout << "No such file" << std::endl;
return 0;
}
std::ofstream ofs_dst((std::string(argv[1]) + ".replace").c_str());
if (ofs_dst.fail()) {
std::cout << "Open file failed." << std::endl;
return (0);
}
- file์ ๋ด์ฉ์ ๊ฐ์ ธ์์ s1์ s2๋ก ๋ฐ๊ฟ์ผํ๋๋ฐ.. getline์ ์ฐ๋ฉด delim์ ๋ฌธ์๊น์ง ๊ฐ์ ธ์ค๊ณ ์ ๊ฑฐํด๋ฒ๋ฆผ. ๋ํดํธ๊ฐ โ\nโ์ผ๋ก ๋์ด์์ผ๋ s1์ โ\nโ๋ก ์ฌ์ฉํ๊ณ ์ถ์ ๋ ์ธ ์๊ฐ ์์! ๊ทธ๋ฌ๋ฉด delim์ โ\0โ๋ก ํ๋ฉดโฆ! ํ์ผ ๋๊น์ง ์ฝ์ด์ ๊ฐ์ ธ์ค๋ ๊ฒ์ด ๋๋นโฆ.. ํ์ผ ๋๊น์ง string์ ๋ด๋ ์ ๋ฐ์ ์๊ฒ ๋น.. while์ ๋๋ ค ํ์ผ ํฌ๊ธฐ๊ฐ input stream์ ๋์ด๋ ๊ด์ฐฎ๋๋ก ํจ!
- replace๋ฅผ ์ฌ์ฉํ ์ ์๊ธฐ ๋๋ฌธ์ ๋์ ํด์ erase์ insert๋ฅผ ์ฌ์ฉ !
std::string line;
while(std::getline(ifs_src, line, '\0')) {
size_t pos = 0;
while ((pos = line.find(s1, pos)) != std::string::npos) {
line.erase(pos, s1.length());
line.insert(pos, s2);
pos += s2.length();
}
ofs_dst << line;
}
ifs_src.close();
ofs_dst.close();
return 0;
}
ex05
ํจ์ ํฌ์ธํฐ ์ฌ์ฉํ๊ธฐ
int (*fp1)();
int (*fp2)(int);
int (*fp3)(int, int);
bool (*fp4)();
void (*fp5)();
๋ฐํ๊ฐ (*๋ณ์์ด๋ฆ)(์ธ์๊ฐ);
๋ฐํ๊ฐ (*๋ณ์์ด๋ฆ[n])(์ธ์๊ฐ); //๋ฐฐ์ด๋ก ๋ง๋ค๋