emptying an int vector and replacing it with string vector

hi all im writing this program that emptys a vector ad replaces it with a string, but i cant get it to work please help.

the final output should be "five four three two one one two three four five"

any help would br very appreciated thanks.

Heres my code:



#include<iostream>
#include <vector>
#include <string>

using namespace std;

void printVector(vector<int>v)

{
vector<string>s;
for (unsigned int i = 0; i<v.size();i++)
{
v.clear();
v.push_back(s.insert());
cout << v[i] << " ";
}
cout << endl;

return;
}

int main()
{
vector<int> a;
a.push_back(5);
a.push_back(4);
a.push_back(3);
a.push_back(2);
a.push_back(1);
a.push_back(1);
a.push_back(2);
a.push_back(3);
a.push_back(4);
a.push_back(5);

for(unsigned int i =0; i<a.size(); i++)
{

cout << a[i] << " ";

}
cout << endl;

vector<string>b;
b.push_back("One");
b.push_back("Two");
b.push_back("Three");
b.push_back("Four");
b.push_back("Five");

for (unsigned int i = 0; i<b.size(); i++)
{
cout << b[i] << " ";
}
cout << endl;


printVector(a);


return 0;
}
Last edited on
First of all, please use code tags when you post code..

Second, I really don't understand what are you doing inside the loop in your printVector function. You have some empty vector s (why do you need it?), then in each iteration of the loop you clear your input vector v (why?), you try to insert something to vector s (which shouldn't compile because you need to provide a position and a value to insert, again, what's the purpose of s?), then you push_back the iterator returned by insert to the emptied copy of your input vector (again, shouldn't compile because v stores integers and not iterators) and also you don't pass vector b from the main function to printVector - where should the printVector function get the names for numbers?

Overall, what I'm trying to say is that you should first understand the logic of your program yourself, as in "which line is doing what and for what purpose". I mean I can tell you directly how to make this work, but unless you understand your code - it will not help you to write better code in future.

So please figure out what are you trying to do with the lines of code I pointed you to, post the code with comments explaining your train of thought (don't forget code tags) and then we will try to help you in a way so that you understand why your code doesn't work and how to fix it.
You can not fill a vector of one base type with values of another type if there is no conversion from the first type to the second one. std::string can not be converted to int.

You could do your task the following way

1
2
3
4
5
6
7
8
9
void printVector( const vector<int> &v, const vector<string> &s )
{
   for ( unsigned int i = 0; i < v.size(); i++ )
   {
      cout << s[v[i]] << " ";
   }

   cout << endl;
}


And call the function the following way

printVector(a, b);
Last edited on
Topic archived. No new replies allowed.