如何创建并正确访问指向std::vector的指针构成的std::vector?
Hey there, let's break down why your code is failing and how to fix it right away!
The Root Problem
Your vecP is a std::vector<std::vector<size_t>*>—meaning each element inside it is a pointer to a std::vector<size_t>, not an actual vector object. When you try to do vecP[1].resize(6) or vecP[1][3] =7, you're using the . operator (for object members) on a pointer, which is invalid in C++.
Correct Ways to Access the Vector
You have two straightforward options to fix this:
Option 1: Use the -> Operator (Pointer Member Access)
Since vecP[1] is a pointer, use -> to call member functions or access elements:
// Resize the second vector (index 1) to 6 elements vecP[1]->resize(6); // Set the 4th element (index 3) to 7 (with bounds checking) vecP[1]->at(3) = 7; // Or use operator[] directly (no bounds checking): // vecP[1]->operator[](3) = 7;
Option 2: Dereference the Pointer First
You can use * to convert the pointer into a reference to the actual vector object, then use the . operator as usual:
// Dereference the pointer, then call resize (*vecP[1]).resize(6); // Dereference and access the element (*vecP[1])[3] = 7;
Note: The parentheses around *vecP[1] are critical here—operator precedence means vecP[1][3] would try to index the pointer itself (which is wrong), so we need to dereference first.
Bonus: A Safer Alternative (Avoid Pointers If Possible)
If you don't need dynamic memory allocation for these vectors, consider using a std::vector<std::vector<size_t>> instead. This eliminates pointer-related headaches and reduces risks like dangling pointers or memory leaks:
std::vector<size_t> vec1, vec2, vec3; std::vector<std::vector<size_t>> vecP = {vec1, vec2, vec3}; // Now you can use . directly: vecP[1].resize(6); vecP[1][3] = 7;
If you need to modify the original vectors through vecP (instead of working with copies), use a vector of references via std::reference_wrapper:
#include <functional> // Required for std::reference_wrapper std::vector<size_t> vec1, vec2, vec3; std::vector<std::reference_wrapper<std::vector<size_t>>> vecP = {vec1, vec2, vec3}; // Access and modify the original vectors: vecP[1].get().resize(6); vecP[1].get()[3] = 7;
内容的提问来源于stack exchange,提问作者Matthew

