erase element from vector
Apr 15, 2014 at 10:45am UTC
hey guys can help me erase the first element in my two vectors i tried using vector.erase(vector.begin()) but my code is crushing.....any help would be highly appreciated thanx in advance
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
#include <iostream>
#include <vector>
#include<iomanip>
using namespace std;
void convertkW(vector<double >kW,vector<double >hp)
{
for (unsigned int i=0; i<9; i++) {
kW.push_back(0.05*i*i+0.15*i);
hp.push_back(kW.at(i)*1.341);
cout<<fixed<<setprecision(2)<<kW.at(i)<<" " <<hp.at(i)<<endl;
}
}
void converthp(vector<double >kW,vector<double >hp)
{
cout<<endl;
for (int j=0; j<9; j++) {
hp.push_back(1.1*j);
kW.push_back(hp.at(j)/1.341);
cout<<fixed<<setprecision(2)<<hp.at(j)<<" " <<kW.at(j)<<endl;
}
}
int main()
{
vector<double >kW;
vector<double >hp;
convertkW(kW,hp);
converthp(kW,hp);
return 0;
}
Apr 15, 2014 at 10:52am UTC
Where do you try to erase the first element?
Apr 15, 2014 at 11:22am UTC
BEFORE OUTPUTING THE RESULTS...DONT WANT THE FIRST ELEMENT TO APPEAR
Apr 15, 2014 at 11:50am UTC
Is your vector has atleast one element?
before calling 'erase', please check for non empty.
Try like this
if (!vector.empty())
vector.erase(vector.begin());
Apr 15, 2014 at 12:54pm UTC
please show the code where the problem occurs
Apr 15, 2014 at 1:30pm UTC
line 12 and 13 has the problem
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
#include <iostream>
#include <vector>
#include<iomanip>
using namespace std;
void convertkW(vector<double >kW,vector<double >hp)
{
for (unsigned int i=0; i<9; i++) {
kW.push_back(0.05*i*i+0.15*i);
hp.push_back(kW.at(i)*1.341);
kW.erase(kW.begin()+1);
hp.erase(hp.begin()+1);
cout<<fixed<<setprecision(2)<<kW.at(i)<<" " <<hp.at(i)<<endl;
}
}
void converthp(vector<double >kW,vector<double >hp)
{
cout<<endl;
for (int j=0; j<9; j++) {
hp.push_back(1.1*j);
kW.push_back(hp.at(j)/1.341);
cout<<fixed<<setprecision(2)<<hp.at(j)<<" " <<kW.at(j)<<endl;
}
}
int main()
{
vector<double >kW;
vector<double >hp;
convertkW(kW,hp);
converthp(kW,hp);
return 0;
}
Apr 15, 2014 at 1:40pm UTC
line 12/13 erase the second element not the first. Remove the +1. And do like NVTKrishna said: check for empty before erase
I'd say take lines 12/13 out of the for loop. This way you erase an element each time you add another.
Topic archived. No new replies allowed.