AlexGreat AlexGreat - 3 months ago 10
C++ Question

Assign int value to vector using iterator

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.

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


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.

Answer

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

Comments