回答你的问题:
如何使用指向向量指针的指针?
让我们看一个基本的例子......
#include <iostream>
#include <string>
#include <vector>
int main() {
// has to be initialized since it is a pointer.
// However, this will compile but will fail at runtime.
std::vector<std::string*>* pvWords = nullptr;
std::string word1 = "Hello";
std::string word2 = "World";
// Here you need the `operator->()` from the vector
// and since it will store pointers to strings,
// you can just pass in the address of...
pvWords->push_back( &word1 );
pvWords->push_back( &word2 );
for ( auto& s : *pvWords ) // here we need to dereference pvWords
std::cout << *s << ' '; // and here we need to dereference s
std::cout << '\n';
return 0;
}
-预期输出-
Hello World
但是,这将编译但在运行时会失败,并导致 Visual Studio 中出现访问冲突错误。这会失败,因为一旦strings 指针超出范围,它们就会被销毁,并且vector 或vector* 试图引用的内存现在无效。您也许可以通过使用动态内存来解决这个问题,但即便如此,它只会使代码更复杂、更难管理,并可能导致更多看不见的错误。
如果我们将上述修复为以下 sn-p,则代码将起作用:
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string*>* pvWords = new std::vector<std::string*>;
std::string word1 = "Hello";
std::string word2 = "World";
pvWords->push_back( &word1 );
pvWords->push_back( &word2 );
for ( auto& s : (*pvWords) )
std::cout << (*s) << ' ';
std::cout << '\n';
delete pvWords; // don't forget to cleanup dynamic memory.
return 0;
}
这将与动态内存一起使用,并将提供以下输出:
Hello World
但是,为了避免所有这些错误和代码的复杂性,只需不要使用任何指针,尤其是在使用 std::string 时。
第一个解决方案可以工作,但如果任何指针在使用前变为无效,并且很难避免运行时错误,则可能会导致问题。
在这种情况下不需要使用指针。您没有在需要继承或多态性的地方存储基类的派生类。
由于std::vector 和std::string 的行为,只需这样做:
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> vWords;
vWords.push_back( "Hello" );
vWords.push_back( "World" );
for ( auto& s : vWords )
std::cout << s << ' ';
std::cout << '\n';
return 0;
}
由于std::vector 和std::string 管理它们自己的内存,因此将产生相同的预期结果,无需任何动态内存分配和内存清理、没有任何错误和任何代码复杂性。
-输出-
Hello World
此版本的代码更易于阅读、更易于使用和调试,更易于其他人使用,并且完全符合您的预期。此解决方案非常简单、快速且高效,没有任何麻烦。