迭代字符串向量作为类的元素

时间:2019-06-12 12:39:15

标签: c++ c++11

在这段代码中,我将sampleClass定义为包含std::vector<std::string>的类。当我尝试遍历向量并打印出其元素时,就会出现问题:

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

class sampleClass {
private:
    std::vector<std::string> vec;

public:
    std::vector<std::string> getVec() const
    {
        return vec;
    }
    void setVec(const std::vector<std::string>& vec_)
    {
        vec = vec_;
    }
};

int main()
{
    sampleClass sc;
    sc.setVec(std::vector<std::string>{ "hello" });

    std::cout << "pushed back element" << std::endl;

    for (std::vector<std::string>::const_iterator currentVecElem = sc.getVec().begin(); currentVecElem != sc.getVec().end(); ++currentVecElem) {
        std::cout << *currentVecElem << std::endl;
    }

    return 0;
}

编译时,代码确实输出pushed back element,然后在此之后遇到分段错误。我怎么了?

编辑:getVec()应该返回const std::vector<std::string>&,而不是std::vector<std::string>。后者导致吸气剂返回vec的全新副本,这意味着其begin()end()迭代器是不同的。 vec副本也会立即立即消失,使其无法使用。前者之所以起作用,是因为我们返回了对未被复制且存在于内存中的向量的引用(直到我们选择释放它)。

0 个答案:

没有答案