Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++ 벡터의 마지막 요소(액세스 및 업데이트)


이 기사에서는 C++에서 벡터의 마지막 요소에 액세스하고 업데이트하는 방법에 대해 설명합니다.

벡터 템플릿이란 무엇입니까?

벡터는 크기가 동적으로 변경되는 시퀀스 컨테이너입니다. 컨테이너는 동일한 유형의 데이터를 보유하는 객체입니다. 시퀀스 컨테이너는 엄격하게 선형 시퀀스로 요소를 저장합니다.

벡터 컨테이너는 연속된 메모리 위치에 요소를 저장하고 아래 첨자 연산자 []를 사용하여 모든 요소에 직접 액세스할 수 있습니다. 배열과 달리 벡터의 크기는 동적입니다. 벡터의 저장은 자동으로 처리됩니다.

벡터의 정의

Template <class T, class Alloc = allocator<T>> class vector;

벡터의 매개변수

이 함수는 다음 매개변수를 허용합니다. -

  • − 포함된 요소의 유형입니다.

  • 할당 − 할당자 개체의 유형입니다.

벡터의 마지막 요소에 어떻게 접근할 수 있습니까?

벡터의 마지막 요소에 액세스하려면 두 가지 방법을 사용할 수 있습니다.

예시

back() 함수 사용

#include <bits/stdc++.h>
using namespace std;
int main(){
   vector<int> vec = {11, 22, 33, 44, 55};
   cout<<"Elements in the vector before updating: ";
   for(auto i = vec.begin(); i!= vec.end(); ++i){
      cout << *i << " ";
   }
   // call back() for fetching last element
   cout<<"\nLast element in vector is: "<<vec.back();
   vec.back() = 66;
   cout<<"\nElements in the vector before updating: ";
   for(auto i = vec.begin(); i!= vec.end(); ++i){
      cout << *i << " ";
   }
   return 0;
}

출력

위 코드를 실행하면 다음 출력이 생성됩니다 -

Elements in the vector before updating: 11 22 33 44 55
Last element in vector is: 55
Elements in the vector before updating: 11 22 33 44 66

예시

size() 함수 사용

#include <bits/stdc++.h>
using namespace std;
int main(){
   vector<int> vec = {11, 22, 33, 44, 55};
   cout<<"Elements in the vector before updating: ";
   for(auto i = vec.begin(); i!= vec.end(); ++i){
      cout << *i << " ";
   }
   // call size() for fetching last element
   int last = vec.size();
   cout<<"\nLast element in vector is: "<<vec[last-1];
   vec[last-1] = 66;
   cout<<"\nElements in the vector before updating: ";
   for(auto i = vec.begin(); i!= vec.end(); ++i){
      cout << *i <<" ";
   }
   return 0;
}

출력

위 코드를 실행하면 다음 출력이 생성됩니다 -

Elements in the vector before updating: 11 22 33 44 55
Last element in vector is: 55
Elements in the vector before updating: 11 22 33 44 66