c++ - 使用迭代器将 int 值赋给 vector

标签 c++ iterator

我在 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/

相关文章:

c++ - 返回 *this

c++ - 在 64 位可执行文件中执行 64 位计算

c++ - 是否可以使用符合 C++17 的 C++14 创建迭代器?

c++ - 如何将一个 qApplication 的 GUI 嵌入到另一个 qApplication 的 mainWindow 中?

java - 获取 TreeMap 中的三个最高值

c++ - 从 C++ 调用 R 函数

c++ - c++中比较vector等随机访问迭代器时,<>的比较内容是什么?

python - 迭代和连接 2 个列表占用大量内存

java - 在特定位置插入 List<List<Map<Integer,Integer>>>

c++ - STL 映射输出迭代器查找值