#include<iostream>#include<memory>intmain(){// Create dynamic array managed by unique_ptrstd::unique_ptr<int[]>arr=std::make_unique<int[]>(5);for(inti=0;i<5;++i)arr[i]=i*10;for(inti=0;i<5;++i)std::cout<<arr[i]<<" ";std::cout<<std::endl;// No need to delete[] manually β itβs automatic!}
#include<iostream>#include<vector>intmain(){std::vector<int>nums={10,20,30};nums.push_back(40);// Add element at the endnums.push_back(50);nums.pop_back();// removes the last elementnums.erase(nums.begin());//removes to first elementnums.insert(nums.begin()+2,99);//insert new element beforestd::cout<<"Vector elements: ";for(intn:nums)std::cout<<n<<" ";std::cout<<"\nSize: "<<nums.size()<<std::endl;std::cout<<"\nSize: "<<nums.at(1)<<std::endl;}
std::list
std::list is a doubly linked list container in the C++ Standard Library.
Feature
std::list
std::vector
Underlying structure
Doubly linked list
Dynamic contiguous array
Memory layout
Elements scattered across heap
Elements stored contiguously
Random access (list[i])
β Not supported
β Supported (O(1))
Insert/erase in middle
β Fast (O(1))
β οΈ Slow (O(n), shifting required)
Iteration speed
β οΈ Slower (poor cache locality)
β Very fast (contiguous memory)
Reallocation
Never (nodes independent)
May reallocate as it grows
Sorting
Has built-in list.sort()
Must use std::sort()
When to use
Frequent insert/erase in middle
Frequent access or random indexing
std::deque
allows fast insertion and removal from both the front and the back.
#include<iostream>#include<deque>intmain(){constsize_tMAX_SIZE=5;std::deque<int>dq;for(inti=1;i<=10;++i){if(dq.size()==MAX_SIZE)dq.pop_front();// remove oldest when fulldq.push_back(i);// add new elementstd::cout<<"Deque: ";for(intx:dq)std::cout<<x<<" ";std::cout<<"\n";}}