c++ - 对 vector 中的值求平方

标签 c++ vector

有人要求我创建一个调用函数的函数 void square(vector<int> &v) vector 中每个整数的平方 v .这是我所拥有的,但我不断收到编译器错误。 提供任何帮助将不胜感激

#include<iostream>
#include<vector>
#include<string>
using namespace std;

void square(vector<int> &v)
{
  for(int i=0; i<v.size(); i++){
    v = v[i]*v[i];
  }
}

这是我的补偿错误:

'void square(std::vector<int>&)':
editor.cpp:11:13: error: no match for 'operator=' in 'v = ((& v)->std::vector<_Tp, _Alloc>::operator[]<int, std::allocator<int> >(((std::vector<int>::size_type)i)) * (& v)->std::vector<_Tp, _Alloc>::operator[]<int, std::allocator<int> >(((std::vector<int>::size_type)i)))'
editor.cpp:11:13: note: candidate is:
In file included from /usr/lib64/gcc/x86_64-slackware-linux/4.7.1/../../../../include/c++/4.7.1/vector:70:0,
                 from editor.cpp:3:
/usr/lib64/gcc/x86_64-slackware-linux/4.7.1/../../../../include/c++/4.7.1/bits/vector.tcc:161:5: note: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(const std::vector<_Tp, _Alloc>&) [with _Tp = int; _Alloc = std::allocator<int>]
/usr/lib64/gcc/x86_64-slackware-linux/4.7.1/../../../../include/c++/4.7.1/bits/vector.tcc:161:5: note:   no known conversion for argument 1 from 'int' to 'const std::vector<int>&'

最佳答案

  1. 您正在尝试将整数分配给 vector 。
  2. size 是一个类方法,应调用为 v.size()

这是一个有效的代码:

void square(vector<int> &v)
{
  for(int i=0; i<v.size(); i++){
    v[i] = v[i]*v[i];
  }
}

关于c++ - 对 vector 中的值求平方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19504473/

相关文章:

c++ - QT : How to determine if the event processor is busy

c++ - WaveOut 程序崩溃

c++ - 在 std::vector 中找到满足条件的最后一个元素

c++ - 将 shared_ptr 与 vector 一起使用时出现段错误

vector - IDRIS向量与链表

c++ - 字符串变量的简单错误

c++ - operator= on pointers 可能导致 mac 上的段错误

c++ - 创建新对象时转换错误

vector - 在 Three.js 中,如何翻译一个 Vector3?

c++ - 模型观察矩阵 - C++、OpenGL