-1
#include<iostream>
#include<list>
#include<string>
#include<iterator>
#include<algorithm>
using namespace std;

void print(const list<string> &l)
{
cout << "The list elements are : ";
copy(l.begin(), l.end(), ostream_iterator<string>(cout, " "));
cout << endl << endl;
}

int main()
{
list<string> l = { "blue","red","black","yellow","green","gold","silver","pink","orange","brown" };
print(l);

list<string>::iterator it;

system("pause");
return 0;
}

I had to create a list of 10 words. I created it and made the print function. But the problem is that for my school project I have to find all the words starting with b and the next one is that I have to find all the words which length is 4 symbols (for example blue). Thank you in advance for your help!

JFMR
  • 23,265
  • 4
  • 52
  • 76
Amanda
  • 37
  • 4
  • what did you try? If this is homework, I would expect that you discussed some means to find an element in a list in lecture, but I dont see anything like that in your code – 463035818_is_not_an_ai Nov 20 '19 at 18:27
  • in class the teacher only gave us some information about vectors and nothing for list and after that she decided that we have to make it on our own .Sorry but im not a genius,i can not make things that i have no idea of. – Amanda Nov 20 '19 at 18:38
  • you dont have to be a genius to type "find element in list c++" in a search engine and find eg this: https://stackoverflow.com/questions/4604136/how-to-search-for-an-element-in-an-stl-list – 463035818_is_not_an_ai Nov 20 '19 at 18:39
  • this example is for int, mine is different and i've searched a lot but there is not much infromation for my homework. Just to find element looks ok, but finding exact first letter from word in list isnt that great – Amanda Nov 20 '19 at 18:46
  • if you know how to work with a `list` you also know how to work with a `list`, at least you should be able to try something – 463035818_is_not_an_ai Nov 20 '19 at 18:47

1 Answers1

3

With std::copy you are copying all the string in the list – no criterium is used for discriminating the strings. You may want to consider std::copy_if() with a suitable predicate instead of std::copy(). The predicate should return true for the string that matches your criteria.

For example:

void print(const std::list<std::string>& lst) {
   auto pred = [](const std::string& str) {
      if (str.empty() || str[0] != 'b' || str.length() != 4)
         return false;
      return true;
   };

   std::copy_if(lst.begin(), lst.end(), std::ostream_iterator<std::string>(std::cout, " "), pred);
}

It will copy strings whose first character is b and are four characters in length. Only the strings that fulfill these requirements will be copied into the output iterator and, as a consequence, streamed into std::cout.

Alternatively, you can simply use a range-based for loop:

for (auto const& str: lst)
   if (/* ... */) // criterium
      std::cout << str << ' '; 
JFMR
  • 23,265
  • 4
  • 52
  • 76