gpt4 book ai didi

c++ - 指向 vector 中元素的指针

转载 作者:行者123 更新时间:2023-11-28 07:31:41 24 4
gpt4 key购买 nike

我对 C++ 还很陌生,已经阅读了一些关于在 vector 中存储对象指针或对象本身的主题。我决定将对象存储在 vector 中,因为我不会在运行时 push_back 很多对象,vector 只创建一次并像这样离开。

我现在的问题是,我有另一个对象获取一个 vector 作为参数并在传递的 vector 中搜索某个对象。如果它找到这个对象,它存储一个指向它的指针,如果没有,变量设置为 NULL

尽管我没有push_back 任何项目,但指针似乎指向其他函数中的错误位置。在 vector 中搜索元素的对象有一个公共(public)函数,在该函数中应返回指针。如果我在每次函数调用时都搜索对象,那将非常慢,所以这不应该是一个选项。还有其他解决方案还是我必须切换到指针 vector ?

一些代码片段:

搜索 vector 对象的构造函数:

MySearch::MySearch(QVector<Obj> objVector)
:objVector(objVector) {
found = NULL
foreach(Obj o, this->objVector) {
if(..found..) {
found = &o;

break;
}
}
}

吸气函数:

Obj* MySearch::getObject() {
return found;
}

最佳答案

问题是因为变量 o 是局部变量,一旦循环结束就会超出范围。如果您使用 vector 元素的地址而不是 o,它会起作用。

#include <iostream>
#include <vector>
#include <string>

using namespace std;

class MySearch
{
public:
MySearch(const vector<string> &items)
: items_(items)
{
// Skipping validation
found_ = &(items_[5]);
}

string *getObject() {return found_;}

private:
vector<string> items_;
string *found_;
};

int main()
{
string str = "test#";
vector<string> aux;
for (int i = 0; i < 10; ++i)
aux.push_back(str + (char)('0' + i)); // test#0 ... test#9

MySearch ms(aux);
cout << *(ms.getObject()) << endl; // test#5

return 0;
}

关于c++ - 指向 vector 中元素的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17573915/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com