🌍 C++ Study/C++ 기초
C++ 벡터에 연속된 숫자 채우기 std::iota
맨텀
2024. 11. 15. 14:03
C#에서는 Enerable.Range
C#에서는 연속된 숫자를 채울 때 Enumerable.Range를 사용했다.
List<int> numbers = Enumerable.Range(1, 10).ToList();
C++에서는 std::iota
C++ 에서는 <numeric> 헤더에 있는 std::iota 를 사용하면된다.
template <class ForwardIterator, class T>
void iota(ForwardIterator first, ForwardIterator last, T value);
참고로 iota (이오타) 는 약어가 아니라 프로그래밍 언어인 APL을 뜻함.
https://stackoverflow.com/questions/9244879/what-does-iota-of-stdiota-stand-for
What does iota of std::iota stand for?
I'm assuming the "i" is increment and the "a" is assign, but I could not figure out or find the answer. Also, it looks very similar to the non-standard itoa which I think is confusing.
stackoverflow.com
인자로는 시작 포인터, 끝포인터, 시작 넘버를 입력해준다.
결과는 컨테이너에 +1씩 증가하게된다.
주의할 점은 컨테이너를 범위만큼 미리 늘려놔야 한다.
#include <string>
#include <vector>
#include <numeric>
using namespace std;
vector<int> solution(int start_num, int end_num) {
vector<int> answer(end_num - start_num + 1);
std::iota(answer.begin(), answer.end(), start_num);
return answer;
}
사실 성능적으로 큰 이점은 없는 듯하여 그냥 명시적으로 반복문으로 쓰는게 협업자에게도 편할 듯 하다.