Reputation: 271
I am trying to iterate through my vector array, but I cannot seem to get it to work, my error is at the second for loop and the error message is the follow:
expected primary expression before 'double'
I have looked through on how to iterate a regular vector, but how do I iterator a vector array? I followed this structure:
#include <iostream>
#include <vector>
int main ()
{
std::vector<int> myvector;
for (int i=1; i<=5; i++) myvector.push_back(i);
std::cout << "myvector contains:";
for (std::vector<int>::iterator it = myvector.begin() ; it != myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
I can't seem to get my vector array version to work.
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main(int arc, char *argv[])
{
vector<double> vector[7];
double num[7];
ifstream infile("data.txt");
string temp;
for(int i = 0; i <= 6; i++)
{
infile >> temp;
cout << temp << ' ';
}
cout << endl;
while(infile >> num[0] >> num[1] >> num[2] >> num[3] >> num[4] >> num[5] >> num[6])
{
for(int i = 0; i <= 6; i++)
{
vector[i].push_back(num[i]);
}
}
cout << endl;
for(int i = 0; i <= 6; i++)
{
// error on this line
// not sure what is wrong before vector<double>:: iterator it = vector[i].begin()
for(vector<double>::iterator it = vector[i].begin(); it != vector[i].end(); ++it)
{
cout << ' ' << *it;
}
}
return 0;
}
Upvotes: 0
Views: 5677
Reputation: 283624
On this line of code
for(vector<double>::iterator it = vector[i].begin(); it != vector[i].end(); ++it)
vector
is not a type, it's a variable. Names in local scopes hide names in global scopes.
You could instead write
for(::std::vector<double>::iterator it = vector[i].begin(); it != vector[i].end(); ++it)
or
for(auto it = vector[i].begin(); it != vector[i].end(); ++it)
but a better solution is to not use the same name for multiple different things.
Upvotes: 2
Reputation: 32884
#include <iostream>
#include <fstream>
#include <vector>
using std::ifstream;
using std::vector;
using std::cout;
int main(int arc, char *argv[])
{
const size_t data_size = 7;
ifstream infile("data.txt");
vector<double> input;
double num;
while ((infile >> num) && (input.size() <= data_size))
{
input.push_back(num);
}
for (vector<double>::iterator it = input.begin(); it != input.end(); ++it)
{
cout << ' ' << *it;
}
return 0;
}
Use minimal variables and get the job one. Also don't name your variables after standard library functions, classes, structs, etc. and avoid using directives like using namespace std;
and prefer using declarations.
Upvotes: 1
Reputation: 129
You can simply traverse a vector of array like this
for (int i=0; i<myvector.size(); i++)
{
for (int j=0; j<myvector.size(); j++)
{
cout<<myvector[i][j]<<endl;
}
}
Upvotes: -1