I'm trying to run this code from C++ Primer plus
#include <iostream>
using namespace std;
int main() {
int i = 20, j= 2*i;
cout << "i = " << i << endl;
int cats = 17,240; //No, I don't want the number 17240
return 0;
}
Why I'm seeing this error expected unqualified-id before numeric constant int cats = 17,240; , I don't know, I need a short explanation. Thanks
int cats = 17,240; would be viewed by the compiler as int (cats = 17),240; due to operator precedence. And int 240; makes no sense, so a compiler diagnostic is issued.
Did you want 17240 cats? If so then drop the comma.
Related
Why are my array of static bools not initialized properly? Only the first one is initialized - I suspect this is because the array is static.
The following MWE was compiled with GCC and is based on a function that I am writing that I have transferred into a main program to illustrate my problem. I have tried with and without c++11. My understanding is because this array is static and initialized to true this should always print the first time I enter my function. So in this MWE it should print once.
#include <iostream>
using namespace std;
const int arraysize = 10;
const int myIndex = 1;
static bool firstTimeOverall = true;
int main()
{
static bool firstCloudForThisClient[arraysize] = {true};
cout.flush();
if (firstCloudForThisClient[myIndex])
{
cout << "I never get here" << endl;
firstCloudForThisClient[myIndex] = false;
if (firstTimeOverall)
{
firstTimeOverall = false;
cout << "But think I would get here if I got in above" << endl;
}
}
return 0;
}
You may need to invert your conditions to take advantage of default initialisation:
#include <iostream>
using namespace std;
const int arraysize = 10;
const int myIndex = 1; // note this index does not access the first element of arrays
static bool firstTimeOverall = true;
int main()
{
static bool firstCloudForThisClient[arraysize] = {}; // default initialise
cout.flush();
if (!firstCloudForThisClient[myIndex])
{
cout << "I never get here" << endl;
firstCloudForThisClient[myIndex] = true; // Mark used indexes with true
if (firstTimeOverall)
{
firstTimeOverall = false;
cout << "But think I would get here if I got in above" << endl;
}
}
return 0;
}
static bool firstCloudForThisClient[arraysize] = {true};
This initializes the first entry to true, and all others to false.
if (firstCloudForThisClient[myIndex])
However, since myIndex is 1 and array indexing is zero-based, this accesses the second entry, which is false.
Your are initializing only first element on an array using array[size] = {true} , if arraysize variable is bigger then 1, the initial value of other elements depends on platform. I think it is an undefined behavior.
If you really need to init your array, use loop instead:
for(int i=0; i < arraysize; ++i)
firstCloudForThisClient[i] = true;
You should access the first element of the array so use:
const int myIndex = 0;
I need to compute 5^64 with boost multiprecision library which should yield 542101086242752217003726400434970855712890625 but boost::multiprecision::pow() takes mpfloat and gives 542101086242752217003726392492611895881105408.
However If I loop and repeatedly multiply using mpint I get correct result.
Is it a bug ? or I am using boost::multiprecision::pow() in a wrong way ? or I there is an alternative of using boost::multiprecision::pow() ?
#include <iostream>
#include <string>
#include <boost/multiprecision/gmp.hpp>
typedef boost::multiprecision::mpz_int mpint;
typedef boost::multiprecision::number<boost::multiprecision::gmp_float<4> > mpfloat;
int main(){
mpfloat p = boost::multiprecision::pow(mpfloat(5), mpfloat(64));
std::cout << p.template convert_to<mpint>() << std::endl;
mpint res(1);
for(int i = 0; i < 64; ++i){
res = res * 5;
}
std::cout << res << std::endl;
}
I' did this program what suppose save pairs of string ,int on one vector and print the strings of the maximum number on vector
but when i try to find this strings don't appears nothing so I try print all values of int's on vector and although was finding the maximum of 10 all values in the vector was printing as 0. Someone can explain was it occurred and how I can access the values , please.
#include <iostream>
#include <utility>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
typedef vector<pair<string,int>> vsi;
bool paircmp(const pair<string,int>& firste,const pair<string,int>& seconde );
int main(int argc, char const *argv[]) {
vsi v(10);
string s;
int n,t;
cin>>t;
for (size_t i = 0;i < t;i++) {
for (size_t j = 0; j < 10; j++) {
cin>>s>>n;
v.push_back(make_pair(s,n));
}
sort(v.begin(),v.end(),paircmp);
int ma=v[v.size()-1].second;
cout<<ma<<endl;
for (size_t j = 0; j < 10; j++) {
cout << v.at(j).second <<endl;
if(v[j].second == ma)
cout<<v[j].first<<endl;
}
}
return 0;
}
bool paircmp(const pair<string,int>& firste,const pair<string,int>& seconde ){
return firste.second < seconde.second;
}
This line
vsi v(10);
creates you a std::vector filled with 10 default-constructed std::pair<std::string, int>s. That is, an empty string and zero.
You then push_back other values to your vector but they happen to be sorted after those ten initial elements, probably because they all have positive ints in them.
Therefore, printing the first member of the first ten elements prints ten empty strings.
This is all I can guess from what you have provided. I don't know what you are trying to accomplish with this code.
Try something like
for (const auto& item : v)
{
std::cout << "{ first: '" << item.first << "', "
<< "second: " << item.second << " }\n";
}
to print all elements of the vector v.
Is there a way I can make the shared pointer point to a different memory location without releasing the memory.pointed by it currently
Please consider the code:
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <iostream>
int
main()
{
int *p = new int();
*p = 10;
int *q = new int();
*q = 20;
boost::shared_ptr<int> ps(p);
// This leads to a compiler error
ps = boost::make_shared<int>(q);
std::cout << *p << std::endl;
std::cout << *q << std::endl;
return 0;
}
You can't.
Of course you can release and reattach, while changing the deleter to a no-op
To be honest, it looks like you'd just want
ps = boost::make_shared<int>(*q);
Prints (live on Coliru):
0
20
What is the best way to store the state of a C++11 random generator without using the iostream interface. I would like to do like the first alternative listed here[1]? However, this approach requires that the object contains the PRNG state and only the PRNG state. In partucular, it fails if the implementation uses the pimpl pattern(at least this is likely to crash the application when reloading the state instead of loading it with bad data), or there are more state variables associated with the PRNG object that does not have to do with the generated sequence.
The size of the object is implementation defined:
g++ (tdm64-1) 4.7.1 gives sizeof(std::mt19937)==2504 but
Ideone http://ideone.com/41vY5j gives 2500
I am missing member functions like
size_t state_size();
const size_t* get_state() const;
void set_state(size_t n_elems,const size_t* state_new);
(1) shall return the size of the random generator state array
(2) shall return a pointer to the state array. The pointer is managed by the PRNG.
(3) shall copy the buffer std::min(n_elems,state_size()) from the buffer pointed to by state_new
This kind of interface allows more flexible state manipulation. Or are there any PRNG:s whose state cannot be represented as an array of unsigned integers?
[1]Faster alternative than using streams to save boost random generator state
I've written a simple (-ish) test for the approach I mentioned in the comments of the OP. It's obviously not battle-tested, but the idea is represented - you should be able to take it from here.
Since the amount of bytes read is so much smaller than if one were to serialize the entire engine, the performance of the two approaches might actually be comparable. Testing this hypothesis, as well as further optimization, are left as an exercise for the reader.
#include <iostream>
#include <random>
#include <chrono>
#include <cstdint>
#include <fstream>
using namespace std;
struct rng_wrap
{
// it would also be advisable to somehow
// store what kind of RNG this is,
// so we don't deserialize an mt19937
// as a linear congruential or something,
// but this example only covers mt19937
uint64_t seed;
uint64_t invoke_count;
mt19937 rng;
typedef mt19937::result_type result_type;
rng_wrap(uint64_t _seed) :
seed(_seed),
invoke_count(0),
rng(_seed)
{}
rng_wrap(istream& in) {
in.read(reinterpret_cast<char*>(&seed), sizeof(seed));
in.read(reinterpret_cast<char*>(&invoke_count), sizeof(invoke_count));
rng = mt19937(seed);
rng.discard(invoke_count);
}
void discard(unsigned long long z) {
rng.discard(z);
invoke_count += z;
}
result_type operator()() {
++invoke_count;
return rng();
}
static constexpr result_type min() {
return mt19937::min();
}
static constexpr result_type max() {
return mt19937::max();
}
};
ostream& operator<<(ostream& out, rng_wrap& wrap)
{
out.write(reinterpret_cast<char*>(&(wrap.seed)), sizeof(wrap.seed));
out.write(reinterpret_cast<char*>(&(wrap.invoke_count)), sizeof(wrap.invoke_count));
return out;
}
istream& operator>>(istream& in, rng_wrap& wrap)
{
wrap = rng_wrap(in);
return in;
}
void test(rng_wrap& rngw, int count, bool quiet=false)
{
uniform_int_distribution<int> integers(0, 9);
uniform_real_distribution<double> doubles(0, 1);
normal_distribution<double> stdnorm(0, 1);
if (quiet) {
for (int i = 0; i < count; ++i)
integers(rngw);
for (int i = 0; i < count; ++i)
doubles(rngw);
for (int i = 0; i < count; ++i)
stdnorm(rngw);
} else {
cout << "Integers:\n";
for (int i = 0; i < count; ++i)
cout << integers(rngw) << " ";
cout << "\n\nDoubles:\n";
for (int i = 0; i < count; ++i)
cout << doubles(rngw) << " ";
cout << "\n\nNormal variates:\n";
for (int i = 0; i < count; ++i)
cout << stdnorm(rngw) << " ";
cout << "\n\n\n";
}
}
int main(int argc, char** argv)
{
rng_wrap rngw(123456790ull);
test(rngw, 10, true); // this is just so we don't start with a "fresh" rng
uint64_t seed1 = rngw.seed;
uint64_t invoke_count1 = rngw.invoke_count;
ofstream outfile("rng", ios::binary);
outfile << rngw;
outfile.close();
cout << "Test 1:\n";
test(rngw, 10); // test 1
ifstream infile("rng", ios::binary);
infile >> rngw;
infile.close();
cout << "Test 2:\n";
test(rngw, 10); // test 2 - should be identical to 1
return 0;
}