【问题标题】:Vector of square root no printing in C++ [duplicate]在C ++中没有打印的平方根向量[重复]
【发布时间】:2021-10-17 21:13:45
【问题描述】:

我无法制作一个返回向量平方的原始元素的向量。

这是我遇到的错误。

no operator "<<" matches these operands -- operand types are: std::ostream << std::vector<int, std::allocator<int>>

#include <iostream>
#include <vector>
#include <cmath>

void squareRoot(std::vector<int> &v){

    int x;
    std::vector<int> squared;

    for(auto i:v){
        int x = i*i;
        squared.push_back(x);
    }
    std::cout << squared << std::endl; //error occurs at this line
    return;
}


int main(){

    std::vector<int> v = {2,4,8,1};
    squareRoot(v);

    return 0;
}

【问题讨论】:

  • 你必须重载operator&lt;&lt;(std::ostream&amp;, std::vector&lt;int&gt; const&amp;)
  • 为什么要对向量的索引进行平方?
  • 你不能只cout&lt;&lt;整个向量,你必须迭代它来打印它的元素。
  • 现在有什么错误?我怀疑的错误是你试图打印整个向量(python 方式)而不迭代它。
  • for(auto i:v) 表示v 中的每个元素,而不是v 中的每个index,因此您不需要v[i],这很可能越界了。 std::vector 也没有 &lt;&lt; 运算符。

标签: c++


【解决方案1】:

您可以为vector&lt;int&gt; 定义&lt;&lt; 运算符(或作为vector&lt;T&gt; 的模板)。在squareRoot前插入以下代码:

std::ostream& operator<<(std::ostream& os, const std::vector<int>& v) {
    os << "[";
    bool first = true;
    for (const auto& x : v) {
        if (first) {
            first = false;
        } else {
            os << ", ";
        }
        os << x;
    }
    os << "]";
    return os;
}

给了

[4, 16, 64, 1]

【讨论】:

  • 变量first那里没有用到,可以去掉
  • @CristianTraìna first 用于防止将", " 放在第一个元素之前。
猜你喜欢
  • 1970-01-01
  • 2013-03-18
  • 2018-01-24
  • 1970-01-01
  • 1970-01-01
  • 2014-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多