I found out the nice tool provided by std::reference_wrapper, but this behaviour sounds weird to me.
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <vector>
#include <numeric>
int main()
{
std::vector<int> vectorA(10);
std::vector<std::reference_wrapper<int>> vec;
std::iota(vectorA.begin(),vectorA.end(),0);
for(auto i: vectorA){
std::cout << "In vectorA: "<< i << " ";
}
std::cout << "\n";
for(unsigned i=0; i< vectorA.size(); i++){
vec.push_back(std::ref(vectorA[i]));
}
for(auto i: vec){
std::cout << "In vec: "<< i << " ";
}
std::cout << "\n";
vectorA.erase(vectorA.begin()+9);
for(auto i: vectorA){
std::cout << "In vectorA: "<< i << " ";
}
std::cout << "\n";
for(auto i: vec){
std::cout << "In vec: "<< i << " ";
}
std::cout << "\n";
}
Why erasing an element referenced in vec (vectorA[9]) does not affect the size of vector vec? Furthermore, why does the vec[9] still be accessible?