리스트와 안전한 갱신
Coddy의 C++ 개발자를 위한 C# 코스 레슨. 48개 중 16번째.
C++ 벡터는 C# List<T>처럼 크기가 늘어나지만, 벡터를 대입하면 일반적으로 요소가 복사되는 반면 C# 리스트를 대입하면 참조가 공유됩니다. 독립적인 외부 컬렉션을 만들려면 new List<int>(values)를 사용하세요. 용량 증가 방식과 반복자/참조 무효화 규칙도 다릅니다.
List<T>는 배열과 달리 크기를 조정할 수 있습니다. Count는 요소의 개수를 반환하고, Add는 값을 추가합니다. 다른 리스트로 새 List<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() {
vector<int> values{2};
values.push_back(5);
cout << values.size() << "\n";
}
Main 내부의 C# 문장
var values = new List<int> { 2 };
values.Add(5);
Console.WriteLine(values.Count);이 내용은 핵심을 짚어 설명하는 발췌문입니다. 과제 파일에는 실행 가능한 전체 래퍼 코드가 포함되어 있으며, 위 코드 조각은 관련 선언과 문장을 보여 줍니다.
참고 출력:
2C# 출력:
2챌린지
쉬움정수 목록이 있는 줄과 추가 정수가 있는 줄을 읽으세요. 추가 정수를 끝에 붙인 새 목록을 반환하세요. 전달된 목록은 수정하지 마세요. 드라이버는 values: 뒤에 쉼표로 구분된 값을 출력합니다.
잠금 해제된 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 = new List<int>(Ints(input[0])); string before0=Snapshot(a0);
var a1 = I(input[1]); string before1=Snapshot(a1);
var result = Exercise.Solve(a0,a1);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
Console.WriteLine("values:" + string.Join(",", result));
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C++ 개발자를 위한 C#의 모든 레슨
1여기서 시작하기
첫 C# 프로그램 실행하기직접 연습해 보세요: 온라인 C# 컴파일러