-
vector <T> help
I cannot get the following code to compile:
Code:
include <vector>
#include <iostream>
using namespace std;
int WeirdProduct( const vector<float> & V1, const vector<float> & V2)
{
int product = 1, minsize;
if( V1.size() < V2.size())
minsize = V2.size();
for(int i=0; i < minsize; i++)
if( V2[i] < 0 )
product = product * i;
return product;
}
void main ()
{
const vector<float> V1(4);
const vector<float> V2;
float array[]={42.3,21.5,-3.1,-4.2,155.8,33.7,-1.9};
for(int i=0; i<=7; i++)
V2.push_back(array[i]);
WeirdProduct(V1,V2);
}
The problem is the V2.push_back(array[i])
line in void main. The error received when trying to compile is :
weird.cpp: In function `int main(...)':
weird.cpp:21: passing `const vector<float,allocator<float> >' as `this' argument of `voi
d vector<float,allocator<float> >::push_back(const float &)' discards qualifiers
Which I presume is an issue with data types of some sort. I am trying to insert the data from a c style array into a vector array via the for loop based upon the value of i, any help would be much appreciated.
Code tags added by Kermi3
-
ok 2 things:
1. In the furture please use Code Tags. They make your code MUCH easier to read and people will be much more likely to help you if you do. And they'll be happy about helping you ;)
For example:
Without code tags:
for(int i=0;i<5;i++)
{
cout << "No code tags are bad";
}
With Code Tags:
Code:
for(int i=0;i<5;i++)
{
cout << "This code is easy to read";
}
This is of course a basic example...more complicated code is even easier to read with code tags than without.
I'veadded code tags for you this time. They can be added by putting [code] at the beginning of your code and [/code] at the end. More information on code tags may be found at the link in my signature. I also suggest you take a look at the board guildlines if you have not done so already. Any further questions or ways I can help please feel free to PM me.
This is a common first post mistake, just remember to use [code] tags in the future and you'll get much more help.
2.
Don't use void main. Instead use int main(). Example:
Code:
int main()
{
cout<<"foo";
//...more code
//end of program
return 0;
}
I hope this helps,
Kermi3
-
My guess is that the error occurs because you are trying to push your floats onto a constant vector. Try taking out both of the const qualifiers for those two vector objects in your main function.
-
Hey, that did it, basically this is just a practice problem and I wanted to see the program actually work, my job was to basically just write the called function and implement it into main, however I could not figure out how to assign a list of values to a vector array. Is this possible by a different method than what I have used in the above example?