如何存储指向std::vector<std::vector<int>>元素的指针向量?
正确的指针类型是
std::vector<int>* 嘿,这个问题其实很好理清,咱们来掰扯清楚:
首先,你得先明确 test_vofv 里每个元素的类型——test_vofv 是 std::vector<std::vector<int>>,所以它的每个元素(比如 test_vofv[0]、test_vofv[1])都是 std::vector<int> 类型的对象。那指向这类对象的指针,自然就是 std::vector<int>* 啦。
你之前用的 std::vector<std::vector<int>>* 是指向整个外层vector的指针(比如 &test_vofv 就是这个类型),和你要存储的「外层vector里的子vector的指针」完全不是一回事,所以类型不匹配是必然的。
给你写个简单的示例代码,一看就懂:
#include <vector> int main() { // 初始化外层vector std::vector<std::vector<int>> test_vofv = {{1,2,3}, {4,5,6}, {7,8,9}}; // 定义正确的指针向量类型 std::vector<std::vector<int>*> vector_of_pointers; // 遍历外层vector,把每个子vector的地址存入指针向量 for (auto& sub_vec : test_vofv) { vector_of_pointers.push_back(&sub_vec); } // 验证:通过指针访问子vector的元素 for (const auto ptr : vector_of_pointers) { for (const int num : *ptr) { // 这里可以打印或处理num,比如 std::cout << num << " "; } } return 0; }
另外补充个小建议:如果担心裸指针的安全性,也可以考虑用 std::reference_wrapper<std::vector<int>> 来存储引用,对应的向量类型就是 std::vector<std::reference_wrapper<std::vector<int>>>,用法和指针类似但更安全,不过这属于拓展选项啦,你可以根据需求选择。
内容的提问来源于stack exchange,提问作者oracle3001
相关产品推荐
相关产品推荐

