Hi, I'm having a problem with vectors.

I have

vector<int> ds;

in a header file.

When I do

ds.push_back(0);

in the cpp file, I get a seg fault.

Does anyone know what the problem is? Thanks

Recommended Answers

All 5 Replies

vector<int> ds; does not go in a header file but in the *.cpp file, unless of course it is a member of some much larger c++ class which you didn't post.

vector<int> ds;
ds.push_back(0);

If the above still does not work then you are doing something wrong some other place, possible trashing memory. Post the whole probram so we can take a look.

Yes I'm implementing a class, and in the header I'm declaring that vector. Apparently the default constructor instantiates and allocates space for the vector, so if I call a function in the cpp file, push_back() shouldn't seg fault since the vector is initialized as an empty vector by default.

Here's the code by the way:

#ifndef _DSETS_H_
#define _DSETS_H_

#include <vector>
using namespace std;

class DisjointSets
{

   public:
      void addelements(int n);
      int find(int a);
      void setunion(int a, int b);
      vector<int> ds;

};

#endif

That's the header, and this is what I have in the cpp so far:

#include "dsets.h"

//Creates n root nodes
void DisjointSets::addelements(int n)
{
   ds.resize(0);
   for(int i = 0; i < n; i++)
   {

      ds.push_back(-1);

   }

}

This worked ok for me

#include <vector>
#include <iostream>
using namespace std;

class DisjointSets
{

   public:
      void addelements(int n);
      int find(int a);
      void setunion(int a, int b);
      vector<int> ds;

};

//Creates n root nodes
void DisjointSets::addelements(int n)
{
   ds.resize(0);
   for(int i = 0; i < n; i++)
   {

      ds.push_back(-1);

   }

}

int _tmain(int argc, _TCHAR* argv[])
{
    DisjointSets s;
    s.addelements(5);
	return 0;
}

That... is odd... I just switched computers and the seg fault stopped happening. I've wasted several hours trying to fix this, lol. Well, thanks for the help anyways. =)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.