크기가 커지는 벡터
Coddy의 Go 개발자를 위한 C++ 코스 레슨. 48개 중 13번째.
Go 슬라이스는 백킹 배열을 공유할 수 있는 디스크립터입니다. C++ 벡터는 버퍼를 직접 소유하며, 복사하면 요소가 복제됩니다. C++ 벡터는 연속된 크기 조정 가능 버퍼를 소유합니다. 재할당이 발생하면 해당 요소를 가리키는 포인터, 반복자, 참조가 무효화됩니다.
Go
package main
import ("fmt")
func main(){
a:=[]int{8};a=append(a,3);a=a[:len(a)-1];fmt.Println(len(a),a[0])
}
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::vector<int> a{8};a.push_back(3);a.pop_back();std::cout<<a.size()<<" "<<a.front()<<"\n";
}
각 프로그램을 독립적으로 추적해 보세요. 이 예제는 과제와 다른 연산이나 데이터를 사용해 개념을 보여 줍니다. 소스와 대상의 출력이 같다고 가정하지 않습니다.
챌린지
쉬움입력: 정수. 입력된 각 값이 같은 순서로 두 번씩 포함된 새 벡터를 반환하세요. 출력이 비어 있으면 empty를 출력합니다.
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::vector<int> v;int n;while(in>>n)v.push_back(n);auto out=duplicate(v);if(out.empty())std::cout<<"empty";for(size_t i=0;i<out.size();++i){if(i)std::cout<<" ";std::cout<<out[i];}std::cout<<"\n";
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Go 개발자를 위한 C++의 모든 레슨
직접 연습해 보세요: 온라인 C++ 컴파일러