【发布时间】: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<<(std::ostream&, std::vector<int> const&)。 -
为什么要对向量的索引进行平方?
-
你不能只
cout<<整个向量,你必须迭代它来打印它的元素。 -
现在有什么错误?我怀疑的错误是你试图打印整个向量(python 方式)而不迭代它。
-
for(auto i:v)表示v中的每个元素,而不是v中的每个index,因此您不需要v[i],这很可能越界了。std::vector也没有<<运算符。
标签: c++