배열과 경계
Coddy의 C++ 개발자를 위한 C# 코스 레슨. 48개 중 13번째.
C++ std::array는 C# 배열처럼 크기가 고정되어 있지만, 크기가 C++ 템플릿 형식의 일부입니다. C# 배열의 Length는 런타임 속성이며, 인덱스로 접근할 때 범위를 확인합니다. C++의 operator[]는 일반적으로 범위를 확인하지 않으며, at은 범위를 확인하는 대안입니다.
C# 배열은 길이가 고정되어 있고 인덱스는 0부터 시작합니다. Length는 속성이며, 범위를 벗어난 인덱스 접근은 예외를 발생시킵니다. 양 끝에 접근하기 전에 배열이 비어 있는지 확인하세요. 요소가 int인 경우에도 배열은 참조 형식입니다.
C++ 참고 코드
#include <algorithm>
#include <array>
#include <cctype>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;
int main() {
array<int,2> values{4,6};
cout << values.size() << "\n";
}
Main 내부의 C# 문장
int[] values = { 4, 6 };
Console.WriteLine(values.Length);이 내용은 특정 부분을 집중적으로 설명하는 발췌문입니다. 과제 파일에는 실행 가능한 전체 래퍼가 포함되어 있으며, 위 코드 조각은 관련 선언과 문장만 보여 줍니다.
참고 출력:
2C# 출력:
2챌린지
쉬움쉼표로 구분된 정수 한 줄을 읽고, 빈 배열은 빈 줄로 나타냅니다. 첫 번째 값과 마지막 값을 더해 반환하세요. 요소가 하나뿐이면 그 값을 두 번 더합니다. 빈 배열은 0을 반환합니다.
잠금 해제된 C# 파일을 수정하세요. 화면에 표시된 잠금 상태의 Main.cs는 설명된 줄을 읽고, Exercise.Solve를 호출하며, 입력이 변경되지 않았는지 확인한 후 마지막에 줄바꿈을 하나 붙여 결과를 출력합니다. 선언된 API를 유지하세요. 두 번째 Main을 추가하거나 진단 출력을 출력하지 마세요.
직접 해보기
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = Ints(input[0]); string before0=Snapshot(a0);
var result = Exercise.Solve(a0);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C++ 개발자를 위한 C#의 모든 레슨
1여기서 시작하기
첫 C# 프로그램 실행하기직접 연습해 보세요: 온라인 C# 컴파일러