-
vectors and C++11
What the heck I thought I could use the new for statement like this. In my book it says it works but it fails for me. What am I missing?
Code:
#include <iostream>
#include <vector>
#include <stdexcept>
#include <iomanip>
using namespace std;
void inputVector(const vector<int> &array)
{
for( int &item : items) //ERROR undeclared "items"
cin>>item;
}
void outputVector(vector<int> &array)
{
for(int item : items) //ERROR undeclared "items"
cout<< item <<" ";
cout << endl;
}
int main(int argc, const char * argv[])
{
vector<int> integers1(4);
vector<int> integer2(5);
cout<<"Enter some numbers"<<integers1.size() <<endl;
inputVector(integers1);
inputVector(integer2);
outputVector(integers1);
outputVector(integer2);
return 0;
}
-
Isn't the error message clear enough? There is no variable named "items" (there is only one named "array"). You have also another error in your code, regarding vectors' const-qualifiers.
-
maybe it is because your vector is called array and not items?
and how do you plan to modify const vector?
-
Ok i moved the const to the output, I knew better then that.
To be honest this code is completely honest this code is pretty much plagiarized. I like to take the code from my textbook and play with it. I get a better understanding of what its really doing. Thats why I am confused. I know I didn't declare items anywhere but my book didn't either. I'll go back and stare at it some more.
-
Works... Not sure why the textbook said otherwise. Thanks for the help!!!
Code:
#include <iostream>
#include <vector>
#include <stdexcept>
#include <iomanip>
using namespace std;
void inputVector(vector<int> &array)
{
for( int &item : array)
cin>>item;
}
void outputVector(const vector<int> &array)
{
for(int item : array)
cout<< item <<" ";
cout << endl;
}
int main(int argc, const char * argv[])
{
vector<int> integers1(4);
vector<int> integer2(5);
cout<<"Enter some numbers "<<integers1.size() <<endl;
inputVector(integers1);
inputVector(integer2);
outputVector(integers1);
outputVector(integer2);
return 0;
}
-
A non-vector comment.
Couldn't the message for getting the user to input be something like this:
Code:
cout << "Enter " << integers1.size() << " numbers" << endl;
Note also that you could use '\n' instead of std::endl. (std::endl vs “\n”)