[英]error: expression must have pointer-to-object type
I tried to design a program that will return the original 32bit value w
but change the number i
element to 1
. 我试图设计一个程序,它将返回原始的32位值
w
但将数字i
元素更改为1
。 Here's the function I got so far. 这是我到目前为止的功能。 But for this part,
v[i]=1;
但对于这部分,
v[i]=1;
, it just says that for i
expression must have pointer to object type. ,它只是说对于
i
表达式必须有指向对象类型的指针。
unsigned int setBit(unsigned int w,unsigned int i)
{
unsigned int v = w;
v[i]=1;
return v;
}
unsigned int v = w;
v[i] = 1; // error, v is not an array
This is not correct because v
is not an array. 这不正确,因为
v
不是数组。 The solution might be using a std::bitset
or simply shifting bits and using some bit manipulation - this would be faster. 解决方案可能是使用
std::bitset
或简单地移位和使用一些位操作 - 这会更快。
unsigned int setBit(unsigned int w,unsigned int i) {
unsigned int v = ( w |= 1 << i);
return v;
}
usage: 用法:
int main(int argc, char *argv[])
{
unsigned int in = 0;
unsigned int res = setBit(in,1); // set 1st bit in 0 to 1, results in 2
return 0;
}
meaning of unsigned int v = ( w |= 1 << i);
unsigned int v = ( w |= 1 << i);
含义unsigned int v = ( w |= 1 << i);
| | - the bitwise OR
- 按位OR
<< - the bitwise shift << - 按位移位
v = ( w |= 1 << i)
is the same as v = ( w = w | 1 << i)
so it means: v
is equal to (take w
and OR
it with 1
left shifted by i
, and assign this to w
) v = ( w |= 1 << i)
与v = ( w = w | 1 << i)
所以它意味着: v
等于(取w
和OR
,其中1
左移i
,并赋值这个到w
)
In C++, []
operator is for string/array/vector/map/...
, but not for a unsigned int
. 在C ++中,
[]
运算符用于string/array/vector/map/...
,但不适用于unsigned int
。
For your example, you probably need to change it to bit array
first to be able to use such way. 对于您的示例,您可能需要首先将其更改为
bit array
才能使用这种方式。
In case you're interested. 如果你有兴趣。
unsigned int setBit(unsigned int w, unsigned int i)
{
std::bitset<sizeof(unsigned int)> bitset((unsigned long long)w);
bs.set(i, 1);
(unsigned int)return bs.to_ulong();
}
Although I would still use piotrus
' answer. 虽然我仍然会使用
piotrus
的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.