访问{vector of vector class}的{vector of vector}

时间:2016-12-23 05:26:23

标签: c++ vector member friend

我想创建一个由另一个类(Human)的向量组成的类(Army)。当试图通过陆军访问人类时,我遇到了分段错误。

以下代码简化为必要:

#include <iostream>
#include <vector>

using namespace std;

class Human {
    private:
         vector <int> hair;
    public:
        //The size of the reserved entries is arbitrary.
        Human () {hair.reserve(12);}
        friend class Army;
        int get_hair(int a) {return hair[a];}

};
class Army {
    private:
        vector <Human> armyVec;
    public:
        //The size of the reserved entries is arbitrary.
        Army () {armyVec.reserve(12);}
        Human get_Human(int a) {return armyVec[a];}
};

int main()
{
    Human Viktor;
    Army Sparta;
    cout << Viktor.get_hair(1) << endl; //OK
    Viktor = Sparta.get_Human(2);
    cout << Viktor.get_hair(1) << endl; //OK
    //Now I want to access it directly:
  cout << Sparta.get_Human(2).get_hair(1) << endl;    //Segfault !!!
    cout << "Done" << endl;
    return 0;
}

输出

0
0
Segmentation fault

它适用于&#34; hair&#34;不是矢量,而是例如整数(相应地改变)。怎么能解决这个问题?

2 个答案:

答案 0 :(得分:0)

reserve仅保留容量(也称为内存)以容纳多个元素。没有元素添加到vector。您可以使用resize添加元素。

这个小程序显示了reservecapacityresizesize之间的区别。

#include <iostream>
#include <vector>

int main() {
    std::vector<int> a;
    a.reserve(10);
    std::cout << "Vector capacity after reserve: " << a.capacity() << std::endl;
    std::cout << "Vector size after reserve: " << a.size() << std::endl;
    a.resize(5);
    std::cout << "Vector capacity after resize: " << a.capacity() << std::endl;
    std::cout << "Vector size after resize: " << a.size() << std::endl;
    return 0;
}

输出:

Vector capacity after reserve: 10
Vector size after reserve: 0
Vector capacity after resize: 10
Vector size after resize: 5

当您知道随时间推移的向量将增长到一定大小并且您希望在增长时避免多个内存分配/副本时,可以使用reserve。换句话说 - 预先保留容量可以提高性能。

答案 1 :(得分:0)

它适用于&#34; hair&#34;不是矢量,而是例如整数(相应地改变)。怎么能解决这个问题?

当我们使用&#34; int hair&#34;只有当我们使用&#34; 静态 int hair&#34;时才代替Vector。尽管人类对象没有在陆军中初始化,但是&#34; static int&#34;这个值总是在课堂上可用(严格输入)。