A function that displays elements of a vector

I need to write a function that takes in a vector of strings and a vector of integer indices and display just those elements in the vector of strings at the given indices.

For example, if the vector of integer indices contains 1 and 4 then the function will display the first and fourth element of the vector of strings.

This is what I have so far:
1
2
3
4
5
void displaySelected (vector<int> i;)
{
	cout << vector<string> (vector<int> i)
	
}


I know it's pretty far off. I understand the concept and can apply it to an array easily but I'm having trouble applying it to a vector.

Thanks
Make sure you know the difference between the type of a thing and the thing itself.

    vector<string> -- a type of thing
    my_strings -- a thing

For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
  {
  // I have a thing called 'my_strings'. Its type is a vector of strings.
  vector<string> my_strings;

  // Let's add some strings to my thing.
  my_strings.push_back( "Hello" );
  my_strings.push_back( "world!" );

  // Let's display the thing to the user.
  for (size_t n = 0; n < my_strings.size(); n++)
    cout << my_strings[ n ] << " ";
  cout << endl;

  return 0;
  }

Your function should take two arguments (two things): the first is a vector of strings and the second is a vector of integers:

    void displaySelected( vector<string>& my_strings, vector<int>& my_indices )

You will need a loop that goes through your list of indices. For each index, use it to lookup a string in your list of strings, and print that string.

This should be enough to help. Good luck!

[edit]Fixed a typo.
Last edited on
Thanks Duoas, I don't have to pass it by reference though right? Because I'm not changing any values.

This is what I managed to come up with, I'm a little confused on how to stop the loop at the end.
1
2
3
4
5
void displaySelected (vector<string>& my_strings, vector<int>& my_indices)
{
	for (my_indices = 0; my_indices < vector::size; my_indices++)
		cout << vector<string> my_strings(my_indices);
}
Last edited on
You really should try to compile the stuff you have and the stuff people give you.
See line 16 of my code above to know when to stop.
Good luck!
Topic archived. No new replies allowed.