Sign in to follow this  
Dv02

std::vector as argument

Recommended Posts

I have been trying to explore my knowledge, however on this i am stumped. .:The Idea:. To pass a vector array into a function .:The Current Code:.
#include<iostream>
#include<vector>

using namespace std;

void cvector(vector<int> &hammer())
{
     for(int i=0;i==2;i++){
     cout<<&hammer[i]<<endl;
     }
}

int main()
{
    vector<int> stuff;
    stuff.push_back(1);
    stuff.push_back(2);
    stuff.push_back(3);
    cvector(stuff);
    
    cin.get();
    return 0;

}


Very Simple. .:The Problem:. Nothing comes up. It compiles but the program doesnt appear. task Manager doesnt even show it processing. Compiler:Dev-Cpp I have searched a few threads and saw a bit more advanced problem, but not like this one. Awaiting reply.

Share this post


Link to post
Share on other sites

// Iterator version of your function
void cvector(std::vector<int>& hammer)
{
for (std::vector<int>::const_iterator i = hammer.begin();
i != hammer.end(); i++)
std::cout << i << std::endl;
}

// Normal (Working) version of your function.
void cvector(std::vector<int>& hammer)
{
for (int i = 0; i < hammer.size(); i++)
std::cout << hammer[i] << std::endl;
}



This is working code, untried but should work.

Share this post


Link to post
Share on other sites
Your for loop is looping exactly 0 times. It's saying, "Set the integer i to 0. Now, as long as i is equal to 2, run the loop body and add 1 to i". Since i is never 2 in the first place, the loop immediately exits (and does nothing).

Also, I suspect that the & in front of hammer[i] is not what you want. That will take the address of the integer stored in position i, and display it. You probably want to display the actual integer itself (eg. 1, 2, 3) so remove the &.

Share this post


Link to post
Share on other sites
Quote:
Original post by Sc4Freak
Your for loop is looping exactly 0 times. It's saying, "Set the integer i to 0. Now, as long as i is equal to 2, run the loop body and add 1 to i". Since i is never 2 in the first place, the loop immediately exits (and does nothing).

Also, I suspect that the & in front of hammer[i] is not what you want. That will take the address of the integer stored in position i, and display it. You probably want to display the actual integer itself (eg. 1, 2, 3) so remove the &.


He also should use const, to show that he wont change the content of hammer inside the function.
for example:

void cvector(const std::vector<int>& hammer);

Share this post


Link to post
Share on other sites
Guest
This topic is now closed to further replies.
Sign in to follow this