请帮我解两道编程题目(?C++Primer?的课后习题)

来源:百度知道 编辑:UC知道 时间:2024/06/14 06:08:51
第一道题是:编写程序定义一个vector对象,其每个元素都是指向string类型的指针,读取该vector对象,输出每个string的内容及其相应的长度。第二道题:编写程序处理vector<int>对象的元素,将每个奇数值元素用该值的两倍替换。由于小弟初学C++,还请大家莫见笑,非常感激!!本人刚高中毕业,由于对计算机非常感兴趣,所以在自学C++,不知前辈们有什么好的建议

第一题:

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

using namespace std;

void print(string &str)
{
cout << str << " " << str.length() << " ";
}

int main()
{
vector<string> vs;

vs.push_back("hello");
vs.push_back("world");
vs.push_back("!!");
for_each(vs.begin(), vs.end(), print);
cout << endl;

return 0;
}

第二题:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

void print(int &n)
{
cout << n << " ";
}

void turn(int &n)
{
if (n % 2 == 1)
{
n *= 2;
}
}

int main()
{
vector<int> vi;

vi.push_ba