Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print elements in a vector c++

Tags:

c++

arrays

vector

I am having trouble with my void print function to print out this vector. I'm not quite sure what it is talking about with "std::allocator. I get these errors:

st1.cpp: In function ‘void Print(std::vector<int, std::allocator<int> >)’:
st1.cpp:51: error: declaration of ‘std::vector<int, std::allocator<int> > v’ shadows a      parameter

Here is the file:

#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;

void Initialize();
void Print();

int main()
{
stack<string> s1, s2;
s1.push("b");
s2.push("a");

if (s1.top() == s2.top())
{
    cout << "s1 == s2" << endl;
}
else if (s1.top() < s2.top())
{
    cout << "s1 < s2" << endl;
}
else if (s2.top() < s1.top())
{
    cout << "s2 < s1" << endl;
}
else 
{
    return 0;
}

vector<int> v;
Initialize();
Print();
}

void Initialize(vector<int> v)
{
int input;
cout << "Enter your numbers to be evaluated: " << endl;
while(input != -1){
    cin >> input;
    v.push_back(input);
    //write_vector(v);
}
}

void Print (vector<int> v){
vector<int> v;
for (int i=0; i<v.size();i++){
    cout << v[i] << endl;
}
}

I just want to print v out to the screen. Any help?

like image 824
TheNameHobbs Avatar asked Feb 01 '13 04:02

TheNameHobbs


2 Answers

Your function declaration and definition are not consistent, you want to generate vector from Initialize, you can do:

void Initialize(vector<int>& v);

To print vector:

void Print(const vector<int>& v);

Now you call:

vector<int> v;
Initialize(v);
Print(v);

Don't forget to change function definition of Initialize, Print to match the new signature I provided above. Also you are redefining a local variable v which shadows function parameter, you just need to comment out that line, also pass vector by const ref:

void Print (const vector<int>& v){
  //vector<int> v;
  for (int i=0; i<v.size();i++){
    cout << v[i] << endl;
  }
}
like image 196
billz Avatar answered Sep 30 '22 19:09

billz


You have to pass by const reference and remove the extraneous vector.

void Print(const std::vector<int>& v){
    for(unsigned i = 0; i< v.size(); ++i) {
        std::cout << v[i] << std::endl;
    }
}

Another way to print it out would be to use iterators like so:

void Print(const std::vector<int>& v) {
    std::vector<int>::iterator it;
    for(it = v.begin(); it != v.end(); ++it) {
        std::cout << (*it) << '\n';
    }
}

Or in C++11 you can do it like so:

void Print(const std::vector<int>& v) {
    for(auto& i : v)
        std::cout << i << '\n';
}

I don't think your Initialize() function works like you expect it to. It seems to just make a copy and then discards it, not modifying any values of the existing vector.

like image 31
Rapptz Avatar answered Sep 30 '22 20:09

Rapptz