배열과 문자열
배열
인덱스와 그 인덱스에 대응하는 같은 종류의 데이터들로 이루어진 자료구조
가장 기초적인 자료구조로 대부분의 프로그래밍 언어에서 사용할 수 있음
고급 프로그래밍 언어들은 다차원 배열을 지원함
배열은 크게 정적 배열과 동적 배열이 있음
배열의 원소
일반적으로 배열에는 데이터들이 순차적으로 저장됨
데이터의 번호가 배열의 시작점부터 데이터가 저장되어 있는 상대적인 위치
배열의 이름과 인덱스를 이용하여 특정 위치의 원소에 접근할 수 있음
정적배열
정적배열
크기가 고정되어 있는 배열
배열에 저장할 수 있는 데이터의 개수가 고정되어 있음
장점
한번 할당하면, 메모리를 추가적으로 할당하거나 해제하지 않아도 됨
특정 위치의 데이터에 접근하는 속도가 빠름
단점
크기가 고정되어 있기 때문에 필요에 따라 조절할 수 없음
일반적으로 스택 영역에 할당 되기 때문에 최대 크기가 제약됨
동적배열
동적배열
장점
단점
필요에 따라 메모릴를 추가적으로 할당하기 때문에, 부가적인 연산이 추가됨
문자열
문자열
문자의 순차 수열을 나타내는 자료구조
일반적으로, 문자 인코딩과 관련된 문자를 대표하는 일련의 자료값을 저장함
Binary String
Null String
문자열 리터럴
C++의 배열
array 컨테이너
#include <array>
template <typename T, std::size_t N> class array;
설명
c++ STL에 포함되어 있는 정적 배열을 표현하는 컨테이너
C++ 11에 추가됨
인자
선언 및 초기화 예시
std::array<int, 5> arr; // 1차원 정수형 배열 선언
std::array<int, 5> arr = {1,2,3,4,5}; // 각 원소 초기화
std::array<int, 5> arr = {0}; // 모든 배열의 원소를 0으로 초기화
std::array<int, 5> arr = {1,2}; // 지정 원소 이외의 모든 원소 0으로 초기화
std::array<std::array<int,5>,5> arr = {0}; //2차원 정수형 배열 선언
멤버함수(iterator)
iteator begin() noexcept;
배열의 첫번째 원소를 가리키는 반복자를 반환함
iterator end() noexcept;
배열의 마지막 원소를 가리키는 반복자를 반환함
reverse_iterator rbegin() noexcept;
배열을 역으로 했을 때, 그 첫번째 원소를 가리키는 역방향 반복자를 반환
reverse_iterator rend() noexcept;
배열을 역으로 했을 때, 그 마지막 원소를 가리키는 역방향 반복자를 반환
멤버함수(capacity)
consexpr size_type size() noexcept;
consexpr bool empty() noexcept;
멤버함수(element access)
reference operator[](size_type n);
reference operator at(size_type n);
reference front();
reference back();
value_type* data() noexcept;
멤버함수 (modifiers)
void fill(const value_type& val);
void swap(array& arr) noexcept;
array 컨테이너 예시
#include <array>
#include <dirent.h>
#include <fcntl.h>
#include <iostream>
#include <pwd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
using namespace std;
int main(int argc, char const *argv[]) {
array<int, 8> arr1;
array<int, 8> arr2 = {0};
array<int, 8> arr3 = {1, 2, 3, 4};
array<int, 8> arr4 = {1, 2, 3, 4, 5, 6, 7, 8};
cout << "elements of arr1 : ";
array<int, 8>::iterator iter;
for (iter = arr1.begin(); iter != arr1.end(); iter++) {
cout << *iter << " ";
}
cout << endl;
cout << "elements of arr2 : ";
for (size_t i = 0; i < arr2.size(); i++) {
cout << arr2[i] << " ";
}
cout << endl;
cout << "elements of arr3 : ";
for (size_t i; i < arr3.size(); i++) {
cout << arr3.at(i) << " ";
}
cout << endl;
cout << "elements of arr4 : ";
array<int, 8>::reverse_iterator riter;
for (riter = arr4.rbegin(); riter != arr4.rend(); riter++) {
cout << *riter << " ";
}
cout << endl;
return 0;
}
#include <array>
#include <dirent.h>
#include <fcntl.h>
#include <iostream>
#include <pwd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
using namespace std;
int main(int argc, char const *argv[]) {
array<array<int, 8>, 4> arr = {0};
array<array<int, 8>, 4>::iterator row;
array<int, 8>::iterator col;
cout << "elements of arr : \\n";
for (row = arr.begin(); row != arr.end(); row++) {
for (col = (*row).begin(); col != (*row).end(); col++) {
cout << *col << " ";
}
cout << endl;
}
cout << endl;
int i = 0;
for (row = arr.begin(); row != arr.end(); row++) {
(*row).fill(i++);
}
cout << "value of arr[0][2]: ";
cout << (arr.front())[2] << endl;
cout << "value of arr[1][3]: ";
cout << (arr.at(1)).at(3) << endl;
cout << "value of arr[2][2]: ";
cout << arr[2][2] << endl;
return 0;
}
vector 컨데이너
#include <vector>
template <class T, class Alloc = allocator<T>> class vector;
설명
C++ STL에 포함되어 있는 동적 배열을 표현하는 컨테이너
인자
T : 데이터의 자료형
Alloc : 할당자의 자료형
선언 및 초기화 예시
std::vector<int> v; //1차원 정수형 동적 배열 선언
std::vector<int> v(5); //기본 크기가 5이고, 0으로 초기화된 동적 배열 선언
std::vector<int> v(5,2); // //기본 크기가 5이고, 2로 초기화된 동적 배열 선언
std::vector<int> v2(v1); :v1과 동일한 동적 배열 선언
std::vector<std::vector<int>> v;// 2차원 정수형 동적 배열 선언
멤버함수(iterator)
iteator begin() noexcept;
배열의 첫번째 원소를 가리키는 반복자를 반환함
iterator end() noexcept;
배열의 마지막 원소를 가리키는 반복자를 반환함
reverse_iterator rbegin() noexcept;
배열을 역으로 했을 때, 그 첫번째 원소를 가리키는 역방향 반복자를 반환
reverse_iterator rend() noexcept;
배열을 역으로 했을 때, 그 마지막 원소를 가리키는 역방향 반복자를 반환
멤버함수(capacity)
void resize(size_type n);
배열의 크기를 n으로 변경함
크기가 증가하는 경우에 추가된 원소를 0으로 초기화
크기가 감소하는 경우에 기존의 원소는 유지
void shrink_to_fit();
size_type size() const noexcept;
size_type capasity() const noexcept;
bool empty() noexcept const;
멤버함수(element access)
reference operator[](size_type n);
reference operator at(size_type n);
reference front();
reference back();
value_type* data() noexcept;
멤버함수 (modifiers)
void assign(size_type n, const value_type& val);
void push_back(const value_type& val);
void pop_back();
iterator insert(const_iterator position, const value_type& val);
배열의 지정한 위치에 val를 추가하고, 그 위치를 가리키는 반복자를 반환
iterator erase(const_iterator position);
배열의 지정한 위치의 원소를 삭제하고, 그 위치를 가리키는 반복자를 반환
void clear() noexcept;
void swap(vector& v);
vector 컨테이너 예시
#include <array>
#include <dirent.h>
#include <fcntl.h>
#include <iostream>
#include <pwd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <vector>
using namespace std;
int main(int argc, char const *argv[]) {
vector<int> v(3);
vector<int>::iterator it;
cout << "size of v: " << v.size() << endl;
cout << "capacity of v: " << v.capacity() << endl;
cout << "elements of v : \\n";
for (int i = 0; i < v.size(); ++i) {
cout << v[i] << " ";
}
cout << endl << endl;
for (int i = 0; i < v.size(); ++i) {
v[i] = i + 1;
}
for (int i = 10; i < 15; ++i) {
v.push_back(i);
}
cout << "--- After push_back ---" << endl;
cout << "size of v: " << v.size() << endl;
cout << "capacity of v: " << v.capacity() << endl;
cout << "elements of v: ";
for (it = v.begin(); it != v.end(); ++it) {
cout << *it << " ";
}
cout << endl << endl;
v.pop_back();
v.pop_back();
cout << "--- After pop_back ---" << endl;
cout << "size of v: " << v.size() << endl;
cout << "capacity of v: " << v.capacity() << endl;
cout << "elements of v: ";
for (int i = 0; i < v.size(); ++i) {
cout << v[i] << " ";
}
cout << endl;
return 0;
}
C++의 문자열
string 컨테이너
#include <string>
typedef std::basic_string<char> string;
설명
c++ STL에 포함되어 있는 문자열을 표현하는 컨테이너
인자
선언 및 초기화
std::string str; // 문자열 선언
std string str = "Hello!"; // 문자열 초기화
멤버함수(iterator)
iteator begin() noexcept;
문자열의 첫번째 원소를 가리키는 반복자를 반환함
iterator end() noexcept;
문자열의 마지막 원소를 가리키는 반복자를 반환함
reverse_iterator rbegin() noexcept;
문자열을 역으로 했을 때, 그 첫번째 원소를 가리키는 역방향 반복자를 반환
reverse_iterator rend() noexcept;
문자열을 역으로 했을 때, 그 마지막 원소를 가리키는 역방향 반복자를 반환
멤버함수(capacity)
void resize(size_type n);
문자열의 크기를 n으로 변경함
크기가 증가하는 경우에 추가된 원소를 \0으로 초기화
크기가 감소하는 경우에 기존의 원소는 유지
void shrink_to_fit();
size_type size() const noexcept;
size_type length() const noexcept;
size_type capacity() const noexcept;
void clear() noexcept;
bool empty() noexcept const;
멤버함수(element access)
reference operator[](size_type n);
reference operator at(size_type n);
reference front();
reference back();
멤버함수 (modifiers)
string& assign(const string& str);
문자열을 str로 대체하고, 그 문자열을 반환
void push_back(char c);
void pop_back();
string& operator+=(const string& str);
문자열의 뒤에 str을 추가하고, 그 문자열을 반환
string& append(const string& str);
문자열의 뒤에 str을 추가하고, 그 문자열을 반환
string& replace(std::size_t pos, std::size_t len, const string& str);
배열의 지정한 위치(pos)부터 len만큼의 문자를 str로 대체하고, 그 문자열을 반환
void swap(string &str);
string& insert(std::size_t pos, const string& str);
문자열의 지정한 위치(pos)에 str을 추가하고, 그 문자열을 반환함.
string& erase(std::size_t pos, std::size_t len);
문자열의 지정한 위치(pos)에서 len만큼 문자를 삭제하고, 그 문자열을 반환함.
멤버 함수 (Operations) (cont`d)
const char* c_str() noexcept;
문자열을 C 스타일의 char형 배열로 변환하여 반환
const char* data() const noexcept;
std::size_t copy(char* str, std::size_t len, std::size_t index = 0) const;
문자열에 지정한 위치(index)에서 len만큼 문자를 C 스타일의 char형 배열을 복사하고, 복사된 크기를 반환
std::size_t find(const string& str, std::size_t pos) const;
문자열에서 지정한 위치(index) 이후에 문자열 str과 일치하는 문자열의 시작 위치를 반환
int compare(const string& str) const;
문자열과 문자열 str을 비교하고, 그 결과를 반환
string substr(std::size_t pos, std::size_t len = pos);
문자열의 지정한 위치(pos)에서 len만큼의 일부 문자열을 반환
string 컨테이너 예시
#include <array>
#include <dirent.h>
#include <fcntl.h>
#include <iostream>
#include <pwd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <vector>
using namespace std;
int main(int argc, char const *argv[]) {
string str1 = "Hello World!";
cout << "str1: " << str1 << endl;
string::reverse_iterator rit;
cout << "str1 (reverse): ";
for (rit = str1.rbegin(); rit != str1.rend(); ++rit) {
cout << *rit;
}
cout << endl << endl;
string str2 = "Bonjour!";
cout << "str2: " << str2 << endl << endl;
str1.swap(str2);
cout << "--- After swap ---" << endl;
cout << "str1: " << str1 << endl;
cout << "str2: " << str2 << endl;
return 0;
}