안녕하세요 저는 벡터가 있습니다.
vector<int> myCuteVector {1,2,3,4};
이제 하위 벡터 요소를 수정 한 후 myCuteVector의 요소도 변경되는 방식으로 myCuteVector의 첫 번째 요소 2 개를 포함하는 방식으로 하위 벡터를 만들고 싶습니다.
의사 코드 :
vector<int> myCuteVector {1,2,3,4};
vector<int> myCuteSubVector = myCuteVector[0:2];
myCuteSubVector[0] = 5;
printf("%d", myCuteVector[0]) //would print also 5;
달성 할 수 있습니까?
이 작업은 std::reference_wrapper
. 다음과 같이 표시됩니다.
int main()
{
std::vector<int> myCuteVector {1,2,3,4};
std::vector<std::reference_wrapper<int>> myCuteSubVector{myCuteVector.begin(), myCuteVector.begin() + 2};
myCuteSubVector[0].get() = 5; // use get() to get a reference
printf("%d", myCuteVector[0]); //will print 5;
}
또는 다음과 같이 반복자를 직접 사용할 수 있습니다.
int main()
{
std::vector<int> myCuteVector {1,2,3,4};
std::vector<std::vector<int>::iterator> myCuteSubVector{myCuteVector.begin(), myCuteVector.begin() + 1};
// it is important to note that in the constructor above we are building a list of
// iterators, not using the range constructor like the first example
*myCuteSubVector[0] = 5; // use * to get a reference
printf("%d", myCuteVector[0]); //will print 5;
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다