C++ 使用迭代器将 int 值赋给向量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17289324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Assign int value to vector using iterator
提问by AlexGreat
I'm sitting on a small exercise in C++ Primer (3.23) for almost 2 days. I've tried many ways of assigning a value to vector<int>
. I'll give you an actual exercise on which I work and code with which I came so far, but its totally wrong. I did a lot of research but found nothing useful.
我在 C++ Primer (3.23) 中坐了将近 2 天的小练习。我已经尝试了很多方法来为vector<int>
. 我会给你一个实际的练习,我的工作和我到目前为止的代码,但它完全错误。我做了很多研究,但没有发现任何有用的东西。
Write a program to create a vector
with 10 int
elements. Using an iterator, assign each element a value that is twice its current value. Test the program by printing vector
编写一个程序来创建一个vector
包含 10 个int
元素的元素。使用迭代器,为每个元素分配一个两倍于其当前值的值。通过打印测试程序vector
And this is my code
这是我的代码
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;
}
My problem is I don't know how to assign an int
value to each vector
element using an iterator (I did to 1 but not to the five elements)! In addition I was breaking my head on how to do this exercise with 10 elements in vector
, to each element must be a different value and an iterator must do the assignment.
Thank you for your time.
我的问题是我不知道如何使用迭代器int
为每个vector
元素分配一个值(我为 1 而不是五个元素)!此外,我对如何使用 10 个元素进行此练习感到非常困惑vector
,每个元素必须是不同的值,并且必须由迭代器进行分配。
感谢您的时间。
采纳答案by fatihk
You can do like this:
你可以这样做:
#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;
}
You just need to give some initial value to the first iterator and the rest is calculated in a for loop
你只需要给第一个迭代器一些初始值,其余的在 for 循环中计算
回答by Sonic Atom
Here's a much cleaner version of the accepted answer, using the concept of incrementing the iterator instead of a for loop:
这是已接受答案的更清晰版本,使用递增迭代器而不是 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++;
}
}