I found a strange behavior of C ternary operator (?:).
In the following code, the expected values of both b and c should be 0, but b is -2.
I checked the C operator precedence, and made sure minus(-) is higher than greater than or equal to (>=), which is higher than the conditional operator (?:). Could anyone kindly explain why the values of b and c are different?
#include <iostream>
#include <vector>
using std::vector;
using std::cout;
using std::endl;
int main() {
int i;
vector<int> a;
for (i = 0; i < 29; ++i)
a.push_back(i);
int b = 27 - a.size() >= 0 ? 27 - a.size() : 0;
int c = 27 - 29 >=0 ? 27 - 29 : 0;
cout << b << endl;
cout << c << endl;
return 0;
}
After looking on the document page of vector, the return type of method size() is size_t which is equal to an unsigned long long.
So, when you do 27 - a.size() this will cause overflow, making the result of the 27 - a.size() >= 0 operator be True. It got nothing to do with C operator precedence.
To prove that, you can do:
#include <iostream>
using std::cout;
using std::endl;
int main() {
unsigned long long tmp = 29;
cout << 27 - tmp << endl; //(this will be a super large integer.)
return 0;
}
Solution:
The solution is simple, you can simply add a typecasting (int) before a.size() in the condition of the ternary operator.
It can be looks like this:
int b = 27 - (int) a.size() >= 0 ? 27 - a.size() : 0;
Related
My pointer array doesn't store my data correctly. I created a file that stored 10 integers, and it only stored the 10th and prints it out 10 times.
Any help would be appreciated, and I apologize if formatting is incorrect as this is my first time using this site.
void displayPointer(vector<int*>& ptrvect) {
for (int i = 0; i <= ptrvect.size() - 1; i++) {
cout << setw(6) << *ptrvect[i];
}
}
void displayArray(vector<int>& vect) {
for (int i = 0; i <= vect.size() - 1; i++) {
cout << setw(6) << vect[i];
}
}
int main(){
ifstream myfile("arrayData.txt");
int values;
vector<int> vect;
vector<int*> ptrvect;
while (myfile >> values) {
ptrvect.push_back(&values);
vect.push_back(values);
}
displayArray(vect);
cout << endl;
displayPointer(ptrvect);
}
The purpose of my code is to sort a pointer vector and leave my original vector untouched, but I realized my pointer vector only has one unique integer from my list before the sorting even occurs.
Ex: arrayData.txt values are 1 3 9 4 8 2 10 48 3 21 and only 21 is printed 10 times when my displayPointer function is called.
I want to find out the function to generate the sequence with the following pattern.
1 2 3 1 1 2 2 3 3 1 1 1 1 2 2 2 2 3 3 3 3 ....
Where the lower bound number is 1 upper number bound number is 3. Each time numbers start from 1 and each number repeats 2 ^ n times, with n starting with 0.
Here it goes, I hope it will help.
#include <iostream>
#include <math.h>
int main(){
for(int n = 0; n < 5;n++){
for(int i = 1; i < 4;i++){
for(int j = 0;j < pow(2,n) ;j++){
std::cout << i;
}
}
}
return 0;
}
Here is a code in C++:
#include <iostream>
#include <cmath>
int main()
{
// These are the loop control variables
int n, m, i, j, k;
// Read the limit
cin >> n;
// Outermost loop to execute the pattern {1..., 2..., 3...} n times
for (i = 0; i < n; ++i)
{
// This loop generates the required numbers 1, 2, and 3
for (j = 1; j <= 3; ++j)
{
// Display the generated number 2^i times
m = pow(2, i);
for (k = 0; k < m; ++k)
{
std::cout << j << ' ';
}
}
}
}
You can use the same logic in any language you choose to implement it.
This question already has an answer here:
Assigning Rcpp objects into an Rcpp List yields duplicates of the last element
(1 answer)
Closed 4 years ago.
I want to create a list of matrices that I am updating in a loop and return it to R. I have
std::vector<IntegerMatrix> zb_list;
and
IntegerMatrix tb(J,nmax), zb(J,nmax);
before the loop. Inside the loop, I update zb and then have
zb_list.push_back(zb);
I also have
Rcout << (zb_list[itr]) << "\n";
Rcout << (zb) << "\n\n";
where itr counts the iterations. These both confirm that zb is changing inside the loop and zb_list keeps track of it.
Then I return zb_list after the loop. When accessing the result in R, the list contains copies of the same zb, the last one computed in the loop. I suspect there is some pass by reference going on... but can't figure it out. I don't have a good understanding of what is going on (tried to use return(wrap(zb_list))without luck) but clearly something is wrong. Also used List zb_list; for defining it which doesn't help. Any suggestions?
EDiT: Here is the minimal working example:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
List test_weird(int ITRmax=2) {
IntegerMatrix zb(2,2);
std::vector<IntegerMatrix> zb_list;
int itr = 0;
while (itr < ITRmax) {
zb( (1+itr)%2 ,(1+itr)%2 ) ++ ;
zb_list.push_back(zb);
Rcout << (zb) << (zb_list[itr]) << "\n\n";
++itr;
}
return List::create(_["zb"] = zb,
_["zb_list"] = zb_list);
}
/*** R
res <- test_weird()
res$zb_list
*/
This the output when the look is running:
0 0
0 1
0 0
0 1
1 0
0 1
1 0
0 1
... and this is the output from R:
> res$zb_list
[[1]]
[,1] [,2]
[1,] 1 0
[2,] 0 1
[[2]]
[,1] [,2]
[1,] 1 0
[2,] 0 1
As you can see both items in the list are the last zb in the loop.
The problem is that push_back(something) makes a copy of something. But if something is a pointer, than subsequent changes will effect all copies of that pointer. In plain C++:
#include <vector>
#include <iostream>
int main() {
std::vector<int*> v;
int* p = new int;
for (int i = 0; i < 2; ++i) {
*p = i;
v.push_back(p);
std::cout << *p << " " << *v[i] << std::endl;
}
std::cout << *v[0] << " " << *v[1] << std::endl;
return 0;
}
produces
$ ./pointer_fun
0 0
1 1
1 1
So if the something is a pointer (like object), which is the case for all Rcpp objects, then you need a deep copy/clone of the object, i.e.
zb_list.push_back(clone(zb));
I am looking for a good way to round an int in Qt to the nearest 5.
e.g:
8 -> 10
12 -> 10
13 -> 15
15 -> 15
17 -> 15
and so on
Rounding in C++ to the nearest integer number usually is done via:
static_cast<int>(number + 0.5);
Now, to round it to the next 5, I would bring it into the system where we can apply this rounding rule (i.e. 5 -> 1, 6 -> 1.2) and then bring it back into the system where 5 really is 5:
int roundToNearestFive(int number)
{
return static_cast<int>(number / 5. + .5) * 5;
}
I find this formulation easiest.
Here a possible solution:
#include<iostream>
int toNearest5(int i) {
int r = i%5, o = 0;
if(r) {
o = r/5. >= .5 ? 5 : 0;
}
return (i-r+o);
}
int main() {
using namespace std;
cout << toNearest5(8) << endl;
cout << toNearest5(12) << endl;
cout << toNearest5(13) << endl;
cout << toNearest5(15) << endl;
cout << toNearest5(17) << endl;
}
The idea is to get the number and round it to the lowest multiple of 5 (you can do that by removing the remainder), that is:
int remainder = i%5;
int rounded = i - remainder;
Now, you can check the remainder and add 5 to the rounded number if the remainder is greater than 2.5, otherwise add 0.
In order to check it, I've divided the remainder by 5 (its upper bound), so that to get a number in [0,1[ and check it with 0.5 to know how to round the original number.
It follows a more compact version of the same function:
int toNearest5(int i) {
int j = i%5;
return (i - j + (j/5. >= .5 ? 5 : 0));
}
I don't know if the Qt framework offers something similar out of the box, but it's a matter of an one line function, you can easily write it for yourself.
Add one to or subtract one from an odd integer such that the even result is closer to the nearest power of two.
if ( ??? ) x += 1; else x -= 1;// x > 2 and odd
For example, 25 through 47 round towards 32, adding one to 25 through 31 and subtracting one from 33 through 47. 23 rounds down towards 16 to 22 and 49 rounds up towards 64 to 50.
Is there a way to do this without finding the specific power of two that is being rounded towards. I know how to use a logarithm or count bits to get the specific power of two.
My specific use case for this is in splitting odd sized inputs to karatsuba multiplication.
If the second most significant bit is set then add, otherwise subtract.
if ( (x&(x>>1)) > (x>>2) ) x += 1; else x -= 1;
It isn't a big deal to keep all of the powers of 2 for a 32 bit integer (only 32 entries) do a quick binary search for the location it's supposed to be in. Then you can easily figure out which number it's closer to by subtracting from the higher and lower numbers and getting the abs. Then you can easily decide which one to add to.
You may be able to avoid the search by taking the log base 2 of your number and using that to index into the array
UPDATE: reminder this code is not thoroughly tested.
#include <array>
#include <cmath>
#include <iostream>
const std::array<unsigned int,32> powers =
{
1,1<<1,1<<2,1<<3,1<<4,1<<5,1<<6,1<<7,1<<8,1<<9,1<<10,1<<11,1<<12,1<<13,1<<14,
1<<15,1<<16,1<<17,1<18,1<<19,1<<20,1<<21,1<<22,1<<23,1<<24,1<<25,1<<26,1<<27,
1<<28,1<<29,1<<30,1<<31 -1
};
std::array<unsigned int,32> powers_of_two() {
std::array<unsigned int,32> powers_of_two{};
for (unsigned int i = 0; i < 31; ++i) {
powers_of_two[i] = 1 << i;
}
powers_of_two[31]=~0;
return powers_of_two;
}
unsigned int round_to_closest(unsigned int number) {
if (number % 2 == 0) return number;
unsigned int i = std::ceil(std::log2(number));
//higher index
return (powers[i]-number) < (number - powers[i-1]) ?
++number:--number;
}
int main() {
std::cout << round_to_closest(27) << std::endl;
std::cout << round_to_closest(23) << std::endl;
return 0;
}
Since I can't represent 2 ^ 31 I used the closest unsigned int to it ( all 1's) this means that 1 case out of all of them will produce the incorrect result, I figured that's not a big deal.
I was thinking that you could use a std::vector<bool> as a very large lookup table on wether to add 1 or subtract 1, seems like overkill to me for an operation that seems to run quite fast.
As #aaronman pointed out, if you are working with integers only the fastest way to do this is to have all powers of 2 in table as there are not that many. By construction, in an unsigned 32 bit integer there are 32 powers of 2 (including the number 1), in a 64 bit integer there are 64 and so on.
But if you want to do it on the fly for a generic case you can easily calculate the surrounding powers of 2 of any number. In c/c++:
#include <math.h>
(...)
double bottom, top, number, exponent;
number = 1234; // Set the value for number
exponent = int(log(number) / log(2.0)); // int(10.2691) = 10
bottom = pow(2, exponent); // 2^10 = 1024
top = bottom * 2; // 2048
// Calculate the difference between number, top and bottom and add or subtract
// 1 accordingly
number = (top - number) < (number - bottom) ? number + 1 : number - 1;
For nearest (not greatest or equal) - see this:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
unsigned int val = atoi(argv[1]);
unsigned int x = val;
unsigned int result;
do {
result = x;
} while(x &= x - 1);
if((result >> 1) & val)
result <<= 1;
printf("result=%u\n", result);
return 0;
}
if you need greatest or equal - change:
if((result >> 1) & val)
to
if(result != val)