【问题标题】:Using an iterator to go through a vector and modify the contents使用迭代器遍历向量并修改内容
【发布时间】:2019-08-16 02:44:07
【问题描述】:

我被 C++ 入门中的一个练习问题困住了。我必须使用迭代器循环遍历初始化的向量并对每个元素进行平方,然后输出每个更改的元素。

#include <iostream>
#include <vector>


using std::vector; 
using std::cout;


int main()
{

    vector<int> v{1,2,3,4,5,6,7,8,9};
    vector<int>::iterator i;
    for (auto i =v.begin();  i != v.end(); i++)   
        i *= i;

    for (auto i =v.begin(); i < v.end; i++)     
        cout << i << " "; 
    cout << endl;
}

我不断收到这条消息:

[错误] 'operator' 和 '')

【问题讨论】:

  • 你想处理元素,而不是迭代器。试试*i *= *i;cout &lt;&lt; *i &lt;&lt; " ";
  • 或使用 ranged-for,例如:for (auto&amp; i : v)
  • vector&lt;int&gt;::iterator i; 未使用。

标签: c++ iterator


【解决方案1】:

首先,您在这里忘记了父代(v.end 之后):

    for (auto i =v.begin(); i < v.end; i++)     

接下来,在这两行中定义同名的变量,从而用另一个覆盖一个变量:

    vector<int>::iterator i;
    for (auto i =v.begin();  i != v.end(); i++)   

你是什么意思:i *= i;

也许你提到了*i *= *i

最后,

    cout << i << " "; 

如果要输出值,试试

    cout << *i << " "; 

【讨论】:

  • 愚蠢的我,这么简单的错误。现在编译器告诉我“'operator *=' 不匹配......”
  • 请显示您的编译器抱怨的确切行。你有没有取消引用迭代器? *i *= *i
  • 15 9 [Error] no match for 'operator*=' (operand types are 'int' and '__gnu_cxx::__normal_iterator>') 它的行15. 当我使用你对我们的建议时程序编译 *i *= *i,但现在它给了我随机数。
  • @AKO 您的初始程序中有很多错误。如果没有看到您当前的版本,我无法讨论您的更正。请提供更新。
  • #include &lt;iostream&gt; #include &lt;vector&gt; using std::vector; using std::cout; using std::endl; int main() { vector&lt;int&gt; v{1,2,3,4,5,6,7,8,9}; for (auto i =v.begin(); i != v.end(); i++) *i *= i; for (auto i =v.begin(); i &lt; v.end(); i++) cout &lt;&lt; *i &lt; " "; cout &lt;&lt; endl; }
【解决方案2】:

range-based for loops 的完美去处:

for (auto& e : v) {
   e *= e;
}

for (const auto& e : v) {
   std::cout << e << " ";
}

【讨论】:

  • 同意,但我想解决这个需要使用迭代器的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-26
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多