求助大神【C++ Primer 习题】 5.18
我自己编了一段代码:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string*> spvec;
string str;
cout << "Enter some strings(ctrl+z to end):" << endl;
while(cin >> str)
spvec.push_back(&str);
vector<string*>::iterator iter=spvec.begin();
while(iter != spvec.end()){
cout << **iter << " " << (**iter).size() << endl;
++iter;
}
return 0;
}
输入 "I am very happy"
运行程序后输出时:
为什么会这样呢?是由于每次str传给vector的地址都是一样的,也就是说其实存放在vector中的指针指向同一个地址么?
[解决办法]
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> spvec;
string str;
cout << "Enter some strings(ctrl+z to end):" << endl;
while(cin >> str)
spvec.push_back(str);
vector<string>::iterator iter=spvec.begin();
while(iter != spvec.end())
{
cout << *iter << " " << (*iter).size() << endl;
++iter;
}
return 0;
}