I have a text file that has 9 columns. How do I access columns 7 and 8 and multiply these values together? My text file only consists of numbers. Both int and double types.
After line 30, myVector[6] and myVector[7] will contain columns 7 and 8 respectively. You can do the following:
1 2 3
double rslt;
rslt = myvector[6] * myVector[7];
However, this is true only after reading the first row. When you read the second row, you continue pushing values onto the vector. Therefore, columns 7 and 8 will be in myvector[15] and myVector[16].
You can accomodate this by keeping your own index and incrementing it by 9 for each row your read, or your can clear the vector at the bottom of the read loop which would assume that you don't have further need for the contents of the row after having processed it.
Edit: I missed that myVector was a vector of vectors of doubles.
double result;
result = myVector[6] * myVector[7];
cout << result << endl;
When I try this I get an error message:
error: no match for 'operator*' in 'myVector.std::vector<_Tp, _Alloc>::operator[]<std::vector<double>, std::allocator<std::vector<double> > >(6u) * myVector.std::vector<_Tp, _Alloc>::operator[]<std::vector<double>, std::allocator<std::vector<double> > >(7u)'|
myVector[6] will return you a vector of doubles (as far as i understand it).
similarly myVector[7] will do the same.
You're then asking your compiler to effectively multiply together two collections of doubles. you need to tell the compiler how this happens i.e. overload the multiplication operator.
#include <vector>
int main()
{
// our vector of vectors of doubles.
std::vector <std::vector<double>> myVector;
// create a vector of doubles and populate it with some data
std::vector<double> vec1;
for(int i=0;i<10;++i)
{
vec1.push_back(static_cast<double>(i));
}
// create another vector of doubles and populate it with some data
std::vector<double> vec2;
for(int j=10;j<20;++j)
{
vec2.push_back(static_cast<double>(j));
}
// we now have 2 vectors of doubles. Add these both to our
// vector of vectors of doubles.
myVector.push_back(vec1);
myVector.push_back(vec2);
// I've commented out as this makes no sense to the compiler
// as 'myVector[0]' will return me a vector, NOT a double.
//double silly = myVector[0];
// get me the 4th double from the first vector we put into our vector of vectors.
double result = (myVector[0])[4];
return 0;
}
Lines 36-37 should be unnecessary. product is only changed at line 22 (within the loop), therefore your test for highest should also be inside the loop. What happens when you eliminate lines 36-37?