[英]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? 我正在尝试将<string>写入向量中-我使用int向量完成了此操作,并且工作正常-所以我怀疑在使用字符串时我需要以不同的方式进行操作-但是虽然我理解我的编译错误是告诉我我正在尝试使用不兼容的类型<char>-我不知道为什么,因为我认为我已经声明了所有内容并正确使用了它-有人可以告诉我我怎么弄错了?
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. 编译器会告诉您带有
std::string
参数的std::basic_string<char>::push_back
不存在。
Use operator+=
: iString += iString
. 使用
operator+=
: iString += iString
。
You probably want strArray.push_back(iString)
. 您可能需要
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... 如果我理解这一权利-这是因为被声明的迭代器需要与集合进行类型兼容,因此要迭代...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.