c++ - 遍历 vector (段错误)

标签 c++ vector std fault

我想迭代器有问题,但我不明白为什么! 你能给我更多信息吗?

我有以下电影类:

public:
    vector<string> casting() const;

private:
    string _titol;
    short _year;
    vector<string> _alies;
    string _director;
    vector<string> _casting;

casting() 方法只返回 _casting vector

我调用了 main.cpp:

void Movies::actorMovies(string actor){
bool existeix = false;
std::map<titleyear,Movie>::iterator it = _pelis.begin();
std::vector<string>::iterator it2;

for(it; it!=_pelis.end(); it++){
    for(it2=it->second.casting().begin(); it2!=it->second.casting().end(); it2++){
        /*if((*it2).compare(actor)==0){
            cout<<"Titol: "<<it->first.t<<endl<<"Any: "<<it->first.y<<endl;
            existeix = true;
        }*/
    }


}
if(!existeix) 
    cout<<"NOT FOUND"<<endl;
}

当我想取消对 if 语句的注释时,就会出现段错误。 有人能看到这里发生了什么吗?

最佳答案

你的前提是错误的。 casting() 方法每次被调用时都会返回 _casting vector 的一个新拷贝。因此 it2 永远不会等于 it->second.casting().end(),因为它是指向完全不同容器的迭代器!

事实上,it2 在完整表达式的末尾立即失效,因为它是一个迭代器,进入一个立即死亡的临时容器。

如果 casting() 旨在提供实际 _casting vector 的 View ,它应该返回一个左值:

const std::vector<std::string> & casting() const { return _casting; }
//                            ^^^

关于c++ - 遍历 vector (段错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33990516/

相关文章:

c++ - 你如何做一个 for 循环作为 while 条件?

c++ - 为什么在比较中将常量放在变量之前?

c++ - 我如何正确地将 shared_pointers 添加到可能的派生类到 std::vector 中?

c++ - 用于写入文件的 stringstream 或 ostringstream?

c++ - 在 3 元素映射 C++ 中添加新项目并使用时间键搜索

c++ - 使用 HOGDescriptor 的问题

graphics - 将二次曲线转换为三次曲线

C++ 多线程优化

c++ - fstream 读取 MSR

c++ - 从内置类型到自定义类的转换