我发现了 std::reference_wrapper 提供的好工具,但这种行为对我来说听起来很奇怪。
#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";
}
为什么擦除vec ( vectorA[9] ) 中引用的元素不会影响向量vec的大小?此外,为什么vec[9]仍然可以访问?