고정 크기 배열
Coddy의 JavaScript 개발자를 위한 C++ 코스 레슨. 48개 중 12번째.
JavaScript 배열은 크기를 조정할 수 있는 객체입니다. 배열을 다른 변수에 할당하면 같은 배열을 공유하고, 끝을 벗어난 인덱스를 읽으면 undefined가 반환되며, at(-1)은 끝에서부터 셉니다. C++의 std::array<T,N>는 크기가 고정된 값 유형입니다. 크기가 자료형의 일부이므로 배열을 늘릴 수 없으며, 일반적인 복사로 요소가 복제됩니다. at은 인덱스를 확인하고 std::out_of_range를 던집니다. []는 확인하지 않으므로 범위를 벗어난 인덱스는 정의되지 않은 동작입니다.
JavaScript
const items = [4, 8];
const alias = items;
alias.push(12);
console.log(items.length, items.at(-1));
console.log(items[5]);
C++
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
int main(){
std::array<int,3> a{4,5,6};
auto b=a;
b[0]=9;
std::cout<<a.size()<<" "<<a[0]<<" "<<b.at(0)<<"\n";
}
각 프로그램을 독립적으로 추적해 보세요. 이 예제들은 과제와 다른 연산이나 데이터를 사용해 개념을 보여 줍니다. 소스 코드와 대상 코드의 출력이 일치한다고 가정하지 마세요.
챌린지
쉬움입력: 정수 3개입니다. 가장 큰 정수와 가장 작은 정수의 차이를 반환하세요.
exercise.hpp와 exercise.cpp에 선언된 API를 구현하세요. 두 파일 모두 편집할 수 있습니다. 공개 시그니처는 그대로 유지하세요. 잠긴 main.cpp는 표준 입력을 읽고 API를 직접 호출합니다. 명시된 경우 공개 API 동작도 별도로 확인합니다. API 내부에서 출력하지 말고 값을 반환하세요. 정수 입력값과 결과는 부호 있는 int 범위에 들어갑니다. 별도 명시가 없는 한 텍스트는 ASCII입니다.
직접 해보기
#include "exercise.hpp"
#include <iostream>
int main(){
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);std::array<int,3>a;in>>a[0]>>a[1]>>a[2];std::cout<<spread(a)<<"\n";
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
JavaScript 개발자를 위한 C++의 모든 레슨
직접 연습해 보세요: 온라인 C++ 컴파일러