我坐在C ++ Primer(3.23)上的一个小练习上将近2天。我尝试了多种方法来为分配值vector<int>
。到目前为止,我将为您提供一个实际的练习和代码,但这完全是错误的。我做了很多研究,但没有发现任何用处。
编写一个程序来创建一个vector
包含10个int
元素的。使用迭代器,为每个元素分配一个为其当前值两倍的值。通过打印测试程序vector
这是我的代码
int main(){
vector<int> num(10);
for (auto it=num.begin();it != num.end() ;++it)//iterating through each element in vector
{
*it=2;//assign value to vector using iterator
for (auto n=num.begin() ;n!=num.end();++n)//Iterating through existing elements in vector
{
*it+=*n;// Compound of elements from the first loop and 2 loop iteration
}
cout<<*it<<" ";
}
keep_window_open("~");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是我不知道如何使用迭代器int
为每个vector
元素分配值(我为1分配了五个元素,但没有给五个元素分配值)!此外,我在如何使用中的10个元素来完成此练习时大吃一惊vector
,因为每个元素必须具有不同的值,并且迭代器必须执行赋值。
感谢您的时间。
这是已接受答案的更清晰版本,使用递增迭代器而不是 for 循环的概念:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> num(10);
int n = 1;
vector<int>::iterator it = num.begin();
vector<int>::iterator itEnd = num.end();
while (it != itEnd)
{
*it = n = n*2;
cout << *it << " ";
it++;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以这样:
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> num(10);
int initial_value = 2;
*num.begin() = initial_value;
cout<<*num.begin()<<" ";
for (std::vector<int>::iterator it=num.begin()+1; it != num.end() ;++it)//iterating thru each elementn in vector
{
*it=*(it-1) * 2;//assign value wtih 2 times of previous iterator
cout<<*it<<" ";
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您只需要给第一个迭代器一些初始值,其余的就在for循环中计算