简体   繁体   中英

How to fix the error in C++ vector operation?

The f() function in the class MapSquare works properly.. When I add the other class MapTriple, it is not working. f() function in the MapSquare should find the square of the elements in the vector and in the MapTriple should multiply 3 to all elements.

MapGeneric is the base class which contains the function map() which is a recursive function to access the vector elements and the f() function is a pure virtual function.

MapSquare and MapTriple are two derived classes overrides the f() function to find the square of vector elements and to multiply 3 with all the vector elements.

MapSquare works properly... but when I add MapTriple, segmentation fault occures. Please help to solve this.

#include<vector>
#include<iostream>
#include<cstdlib>
#include<stdio.h>
#include<stdlib.h>
using namespace std;

class MapGeneric
{
   public:
        virtual int f(int){};
        vector<int> map(vector<int>, int);
};
class MapSquare:public MapGeneric
{
   public: int f(int);

};
class MapTriple:public MapGeneric
{
   public: int f(int);
};
class MapAbsolute:public MapGeneric
{
   public: int f(int);
};
vector<int> MapGeneric::map(vector<int> v, int index)
{

   if(index>=1)
   {
      v[index]=f(v[index]);
      return map(v,index-1);
   }
   return v;

}
int MapSquare::f(int x)
{
   return x*x;
}
int MapTriple::f(int x)
{
 return 3*x;
}
int MapAbsolute::f(int x)
{
  return abs(x);
}
int main()
{
   //mapping square
   MapSquare ob;
   vector<int> L,L1,L2;
   for (int i = 1; i <= 5; i++) 
      L.push_back(i);
   L1=ob.map(L,sizeof(L));
   cout<<"Square  = ";
   for ( vector<int>::iterator i = L1.begin(); i != L1.end(); ++i) 
      cout << *i<<" ";

   //mapping triple
   MapTriple t;

   L2=t.map(L,sizeof(L));
   cout<<endl<<"Triple  = ";
   for(vector<int>::iterator i=L2.begin();i!=L2.end();++i)
     cout<<*i<<" ";

   return 0;
 }

A number of problems here. It looks as though you think that C++ indices start at 1, rather than zero?

if(index>=1)
{
   v[index]=f(v[index]);
   return map(v,index-1);
}

To me that immediately looks wrong, surely you mean:

// use size_t for indices (which cannot be negative)
vector<int> MapGeneric::map(vector<int> v, size_t index)
{
  // make sure the index is valid!
  if(index < v.size())
  {
    v[index] = f(v[index]);
    return map(v, index - 1);
  }
  return v;
}

Secondly, the sizeof() operator does not do what you expect!! It returns the size of std::vector (which is usually 24bytes on 64 bit systems - basically 3 pointers). You should use the size() method to determine the length of the array.

// remember that indices are zero based, and not 1 based!
L1=ob.map(L, L.size() - 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM