[英]Vector c++ no match for operator* when multiplying two elements of a vector
This is a part of a code I wrote:这是我写的代码的一部分:
for(int i=1;i<=n;i++) a.push_back(i);
while(a.size()!=1){
b+=a.begin()*a.end()+a.begin()+a.end();
a.erase(a.begin());
a.erase(a.end());
}
This is the first time I am using vectors, so I dont know where I went wrong.这是我第一次使用向量,所以我不知道我哪里出错了。 The error I get is:
我得到的错误是:
error: no match for ‘operator*’ (operand types are ‘std::vector::iterator {aka __gnu_cxx::__normal_iterator >}’ and ‘std::vector::iterator {aka __gnu_cxx::__normal_iterator >}’)
b+=a.begin()*a.end()+a.begin()+a.end();
~~~~~~~~~^~~~~~~~
begin()
and end()
return iterators . begin()
和end()
返回迭代器。 You can't multiply iterators.你不能乘以迭代器。 Use
front()
and back()
to access the first and last value.使用
front()
和back()
访问第一个和最后一个值。
b += a.front() * a.back() + a.front() + a.back();
Looks like you over complicating this code.看起来你把这段代码复杂化了。 You do not need vector to calculate this value.
您不需要向量来计算此值。
int f(int n) {
int r = 0;
for(int i=1; i <= (n + 1)/2; i++) {
auto b = i;
auto e = n + 1 - i;
r += b * e + b + e;
}
return r;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.