我在 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;
}
我的问题是我不知道如何分配 int
每个 vector
的值(value)使用迭代器的元素(我对 1 但不是五个元素)!此外,我对如何使用 vector
中的 10 个元素进行此练习感到很困惑。 ,每个元素必须是不同的值,并且迭代器必须进行赋值。
感谢您的宝贵时间。
最佳答案
这是已接受答案的一个更清晰的版本,使用递增迭代器而不是 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++;
}
}
关于c++ - 使用迭代器将 int 值赋给 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17289324/