简体   繁体   中英

Getting error using vector push_back with <string> in c++

I am trying to write a < string > into a vector - I did this exact thing with a vector of int and it worked OK - so I suspect I need to do this differently when using a string - but While I understand my compile error is telling me that I am trying to use incompatible types < char > - I don't know why because I THOUGHT I had declared everything and used it correctly - can someone please tell me how I got this wrong?

Here is the code I am trying to use:

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

int main()
{
   std::vector<std::string> strArray;
   std::vector<int>::const_iterator y;

   std::string iString = "";

   while (iString != "quit")
   {
      std::cout << "Enter string: ";
      std::cin >> iString;
      iString.push_back(iString);
   }

   std::cout << "Your list is:\n";
   for (y= iString.begin(); y <= iString.end(); y++)
   {
      std::cout << (*y)
                << std::endl;
   }
   std::cout <<  std::endl;

   return 0;
}

And here is the error message:

check10a.cpp: In function ‘int main()’:
check10a.cpp:57:32: error: no matching function for call to ‘std::basic_string<char>::push_back(std::string&)’
       iString.push_back(iString);

I would really appreciate a bit of a pointer here...

The compiler tells you that std::basic_string<char>::push_back with std::string argument doesn't exist.

Use operator+= : iString += iString .


You probably want strArray.push_back(iString) .

Just for the benefit of anyone else who might find this - therre was another error in my code, where in fact I had not understood a piece of the required concept around iterators:

this line here:

std::vector<int>::const_iterator y;

in fact needed to be:

std::vector<std::string>::const_iterator y;

If I understand this right - it is because the iterator being declared needs to be type compatible with the collection it is iterating over...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM