question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
70,786,374 | 70,786,414 | the result in c flipped to negative number | unsigned int x;
unsigned int y;
x = 0x66;
y = 0x39;
unsigned z;
z = ~x | ~y;
printf("%d\n",z);
my code is like this, and I would like to compute ~x | ~y, I define z as unsigned, but the z is still the negative number. why? and is this the problem in ~x, so what is the ~x operation in computer.
thank you
| You are telling printf to print a signed input, so it will interpret its input accordingly. Try printf("%u\n", z);.
|
70,786,406 | 70,786,525 | A C++ Program which works fine in online compilers and linux operating systems, but not on Windows | While compiling a problem:
Geeks For Geeks: First Repeating Element on a Windows operating system I noticed that I was not getting any output for my solution. But when I compiled the same code on a Linux operating system and on online compilers, it worked absolutely fine without producing any errors.
Code:
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin>>n;
int arr[n];
for(int i=0; i <n; i++) {
cin>>arr[i];
}
int size= 1e6+1; // WA on windows
int A[size];
int min_index=INT_MAX;
for(int i=0; i<size; i++) {
A[i]=-1;
}
for(int i=0; i<n; i++) {
if(A[arr[i]]!=-1)
min_index=min(min_index, A[arr[i]]);
else
A[arr[i]]=i;
}
if(min_index==INT_MAX)
cout<<"-1";
else
cout<< min_index+1;
return 0;
}
Sample Test Case:
7
1 5 3 4 3 5 6
Expected output:
2
Output on Windows:
Screenshot
Output on Linux:
Screenshot
Explanation for the program from line 14 of code:
I created an array A of size 1e6+1 to store value i on its arr[i]th index.
Array A was earlier initialized with value -1. It runs for n number of times and variable min_index stores the index of the least repeating number from the array arr.
After initializing smaller values of array int size = 10 and using very small test cases(also max value of arr[i] is lesser than size of A; I realize that the program runs perfectly in Windows.
As far as I understand, Windows might be having some trouble intializing arrays of such large length (Please correct me if I'm wrong). But why isn't it the same in the case of Linux?
| #include <bits/stdc++.h> is not standard C++, hence you should not expect it to be portable.
int arr[n]; is not standard C++. Some compilers offer variable length arrays as extension, but it isnt portable. Same goes for int A[size];.
Sadly most of the C++ code presented on that site is not proper C++ code but some dialect.
For more details see: Why should I not #include <bits/stdc++.h>? and Why aren't variable-length arrays part of the C++ standard?. That Q&As should also explain the standard portable alternatives.
|
70,787,229 | 70,787,312 | Accessing pointers inside class | i am trying to use a pointer variable in a class but instead it gave me an error
Car.cpp:15:16: error: right hand operand to ->* has non-pointer-to-member type 'int *'
return this->*tires;
here is my program
main.cpp
#include <iostream>
#include "Car.h"
using namespace std;
int main(){
int x = 5;
Car honda("honda", &x);
cout << honda.getBrand() << " " << honda.getTires() << endl;
x = 6;
cout << honda.getBrand() << " " << honda.getTires() << endl;
return 0;
}
Car.h
#ifndef CAR_H
#define CAR_H
#include <string>
using namespace std;
class Car {
private:
string brand;
int *tires;
public:
Car(string brand, int *tires);
string getBrand();
int getTires();
};
#endif
Car.cpp
#include "Car.h"
using namespace std;
Car::Car(string brand, int *tires){
this->brand = brand;
this->tires = tires;
}
string Car::getBrand(){
return this->brand;
}
int Car::getTires(){
return this->*tires;
}
on Car.cpp the method Car::getTires lies the error which seems to already be logical, i tried to use this->tires or this->(*tires) but it still gave me error.
| The entire variable is called this->tires, the this referring to the current object and the tires referring to the member itself.
As such, you need to dereference the variable and not 'a part of it`.
Either use:
int Car::getTires(){
return *tires;
}
which works, because the this is implied automatically by the compiler or
int Car::getTires(){
return *(this->tires);
}
return *this->tires; should also work, because the operator precedence puts the -> before the * (meaning it first evaluates the this prior to trying dereferencing the variable). (https://en.cppreference.com/w/cpp/language/operator_precedence)
|
70,787,335 | 70,790,145 | Optimize member function selection at runtime on CPU/GPU | I have the following piece of code that needs to optimized (and be later ported to the GPU through SYCL or ArrayFire):
struct Item {
float value;
int f;
float Func(float);
float Func1(float);
float Func2(float);
float Func3(float);
};
float Item::Func(float v) {
value = v;
switch(f) {
case 1: return Func1(v);
case 2: return Func2(v);
case 3: return Func3(v);
}
return Func1(v);
}
std::vector<Item> items;
AFAIK, on GPUs the function pointer approach is not suitable.
Is there a more performant approach on CPUs and/or GPUs than this one?
| There is a blog post about how to implement an alternative to function pointers using SYCL on this website. The solution uses the template feature and function objects instead. I believe the history of this is that most hardware doesn't support jumping to computed addresses.
|
70,787,594 | 70,788,140 | Assertion failed in imread() function | I'm trying to do a simple template matching with openCV-python, but right in the beginning getting an error.
I've run the following code:
import cv2 as cv
import numpy as np
haystackImg = cv.imread('fullImage.png', cv.IMREAD_UNCHANGED)
needleImg = cv.imread('diamond.png', cv.IMREAD_UNCHANGED)
result = cv.matchTemplate(haystackImg,needleImg, cv.TM_CCOEFF_NORMED)
cv.imshow('result', result)
cv.waitKey() ```
...and I got this error:
[ WARN:0@0.186] global D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp (239) cv::findDecoder imread_('fullImage.png'): can't open/read file: check file path/integrity
[ WARN:0@0.195] global D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp (239) cv::findDecoder imread_('diamond.png'): can't open/read
file: check file path/integrity ython39/python.exe "c:/U
Traceback (most recent call last):
File "[myFilePath]\starting.py", line 8, in <modd file: check file path/ule>
result = cv.matchTemplate(haystackImg,needleImg, cv.TM_CCOEFF_NORMED)
cv2.error: OpenCV(4.5.5) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\templmatch.cpp:588: error: (-215:Assertion failed) corr.rows <= img.rows +
templ.rows - 1 && corr.cols <= img.cols + templ.cols - 1 in function 'cv::crossCorr'
The confusing part of it, that I didn't even have a D: drive, and the module is searching for something on that. I reinstalled it, but it didn't help.
| The problem was, that my source path contained non ASCII characters such as á and é... Created a new location without any non ASCII characters and white-spaces, and it works fine now.
|
70,787,871 | 70,788,350 | The best way to implement cloneable c++ classes? | I have seen solutions (including in this site) to the problem of having to implement a clone method in a class, so it returns a heap-allocated clone of itself even if we only have the Baseclass.
The problem come up when you have to implement in a lot of classes the same method again and again, and I remember a way of doing this when you only have to inherit from a template class (name it Cloneable) so it implements it, but the way i'm trying to do it doesn't work:
template<typename T, typename B> class Cloneable{
public:
B* clone(){return new T(*this);}
};
class Bottom {
public:
virtual void sayhi() = 0;
virtual Bottom* clone() = 0;
};
class Middle: public Cloneable<Middle, Bottom>, public Bottom {
public:
void sayhi() override {cout << "Hi from the Middle" << endl;}
};
//class Top: public Middle ...?
int main() {
Bottom* b1 = new Middle();
b1->sayhi();
delete b1;
}
I remember that the person that showed this to me actually did it with just one argument in Cloneable, but anyways, i would thank any way that you can imagine of doing this.
| You could use the Curious Recurring Template Pattern where a derived class actually derives from an instanciation of it base class depending on itself. Demo:
#include <iostream>
template<typename T>
class Clonable {
public:
T* clone() {
return new T { * static_cast<T *>(this)};
}
};
template<class T>
class Base : public Clonable<T> {
public:
int x = 2;
virtual ~Base() {}
};
class Derived : public Base<Derived> {
public:
int y = 3;
};
int main() {
Base<Derived> *d = new Derived;
static_cast<Derived *>(d)->y = 6;
Derived *c = d.clone(); // we are even cloning from a Base *!
std::cout << c->x << ' ' << c->y << '\n';
delete c;
delete d;
}
It compiles with no warning and correctly outputs 2 6, proving that no slicing occurred.
|
70,788,168 | 70,788,451 | How to make an object take and store an Array of arbitrary, but compile-time known size? | Background
For an embedded project, I want a class that takes a list of structs. This list is known at compile-time, so I shouldn't have to resort to dynamic memory allocation for this.
However, how do I make a struct/class that encapsulates this array without having to use its size as a template parameter?
Templates
My first idea was to do exactly that:
struct Point {
const uint16_t a;
const double b;
};
template<size_t n>
struct Profile {
Array<Point, n> points;
Profile(const Array<Point, n> &points) : points(points) {}
};
Here, Profile is the class that stores/encapsulates the array of points (the 2-member structs). n, the size of the array, is a template parameter.
I'm using this implementation of Array, similar to std::array, btw, because I don't have access to the STL on this embedded platform.
However, no I have another class that uses this Profile that now also has to be templated because Profile is templated with the size of the array:
template<size_t n>
class Runner {
private:
const Profile<n> profile;
public:
Runner(const Profile<n> &profile) : profile(profile) {};
void foo() {
for(auto point : profile.points) {
// do something
}
}
};
As can be seen, this Runner class operates on a Profile and iterates over it. Having to template Runner is not that much of an issue by itself, but this Runner in turn is used by another class in my project, because this other class calls Runner::foo(). Now I have to template that class as well! And classes that use that class, etc.
That's getting out of hand! What started with just one template parameter to specify the size, now propagates through my entire application. Therefore, I don't think this is a good solution.
Question
Is there a way to 'hide' the size of the array in Profile or Runner? Runner only needs to iterate over it, so the size should in principle only affect its implementation, not its public interface. How would I do that, though?
Also, can I avoid having to manually specify n at all, and just pass an array to Profile's constructor and let the compiler figure out how big it is? At compile-time, of course. I feel like this should be possible (given this array is known at compile-time), but I don't know how exactly.
Other approaches
Macros
I could write a macro like
#define n 12
and include that in both the Profile.h and the place where I instantiate a Profile. This feels dirty though, I and would like to avoid macros.
Vector
I could avoid this fuss by just using a std::vector (or equivalent) instead, but that is allocated at run-time on the heap, which I would like to avoid here since it shouldn't be necessary.
|
Is there a way to 'hide' the size of the array in Profile or Runner?
Yes. The solution is indirection. Instead of storing the object directly, you can point to it. You don't need to know the size of what you're pointing at.
A convenient solution is to point into dynamic storage (for example std::vector) because it allows you to "bind" the lifetime of the dynamically sized object to a member. That's not necessary in general, and you can use automatic storage instead. However, in that case you cannot bind the lifetime of the pointed object, and you must be very careful to not let the pointed object be destroyed before you stop using it.
The indirection can be done at whatever level you prefer. If you do it at the lowest level, you simply store the array outside of Profile. In fact, if all that profile does is contain an array, then you don't need a class for it. Use a generic span:
struct Runner {
span<const Point> profile;
void foo() {
for(auto point : profile) {
// do something
}
}
};
Point points[] {
// ... number of points doesn't matter
};
Runner runner {
.profile = points,
};
By span, I mean something like std::span. If you cannot use the standard library, then use another implementation. It's basically just a pointer and size, with convenient template constructor.
To clarify, you can pick any two, but you cannot have all three of these:
Lifetime of the array bound to the class (safe)
No compiletime constant size
No dynamic storage
1,2 (no 3) = std::vector, RAII
1,3 (no 2) = std::array, templates, no indirection
2,3 (no 1) = std::span, be careful with lifetimes
|
70,788,173 | 71,668,088 | Eigen static lib memory align | I am using C++17, GCC 7.4.0, Eigen 3.3.4
This is my minimal example. I have 2 classes: B and C. C is in a static library.
The program crashes with Segmentation Fault when trying to create an instance of B.
Static library is built with optimizations (Build Type: Release). If built without optimizations, the program does not crash.
The program only crashes when it's run in Debug. If I run it in Release, it does not crash.
main.cpp
#include "B.h"
using namespace std;
int main() {
B b; // Program crashes here
return 0;
}
B.h
#pragma once
#include "C.h"
using namespace std;
class B {
public:
C c;
B();
~B();
};
B.cpp
#include "B.h"
#include <iostream>
B::B() {
cout << (uint64_t)this << endl; // This is never printed. Program crashes before this gets printed
}
B::~B() {
}
C.h
#pragma once
#include <vector>
#include <eigen3/Eigen/Core>
#include <eigen3/Eigen/Geometry>
using namespace std;
using namespace Eigen;
class C {
public:
Quaterniond q;
Vector3d v;
C();
~C();
};
C.cpp -- this is packed into a static library
#include "C.h"
C::C() {
v = Matrix<double, 3, 1>{0, 0, 0};
Eigen::AngleAxisd y90(M_PI / 2, Eigen::Vector3d::UnitY());
q = Quaterniond(y90);
}
C::~C() {
}
Also, if I remove Quaterniond q from the class C, re-build the static lib, and run the program, it does not crash.
EDIT:
This looks to me connected to Eigen memory alignment issues.
But, as it says in the link, I should not experience these issues since I am using C++17.
Anyways, according to @mmomtchev suggestion, I modified my code like this:
C.h -- modified
#pragma once
#include <vector>
#include <eigen3/Eigen/Core>
#include <eigen3/Eigen/Geometry>
using namespace std;
using namespace Eigen;
class C {
public:
Matrix<double, 3, 1, Eigen::DontAlign> v;
Quaternion<double, Eigen::DontAlign> q;
C();
~C();
};
And the program doesn't crash. So this supports my theory... It could be simply that one is not safe with C++17 if using static libs.
EDIT 2:
I posted a continuation here. I wasn't sure whether this is the same or a different problem.
| Judging from your comments at your other post, you might be using different architecture options while compiling the library and the executable (-m... flags for gcc)?
At least, I could reproduce the crash using Eigen 3.3.4 when I compiled the static library in gcc-7.5.0 with the flags -O0 -DNDEBUG -g -std=c++17 -mavx, while the executable is built with -O0 -DNDEBUG -g -std=c++17. This results in a segmentation fault in _mm256_store_pd(), which gets called when Eigen tries to assign a new value to C::q in the line q = Quaterniond(y90); in C::C().
The crash is not completely deterministic.
The crash has the following reason: Object B and thus also its member c is created on the stack in the main executable. Its alignment is enforced by Eigen to a certain value. See the specialization of plain_array in Eigen. That value depends on the active architecture. Without any special flags it is 16 bytes, so the address of the local variable b is e.g. 0x7fffffffe670, and thus also of B::c, and thus also of C::q (all of them are the first members).
Then the code assign a new value to C::q from within the static library which was compiled with AVX in my example. Thus, it uses the AVX instruction _mm256_store_pd() for this, which requires 32 byte alignment. But the address 0x7fffffffe670 is only 16 byte aligned, not 32. Therefore, it causes a segmentation fault.
For me, sometimes the local variable happens to be 32 byte aligned, sometimes not. No idea what this depends on.
The macro EIGEN_MAKE_ALIGNED_OPERATOR_NEW does not help here, because no dynamic memory allocation is involved. In fact, it wouldn't help anyway: In your other post the code involves dynamic memory allocations, but as explained there, you once again run into mismatching assumptions of alignment when the architectures are different.
The optimization level should have nothing to do with the problem, and AFAIK gcc does not automatically use different target architectures at different optimization levels. It also should have nothing to do with C++17 specifically as Eigen is using compiler specific attributes to align the data on the stack correctly.
The solution is to ensure that you compile the static library and the executable with the same architecture flags.
|
70,788,208 | 70,788,825 | Ending a loop on time expiration | I have a long computation in a loop, which I need to end prematurely if allowed compute time expires (and return a partially computed result). I plan to do it via SIGALARM handler and a timer:
// Alarm handler will set it to true.
bool expired = false;
int compute ()
{
int result;
// Computation loop:
for (...) {
// Computation here.
if (expired)
break;
}
return result;
}
My question is: how to correctly define the expired variable (volatile bool or std::atomic<bool>, or std::sig_atomic_t, etc), how to set it true in the signal handler (just an assignment or atomic operation), and how to check its value in the compute function?
This is a single-threaded C++17 code...
| If you aren't using multiple threads, you don't need an atomic operation. Just set the global variable expired = true in the signal handler.
EDIT: as @Frank demonstrated below, the compiler might optimize it out. You can avoid this by declaring expired as volatile bool expired = false;
|
70,788,244 | 70,788,927 | Do I need to/How to free wstring, wstringstream, vector | Here is my working code. Do I need to clear or free wstring, wstringstream, vector in the func()? If so, how? I see there is a .clear() function for the vector and wstring and wstream.
This sample program is to show the code. I use the wstringstream, wstring, and vector where I have a delimited-string and I need to extract and act on each item in the list.
Any suggestions for optimizing this code and/or doing housekeeping is appreciated too.
#include <windows.h>
#include <strsafe.h>
#include <vector>
#include <sstream>
using namespace std;
void func()
{
WCHAR sComputersInGroup[200] = L"PC1|PC2|PC3|PC4|";
WCHAR sSN[200]{};
wstringstream wSS(sComputersInGroup);
wstring wOut;
vector<wstring> vComputer;
while (wSS.good())
{
getline(wSS, wOut, L'|');
vComputer.push_back(wOut);
}
INT i = 0;
while (i < (INT) vComputer.size())
{
if (vComputer[i].length() > 0)
{
StringCchCopy(sSN, 16, vComputer[i].c_str());
}
i++;
}
}
int main()
{
for (INT i=0;i<20000;i++)
func();
}
| Most containers in C++ have two quantities. A size (how much it holds) and capacity (how much it already has allocated). vector::resize for example, changes the size, but will not alter the capacity unless required. vector::reserve changes the capacity, but the size.
By convention, all C++ objects free resources, including memory, when they are deleted. If you need more control, you can use the resize/reserve functions to manually manipulate memory. You can also "move" the memory out of the object to make it live longer than the object itself.
However, by default, C++ will allocate/free memory all by itself (easy to use/hard to misuse).
|
70,788,871 | 70,789,245 | boost::pfr with customized member | I'm trying to use boost::pfr for basic reflection, and it fails to compile when one of the member is customized type, like a class or struct, why is this? What's the way to fix it? I'm using C++17.
// this works:
struct S1 {
int n;
std::string name;
};
S1 o1{1, "foobar"};
std::cout << boost::pfr::io(o1) << '\n';
// but this does not work:
struct S2 {
int m;
S1 s1; // <===== this fields fails to compile
};
S2 o2;
std::cout << boost::pfr::io(o2) << '\n';
| You need to provide operator<< for S1, as boost::pfr::io relies on it existing:
std::ostream& operator<<(std::ostream& os, const S1& x)
{
return os << boost::pfr::io_fields(x);
}
live example on godbolt.org
|
70,789,279 | 70,789,414 | create vector of array of string and void function pointer in c++ | how to create an array or vetor like this in python:
this program in python:
a = [["foo",foofunc]["bar",barfunk]]
an array (or any thing) with another multi type array in,
| I think you're looking for a vector of pair<std::string, void (*)() as shown below:
#include <iostream>
#include <utility>
#include <string>
#include <vector>
void foofunc()
{
std::cout<<"foofunc called"<<std::endl;
//do something here
}
void barfunc()
{
std::cout<<"barfunc called"<<std::endl;
//do something here
}
int main()
{
//create a vector of pair of std::string and pointer to function with no parameter and void return type
std::vector<std::pair<std::string, void (*)()>> a;
//add elements into the vector
a.push_back({"foo", &foofunc});
a.push_back({"bar", &barfunc});
//lets try calling the functions inside the vector of pairs
a[0].second();//calls foofunc()
a[1].second(); //calls barfunc()
return 0;
}
The output of the above program can be seen here.
|
70,789,891 | 70,832,078 | C++ bit field member variable initialization value (UE4 example) | I'm wondering what value a bit-field class member variable will have if it is not explicitly initialized.
Using an example from unreal engine 4.27:
//member variable of UPrimitiveComponent
//there are other uint8 bitfields declared above and below this
UPROPERTY(...some UE4 macro stuff...)
uint8 bCastHiddenShadow:1;
It is not explicitly initialized in the header, the constructor member initializer list or the constructor body. Yet it seems to get initialized to 0 fine. For a non-bitfield variable I think this would be undefined behaviour, but I assume this isn't the case here? Or does the value depend on the initialization of nearby packed bit-field variables (some of which are explicitly initialized)?
(Or, not sure if the UPROPERTY macro is somehow doing some magic to initialize it? Apologies, couldn't find a full definition of the macro anywhere)
| Dug a little bit deeper, so I'll try to answer this myself. I believe that for a normal C++ class it would be undefined behaviour as I cannot find any info suggesting otherwise for bit-fields specifically.
For the UE4 example, most objects in the engine including the cited UPrimitiveComponent example are derived from UObject, and I did find deep in the documentation that these are automatically zero initialized:
Automatic Property Initialization
UObjects are automatically zeroed on initialization, before the constructor is called. This happens for the whole class, UProperties and native members alike. Members can subsequently be initialized with custom values in the class constructor.
https://docs.unrealengine.com/4.27/en-US/ProgrammingAndScripting/ProgrammingWithCPP/UnrealArchitecture/Objects/Optimizations/
In the code this will happen in StaticAllocateObject in UObjectGlobals.cpp, the memory is earlier malloc'd and then FMemory::Memzero is called which ultimately uses memset to zero the memory
|
70,790,295 | 70,791,947 | Is there a way in gmock to return modified input arg without invoke? | I want to do something like this:
EXPECT_CALL(*mock, method(5)).WillOnce(Return(arg1 * 2));
where arg1 should be equal to first arg of called method. Is there a way to do that without testing::Invoke?
| Method 1:
You can use a custom matcher, as the other answer mentioned, however, notice that the preferred way of using custom matchers is by using functors, not the ACTION macro (See here).
Here is an example:
// Define a functor first:
struct Double {
template <typename T>
T operator()(T arg) {
return 2 * (arg);
}
};
TEST(MyTest, CanDoubleWithFunctor) {
MyMock mock;
// Use the functor in the test:
EXPECT_CALL(mock, method(5)).WillOnce(Double{});
EXPECT_EQ(mock.method(5), 10);
}
See a working example here: https://godbolt.org/z/h4aaPdWMs
Method 2:
Besides the custom matcher, you can use WithArg see here, and pass the first argument to it, which will then be passed to a function that takes one argument. This function can be standalone, or a lambda function:
class MyMock {
public:
MOCK_METHOD(int, method, (int), ());
};
TEST(MyTest, CanDouble) {
MyMock mock;
EXPECT_CALL(mock, method(5)).WillOnce(WithArg<0>([](int x) {
return x * 2;
}));
EXPECT_EQ(mock.method(5), 10);
}
See this working example.
|
70,790,551 | 70,790,939 | Clip Space in OpenGL and DirectX 12 | I am implementing a custom mathematics library to create model, view and projection matrices in OpenGL and DirectX. I am doing this, to improve my understanding in the mathematics behind 3D applications.
At first I took a look at right-handed and left-handed coordinate systems. I realized, that if I create my view matrix as well as my projection matrix with the same handedness, the scene renders correctly no matter if I use OpenGL or DirectX (except inverted translation/rotation/etc.). This is a bit confusing because every article I read pointed out, that OpenGL uses a right-handed and DirectX a left-handed coordinate system. Is my assumption right, that the coordinate system completely depends on the handedness of the view and projection matrices?
When I took a look at clip spaces, things became more difficult to understand. The articles stated, that the clip volume on the X and Y axis ranges from -1.0 to 1.0 in both APIs. On the Z axis OpenGL clips from -1.0 to 1.0 and DirectX clips from 0.0 to 1.0. However, in OpenGL the scene renders correctly no matter if I use a projection matrix for clipping between -1.0 and 1.0 or 0.0 and 1.0. In DirectX only the projection matrix for clipping between 0.0 and 1.0 works. If I use the other one, nothing is rendered.
So my question to this topic is: Can the clipping volume be changed on the Z axis or are those fixed implementations. If they are fixed, then why can I use both types of clipping volumes in OpenGL and only a single one in DirectX?
|
However, in OpenGL the scene renders correctly no matter if I use a projection matrix for clipping between -1.0 and 1.0 or 0.0 and 1.0. In DirectX only the projection matrix for clipping between 0.0 and 1.0 works
OpenGL renders because [0.0, 1.0] falls within the range [-1.0, 1.0], but DirectX does not because [-1.0, 1.0] can fall outside of [0.0, 1.0]. If you invert the depth of your test scene, you'll likely be able to see stuff in DirectX using the wrong projection matrix.
Can the clipping volume be changed on the Z axis or are those fixed implementations. If they are fixed, then why can I use both types of clipping volumes in OpenGL and only a single one in DirectX?
No, you can't change that behavior as it's part of the spec. The point of all the transformations you do as part of the rendering pipeline is to get your scene into clipping space. That means, for example, mapping your scene's depth from [-9999, 9999] down to [-1.0, 1.0] for OpenGL, or [0.0, 1.0] for DirectX
Is my assumption right, that the coordinate system completely depends on the handedness of the view and projection matrices?
Not sure what you're asking here. You already observed that a scene in OpenGL looks inverted in DirectX if you don't account for the difference in handedness. The view and projection matrix that your application uses doesn't change the behavior of the OpenGL and DirectX implementations.
|
70,790,637 | 70,805,372 | MFGetService doesnt get IMFSimpleAudioVolume on first try | I am playing a mp3 file with windows media foundation and try to set the volume but when i try to get IMFSimpleAudioVolume interface it takes a seemingly random amount of tries to do so. I have got 1 through 200ish tries.
I tried using IMFAudioStreamVolume but the results are the same
Here is the main.cpp
#include <iostream>
#include <windows.h>
#include <mfapi.h>
#include <mfidl.h>
#include <winrt/base.h>
#pragma comment (lib, "Mfplat.lib")
#pragma comment (lib, "Mfuuid.lib")
#pragma comment (lib, "Mf.lib")
#pragma comment (lib, "Winmm.lib")
template <class T>
using comptr = winrt::com_ptr<T>;
void AddBranchToTopology(comptr<IMFTopology> topology, comptr<IMFMediaSource> mediaSource, comptr<IMFPresentationDescriptor> presentationDesc);
int main()
{
MFStartup(MF_VERSION);
HRESULT hr = S_OK;
comptr<IMFMediaSession> mediaSession;
hr = MFCreateMediaSession(NULL, mediaSession.put());
comptr<IMFSourceResolver> sourceResolver;
MFCreateSourceResolver(sourceResolver.put());
comptr<IMFMediaSource> mediaSource;
MF_OBJECT_TYPE objType = MF_OBJECT_INVALID;
{
comptr<IUnknown> unknown;
hr = sourceResolver->CreateObjectFromURL(L"<file path>",
MF_RESOLUTION_MEDIASOURCE, NULL, &objType, unknown.put());
mediaSource = unknown.as<IMFMediaSource>();
unknown.detach();
}
comptr<IMFPresentationDescriptor> presentationDesc;
hr = mediaSource->CreatePresentationDescriptor(presentationDesc.put());
comptr<IMFTopology> topology;
hr = MFCreateTopology(topology.put());
AddBranchToTopology(topology, mediaSource, presentationDesc);
mediaSession->SetTopology(NULL, topology.get());
comptr<IMFSimpleAudioVolume> simpleVolume;
DWORD tries = 0;
while (!simpleVolume)
{
hr = MFGetService(mediaSession.get(), MR_POLICY_VOLUME_SERVICE, IID_PPV_ARGS(simpleVolume.put()));
tries++;
}
std::cout << tries << "\n";
PROPVARIANT var;
PropVariantInit(&var);
var.vt = VT_EMPTY;
mediaSession->Start(&GUID_NULL, &var);
simpleVolume->SetMasterVolume(0.5f);
while (true)
{
if (GetAsyncKeyState(VK_ESCAPE) & 1)
{
break;
}
}
mediaSession->Shutdown();
mediaSource->Shutdown();
MFShutdown();
return 0;
}
void AddBranchToTopology(comptr<IMFTopology> topology, comptr<IMFMediaSource> mediaSource, comptr<IMFPresentationDescriptor> presentationDesc)
{
comptr<IMFStreamDescriptor> streamDesc;
comptr<IMFTopologyNode> sourceNode;
comptr <IMFTopologyNode> outputNode;
comptr<IMFActivate> activate;
BOOL selected = FALSE;
HRESULT hr = S_OK;
hr = presentationDesc->GetStreamDescriptorByIndex(0, &selected, streamDesc.put());
hr = MFCreateAudioRendererActivate(activate.put());
hr = MFCreateTopologyNode(MF_TOPOLOGY_SOURCESTREAM_NODE, sourceNode.put());
hr = sourceNode->SetUnknown(MF_TOPONODE_SOURCE, mediaSource.get());
hr = sourceNode->SetUnknown(MF_TOPONODE_PRESENTATION_DESCRIPTOR, presentationDesc.get());
hr = sourceNode->SetUnknown(MF_TOPONODE_STREAM_DESCRIPTOR, streamDesc.get());
hr = topology->AddNode(sourceNode.get());
hr = MFCreateTopologyNode(MF_TOPOLOGY_OUTPUT_NODE, outputNode.put());
hr = outputNode->SetObject(activate.get());
hr = outputNode->SetUINT32(MF_TOPONODE_STREAMID, 0);
hr = outputNode->SetUINT32(MF_TOPONODE_NOSHUTDOWN_ON_REMOVE, FALSE);
hr = topology->AddNode(outputNode.get());
hr = sourceNode->ConnectOutput(0, outputNode.get(), 0);
activate->ShutdownObject();
}
| IMFMediaSession::SetTopology is asynchronous, so you'd want to sync before asking for service.
This method is asynchronous. If the method returns S_OK, the Media Session sends an MESessionTopologySet event when the operation completes.
mediaSession->SetTopology(NULL, topology.get());
// INSERT BEGIN //
// https://learn.microsoft.com/en-us/windows/win32/medfound/mesessiontopologyset
auto const MediaEventGenerator = mediaSession.as<IMFMediaEventGenerator>();
for(; ; )
{
winrt::com_ptr<IMFMediaEvent> MediaEvent;
winrt::check_hresult(MediaEventGenerator->GetEvent(0, MediaEvent.put()));
MediaEventType Type;
winrt::check_hresult(MediaEvent->GetType(&Type));
//std::cout << Type << std::endl;
if(Type == MESessionTopologySet)
break;
}
// INSERT END //
comptr<IMFSimpleAudioVolume> simpleVolume;
This is just for illustration, in real code you would want to subscribe to events and handle asynchronously (see e.g. Media Foundation samples).
|
70,791,122 | 70,791,157 | How do C++ compilers handle malloc failures during new operator? | C++ compilers implement new Obj as a wrapper to malloc(sizeof(Obj)). But malloc can fail! What code do C++ compilers insert to handle the failures, and what does it do?
| C++ standard says about the behaviour:
[basic.stc.dynamic.allocation]
An allocation function that has a non-throwing exception specification ([except.spec]) indicates failure by returning a null pointer value.
Any other allocation function never returns a null pointer value and indicates failure only by throwing an exception ([except.throw]) of a type that would match a handler ([except.handle]) of type std::bad_alloc ([bad.alloc]).
In the non-throwing case, there is no handling needed because returning null is exactly how malloc signifies failure.
In the throwing case, a language implementation that wraps malloc has to check whether the allocation was successful, and throw if it wasn't.
|
70,791,164 | 70,791,390 | Why was it nessesury to allow std::move accept reference to lvalue besides reference to rvalue in Uref embodiment for both? | Considering that rvalue-ness and lvalue-ness are not a features of objects but of expressions.
Why isn't std::move implemented only for lvalue reference argument, but for universal one? Whereas it is useful only for retrieving rvalue reference from an lvalue? When rvalue is rvalue already and it does not need std::move functionality.
template <typename T>
typename std::remove_reference_t<T>&& move(T&& x)
{
return static_cast<std::remove_reference_t<T>&&>(x);
}
|
Why isn't std::move implemented only for lvalue reference argument, but for universal one?
Because lvalue references to non-const cannot be bound to xvalues.
When rvalue is rvalue already and it does not need std::move functionality.
We want std::move(some_expression) to work whether some_expression is an rvalue expression or lvalue expression. That is particularly important in templates where that detail can depend on template arguments and we don't want to write separate specialisations for each.
Basically same reason as why these are allowed:
using T = const U;
const T var;
using S = T&;
S& ref = var;
In this case, we want to be able to declare const T var, and S& whether the types are already const/reference or not.
|
70,791,675 | 70,792,331 | Append bin folder to PATH environement variable after installation | I have done a C++ program for Windows and an NSIS installer using CPack.
I want that after the installation, the user can call my program from the terminal without giving the whole path of the exe.
Sometimes some installers even add an Add useful environment variables checkbox at the end of the installation to give the user a choice.
Is it possible to add to the PATH environment variable the path to our bin folder at the end of the installation using CPack and NSIS Generator?
If this is not possible, how do other programs add environment variables during installation?
| As always, check the documentation... https://cmake.org/cmake/help/latest/cpack_gen/nsis.html
CPACK_NSIS_MODIFY_PATH
Modify PATH toggle. If this is set to ON, then an extra page will appear in the installer that will allow the user to choose whether the program directory should be added to the system PATH variable.
Note that this is hard-coded to be the $INSTDIR\bin path and is not configurable. In particular, setting CMAKE_INSTALL_BINDIR to anything other than bin will break.
|
70,792,064 | 70,792,210 | What is the purpose of 'flag' in a prime number program? | I saw this code from a website and there wasn't any explanation behind or specifically the purpose of the flag line.
#include <iostream>
using namespace std;
int main()
{
int n, i, m = 0, flag = 0;
cout << "Input a number: ";
cin >> n;
m = n / 2;
for(i = 2; i <= m; i++)
{
if(n % i == 0)
{
cout << "Input is not a prime number." << endl;
flag = 1;
break;
}
}
if (flag == 0) {
cout << "Input is a prime number." << endl;
}
return 0;
}
P.S. It's a rookie question.
| Since that loop can exit for 2 reasons
the number is not prime (there is a break statement)
once i reaches m (the for loop terminates)
the code after the loop needs to know which exit happened so that it can say that the number is prime if it exited for the second reason. A more canonical way to do it is
for(i = 2; i <= m; i++)
{
if(n % i == 0)
{
cout << "Input is not a prime number." << endl;
break;
}
}
if (i > m) {
cout << "Input is a prime number." << endl;
}
ie look at the loop condition variables and see if the loop exit condition happened
of at least use a bool with a good name
bool not_prime = false;
|
70,792,489 | 70,793,147 | What is the last parameter in VirtualProtect used for? | I want to use both VirtualAlloc and VirtualProtect to inject a shellcode into the local process but I can't figure out what is the last argument (lpflOldProtect) and how do I declare it.
void fun()
{
size_t dwSize = 511; // size of shellcode
LPVOID base_add = VirtualAlloc(NULL , dwSize , MEM_RESERVE, PAGE_NOACCESS);
if (base_add == NULL )
{
cout << "Failed to allocate space " << endl;
return ;
}
LPVOID end_add = base_add + dwSize;
// change mem protection option
PDWORD lpflOldProtect = 0;
bool change_protection = VirtualProtect(base_add,dwSize,PAGE_EXECUTE_READWRITE, lpflOldProtect );
if (change_protection)
{
cout << "Successfully changed protection" << endl;
}
else
{
cout << " Failed" << endl;
}
}
According to Microsoft documentation, the last parameter in VirtualProtect is:
A pointer to a variable that receives the previous access protection value of the first page in the specified region of pages. If this parameter is NULL or does not point to a valid variable, the function fails.
What do they mean by this? What is the value of the first page in the specified region? Isn't that the base address?
| The fourth (last) argument to the VirtualProtect function should be the address of a DWORD variable in which to receive the value of the previous protection flags for the memory block (or, to be exact, the first page of that block). You can use this, should you desire, to 'reset' that protection level when you're done doing whatever it is for which you need to change that protection.
In your code, you are declaring a pointer in the PDWORD lpflOldProtect = 0; line and assigning that pointer a NULL (zero) value – so, as per the document you linked, your call to VirtualProtect will fail.
Instead, you should declare an actual DWORD variable and pass the address of that variable as the last argument. In your case, the modified code will look something like this:
DWORD flOldProtect = 0;
BOOL change_protection = VirtualProtect(base_add, dwSize, PAGE_EXECUTE_READWRITE, &flOldProtect);
// Pass address of the DWORD variable ^
if (change_protection)
{
//...
Note that, in the linked document, the last argument is marked as [out] – which means that its value before the call is not used by the function, so you don't really need to initialize it; however, some compilers and/or code analysers may complain about using an uninitialized value, which is why I set it to zero.
Also note that the return value of the function is of type BOOL (declared in the Windows system headers as typedef int BOOL;), not bool; in most cases, the implicit cast your code makes won't cause any problems but, again, some compilers may issue a warning about that conversion.
|
70,792,553 | 70,792,888 | Exe not working properly outside of visual studio? | My program runs fine in the IDE (Visual Studio 2022), in debug and release modes.
When I make a build and want to start the .exe from Explorer, it starts and runs, but... well, have a look:
This is how it should be:
This is what it looks like outside of VS:
So far, I have tried to set the Runtime Library to Multi-threaded (/MT), but that didn't work.
Otherwise, I really don't seem to find much. It seems the standalone .exe is missing some dependencies, but I can't figure out what I need to do. From my understanding, everything I have included in the header should get compiled "into" the .exe as well.
The int128_t doesn't seem to work. Neither do the ANSI color codes.
The timer is working, though.
The code:
#include <iostream>
#include <chrono>
#include <boost/multiprecision/cpp_int.hpp>
namespace mp = boost::multiprecision;
bool isPrime(mp::int128_t n);
mp::int128_t n{ 0 }, y{ 0 };
int main()
{
std::cin >> y;
std::cin >> n;
std::cout << "\n";
for (y; y <= n; y++)
{
int lengthy = to_string(y).length();
const auto start = std::chrono::steady_clock::now();
if (isPrime(y) == true)
std::cout << "\033[1;7;32m" << std::setw(lengthy) << std::left << y << "\033[0m ";
else
{
std::cout << std::setw(lengthy) << std::left << y << " ";
}
const auto end = std::chrono::steady_clock::now();
std::chrono::duration<double> elapsed = end - start;
if (elapsed.count() >= 0.1)
std::cout << "\033[1;7;36m" << std::setw(10) << std::left << elapsed.count() << "\033[0m ";
else
{
std::cout << "\033[1;36m" << std::setw(10) << std::left << elapsed.count() << "\033[0m ";
}
}
std::cout << "\n";
std::cin >> y;
}
bool isPrime(mp::int128_t n)
{
if (n == 2 || n == 3)
return true;
if (n <= 1 or n % 2 == 0 or n % 3 == 0)
return false;
for (uint64_t i = 5; i * i <= n; i += 6)
{
if (n % i == 0 or n % (i + 2) == 0)
return false;
}
return true;
}
| See https://en.wikipedia.org/wiki/ANSI_escape_code, specifically:
In 2016, Microsoft released the Windows 10 version 1511 update which unexpectedly implemented support for ANSI escape sequences, over two decades after the debut of Windows NT.[13] This was done alongside Windows Subsystem for Linux, allowing Unix-like terminal-based software to use the sequences in Windows Console. Unfortunately this defaults to off, but Windows PowerShell 5.1 enabled it. PowerShell 6 made it possible to embed the necessary ESC character into a string with `e.[14] Windows Terminal, introduced in 2019, supports the sequences by default, and Microsoft intends to replace the Windows Console with Windows Terminal.[15]
Color codes work in Visual Studio Code (Terminal).
ADDITIONAL INFO:
https://devblogs.microsoft.com/commandline/new-experimental-console-features/
|
70,792,678 | 70,792,679 | Can C++ coroutines contain plain `return` statements? | I am writing a C++ coroutine for a UWP control using C++/WinRT:
winrt::fire_and_forget MyControl::DoSomething()
{
if (/* some condition */)
{
// Why does this work?!
return;
}
co_await winrt::resume_foreground(Dispatcher());
// Do some stuff
co_return;
}
This is compiling for me, but as far as I know, C++ coroutines do not allow plain return statements. Is this a bug in the compiler?
(Interestingly, I cannot change the co_return to return; I get a compiler error. Is it that only return statements after a co_await or co_yield must be co_return?)
| This seems to be a legacy implementation for MSVSC. MSVSC implemented coroutines before the standard was formally complete, so there are two implementations of async (/async and /async:strict). I seem to have the old, non–standard-compliant version turned on.
The standard is clear that you cannot use plain return statements in coroutines (emphasis added):
Coroutines cannot use variadic arguments, plain return statements, or placeholder return types (auto or Concept). Constexpr functions, constructors, destructors, and the main function cannot be coroutines.
— https://en.cppreference.com/w/cpp/language/coroutines
You can verify that this is a legacy behavior with a simple example (view in Godbolt):
// ... boilerplate to make std::futures awaitable ...
// via https://stackoverflow.com/a/70406948/788168
std::future<int> compute_value()
{
if (rand() > 5)
{
// Shouldn't work:
return 5;
}
int result = co_await std::async([] { return 30; });
co_return result;
}
int main() {
compute_value();
}
With the x64 msvc v19.latest compiler and the /std:c++20 flag, we get this error:
example.cpp
<source>(38): error C3773: Use of 'return' in this context is a non-conforming extension in C++20
<source>(38): note: Please use '/await' command-line option to enable relevant extensions
Compiler returned: 2
So, to answer the questions:
This is compiling for me, but as far as I know, C++ coroutines do not allow plain return statements. Is this a bug in the compiler?
(Interestingly, I cannot change the co_return to return; I get a compiler error. Is it that only return statements after a co_await or co_yield must be co_return?)
It's not a bug in the compiler, it's just a non-standard implementation. If you use the standard implementation (with /async:strict or /std:c++20), that plain return statement will not compile. Standards-compliant coroutines cannot use plain return statements, ever.
|
70,792,911 | 70,792,996 | Generalize integral template parameters | Is there a way to generalize an integral template parameter so that it supports e.g. int and std::size_t. Here is non-compiling example of what I have in mind. Is there a way to implement the function f without adding a copy of it that takes std::size_t as a parameter?
#include <cstddef>
#include <iostream>
template <int N>
struct foo {
static constexpr int n = N;
int a[N];
};
template <std::size_t N>
struct bar {
static constexpr int n = N;
float a[N];
};
template <template<int> typename T, int N>
void f(T<N> t) {
std::cout << T<N>::n << " - " << N << std::endl;
}
int main() {
bar<10> B;
foo<20> F;
f(B);
f(F);
}
| Since c++17 you can use auto for non-type template parameters.
template <template<auto> typename T, auto N>
...
|
70,793,143 | 70,793,297 | Return with aggregate initialization without type name | In C++ 20, for a type like this:
struct Person {
std::string name;
int age;
};
We can return it from a function using aggregate initialization, with or without writing out the type name:
Person getJohn()
{
// With type name
return Person {
.name = "John",
.age = 42,
};
// Without type name
return {
.name = "John",
.age = 42,
};
}
What's the difference between specifying and not specifying the type name explicitly? One thing I noticed is that without a type name, if I mess up the field names/order, the error message given by my compiler and IDE is less clear than if I have a type name. But other than that, are the two forms semantically different in any way?
| They should always be equivalent. A return statement performs copy-initialization ([stmt.return]/2). A copy-initialization from a designated-initializer-list performs aggregate initialization ([dcl.init.list]/3.1). If the operand is simply the designated-initializer-list itself, we are done. The return object has been aggregate-initialized. If the operand is Person designated-initializer-list, then guaranteed copy elision applies ([dcl.init.general]/16.6.1) which again means that the return object is simply aggregate-initialized (there is no additional temporary object).
Omitting the type can only make a difference in non-aggregate-initialization contexts: if the user-defined constructor selected for the initialization has been declared explicit, the program is ill-formed. But aggregate initialization doesn't use a constructor.
|
70,793,440 | 70,849,917 | An auto-scaled on-off background image in a QLineEdit | I have a couple of QLineEdit widgets that need to have their backgrounds appear and disappear upon certain code changes, and need those backgrounds to also rescale when widget size changes.
I am getting quite lost in all the stackoverflow and documentation on the Qt website. My main point of confusion is how I register only specific widgets with a paintEvent function I make.
In pseudo-ish code, I've been led to believe that my auto-scaling background image idea requires some combination of QPainter and QPixmap:
void MyGUI::paintEvent(QWidget mywidget, string path){
QPainter painter(mywidget);
QPixmap _mypix(path);
int widgetHeight = mywidget.height();
int imageHeight = _mypix.height();
float imageratio = _mypix.width()/_mypix.height();
if(imageHeight > widgetHeight){
painter.drawPixmap(0,0,imageratio*widgetHeight, widgetHeight, _mypix);
}
else{ painter.drawPixmap(0,0,_mypix.width(), _mypix.height(), _mypix);}
}
Then in the main UI, I want to call the above function situationally to turn on and off this background image. While the image is on, though, I want it to resize as per the above function (aka depending on its widget's height, not the main GUI height):
Blah blah constructor stuff
{
ui->setupUi(this);
paintEvent(ui->widget1, "path\to\background1.png");
paintEvent(ui->widget2, "path\to\background2.png");
connect(this,SIGNAL(MaybeTurnOffBackground()),this,SLOT(TurnOffBackgroundSometimes(bool)));
}
void MyGUI::TurnOffBackgroundSometimes(bool backgroundOn)
{
if(backgroundOn)
{
paintEvent(ui->widget1, "path\to\background1.png");
paintEvent(ui->widget2, "path\to\background2.png");
}
else{
//something that removes the images
}
}
Hope it's clear enough. I have no idea how to make this type of behavior come about. I get the sense I am somewhat overcomplicating things by using the paintEvent business, but I'm not sure what the alternative is.
| Solved my own problem. Ended up doing it entirely in stylesheets. I don't know what my philosophical opposition was to using image instead of background-image, aside from the worry that it would interact poorly with text that is inputted into the QLineEdit. Thankfully that is not a concern, and text receives the most Z height in the box overall so the image will still appear behind it.
Some answers have specified that you need a border, e.g. "border: 1px solid white". I tested first with border, then without, and it functions the same so I left the border out. YMMV.
#myWidget1{
image: url(":/main/assets/myAsset1.png");
image-position: left;
padding: 5px;
}
Regarding the on-off feature... I'd actually already solved this. I just created a custom property, and toggled it off and on in SLOTS as necessary.
Stylesheet:
#myWidget1{
background:rgba(125,0,0,55);
}
#myWidget1[status="active"]{
image: url(":/main/assets/myAsset1.png");
image-position: left;
padding: 5px;
}
Sample code in a slot:
if(active){
ui->myWidget1->setProperty("status","active");
}
else{
ui->myWidget1->setProperty("status","notactive");
}
The nice thing is I don't actually have to define what style "notactive" takes in the stylesheet. It just defaults to the baseline style.
|
70,793,544 | 70,793,736 | Why in order to use default constructor in Derived Class, we need a default constructor in the Base Class | As you have seen in the title i need to find the error in the code bellow,
Here is what i know:
I know that in order to use default constructor in B, we need a default constructor in A
What i don't know is:
Why? I guess it's because B inherits A but i need to know exactly why exactly
Here is the code:
#include <iostream>
using namespace std;
class A
{
protected:
int i;
public:
A(int i) :i (i) {}
};
struct B : A
{
B() {}
void set(int i) { this-> i = i; }
void print() { cout << i << endl; }
};
int main()
{
B b; b.set(2);
b.print();
}
| I think your title is misleading, but the question is valid.
In order to construct B, A needs to be constructed as well (that you know)
but how can A be constructed without knowing the value of int i in its constructor?
But you could use the parameter-less constructor of B to provide value for i:
struct B : public A {
public:
B(): A(53 /* value for int i */) { }
...
but unless you specify what constructor of A should B use, the compiler will search for the default constructor (which does not exist in A`s case)
|
70,794,146 | 70,794,264 | String name of template function | I know you can use the preprocessor to get the textual name of a standard function at compile time via __func__
My question is, is there any way to get the textual name of a template function including its specific implementation details (mangled is better than nothing)?
For example,
template <typename T>
void myFunction() {
std::cout << //Function name here;
};
Output:
myFunction<int>(); -> "myFunction<int>" (or mangled name)
myFunction<char>(); -> "myFunction<char>" (or mangled name)
| For use with g++ you can use __PRETTY_FUNCTION__.
So for
#include <iostream>
template<typename T>
void myFunction() {
std::cout << __PRETTY_FUNCTION__ << '\n';
};
int main() {
myFunction<int>();
myFunction<char>();
}
I get
void myFunction() [with T = int]
void myFunction() [with T = char]
|
70,794,769 | 70,795,265 | What is the official Rust guidance for interoperability with C++, in particular passing and returning structs as arguments? | I'm trying to adapt some layers of existing C++ code to be used by Rust and apparently the way is through a C API.
For example, one function might return a struct as an object
#pragma pack(push,4)
struct Result {
char ch;
int32_t sum1;
int32_t sum2;
};
#pragma pack(pop)
extern "C"
Result
muladd(int32_t a, int32_t b, int32_t c) {
return Result{1, a+b*c, a*b+c};
}
And from Rust I'm doing
#[repr(C,align(4))]
pub struct Result {
pub ch: i8,
pub sum1: i32,
pub sum2: i32,
}
extern "C" {
pub fn muladd( a:i32, b:i32, c:i32 ) -> Result;
}
pub fn usemuladd( val: i32 ) -> i32 {
unsafe {
let res = muladd( val, val, val );
return res.sum1;
}
}
I'm seeing odd results with respect to alignment and packing of structures. I have read that Rust can play around with structs, and neither ordering or packing are guaranteed.
It seems that using #[repr(C)] and extern "C" is the key to a happy compatibility layer. My question is then: can I trust that these two will get me solid through or there will always be unannounced edge cases that I have to worry about?
https://godbolt.org/z/aEh4jKxxf
| extern "C" on both sides + #[repr(C)] on the Rust side + only using C-compatible types for interfacing between C++ and Rust, should work.
Alternatively, see cxx and autocxx.
|
70,795,082 | 70,795,121 | can someone help me with the #include being nested to deeply error before i go insane? thx | //main.cpp
#include <iostream>
#include <array>
#include <iomanip>
#include "Board.h"
#include "Game.h"
//Player.h
#include <array>
#include <string.h>
#include <random>
#include "Property.h"
#include "Game.h"
#ifndef Player_h
#define Player_h
//Property.h
#include "Space.h" //#include nested too deeply error
#ifndef Property_h
#define Property_h
//Space.h
#include <sstream>
#include <string>
#ifndef Space_h
#define Space_h
//FreeParking.h + a couple others inheriting from space; there's no error in any of these either
#include "Space.h"
#ifndef FreeParking_h
#define FreeParking_h
//Board.h
#include "Player.h"
#include <array>
#include <random>
#ifndef Board_h
#define Board_h
//Game.h
#include <array>
#include "Property.h"
#include "CommunityChest.h"
#include "Tax.h"
#include "FreeParking.h"
#include "Jail.h"
#include "GoToJail.h"
#include "Go.h"
#include "Player.h"
#ifndef Game_h
#define Game_h
I don't think I made any changes to the #includes today but just got this error even though the program was running fine 20 minutes ago. I only posted the includes because I'm not sure if the actual code matters for this error or not. If it does I'll try to go over the stuff I wrote today, but most of it was just changing things that already worked previously.
| Player.h includes Game.h and Game.h includes Player.h. This is an infinite loop. There might be more, but that's just the first one I saw.
You should remove at least one of those includes to break the infinite loop. If you get errors when you do that, you might be able to fix them using a forward declaration that looks something like this:
class Player;
A forward declaration like that would allow you to compile some code that uses the Player class, even though a complete definition of the Player class is not available at that point in the program.
Two more tips to make things more sane:
Put your include guards at the very top of your file before you include anything.
Use #pragma once as the include guard instead of your more complicated thing.
|
70,795,458 | 70,799,685 | Is there a clean way to convert runtime values to compile time values? | I'd like to create a type with non-type parameters based on run-time values, the make_fruit function:
struct IFruit {
// interface
};
enum Species {
Apple,
Orange,
Peach,
};
enum Color {
Red,
Green,
Blue,
Yellow,
};
template <Species S, Color C> struct Fruit : public IFruit {
// impl
};
IFruit* make_fruit(Species s, Color c) {
// return new Fruit<s, c>
}
Is there a clean way to do it? As in, not writing 12 switch cases.
Edit: note: the classes IFruit, Fruit and enums Color, Species are given (by some library) and cannot be modified.
| You can avoid to write the combinatory yourself thanks to std::visit of std::variant (both C++17):
using SpeciesVariant = std::variant<
std::integral_constant<Species, Species::Apple>,
std::integral_constant<Species, Species::Orange>,
std::integral_constant<Species, Species::Peach>
>;
using ColorVariant = std::variant<
std::integral_constant<Color, Color::Red>,
std::integral_constant<Color, Color::Green>,
std::integral_constant<Color, Color::Blue>,
std::integral_constant<Color, Color::Yellow>
>;
SpeciesVariant to_variant(Species s)
{
switch (s) {
case Species::Apple: return std::integral_constant<Species, Species::Apple>{};
case Species::Orange: return std::integral_constant<Species, Species::Orange>{};
case Species::Peach: return std::integral_constant<Species, Species::Peach>{};
}
throw std::runtime_error("Bad argument");
}
ColorVariant to_variant(Color c)
{
switch (c) {
case Color::Red: return std::integral_constant<Color, Color::Red>{};
case Color::Green: return std::integral_constant<Color, Color::Green>{};
case Color::Blue: return std::integral_constant<Color, Color::Blue>{};
case Color::Yellow: return std::integral_constant<Color, Color::Yellow>{};
}
throw std::runtime_error("Bad argument");
}
and finally:
std::unique_ptr<IFruit> make_fruit(Species s, Color c)
{
return std::visit([](auto s, auto c) -> std::unique_ptr<IFruit> {
return std::make_unique<Fruit<s, c>>();
}, to_variant(s), to_variant(c));
}
Demo
|
70,795,472 | 70,795,499 | Issues reading floats from .txt file | I am trying to read a .txt file with some floats into my code.
I wrote a sample code just to tackle the issue outside my main code and I am using the following floats to test it:
10.8f
100.8f
-10.8f
The issue I am running into is that the code only reads in the first float properly and displays it but all the other floats following it do not look correct:
10.8
0
4.57874e-41
Code:
#include<fstream>
#include<iostream>
#include <vector>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
float Cam1,Cam2,Cam3;
string path = "sample.txt"; //Text file with above mentioned floats
ifstream fin;
fin.open(path);
if(fin.is_open())
{
fin >> Cam1;
fin >> Cam2;
fin >> Cam3;
fin.close();
}
cout << Cam1 << '\n';
cout << Cam2 << '\n';
cout << Cam3 << '\n';
}
I really am confused as to why it reads the first properly but not the others, it works when I change the values as well, the above is just one example case. I am fairly new to C++ so any help would be greatly appreciated thank you!
| The f suffix is valid in C++ code, but not in input text parsed by istream. It's useful in code to distinguish between float and double constants, but user input doesn't control variable data types.
|
70,795,510 | 70,796,435 | Create grid of images with increasing grey scale values | I'm trying to write some C++ to create a 1048x1048x8 bit matrix of 256x256 squares. The first should have a grey scale value of 0 while the last should be 255. This is what I've tried so far. Any feedback is appreciated.
First image is my result. Second is the desired.
[1]: https://i.stack.imgur.com/BmGOZ.png
[2]: https://i.stack.imgur.com/FMpi1.png
using namespace std;
#include <fstream>
#include <iostream>
int main()
{
char img[256][256];
ofstream binaryFile("file.raw", ios::out | ios::binary);
if (!binaryFile) {
cout << "cannot create file";
return 1;
}
//create raw file
char color = 0;
//nested for loops to iterate the pixel with varying grey scale values
for (int y = 0; y < 15; y++) {
for (int i = 0; i < 256; i++) {
for (int j = 0; j < 256; j++) {
img[i][j] = color;
}
}
color = color + 15;
for (int i = 0; i < 256; i++) {
img[0][i] = 0;
img[i][0] = 0;
img[255][i] = 0;
img[i][255] = 0;
}
for (int i = 0; i < 256; i++) {
for (int j = 0; j < 256; j++) {
binaryFile.write((char*)&img[i][j], sizeof(img[i][j]));
}
}
}
// end raw file editing
binaryFile.close();
if (!binaryFile.good()) {
cout << "Error occurred at writing time!" << endl;
return 1;
}
}
| So each row of pixels (from left to right) spans 4 different colored squares (4 columns using x), and each square is 256 pixels wide:
for (int x = 0; x < 4; x++) {
for (int j = 0; j < 256; j++) {
// write one pixel here
}
}
Each column of pixels (from top to bottom) also spans 4 different colored squares (4 rows using y), and each square is 256 pixels high:
for (int y = 0; y < 4; y++) {
for (int i = 0; i < 256; i++) {
// inner loop here
}
}
Then all you have to do is to determine the color of each square. The color should advance 1 "increment" of 17 (max color / number of increments = 255 / 15) for each row. And each row should advance the color 4 "increments" of 17.
Now i hear you say, 17? That can't be right. Just hold on a bit longer.
For each column x, increment by 1. And for each row y, increment by 4. That comes down to: x + ( y * 4 ). Apply the increment 17 like we said before, and you get: ( x + ( y * 4 ) ) * 17. Since the * takes precedence over +, the internal brackets ( ) are not needed, leaving just: (x+y*4)*17.
That will make the colors for each square look like this:
Col 0
Col 1
Col 2
Col 3
Row 0
0
17
34
51
Row 1
68
85
102
119
Row 2
136
153
170
187
Row 3
204
221
238
255
See? Nicely spaced colors, starting on 0 and ending on 255.
Putting it all together:
for (int y = 0; y < 4; y++) {
for (int i = 0; i < 256; i++) {
for (int x = 0; x < 4; x++) {
char color = (x+y*4)*17;
for (int j = 0; j < 256; j++) {
binaryFile.put(color);
}
}
}
}
|
70,795,807 | 70,796,103 | STL vector implementation header size | Is there a requirement in C++ that
sizeof(std::vector<T>) == sizeof(std::vector<S>)
where S and T are arbitrary copy-assignable and copy-constructible types? For example, on my 64-bit Windows laptop with GCC we have
sizeof(std::vector<int>) ==
sizeof(std::vector<std::tuple<std::vector<double>,
int, std::map<int, std::string> > >)
== 24
| No, there is no requirement that the size of all std::vector specializations be the same. The compiler is allowed to have different layouts and sizes for different specializations if it wants to.
In practice, one example is vector<bool> which happens to give a different result in at least one instance:
std::cout << sizeof(std::vector<int>); // 24
std::cout << sizeof(std::vector<bool>); // 40
|
70,796,490 | 70,796,619 | Valgrind thinks my std::ranges of raw pointers are leaking, even after they've been copied to unique pointers | I'm trying to load all true-type fonts in a directory using C++20 ranges and functional-style programming. However, since fonts are a resource, I'm allocating memory within the ranges interface. I think this is why valgrind thinks I have a leak. I have a few std::views of freshly allocated raw pointers that eventually get discarded - however, these raw pointers are transformed and copied into a vector of unique pointers.
The code in question:
// free a font resource
struct font_deleter {
void operator()(TTF_Font * font) { TTF_CloseFont(font); }
};
// aliases
using unique_font = std::unique_ptr<TTF_Font, font_deleter>;
using font_table = std::unordered_map<std::string, TTF_Font *>;
template<typename expected_t>
using result = tl::expected<expected_t, std::string>;
// determine if a path is a valid font file
auto _is_font_fxn(std::error_code & ec) {
return [&ec](fs::path const & path) {
return fs::is_regular_file(path, ec) and path.extension() == ".ttf";
};
}
// load a font-name, font-pointer pair from a font file
font_table::value_type _load_as_pair(fs::path const & path)
{
return std::make_pair(path.stem(), TTF_OpenFont(path.c_str(), 100));
}
// create a unique font pointer from a name-pointer pair
unique_font _ufont_from_pair(font_table::value_type const & pair)
{
return unique_font(pair.second, font_deleter{});
}
// determine if a font pointer is null from a name-pointer pair
bool _font_is_null(font_table::value_type const & pair)
{
return pair.second == nullptr;
}
result<std::vector<unique_font>>
button_factory::load_all_fonts(fs::path const & dir)
{
namespace views = std::views;
namespace ranges = std::ranges;
std::error_code ec; // using error codes tells filesystem not to throw
// make sure the path exists and is a valid directory
if (not fs::exists(dir, ec) or not fs::is_directory(dir, ec)) {
std::stringstream message;
if (ec) { message << ec.message(); } // an os call failed
else if (not fs::exists(dir)) { message << dir << " doesn't exist"; }
else if (not fs::is_directory(dir)) { message << dir << " isn't a directory"; }
return tl::unexpected(message.str());
}
// recursively get all paths in directory
std::vector<fs::path> paths(fs::recursive_directory_iterator(dir, ec), {});
// filter only font files and load them as name-font pairs
auto is_font = _is_font_fxn(ec);
auto fonts = paths | views::filter(is_font) | views::transform(&_load_as_pair);
// put all the successfully loaded fonts into a vector of unique pointers
// the font resources are freed automatically if returning unexpected
// otherwise this is the expected result
std::vector<unique_font> font_handle;
auto into_handles = std::back_inserter(font_handle);
ranges::transform(fonts, into_handles, &_ufont_from_pair);
// abort if any os calls failed in the process, or if some fonts didn't load
if (ec) { return tl::unexpected(ec.message()); }
if (ranges::any_of(fonts, &_font_is_null)) { return tl::unexpected(TTF_GetError()); }
// add all the loaded fonts definitions to the button factory
auto into_table = std::inserter(_fonts, _fonts.end());
ranges::copy(fonts, into_table);
return font_handle;
}
As a side note, I'm using TartanLLama's implementation of the proposed std::expected, which is where the tl:: namespace comes from.
I'm getting some gnarly template error messages from valgrind, so I'll try to just share the important bits. 62,000 bytes are lost in two blocks, and while the template error is a nightmare, it seems to all be coming from the ranges interface. It seems like the message in the first block is coming from the call to ranges::any_of and the second one from ranges::copy - both blocks mention _load_pair - I'm guessing as the source of the memory that's leaking.
Is there some reason I'm not seeing about why this might leak memory, or is this a valgrind bug?
| views::transform is lazy - the transform function isn't called until an element of the view is accessed. But that also means that the transform function is called every time an element of the view is accessed.
So every time you iterate through fonts - first for the transform, then for the any_of, and finally for the copy, you are calling _load_as_pair and therefore TTF_OpenFont again - and leaking the result.
|
70,796,803 | 70,798,203 | How to properly increment this 'half-diamond' shape? | I am trying to get the slashes to form a half-diamond type of shape, but I cannot seem to get the incrementation correct. I currently have:
else if (menuOption == 2) {
int numberOfDolls = 0;
cout << "Number of dolls -> ";
cin >> numberOfDolls;
for (int i = 1; i <= numberOfDolls; i++) {
for (int j = 1, n = numberOfDolls; j <= i; j++)
cout << setw(n--) << '/' << endl;
for (int k = 1, s = numberOfDolls; k <= i; k++)
cout << setw(s++) << '\\' << endl;
cout << setw(numberOfDolls + 1) << "-" << endl;
}
}
This yields the following if the user, let's say, inputs 3:
/
\
-
/
/
\
\
-
/
/
/
\
\
\
-
It should look like:
/
\
-
/
/
\
\
-
/
/
/
\
\
\
-
I would greatly appreciate any help as I am new to C++.
| int numberOfDolls = 0;
int deltaIndent = 0;
cout << "Number of dolls -> ";
cin >> numberOfDolls;
for (int i = 1; i <= numberOfDolls; i++) {
deltaIndent = numberOfDolls - i;
for (int j = i; j > 0 ;j--)
cout << setw(j + deltaIndent) << '/' << endl;
for (int j = 1; j <= i ; j++)
cout << setw(j + deltaIndent) << '\\' << endl;
cout << setw(numberOfDolls + 1) << "-" << endl;
}
output
Number of dolls -> 4
/
\
-
/
/
\
\
-
/
/
/
\
\
\
-
/
/
/
/
\
\
\
\
-
|
70,797,019 | 70,797,617 | Is (int)(unsigned)-1 == -1 undefined behavior | I am trying to understand the meaning of the statement:
(int)(unsigned)-1 == -1;
To my current understanding the following things happen:
-1 is a signed int and is casted to unsigned int. The result of this is that due to wrap-around behavior we get the maximum value that can be represented by the unsigned type.
Next, this unsigned type maximum value that we got in step 1, is now casted to signed int. But note that this maximum value is an unsigned type. So this is out of range of the signed type. And since signed integer overflow is undefined behavior, the program will result in undefined behavior.
My questions are:
Is my above explanation correct? If not, then what is actually happening.
Is this undefined behavior as i suspected or implementation defined behavior.
PS: I know that if it is undefined behavior(as opposed to implementation defined) then we cannot rely on the output of the program. So we cannot say whether we will always get true or false.
| Cast to unsigned int wraps around, this part is legal.
Out-of-range cast to int is legal starting from C++20, and was implementation-defined before (but worked correctly in practice anyway). There's no UB here.
The two casts cancel each other out (again, guaranteed in C++20, implementation-defined before, but worked in practice anyway).
Signed overflow is normally UB, yes, but that only applies to overflow caused by a computation. Overflow caused by a conversion is different.
cppreference
If the destination type is signed, the value does not change if the source integer can be represented in the destination type. Otherwise the result is:
(until C++20) implementation-defined
(since C++20) the unique value of the destination type equal to the source value modulo 2n where n is the number of bits used to represent the destination type.
(Note that this is different from signed integer arithmetic overflow, which is undefined).
More specifics on how the conversions work.
Lets's say int and unsigned int occupy N bits.
The values that are representable by both int and unsigned int are unchanged by the conversion. All other values are increased or decreased by 2N to fit into the range.
This conveniently doesn't change the binary representation of the values.
E.g. int -1 corresponds to unsigned int 2N-1 (largest unsigned int value), and both are represented as 11...11 in binary. Similarly, int -2N-1 (smallest int value) corresponds to unsigned int 2N-1 (largest int value + 1).
int: [-2^(n-1)] ... [-1] [0] [1] ... [2^(n-1)-1]
| | | | |
| '---|---|-----------|-----------------------.
| | | | |
'---------------|---|-----------|----------. |
| | | | |
V V V V V
unsigned int: [0] [1] ... [2^(n-1)-1] [2^(n-1)] ... [2^n-1]
|
70,797,182 | 70,797,345 | Question About a Probability Model Using C++ | I am trying to solve a probability question theoretically and then modeling it on C++ but my code outputs a different probability from the theoretical one.
Question:
A balanced coin is tossed three times. Calculate the probability that exactly two of the three tosses result in heads.
Answer:
Sample space: {(H,H,H), (H,H,T), (H,T,H), (H,T,T), (T,T,T), (T,T,H), (T,H,T), (T,H,H)}
Probablity that exactly two of the three tosses result in heads = 3/8
C++ Code:
#include <iostream>
#include <time.h>
#include <stdlib.h>
bool TossCoinXNumber(int x);
int TossCoin();
void CalcProbability(int x);
using namespace std;
int main()
{
srand (time(NULL));
CalcProbability(1000000);
return 0;
}
int TossCoin(){
int toss = rand() % 2;
return toss;
}
bool TossCoinXNumber(int x){
int heads=0;
int tails = 0;
for(int i = 0; i < x; i++){
if(TossCoin() == 1){
heads++;
}
else if(TossCoin() == 0){
tails++;
}
}
if(heads == 2 && tails == 1){
return true;
}
return false;
}
void CalcProbability(int x){
double probability = 0.0;
double count = 0.0;
for(int i = 0; i < x; i++){
if(TossCoinXNumber(3) == true){
count++;
}
}
probability = (count*1.0) / (x*1.0);
cout << probability;
}
Code Output: 0.187053
Which is different than the theoretical probability of 3/8
| As n. 1.8e9-where's-my-share m. correctly pointed out, You are calling TossCoin() twice. This is your modified code that fixes the problem:
#include <stdlib.h>
#include <time.h>
#include <iostream>
bool TossCoinXNumber(int x);
int TossCoin();
void CalcProbability(int x);
using namespace std;
int main()
{
srand(time(NULL));
CalcProbability(1000000);
return 0;
}
int TossCoin()
{
int toss = rand() % 2;
return toss;
}
bool TossCoinXNumber(int x)
{
int heads = 0;
int tails = 0;
for (int i = 0; i < x; i++)
{
int toss = TossCoin();
if (toss == 1)
{
heads++;
}
else if (toss == 0)
{
tails++;
}
}
if (heads == 2 && tails == 1)
{
return true;
}
return false;
}
void CalcProbability(int x)
{
double probability = 0.0;
double count = 0.0;
for (int i = 0; i < x; i++)
{
if (TossCoinXNumber(3) == true)
{
count++;
}
}
probability = (count * 1.0) / (x * 1.0);
cout << probability;
}
This is the shorter code that I prefer:
#include <iostream>
#include <random>
using namespace std;
int main(void)
{
int tries = 1000000, count = 0;
for (int i = 0; i < tries; ++i)
{
int heads = 0;
for (int j = 0; j < 3; ++j) heads += (rand() % 2);
count += (heads == 2);
}
cout << count / float(tries) << endl;
}
In this code, the integer results of comparisons are used to increment heads, count so we don't have any ifs.
|
70,797,294 | 70,801,189 | How to read file having different line ending in C++ | I have two files "linuxUTF8.srt" and "macANSI.srt". I am reading these files using getline().
as macANSI.srt has '\r' as line ending I am reading the whole file rather than a single line.
I know I have to pass '\r' as delimiter but how do I know what type of line ending character I am dealing with.
| As Sebastian said, we will need to read the block and then find out the appropriate line-ending.
So, we will need to open the file in binary mode and read the last characters.
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void SetLineEnding(char *filename, std::string &newline, char &delimiter)
{
std::string str;
std::ifstream chk(filename,std::ios::binary);
if(getline(chk, str))
{
if(str.size() && str[str.size()-1] == '\r')
{
//It can be either \r or \r\n
if(getline(chk, str))
{
delimiter = '\n';
newline = "\\r\\n";
}
else
{
delimiter = '\r';
newline = "\\r";
}
}
else
{
delimiter = '\n';
newline = "\\n";
}
}
}
int32_t main()
{
string newLine;
string delimiter;
char filename[256];
in>>filename;
SetLineEnding(filename,newLine,delimiter);
std::ifstream inp(filename,ios::in);
if(!inp.is_open())
{
cout<<"File not opened"<<endl;
return 0;
}
//getline() function with delimiter
string str;
getline(inp,str,delimiter);
return 0;
}
Now you can pass delimiter to getline() and you will be able to read according to line-ending.
|
70,797,356 | 70,797,719 | Cannot produce any output on increasing size of arr of vectors | I m using minGW compiler along with VScode on windows 10
Problem I m facing is provided below :
here I can see output while using an arr of vectors of size 1500
Hello World
Execution works
.
.
.
But on declaring an arr of vectors of large size I cannot receive any output in terminal
How will I be able o work with an arr of vectors of size 150000 or more ?
| You blew up the stack. Every std::vector object occupies 24 bytes on the stack (in GCC's implementation). Now 150000 * 24 = 3.6 MB which may easily cause a problem for you.
Instead, try this (one of the easiest ways):
std::vector< std::vector<int> > v( 150'000 );
or maybe this:
std::vector< std::vector<int> > v( 150'000, std::vector<int>( 1000 ) );
The above statement will create a vector that owns 150000 other vectors each of which has 1000 elements initialized to 0.
|
70,797,699 | 70,798,073 | Getting An Exception When Compiling The Win32 Console Project In My Code With Unicode (C++ Mingw64 VSCODE) | I am using mingw64 compiler with VSCode. I wrote some code following a tutorial to print something to the console using <Windows.h>. I then modified my code to work with UNICODE characters. I have used WriteConsoleOutputCharacter*( ) to do so. But I get a runtime exception when I run the program.
Segmentation Fault in VSCode. Please let me know if there's an error in my code.
#define UNICODE
#define _UNICODE
#include <windows.h>
const short screenWidth = 80, screenHeight = 80;
const wchar_t* consoleTitle = L"My Console Window";
int main()
{
HANDLE hIn = GetStdHandle(STD_INPUT_HANDLE);
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
SMALL_RECT windowArea = { 0, 0, screenWidth - 1, screenHeight - 1 };
COORD windowSize = { screenWidth, screenHeight };
SetConsoleWindowInfo(hOut, TRUE, &windowArea);
SetConsoleTitle(consoleTitle);
SetConsoleActiveScreenBuffer(hOut);
SetConsoleScreenBufferSize(hOut, windowSize);
wchar_t* screenBuffer = new wchar_t[screenWidth * screenHeight];
for (int y = 0; y < screenHeight; y++)
{
for (int x = 0; x < screenWidth; x++)
{
screenBuffer[y * screenWidth + x] = L' ';
}
}
LPDWORD numberOfCharsWritten = 0;
WriteConsoleOutputCharacter(hOut, screenBuffer, screenWidth * screenHeight, { 0, 0 }, numberOfCharsWritten);
return 0;
}
| You have to declare DWORD variable not LPDWORD, and pass the variable's memory.
DWORD numberOfCharsWritten = 0;
WriteConsoleOutputCharacter(hOut, screenBuffer, screenWidth * screenHeight, { 0, 0 }, &numberOfCharsWritten);
|
70,798,468 | 70,799,082 | GDB: Debug two instances of the same application simultaneous | I am trying to debug two instances of the same application. Therefore I setup as followed:
(gdb) set target-async on
(gdb) set non-stop on
(gdb) attach pid1
(gdb) set scheduler-locking off
(gdb) add-inferior
(gdb) inferior 2
(gdb) attach pid2
(gdb) set scheduler-locking off
(gdb) b hello-world.cpp:8
Breakpoint 1 at 0x557a557761fd: ../hello-world.cpp:8. (2 locations)
(gdb) continue
The Problem I have is that only the currently selected inferior is continued. Is there a way to let all inferiors continue with one command?
Solution:
It works if the following sequnce is used:
(gdb) attach pid1
(gdb) add-inferior
(gdb) inferior 2
(gdb) attach pid2
(gdb) set schedule-multiple on
(gdb) b hello-world.cpp:8
Breakpoint 1 at 0x557a557761fd: ../hello-world.cpp:8. (2 locations)
(gdb) continue
Thanks to Klaus!
| To continue all attached processes you have to set the scheduler mode in gdb.
set scheduler-locking off
A continue now let all threads continue.
For a detailed description of scheduler mode take a look here
As you ask in the comments what the complete procedure was:
(gdb) attach <pid 1>
(gdb) add-inferior
(gdb) inferior 2
(gdb) attach <pid 2>
(gdb) set scheduler-locking off
(gdb) b myprog.cpp:55
|
70,798,928 | 70,799,265 | using a function to print basic student information in c++ | I want to print in c++ some general information about students by using a function with parameters
void generalities(string fname,string lname,string email,int phone, int age) {\
cout << fname << lname<<" email: "<<email << " Phone: "<<phone<< " Age "<<age;\
}
int main() {\
std::cout << "Team generalities";\
generalities("Ledjet","Lushka","ledjet.lushka@cit.edu.al",0694339874,20);
generalities("Enio","Sefa","enio.sefa@cit.edu.al",0699274494,20);
return 0;
}
but I get the following errors
error: invalid digit "9" in octal constant
error: variable or field ‘generalities’ declared void
error: ‘string’ was not declared in this scope; did you mean ‘std::string’?
error: expected primary-expression before ‘int’
error: ‘generalities’ was not declared in this scope
| The answer @digito_evo gave was a nice improvement. I would go further and overload the operator<< for the struct.
#include <iostream>
#include <string>
struct Generalities
{
std::string fname;
std::string lname;
std::string email;
std::string phone;
std::string age;
friend std::ostream& operator<<(std::ostream& os, const Generalities& g);
};
std::ostream& operator<<(std::ostream& os, const Generalities& g)
{
os << g.fname << ' ' << g.lname << " email: " << g.email << " Phone: "<< g.phone << " Age: " << g.age << '\n';
return os;
}
int main( )
{
std::cout << "Team generalities\n";
std::cout << Generalities{ "Ledjet", "Lushka", "ledjet.lushka@cit.edu.al", "0694339874", "20" };
return 0;
}
|
70,798,937 | 70,799,080 | Whether an implicit type conversion occurs between decimal literals and float types | In C++,the type of floating-point literals is double by default;
auto dval = 3.14; // dval is a double
So,in the statement float fval = 3.14 , 3.14 -> float means double -> float?
Another similar question:
float fval = ival + 3.14;
what type conversion is happening here
| Yes. In the declaration float fval = 3.14 the initialiser is implicitly converted from double to float.
|
70,799,056 | 71,975,198 | Cython: Assign pointer values, not the pointer itself | C/C++ allows assigning values of a pointer to another pointer of the same type:
#include <iostream>
using namespace std;
int main() {
int* a = new int();
int* b = new int();
*a = 999;
*b = *a; // Can't do in Cython this?
cout <<"Different pointers, same value:" <<endl;
cout <<a <<" " <<b <<endl;
cout <<*a <<" " <<*b <<endl;
}
Is it possible to write the line *b = *a above in Cython?
All these fail:
from cython.operator cimport dereference as deref
cdef cppclass foo: # Can't `new int()` in Cython, make a class
int value
cdef foo* a = new foo()
cdef foo* b = new foo()
a.value = 999
deref(b) = deref(a) # Error: Cannot assign to or delete this
b = deref(a) # Error: Cannot assign type 'foo' to 'foo *'
deref(b) = a # Error: Cannot assign to or delete this
b = a # Works, but pointer 'b' is gone!!! not a clone.
| Using b[0] = a[0] seems to do the trick. Indexing is another way to dereference the pointer. Here's some example code and its output.
# distutils: language=c++
cdef cppclass foo:
int value
cdef foo* a = new foo()
cdef foo* b = new foo()
a.value = 999
b.value = 777
print('initial values', a.value, b.value)
print('initial pointers', <long>a, <long>b)
b[0] = a[0]
print('final pointers', <long>a, <long>b)
print('final values', a.value, b.value)
As you can see, the values of b have changed, but the pointer still references the same address as before.
initial values 999 777
initial pointers 105553136305600 105553136304304
final pointers 105553136305600 105553136304304
final values 999 999
|
70,799,228 | 70,799,661 | How to cast a double into std::chrono::milliseconds | I am using boost::asio::steady_timer m_timer and if I am not mistaken, in order to call m_timer.expires_after(expiration_time_ms);, expiration_time_ms should be a std::chrono::milleseconds variable.
Nevertheless, in my case, I have the expiration time as a double. I would like to know if it is possible to cast a double into std::chrono::milliseconds
The aim is to call
void
setExpirationTime(my_casted_double) {
boost::asio::steady_timer m_timer;
m_timer.expires_after(my_casted_double)
}
| m_timer.expires_after will accept any duration which is convertible to boost::asio::steady_timer::duration it doesn't need to be std::chrono::milliseconds (and if you don't want to discard the fractional milliseconds from your duration you shouldn't be converting to std::chrono::milliseconds).
You can convert your double into a std::chrono::duration as follows:
double milliseconds = 0.1;
std::chrono::duration<double, std::milli> chrono_milliseconds{ milliseconds };
chrono_milliseconds can't however be passed automatically into expires_after as there is no automatic conversion from floating point durations to integer ones. You can fix this with a std::chrono::duration_cast:
m_timer.expires_after(
std::chrono::duration_cast<boost::asio::steady_timer::duration>(chrono_milliseconds));
|
70,800,927 | 70,801,960 | AllocConsole() doesnt show up | I'm trying to inject a dll into a testprogam and use AllocConsole() for debugging.
AllocConsole();
However, the console wont show up and I realized that the program I was trying to inject is running under SYSTEM and I was using an administrator account so the console wont show up on my desktop. Only the conhost process was created.
So... How to make a console from AllocConsole() show up on every accounts desktop?
| The program is running as SYSTEM so likely it's a service running in the services session (session 0). It's not possible to allocate a console and show it in another session (e.g. the console session). It's not possible for a process to have a window (or console) that is visible in all sessions or even on multiple desktops.
If you don't know what Session Isolation is best start reading here: Application Compatibility - Session 0 Isolation
If you want to output simple debugging, an easy method is using OutputDebugString (and use a tool like DbgView to read the output) or writing to the eventlog. For more detailed output you could setup a named pipe or some other inter processs communication.
|
70,801,160 | 71,016,160 | Teechart set num of decimals on Axis and hide Axis labels for further series | hope you can help me.
In Builder C++ create a new "Windows VCL Application". Add a "Tchart" from "Palette".
Right click on the chart -> Edit Chart -> Click on Series -> Add... -> Line -> Ok to create Series1 and repeat to create Series2.
Close
In Unit1.cpp copy my following sample:
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
#include <vector>
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
std::vector<float> x1, y1, x2, y2;
for (int i = 0; i < 2000; i++) {
float r1 = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
float r2 = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
x1.push_back(i+r1);
y1.push_back(r1);
x2.push_back(i+r2);
y2.push_back(r2);
}
Chart1->BottomAxis->AxisValuesFormat = "0.0";
for (unsigned i = 0; i < x1.size(); i++) {
Chart1->Series[0]->AddY(y1[i], x1[i]);
Chart1->Series[1]->AddY(y2[i], x2[i]);
}
}
//---------------------------------------------------------------------------
Compile and run. As you can see the values on the X axis appear overlapped.
In order to solve I would
display the X axis values with only 1 decimal
hide the X axis labels for Series1 (i. e., Series2)
For the 1st point I've tried as you see in the code but it seems not working.
Thank you very much in advance.
| You are adding points to the Line series with the AddY method, passing the x values as the second parameter, which is the label.
Doing so, the bottom axis labels indeed overlap.
Instead, I'd use the AddXY method, passing the x values as the first parameter and the y values as the second:
for (unsigned i = 0; i < x1.size(); i++) {
Chart1->Series[0]->AddXY(x1[i], y1[i]);
Chart1->Series[1]->AddXY(x2[i], y2[i]);
}
This looks fine for me here:
|
70,801,246 | 70,805,436 | how does one convert std::u16string -> std::wstring using <codecvt>? | I found a bunch of questions on a similar topic, but nothing regarding wide to wide conversion with <codecvt>, which is supposed to be the correct choice in the modern code.
The std::codecvt_utf16<wchar_t> seems to be a logical choice to perform the conversion.
However std::wstring_convert seem to expect std::string at one end. The methods from_bytes and to_bytes emphasize this purpose.
I mean, the best solution so far is something like std::copy, which might work for my specific case, but seems kinda low tech and probably not too correct either.
I have a string feeling that I am missing something rather obvious.
Cheers.
| The std::wstring_convert and std::codecvt... classes are deprecated in C++17 onward. There is no longer a standard way to convert between the various string classes.
If your compiler still supports the classes, you can certainly use them. However, you cannot convert directly from std::u16string to std::wstring (and vice versa) with them. You will have to convert to an intermediate UTF-8 std::string first, and then convert that afterwards, eg:
std::u16string utf16 = ...;
std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> utf16conv;
std::string utf8 = utf16conv.to_bytes(utf16);
std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> wconv;
std::wstring wstr = wconv.from_bytes(utf8);
Just know that this approach will break when the classes are eventually dropped from the standard library.
Using std::copy() (or simply the various std::wstring data construct/assign methods) will work only on Windows, where wchar_t and char16_t are both 16-bit in size representing UTF-16:
std::u16string utf16 = ...;
std::wstring wstr;
#ifdef _WIN32
wstr.reserve(utf16.size());
std::copy(utf16.begin(), utf16.end(), std::back_inserter(wstr));
/*
or: wstr = std::wstring(utf16.begin(), utf16.end());
or: wstr.assign(utf16.begin(), utf16.end());
or: wstr = std::wstring(reinterpret_cast<const wchar_t*>(utf16.c_str()), utf16.size());
or: wstr.assign(reinterpret_cast<const wchar_t*>(utf16.c_str()), utf16.size());
*/
#else
// do something else ...
#endif
But, on other platforms, where wchar_t is 32-bit in size representing UTF-32, you will need to actually convert the data, using the code shown above, or a platform-specific API or 3rd party Unicode library that can do the data conversion, such as libiconv, ICU. etc.
|
70,801,835 | 70,805,679 | How can I include OpenBLAS and LAPACK manually in xeus-cling binder? | I'm trying to create a C++ Jupyter Notebook using xeus-cling and mybinder. I wanted to include the library armadillo and I was able to do that locally in a Jupyter Notebook as follows:
#pragma cling add_library_path("armadillo-10.7.5")
#pragma cling add_include_path("armadillo-10.7.5/include/")
#pragma cling load("armadillo")
#include <armadillo>
using namespace std;
using namespace arma;
mat A(4, 5, fill::randu);
mat B(4, 5, fill::randu);
cout << A*B.t() << endl;
where the file structure is as it's in this Github repository (you can also find the binder link in README): https://github.com/AntonioDaSilva/xeus-cling
However, armadillo requires the libraries OpenBLAS and LAPACK which I cannot install on mybinder since I do not have admin privileges. I believe this is the reason I get the following error when I run the code above in the binder:
cling::DynamicLibraryManager::loadLibrary(): libblas.so.3: cannot open shared object file: No such file or directory
IncrementalExecutor::executeFunction: symbol 'dgemv_' unresolved while linking function '_GLOBAL__sub_I_cling_module_6'!
IncrementalExecutor::executeFunction: symbol 'dsyrk_' unresolved while linking function '_GLOBAL__sub_I_cling_module_6'!
IncrementalExecutor::executeFunction: symbol 'ddot_' unresolved while linking function '_GLOBAL__sub_I_cling_module_6'!
IncrementalExecutor::executeFunction: symbol 'dgemm_' unresolved while linking function '_GLOBAL__sub_I_cling_module_6'!
Can you please help me figure out how to include these libraries manually in the binder?
| I suspect you can add an apt.txt configuration file to your repo with the following contents based on here:
libblas-dev
liblapack-dev
That may not quite be the current ones to list and so you may need to look around more to find the current best ones for installing with apt-get in current linux systems; however, that's the idea.
See more about the apt.txt configuration file use in the bottom of this reply on the Jupyter Discourse forum here.
(There is currently an issue when using apt.txt and install.R in combination, see here. I think this is specific to R installs; however, I thought I'd mention it in case you see issues upon adding apt.txt. I suspect it would be fixed in a few days.)
By the way, for everyone seeing this. There's a more suitable channel for getting help with this type of thing as it is very specific and not general to installing onto linux. At the Jupyter Discourse community forum there's a category of 'repo help' for Binder that you can post things like this and Jupyter/MyBinder folks will see and can exchange ideas to help get you sorted.
|
70,801,992 | 70,802,615 | Are variable templates declared in a header, an ODR violation? | What happens when a header file contains a template variable like the following:
template <class T>
std::map<T, std::string> errorCodes = /* some initialization logic */;
Is this variable safe to use? Doing some research on this I found that:
Templates are implicitly extern but that does cause ODR violations
Without any static or inilne or constexpr decoration I can end up with multiple definitions
Keyword inline of C++17 changes the rules but c++20 has a different behavior(?)
So which one is it?
| Templates get an exception from the one-definition rule, [basic.def.odr]/13:
There can be more than one definition of a [...] templated entity ([temp.pre]) [...] in a program provided that each definition appears in a different translation unit and the definitions satisfy the following requirements.
There's a bunch of requirements there, but basically if you have a variable template in a header (a variable template is a kind of templated entity) and just include that header from multiple translation units, they will have the same token-for-token identical definition (because #include), so having more than one definition is fine.
This is the same reason that you don't need to declare function templates inline in headers, but do need to declare regular functions inline.
In C++17, this wording read:
There can be more than one definition of a class type, enumeration type, inline function with external linkage ([dcl.inline]), inline variable with external linkage ([dcl.inline]), class template, non-static function template, static data member of a class template, member function of a class template, or template specialization for which some template parameters are not specified ([temp.spec], [temp.class.spec]) in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements.
Note that variable template is not in that list, which was just an omission (it was very much always intended to work). This was CWG 2433, adopted in 2019, but as a defect report (DR) so I wouldn't consider it as counting as a C++20 change. This is the DR that introduced the "templated entity" bullet I cited earlier (rather than listing out several different kinds of templated entity manually, and missing one).
|
70,802,060 | 72,979,198 | C++ standards conflict in compile_commads | I'm working on some project which uses C++17 standard with clangd-13.0. Sometime after I decided to add library that used C99 standard in its CMakeLists file and now clangd always does analysis based on a C99 standard even in cpp files.
My CMakeLists file looks like this:
cmake_minimum_required(VERSION 3.21)
project(my_proj)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_EXPORT_COMPILE_COMMANDS 1)
set(SOURCES include/some_header.h src/some_source.cpp)
# Adding library that mostly uses C code
add_subdirectory(lib/path/to/lib)
add_library(${PROJECT_NAME} STATIC ${SOURCES})
target_link_libraries(${PROJECT_NAME}
imported_lib
)
Can I somehow exclude this library from compile_commands or enforce usage of C++17 standard?
Edit:
After I've removed declaration of -std=c99 flag the problem still occurs, clangd analyses cpp code as pure C, even though compile_commands.json doesn't contain any -std parameter for library files
| As @drescherjm stated in comments I had just to do:
set_property(TARGET tgt_name PROPERTY CXX_STANDARD 17)
set_property(TARGET tgt_name PROPERTY CXX_STANDARD_REQUIRED ON)
Or
set_target_property(tgt_name PROPERTIES
CXX_STANDARD 17
CXX_STANDARD_REQUIRED ON
)
|
70,802,977 | 70,803,148 | the pixel values changed while using imwrite to jpg files in c++ | I'm writing a code like this in c++:
I wish to have a 100% same copy image of test1.jpg.
Unfortunately, I find lots of pixel values change after cv::imwrite.
int main()
{
cv::Mat img1 = cv::imread("./test1.jpg");
cv::imwrite("test2.jpg", img1);
cv::Mat img2 = cv::imread("./test2.jpg");
int count = 0;
for (int i = 0; i < 250; i++) {
for (int j = 0; j < 250; j++) {
if (img1.at<uchar>(i, j) != img2.at<uchar>(i, j)) {
count++;
}
}
}
std::cout << count << std::endl;
return 0;
}
I use count in this program to see how many differences are there between these two images,
although both images (test1.jpg and test2.jpg) have the same size at 46kb, the count's value is as high as 16768!
Is there any method to avoid the change of pixel? I'm only going to use jpg files in the program.
Thanks a lot!
| If you want non-lossy compression, you can't use jpg's and have to use a .png (there's .bmp as well but its uncompressed)
jpg = cv.imread("../resources/fisheye/1_1.jpg")
cv.imwrite("1_1.png", jpg)
png = cv.imread("1_1.png")
np.sum(np.where(jpg != png, 1, 0)) # number of differing pixels between images
Output: 0
|
70,803,002 | 70,803,387 | Difference between const std::array<T,N> and std::array<const T, N> | Is there any practical difference between std::array<const T, N> and const std::array<T, N>?
It looks that non-const array holding const elements is still not able to be swapped; assignment operator is not working either.
When should I prefer one over the other one?
#include <array>
std::array<const int, 5> array_of_const = {1,2,3,4,5};
std::array<const int, 5> array_of_const2 = {1,2,3,4,5};
const std::array<int, 5> const_array = {1,2,3,4,5};
const std::array<int, 5> const_array2 = {1,2,3,4,5};
int main()
{
// Assignment doesn't work for either
array_of_const = array_of_const2;
const_array = const_array2;
// Swapping doesn't work for either
array_of_const.swap(array_of_const2);
const_array.swap(const_array2);
// Indexing...
array_of_const[0] = 0;
const_array[0] = 0;
return 0;
};
| Copies of std::array<const T, N> are still "logically const", whereas by default a copy of const std::array<T, N> is mutable. If allowing or preventing that matters to you, one is preferable to the other.
There are differences in what templates they match, e.g. the case in Ilya's answer.
|
70,803,177 | 70,803,383 | Making my own Vector. Whats wrong with it? | i am trying to make my own vector but i cant get it to work as i want.
I get a error message on the Move-constructor it says: Exception thrown at 0x00007FF751A77ACC in auto-tests.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF.
The first one got solved. But now i got the same error with another part of the code. The push_back finction, here is the code.
Here is the code for the move-constructor:
template<typename T>
inline Vector<T>::Vector(Vector&& other)
: m_nrOfElements(other.m_nrOfElements), m_capacity(other.m_capacity)
{
for (int i = 0; i < m_nrOfElements; i++)
{
m_elements[i] = other.m_elements[i]; /// HERE IS WHERE THE ERROR IS!
}
other.m_elements = nullptr;
other.m_capacity = 0;
other.m_nrOfElements = 0;
}
| You haven't allocated memory for m_elements - and you shouldn't, since this is a move constructor. Just use std::exchange to "steal" the pointer from other and replace it with the value you desire - that is, nullptr.
Example:
#include <utility>
template<typename T>
inline Vector<T>::Vector(Vector&& other)
: m_nrOfElements(std::exchange(other.m_nrOfElements, 0),
m_capacity(std::exchange(other.m_capacity, 0),
m_elements(std::exchange(other.m_elements, nullptr))
{
// constructor body can now be empty
}
|
70,803,625 | 70,803,901 | C++ square bracket overloading with and without const/ampersand | I am writing C++ code, and ran into a case where I wish to overload the square bracket operator for my class. From various sources, I find that you usually make two methods to do this, one with the const keyword, and one without the const keyword, but with an ampersand (&) before the method name. An example is given below.
int MyClass::operator[](unsigned int i) const {
return this->values[i];
}
int & MyClass::operator[](unsigned int i) {
return this->values[i];
}
My questions are as follows:
Why do I have two methods, one with the const keyword, and one without it?
What does the ampersand (&) in my second method do?
Why can I set a value at a given index using square brackets, when none of my methods are setters, and which of these two methods is invoked when I set a value?
|
Why do I have two methods, one with the const keyword, and one without it?
The const keyword sets a constraint that prevents the function from modifying the object. For example, if you use the const keyword in a setter, you'll get a compiler error.
So the first function won't allow any modification on the object and in this case it will return a copy of the accessed element. The first function is a getter in disguise, it is a read only access, so to speak.
What does the ampersand (&) in my second method do?
The second function, instead, has the ampersand after the type, which means that it will return a reference of the returned value and not a copy of it. The returned value is part of the object, so returning a reference to it implies a potential modification and the const keyword wouldn't allow it.
So this second function is a setter in disguise, it is a write access.
Why can I set a value at a given index using square brackets, when none of my methods are setters, and which of these two methods is invoked when I set a value?
As we've seen, the second function acts like a setter. When you use it, the returned value is a reference to the real element inside your object, and is valid for assignation (we call it a lvalue, more about them here).
The point of this overload is: whenever you use the operators for a read operation (right side of the assignation or as a parameter) the first function will be called. If you use it for a write operation, it will be the second. In fact, this is how the same operator works for the STL containers you are probably using in your code.
|
70,804,150 | 70,804,381 | How to assign an object to an inhereted function | how can I assign an inherited method to an object?
, can you explain to me what is wrong with my code?
I am a newbie, so I would like to know if there is a better way to do it
int main(){
CalculateData data;
data = data.ReadData(data);//does not let me assign data to the method??
}
Rest of the code
#include<string>#include<fstream>#include<iostream>#include<vector>using namespace std;
class File//base class
{
private:
double Size;
public:
vector <double>values;
double GetSize();
void SetSize(double size);
File ReadData(File data);
};
class CalculateData :public File {//inherent from file class
public:
std::vector <double> value;
}
File File::ReadData(File file) {//method of File class
{std::fstream File("Data.txt", std::ios_base::in);
double a;
int counter = 0;
while (File >> a)
{
//printf("%f ", a);
file.values.push_back(a);
counter++;
}
file.SetSize(counter);
cout << "size is " << file.GetSize() << endl;
File.close();
}
return file;
}
| Frankly, it is hard to help, because the error is just a consequence of a flawed approach. I'll use an example simpler than yours that has most of the same issues:
#include <iostream>
struct Base {
int value;
Base read(Base b) {
b.value = 42;
return b;
};
};
struct Derived : Base{
int values;
};
int main() {
Derived d;
d = d.read(d);
}
The immediate problem is the compiler error:
<source>: In function 'int main()':
<source>:17:17: error: no match for 'operator=' (operand types are 'Derived' and 'Base')
17 | d = d.read(d);
| ^
<source>:11:8: note: candidate: 'constexpr Derived& Derived::operator=(const Derived&)'
11 | struct Derived : Base{
| ^~~~~~~
<source>:11:8: note: no known conversion for argument 1 from 'Base' to 'const Derived&'
<source>:11:8: note: candidate: 'constexpr Derived& Derived::operator=(Derived&&)'
<source>:11:8: note: no known conversion for argument 1 from 'Base' to 'Derived&&'
d is a Derived and read returns a Base. They are different types, you cannot assign them to each other unless you provide some conversion between them.
However, it does not make sense that read takes a Base as argument (by value) and returns that just to let the caller assign it to the object they called the method on. If the method is intended to modify the current object then it should do so directly:
void read() {
value = 42;
}
There is absolutely no need to pass a Base as argument, which will be copied anyhow, because you pass it by value.
The next thing that is fishy in the code is that Derived has another member which is similar named as the one of Base but unused. Derived already does inherit the value member from Base. It does not need another values member.
Last but not least, initialization of members should take place in the initializer list of the constructor (if not in-class initializers are used). If initialization is complicated a static method can be used. Hence:
struct Base {
int value;
Base() : value( read_input() ) {}
static int read_input() {
return 42;
}
};
struct Derived : Base {};
int main() {
Derived d;
}
This code does the same as the above. As it is not clear what the purpose of Derived is, it can be removed.
|
70,804,419 | 70,804,452 | abnormal behaviour in cout. It is printing twice character array after declaration of another same valued character array | So I was writing the code to print a character array in c++. The normal code is:-
#include <iostream>
using namespace std;
int main()
{
char X[5] = {'A', 'B', 'C', 'D', 'E'};
cout << X << endl;
return 0;
}
and it's printing:-ABCDE as expected but I tried to create another character array like this
#include <iostream>
using namespace std;
int main()
{
char X[5] = {'A', 'B', 'C', 'D', 'E'};
char Y[5] = {'A', 'B', 'C', 'D', 'E'};
cout << X << endl;
return 0;
}
and I thought that I'll get same output but it didn't happend.
the output was ABCDEABCDE I didn't understood why it happened.
At that time I was coding in my computer. So, I visited online c++ compiler and still got the same result.
Please anyone help me to understood why it happened?
I am using C++14 in my computer.
This is the link of online compiler website on which I rechecked my code.
| The behaviour is undefined.
std::ostream's overload for a const char* (selected due to pointer decay), doesn't stop outputting until NUL is reached.
So including NUL terminators in both arrays is the fix:
char X[/*let the compiler do the counting*/] = {'A', 'B', 'C', 'D', 'E', 0};
&c.
|
70,804,439 | 70,804,719 | How to use `std::function<void()>` as a typename in initializing a map? | I want to use std::function<void()> as a typename in initializing a map:
namespace kc
{
class kcmessage
{
private:
std::string value;
void warning() {}
void error()
{
exit(1);
}
std::map<std::string, std::function<void()>> msgtypes = {
{ "WARNING", warning },
{ "ERROR", error }
};
int msgtype;
};
}
But it's not working: error: could not convert ‘{{"WARNING", ((kc::kcmessage*)this)->kc::kcmessage::warning}, {"ERROR", ((kc::kcmessage*)this)->kc::kcmessage::error}}’ from ‘<brace-enclosed initializer list>’ to ‘std::map<std::__cxx11::basic_string<char>, std::function<void()> >’ (<brace-enclosed initializer list>)
| If you want to access a member function ( non static ) you have to bind the method to the instance of the class. For that you can use std::bind but it is much easier to simply use a lambda for that purpose.
#include <functional>
#include <map>
#include <string>
#include <iostream>
namespace kc
{
class kcmessage
{
private:
std::string value;
void warning() {std::cout << "Waring called!"<<std::endl;}
void error()
{
std::cout << "Error called" << std::endl;
//exit(1);
}
std::map<std::string, std::function<void()>> msgtypes = {
{ "WARNING", [this](){ warning();} },
{ "ERROR", [this](){ error();} }
};
int msgtype;
public:
void CallAll()
{
for( auto& el: msgtypes)
{
el.second();
}
}
};
}
int main()
{
kc::kcmessage{}.CallAll();
}
Execute it here
You can make your methods also static ones, but in this case you can't any longer access your member data if needed which is typically the case.
|
70,804,496 | 70,804,671 | Why does it show terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_S_construct null not valid | At first, I thought there is an error when I was using the while loop so I've tried using for loop but it still displays the same error. I have tried to look up the reason why this error happened but I am still unable to figure out which line in these codes caused the error.
int main()
{
ifstream patientData;
string name;
int count = 0;
patientData.open("PatientList.txt");
string patient_name[NUM_PATIENTS] = {0};
double ward[NUM_PATIENTS] = {0};
double surgery[NUM_PATIENTS] = {0};
double medication[NUM_PATIENTS] = {0};
double service[NUM_PATIENTS] = {0};
double totalCharge[NUM_PATIENTS] = {0};
while(count < NUM_PATIENTS)
{
getline(patientData, patient_name[count], '\t');
patientData >> patient_name[count];
patientData >> surgery[count];
patientData >> medication[count];
patientData >> service[count];
patientData >> totalCharge[count];
count++;
}
patientData.close();
return 0;
}
I apologize in advance if this sounds like a stupid question.
Currently, I'm following the guide from a textbook named "Starting Out with C++ From Control Structures through Objects Ninth Edition by Tony Gaddis"
Can someone help me?
| In short: You are trying to initialize your arrays with 0, which is a nullptr. So you are actually trying to initialize your first string in the array with a nullptr.
Let's examine
string patient_name[NUM_PATIENTS] = { 0 };
It defines an old style C array of NUM_PATIENT strings.
It initializes this array with { 0 }.
... which means, the first string get's initalized with 0, the rest of the strings get default-initialized.
... which means, the first string in the array is initialized thus: string(0), which is similar to string(nullptr) - which probably leads to your exception string::_S_construct null not valid
Actually all your attempts at initalizing are wrong.
You don't need to write = {0} for the patient_name[NUM_PATIENT] array at all, because the strings in this array are "default-initialized". They know how initialize themselves to an empty string.
string patient_name[NUM_PATIENT]; is enough.
But your other arrays don't get properly initialized at all. = {0} will initialize the first element of your vector. The remaining elements are "default" initialized (for classes) or not initialized at all (for doubles).
Don't use patient_name[NUM_PATIENT] at all. Get a better textbook. This is an old-style C array. Use std::vector (best) or std::array (better).
Much better would be this:
std::vector<string> patient_names;
std::vector<double> medication...
for (size_t i=0; i<NUM_PATIENT; ++i) {
string next_patient;
getline(patients, next_patient);
patient_names.emplace_back(next_patient);
...
or, to stick close to the text book:
std::vector<string> patient_name(NUM_PATIENTS);
...
while (count<NUM_PATIENTS) {
getline(patients, patient_name[count]);
|
70,804,688 | 70,805,618 | Use member in constructor initializer list | Can I safely use members to initialize others?
class Class {
public:
Class(X argument) : memberA(argument), memberB(memberA) {}
A memberA;
B memberB;
};
Here we use the argument to the constructor to initialize memberA. We then rely on the fact that this happens before the initialization of memberB and initialize memberB using memberA.
If we assume X, A, and B to be std::string the above example works (tested with gcc), as long as we do not change the order in which the members are declared. But is this actually guaranteed by the standard or am I abusing an implementation detail of the compiler?
| Yes, this is safe as per class.base.init#15
The expression-list or braced-init-list of a mem-initializer is in the function parameter scope of the constructor and can use this to refer to the object being initialized.
This Note also has an example with this->i to show that previously initialized class members can be used to initialize other class members inside a mem-initializer. (The this-> is only necessary in this example to disambiguate the member and the constructor parameter, both named i).
Be careful that the member is already initialized before using it, since from class.base.init#13.3
... non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).
|
70,804,783 | 70,804,950 | Flip order of std::pair | How can I flip the order of std::pair?
Is there an in-build command or I need to create a new pair.
Currently I am doing this by creating a new pair.
std::pair el_ids(0,1);
el_ids = std::make_pair(el_ids.second, el_ids.first);
| As long as both types of the pair are the same you can just swap them (like @273k has pointed out in the comments), e.g.:
godbolt example
std::pair p = {1, 2};
std::swap(p.first, p.second);
If the types are different you'd have to write a small utility function for it, since there's no built-in way to do that, e.g.:
godbolt example
template<class T>
constexpr auto pair_swap(T&& pair) {
return std::make_pair(
std::forward<T>(pair).second,
std::forward<T>(pair).first
);
}
// Usage Example:
std::pair p = {std::string{"A"}, 12};
auto p2 = pair_swap(std::move(p));
|
70,804,944 | 70,805,068 | How to get file date Accessed? | I'm looking for this function from std::filesystem but can't figure it out.
How to access this information?
| Only write time (Modified in your screenshot) is accessible via standard libraries. You'd need to use platform-specific APIs to get access to the other information.
For example, assuming Windows (based on the screen shot), you'd use GetFileTime(); this function is able to retrieve the created, modified, and accessed times. You will need a handle to the file. The link above includes a link to a full example, but summarizing the example essentially you can do:
HANDLE hFile = /* get the file handle */
FILETIME ftCreate, ftAccess, ftWrite;
GetFileTime(hFile, &ftCreate, &ftAccess, &ftWrite);
|
70,805,071 | 70,805,112 | is there a way to use an unspecified parameter in c++? | I'm trying to have a simple function that is used for debugging in my program just for easeability and I'm wondering if there is a way to just not specify the kind of variable without instead overloading it for every kind possible. In my case would it be possible to have var be able to be any type of variable?
void debugPrinter(std::string name, int var )
{
std::cout << name << ": " << var << "\n";
}
| Yes, you can make debugPrinter a template.
template <typename T>
void debugPrinter(std::string name, const T & var )
{
std::cout << name << ": " << var << "\n";
}
In C++ 20, that can be abbreviated as
void debugPrinter(std::string name, const auto & var )
{
std::cout << name << ": " << var << "\n";
}
I've taken the parameter by const reference, because you don't need to copy the value to print it.
|
70,805,526 | 70,808,214 | C++ parsing ambiguity: Constructor vs. parenthesized declarator | I'm trying to write a yacc (menhir) grammar for parsing a very reduced subset of C++ (no templates, headers only with no function bodies allowed...) and am already running into ambiguities.
typedef int B;
class A {
A(); // (*)
B(c)(); // (**)
};
Case * is a constructor and case ** is a parenthesized declarator. How does the parser tell the difference? I can imagine some ways I could tell, but I want to know how a compliant c++ parser does it. I also understand that I likely won’t be able to parse even a practical subset of C++ with yacc, but I just want to understand a bit better what’s going on. In the end maybe I’ll switch to a parser combinator or something. Also, I should note that I have zero interest in linking against clang as I intend to add some custom syntax.
| Parsing C++ is frustrating exercise, because C++ is essentially not context-free. You need to know whether an identifier refers to a template, a type, or something else, and name resolution in C++ is not a simple task either. You might, for example, have to instantiate a template in order to know whether a member of templated class is a variable or a typename. (Programs only have to use typename for names in dependent types.)
So you certainly cannot expect to parse a translation unit without considering included header files. (Anyway, you couldn't do that because a header file could define a macro whose expansion changes the syntax in unexpected ways. So you need a preprocessor.)
When I wrote this answer, my eyes had skipped over the parentheses in which OP noted that by "yacc" they meant "menhir". Sorry. Unfortunately, menhir does not generate GLR parsers, as far as I know. But I think the approach is still valid, and useful enough that I'm leaving it in place. Perhaps there is an OCaml GLR (or GLL) parser generator, or perhaps C/C++ generated code is still of use.
Having said all that, all is not lost. You could use bison to generate a GLR parser, and then try to write custom disambiguation functions. If the disambiguation function needs to know whether a name is a typedef or not, it can try to look it up in the symbol table. Unlike the classic "lexer hack" approach, GLR disambiguation happens in the parser, so it doesn't require building unwieldy backchannels.
This can be an iterative process, because you don't need to figure out how to resolve ambiguities which are not present in the particular code you are trying to compile. Eventually, you'll probably want to handle all of them, but doing them as needed might prove to be a more fulfilling experience.
|
70,805,753 | 70,806,378 | Resolution of built-in operator == overloads | In the following code struct A has two implicit conversion operators to char and int, and an instance of the struct is compared for equality against integer constant 2:
struct A {
constexpr operator char() { return 1; }
constexpr operator int() { return 2; }
};
static_assert( A{} == 2 );
The code passed fine in GCC and MSVC, but Clang complains:
<source>:5:20: error: use of overloaded operator '==' is ambiguous (with operand types 'A' and 'int')
static_assert( A{} == 2 );
~~~ ^ ~
<source>:5:20: note: because of ambiguity in conversion of 'A' to 'float'
<source>:2:15: note: candidate function
constexpr operator char() { return 1; }
^
<source>:3:15: note: candidate function
constexpr operator int() { return 2; }
^
<source>:5:20: note: built-in candidate operator==(float, int)
static_assert( A{} == 2 );
^
<source>:5:20: note: built-in candidate operator==(double, int)
<source>:5:20: note: built-in candidate operator==(long double, int)
<source>:5:20: note: built-in candidate operator==(__float128, int)
<source>:5:20: note: built-in candidate operator==(int, int)
...
Demo: https://gcc.godbolt.org/z/h9Kd66heM
The general question is which compiler right here? And in particular it is interesting to know why Clang does not prefer operator==(int, int), however lists it among others?
| This is CWG 507. An example similar to yours was given, and the submitter explained that according to the standard, the overload resolution is ambiguous, even though this result is very counter-intuitive.
Translating to your particular example, when comparing operator==(int, int) and operator==(float, int) to determine which is the better candidate, we have to determine which one has the better implicit conversion sequence for the first argument (obviously in the second argument, no conversion is required). For the first argument of operator==(int, int), we just use A::operator int. For the first argument of operator==(float, int), there is no way to decide whether to use A::operator int or A::operator char, so we get the "ambiguous conversion sequence". The overload resolution rules say that the ambiguous conversion sequence is no better or worse than any other user-defined conversion sequence. Therefore, the straightforward conversion from A{} to int (via A::operator int) is not considered better than the ambiguous conversion from A{} to float. This means neither operator== candidate is better than the other.
Clang is apparently following the letter of the standard whereas GCC and MSVC are probably doing something else because of the standard seeming to be broken here. "Which compiler is right" depends on your opinion about what the standard should say. There is no proposed resolution on the issues page.
I would suggest removing operator char unless you really, really need it, in which case you will have to think about what else you're willing to give up.
|
70,806,928 | 70,807,220 | Is there any easy way to read a line from a file, split the first text part into a string, then split the last number part into a float? | I have an issue that I haven't been able to find a good way to solve, mostly because I am relatively new to C++, but not new to programming. I have a file with several lines in it, one of them being:
Plain Egg 1.45
I need to be able to read that line and split the first part, "Plain Egg", into a string, and then the last part, 1.45, into a float, and then do that for the rest of the lines. The following is some code I have so far, but I have been having an issue where it refuses to even read the file for some reason:
string line;
ifstream menuFile("menu.txt");
if (menuFile.is_open())
{
int i = 0;
while (getline(menuFile, line));
{
cout << line << endl;
istringstream iss(line);
iss >> dataList[i].menuItem >> dataList[i].menuPrice;
/*iss >> dataList[i].menuPrice;*/
i++;
}
}
else
{
cout << "Unable to open file.";
}
When I run it, it doesn't spit out "Unable to open file.", and when I trace it, it does enter the if loop, but it just doesn't read it. Besides that problem though, I want to know if this code would work in the way I want it to, and if doesn't, how to solve this problem.
EDIT: When I run it, it outputs what the last line of the file said, that being "Tea 0.75". The full file is as follows:
Plain Egg 1.45
Bacon and Egg 2.45
Muffin 0.99
French Toast 1.99
Fruit Basket 2.49
Cereal 0.69
Coffee 0.50
Tea 0.75
EDIT 2: For some reason, the following code goes straight to the last line, Tea 0.75, and I have no idea why, shouldn't the getline just go line by line until the last line(?):
string line;
int index;
ifstream menuFile("menu.txt");
if (menuFile.is_open())
{
while (getline(menuFile, line));
{
cout << line << endl;
index = line.find_last_of(' ');
cout << index << endl;
}
}
EDIT 3: Above code has a semicolon at the end of the while loop, no wonder it was just ending on the last line, ughhh.
|
Grab the line into a string.
Get the position of the last separator.
Your text is a substring of the line until the position of the separator.
Your number is a substring of the line from the position of the separator. You'll need to convert it to double first (and you should check for errors).
[Demo]
#include <iostream> // cout
#include <string> // find_last_of, getline, stod
int main()
{
std::string line{};
while (std::getline(std::cin, line))
{
auto pos{line.find_last_of(' ')};
auto text{line.substr(0, pos)};
auto number{std::stod(line.substr(pos))};
std::cout << "text = " << text << ", number = " << number << "\n";
}
}
// Outputs
//
// text = Plain Egg, number = 1.45
// text = Bacon and Egg, number = 2.45
// text = Muffin, number = 0.99
// text = French Toast, number = 1.99
// text = Fruit Basket, number = 2.49
// text = Cereal, number = 0.69
// text = Coffee, number = 0.5
// text = Tea, number = 0.75
//
A more robust solution taking into account @Dúthomhas' comments:
Trims the right hand side of the string before finding the last separator.
Catches std::stod exceptions.
This solution detects:
Blank lines.
Lines without texts.
Lines without numbers.
Incorrect number formats.
[Demo]
#include <boost/algorithm/string.hpp>
#include <fmt/core.h>
#include <iostream> // cout
#include <string> // find_last_of, getline, stod
int main()
{
std::string line{};
while (std::getline(std::cin, line))
{
try
{
boost::trim_right(line);
auto pos{line.find_last_of(' ')};
auto text{line.substr(0, pos)};
auto number{std::stod(line.substr(pos))};
std::cout << "text = " << text << ", number = " << number << "\n";
}
catch (const std::exception&)
{
std::cout << fmt::format("* Error: invalid line '{}'\n", line);
}
}
}
// Outputs:
//
// text = Plain Egg, number = 1.45
// text = Bacon and Egg, number = 2.45
// text = Muffin, number = 0.99
// text = French Toast, number = 1.99
// * Error: invalid line ''
// * Error: invalid line 'Fruit Basket'
// * Error: invalid line '0.75'
// * Error: invalid line 'Coffee blah'
|
70,807,006 | 70,807,086 | Is accessing to std::array<std::uint8_t, 2> while std::uint16_t is active inside a union well defined behavior? | If I have an union
union Bytes {
std::uint16_t bytes;
std::array<std::uint8_t, 2> split_bytes;
};
and I use it like this
int main(){
auto bytes = Bytes{0xFF'EE};
// do something with bytes.split_bytes[0] and bytes.split_bytes[1]
}
Assuming the target machine is little endian, is my usage well-defined behavior?
|
Is accessing to std::array<std::uint8_t, 2> while std::uint16_t is active inside a union well defined behavior?
Reading an inactive union member is undefined behaviour. Assigning an inactive trivial union member activates it.
Since the target of your attempted type punning is std::uint8_t which is unsigned char, you can use reinterpret_cast to read a std::uint16_t. However, as you seem to be aware, the order of the bytes varies between systems, and making assumptions about the order will result in a poorly portable program.
|
70,807,171 | 70,808,717 | Time complexity/performance of edge and vertex properties in Boost Graph | Consider:
typedef adjacency_list<
listS, //out edges stored as std::list
listS, //verteices stored as std::list
directedS,
property<vertex_name_t, std::string>,
property<edge_weight_t, double>
> user_graph;
Storage of edges and vertices as std::list precludes random access via [index].
Consider further that property maps are defined so.
typedef property_map<user_graph, vertex_name_t>::type name_map_t;
typedef property_map<user_graph, edge_weight_t>::type weight_map_t;
user_graph g;
name_map_t name_map = get(vertex_name, g);
weight_map_t weight_map = get(edge_weight, g);
Even though random access of actual edges/vertices is not possible via [index], is it guaranteed that access to the name of a vertex and weight of an edge are efficient and fast under random access like so:
graph_traits<user_graph>::vertex_iterator vi, vi_end;
for(tie(vi, vi_end)=vertices(g); vi != vi_end; ++vi)
cout<<"Name of vertex is "<<name_map[*vi];//Question is, is this efficient given storage of vertices as std::list
Part of my confusion comes from general std::map characteristic that it too does not support random access (See here)
Is it the case that whether vertices are stored as std::vector or std::list or std::set, regardless, access to its property maps via vertex descriptors using some_map[vertex_descriptor] or some_map[*vertex_iterator] is always guaranteed to be efficient (constant time)?
|
is it guaranteed that access to the name of a vertex and weight of an edge are efficient and fast under random access like so:
Yes. The properties are actually stored inline with the vertex/edge node. A descriptor is effectively a type erased pointer to that node. name_map[*vi] ends up inlining to something like get<N>(*static_cast<storage_node*>(vi)) if you imagine the property storage as a kind of tuple with a get<> accessor¹.
Part of my confusion comes from general std::map characteristic that it too does not support random access
Property maps are not like std::map; They may be consecutive, they may be node-based, ordered, unordered, or even calculated. In fact Boost Property Map maybe closer to the concept of a Lense in some functional programming languages. It is a set of functions that can be used to model (mutable) projections for a given key type.
See also:
map set/get requests into C++ class/structure changes
examples like Is it possible to have several edge weight property maps for one graph?,
and Boost set default edge weight to one
Curiosity Wins... Code Gen
Let's see what code gets generated:
Live On Compiler Explorer
#include <boost/graph/adjacency_list.hpp>
#include <fmt/format.h>
using G =
boost::adjacency_list<boost::listS, // out edges stored as list
boost::listS, // vertices stored as list
boost::directedS,
boost::property<boost::vertex_name_t, std::string>,
boost::property<boost::edge_weight_t, double>>;
using V = G::vertex_descriptor;
using E = G::edge_descriptor;
void test(V v, E e, G const& g) {
auto name = get(boost::vertex_name, g);
auto weight = get(boost::edge_weight, g);
fmt::print("{} {}\n", name[v], weight[e]);
}
int main()
{
G g;
E e = add_edge(add_vertex({"foo"}, g), add_vertex({"bar"}, g), {42}, g).first;
test(vertex(0, g), e, g);
}
Prints
foo 42
But more interestingly, the codegen:
test(void*, boost::detail::edge_desc_impl<boost::directed_tag, void*>, boost::adjacency_list<boost::listS, boost::listS, boost::directedS, boost::property<boost::vertex_name_t, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, boost::no_property>, boost::property<boost::edge_weight_t, double, boost::no_property>, boost::no_property, boost::listS> const&): # @test(void*, boost::detail::edge_desc_impl<boost::directed_tag, void*>, boost::adjacency_list<boost::listS, boost::listS, boost::directedS, boost::property<boost::vertex_name_t, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, boost::no_property>, boost::property<boost::edge_weight_t, double, boost::no_property>, boost::no_property, boost::listS> const&)
sub rsp, 40
mov rax, qword ptr [rsp + 64]
movups xmm0, xmmword ptr [rdi + 24]
mov rax, qword ptr [rax]
movaps xmmword ptr [rsp], xmm0
mov qword ptr [rsp + 16], rax
mov rcx, rsp
mov edi, offset .L.str
mov esi, 6
mov edx, 173
call fmt::v7::vprint(fmt::v7::basic_string_view<char>, fmt::v7::format_args)
add rsp, 40
ret
You see, no algorithmic overhead, just dereferences.
¹ In reality, the properties are stored in a kind of Lisp-like list type that end up behaving similarly to a tuple. Boost Graph predates tuples by considerable time margin. I suppose if you want one can compare it closely to Boost Fusion's map type (which also has a type key).
|
70,807,246 | 70,807,351 | Is there any possibility that std::unordered_map collides? | I seen a post in here that you could "meet with the Birthday problem." while using std::unordered_map
When should I use unordered_map and not std::map
Which really surprises me, that is the same that saying std::unordered_map is unsafe to use. Is that true? If i'm not explaining myself, let me show you an example:
unordered_map<size_t, size_t> m;
for (size_t i = 0; i < 100; ++i)
m[i] = i;
for (size_t i = 0; i < 100; ++i)
if (m[i] != i)
cerr << "ERROR!" << endl;
If this code is in main, is there any possibility that it prints ERROR!?
|
Is there any possibility that std::unordered_map collides?
It isn't the container that has collisions, but the hash function that you provide for the container.
And yes, all hash functions - when their output range is smaller than the input domain - have collisions.
is there any possibility that it prints ERROR!?
No, it isn't possible. It's completely normal for the hash function to put multiple values into a single bucket. That will happen in case of hash collision, but it also happens with different hash values. The lookup function will get the correct value using linear search. The identity of a key is determined by the equality function, not by the hash function.
|
70,807,458 | 70,808,543 | What am I doing wrong trying to change QPushButton text at runtime? | I'm new to coding with QTCreator, and Linux Graphical Development in general. What is the, probably trivial, thing I am doing wrong here?
I could write this code and make it work easily without using the form method, but I'd really prefer to use the graphical interface, as it should be faster (once I know what compiler wants me to do).
When I enter this code it tells me that btnStopGo isn't defined in this context.
I used the forms interface to drop the button onto a form.
The code is in the file mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
...
void MainWindow::on_btnStopGo_clicked()
{
if (bDoStream){
if (bStreaming){
//TODO: Send stop stream signal, save stream to file, dispose stream
bStreaming = false;
btnStopGo->setText("Go");
}
else{
btnStopGo->setText("Stop");
bStreaming = true;
// TODO: request a stream of quotes
}
}
else {
// TODO: Get a single quote tick
}
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT;
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
...
private slots:
...
void on_btnSelect_clicked();
void on_btnStopGo_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
Other visible files in the project are : Hello2.pro, main.cpp, and mainwindow.ui. main.cpp declares mywindow as the variable to access the main window. I've tried using "ui.btnStopGo", mywindow.btnStopGo, ui->btnStopGo (blows up the compiler), and every other combo I can think of. None of them work so far.
I don't know if this is relevant but I'm using:
Qt Creator 4.11.0
Based on Qt 5.12.8 (GCC 9.3.0, 64 bit)
on a Linux Mint 20 Cinnamon with KDE added manually.
| If you put the button in the form designer, and called the button btnStopGo, then it ends up compiled into the ui_mainwindow.h and .cc files. Your MainWindow class, which you wrote yourself, doesn't have a (member) variable called btnStopGo. It does have a variable ui, which points to the user interface which was generated from the form designer.
Use ui->btnStopGo->setText("stop") instead.
|
70,807,911 | 70,808,559 | Is there a reason this is wrong? | #include <iostream>
#include <bits/stdc++.h>
#include <numeric>
using namespace std;
int
gcd (int a, int b)
{
if (a == 0)
return b;
return gcd (b % a, a);
}
int
phi (unsigned int n)
{
unsigned int result = 1;
for (int i = 2; i < n; i++)
if (gcd (i, n) == 1)
result++;
return result;
}
int
gen_priv_n (int p1, int p2)
{
int n = phi (p1) * phi (p2);
return n;
}
int
gen_pub_n (int p1, int p2)
{
int n = (p1 * p2);
return n;
}
int
gen_priv_key (int n, int e)
{
int x = (phi (e) * n + 1) / e;
return x;
}
int
encrypt (int n, int e, int data)
{
int crypt_data = int (pow (data, e)) % n;
return crypt_data;
}
int
decrypt (int c, int d, int n)
{
int data = int (pow (c, d)) % n;
return data;
}
int
main ()
{
int ph1 = 53;
int ph2 = 59;
int e = 3;
int message = 89;
int pub_n = gen_pub_n (ph1, ph2);
cout << "PUBN " << pub_n << "\n";
int priv_n = gen_priv_n (ph1, ph2);
cout << "PRIVN " << priv_n << "\n";
int d = gen_priv_key (gen_priv_n (ph1, ph2), e);
cout << "PRIVKEY " << d << "\n";
int c = encrypt (pub_n, e, message);
cout << "ENCRYPTED " << c << "\n";
int data = decrypt (c, d, pub_n);
cout << "MESSAGE " << data;
}
The PUBN, PRIVN, PRIVKEY, and ENCRYPTED all return the expected numbers, however, the decrypt function should return 89(the message variable), but does not. I'm assuming an arithmetic error in the codes order of operations but I'm not sure. Can the issue be pointed out?
The results of the variables are:
PUBN 3127
PRIVN 3016
PRIVKEY 2011
ENCRYPTED 1394
MESSAGE -763 <-- unexpected result, should be 89
| The decrypt (and encrypt) function is broken in that it (a) is exceeding platform representation of int, and (b) is unnecessarily using pow to do it in the first place.
In your trivial example you should be utilizing a technique called modulo chaining . The crux of this is the following.
(a * b) % n == ((a % n) * (b % n)) % n
In your case, you're performing simple exponentiation. That means, for example a^2 % n would be:
(a * a) % n = ((a % n) * (a % n)) % n
Similarly, a^3 % n is:
(a * a * a) % n = (((a % n) * (a % n)) % n) * (a % n)) % n
Using modulo chaining allows you to compute what would otherwise be very large product computation mod some N, so long as no product term pair exceeds your platform representation (and it doesn't in your case).
A trivial version of integer pow that does this is below:
int int_pow_mod(int c, int d, int n)
{
int res = 1;
// may as well only do this once
c %= n;
// now loop.
for (int i=0; i<d; ++i)
res = (res * c) % n;
return res;
}
Understand, this is no silver bullet. You can easily contrive a c that still produces a product exceeding INT_MAX, but in your case, that won't happen due to your choices of starting material. A general solution will employ this with a big-number library that allows exceeding platform int representation. Regardless, doing that should deliver what you seek, as shown below:
#include <iostream>
using namespace std;
unsigned int gcd(unsigned int a, unsigned int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
int phi(unsigned int n)
{
unsigned int result = 1;
for (unsigned int i = 2; i < n; i++)
if (gcd(i, n) == 1)
result++;
return result;
}
int gen_priv_n(int p1, int p2)
{
int n = phi(p1) * phi(p2);
return n;
}
int gen_pub_n(int p1, int p2)
{
int n = (p1 * p2);
return n;
}
int gen_priv_key(int n, int e)
{
int x = (phi(e) * n + 1) / e;
return x;
}
int int_pow_mod(int c, int d, int n)
{
int res = 1;
// may as well only do this once
c %= n;
// now loop.
for (int i=0; i<d; ++i)
res = (res * c) % n;
return res;
}
int encrypt(int n, int e, int data)
{
int crypt_data = int_pow_mod(data, e, n);
return crypt_data;
}
int decrypt(int c, int d, int n)
{
int data = int_pow_mod(c, d, n);
return data;
}
int main()
{
int ph1 = 53;
int ph2 = 59;
int e = 3;
int message = 89;
int pub_n = gen_pub_n(ph1, ph2);
cout << "PUBN " << pub_n << "\n";
int priv_n = gen_priv_n(ph1, ph2);
cout << "PRIVN " << priv_n << "\n";
int d = gen_priv_key(gen_priv_n(ph1, ph2), e);
cout << "PRIVKEY " << d << "\n";
int c = encrypt(pub_n, e, message);
cout << "ENCRYPTED " << c << "\n";
int data = decrypt(c, d, pub_n);
cout << "MESSAGE " << data;
}
Output
PUBN 3127
PRIVN 3016
PRIVKEY 2011
ENCRYPTED 1394
MESSAGE 89
|
70,808,072 | 70,808,468 | c++ not getting inputs when looping | #include <iostream>
using namespace std;
int main(){
char opp;
double num1,num2;
bool cont=true;
while (true){
cout<<"Enter first number"<<endl;
cin>>num1;
cout<<"Enter operator"<<endl;
cin>>opp;
cout<<"Enter second number"<<endl;
cin>>num2;
if (opp=='+'){
cout<<num1<<opp<<num2<<"="<<num1+num2<<endl;
}
else if (opp=='-'){
cout<<num1<<opp<<num2<<"="<<num1-num2<<endl;
}
else if (opp=='*'){
cout<<num1<<opp<<num2<<"="<<num1*num2<<endl;
}
else if (opp=='/'){
cout<<num1<<opp<<num2<<"="<<num1/num2<<endl;
}
else{
cout<<"INVALID OPERATOR"<<endl;
}
}
return 0;
}
I am new to c++ and have written a basic calculator, now I wanted to make the main function loop forever. But when I do this it just keeps looping through the prints and doesn't let the user input anything.
| You can get the input and store it in std::string and then convert it to anything that is needed (like double, char, etc).
Also, it's better to use a switch statement instead of that if-else if-else chain.
With a bit of refactoring (and keeping things as simple as possible):
#include <iostream>
#include <string>
#include <stdexcept>
struct OperationData
{
double num1;
double num2;
double result;
char opp;
};
double get_input_double( )
{
std::string num_str;
std::getline( std::cin, num_str );
return std::stod( num_str );
}
void printResult( const OperationData& operation_data )
{
std::cout << operation_data.num1 << ' ' << operation_data.opp
<< ' ' << operation_data.num2 << " = " << operation_data.result << '\n';
}
int main( )
{
while ( true )
{
std::cout << "Enter e or E to exit the program, or any other character to continue: ";
std::string isExiting { " " };
std::getline( std::cin, isExiting );
if ( isExiting[0] == 'e' || isExiting[0] == 'E' ) { break; }
std::cout << "Enter the first number\n";
double num1 { };
try
{
num1 = get_input_double( );
}
catch ( const std::invalid_argument& ) { std::cout << "Invalid argument\n"; continue; }
catch ( const std::out_of_range& ) { std::cout << "Entered value out of range\n"; continue; }
std::cout << "Enter the operator\n";
std::string opp_str { " " };
std::getline( std::cin, opp_str );
const char opp { opp_str[0] };
std::cout << "Enter the second number\n";
double num2 { };
try
{
num2 = get_input_double( );
}
catch ( const std::invalid_argument& ) { std::cout << "Invalid argument\n"; continue; }
catch ( const std::out_of_range& ) { std::cout << "Entered value out of range\n"; continue; }
switch ( opp )
{
case '+' :
printResult( { num1, num2, num1 + num2, opp } );
break;
case '-' :
printResult( { num1, num2, num1 - num2, opp } );
break;
case '*' :
printResult( { num1, num2, num1 * num2, opp } );
break;
case '/' :
printResult( { num1, num2, num1 / num2, opp } );
break;
default :
std::cout << "INVALID OPERATOR\n";
}
}
}
Sample input/output:
Enter e or E to exit the program, or any other character to continue:
Enter the first number
45.5
Enter the operator
/
Enter the second number
3
45.5 / 3 = 15.1667
Enter e or E to exit the program, or any other character to continue: E
Note: If the input is not convertible to double, std::stod will throw a std::invalid_argument or a std::out_of_range exception and in the above code there are try-catch blocks to handle the exceptions. An appropriate message will be displayed and the program will jump to the beginning of the loop to start the process from the first step whenever an exception is thrown.
|
70,808,153 | 70,808,185 | output and misunderstanding in C++ | I want to know why the output is (1), and why In the second assignment to variable b, the expression (i+=2) does not get evaluated. finally how does this program execute step by step?
I am still a beginner.
`
int i = 0;
bool t = true;
bool f = false,
b;
b = (t && ((i++) == 0));
b = (f && (i += 2 > 0));
cout << i << endl;
`
| Because the && operator short-circuits and f is false, 1 += 2 is not being evaluated.
Since the entire expression can only be true if both operands to && are true, there is no need to evaluate (i += 2 > 0) to determine that the value of the entire expression is false. Given the lack of need to evaluate the second operand in this scenario, many programming languages guarantee that it will not be, including C and C++.
Be careful about using operands with side-effects in boolean expressions.
|
70,808,433 | 70,810,764 | Make a range from Iterated function application | If I have a function
std::array<unsigned,2> fib(std::array<unsigned,2> p)
{
return {p[1],p[1]+p[0]};
}
I'd like to have a way to elegantly generate the infinite range
[x,fib(x),fib(fib(x)),fib(fib(fib(x))),...]
This comes up frequently enough that I need to find what's the best way to do this?
| I found that the generator from this repo works well:
template<typename F, typename Arg>
tl::generator<Arg> iterated_application(F fn, Arg x) {
while (true) {
co_yield x;
x = fn(x);
}
}
Which can be used as
int main()
{
auto fib = [](auto a) {return std::array{ a[1],a[1] + a[0] }; };
for (auto i : iterated_application(fib, std::array{ 0,1 })
| std::views::keys
| std::views::take(10))
std::cout << i << std::endl;
}
https://godbolt.org/z/v73zvY9cM
|
70,808,560 | 70,808,706 | How to detect when a process doesnt exist anymore? | Trying to find a way to get notified when a process doesn't exist anymore, other way than constantly checking for something like"if process exist".
Which options do i have?
| You can open a process with OpenProcess and use WaitForSingleObject on that process. The function WaitForSingleObject will return as soon as the target process no longer exists. However, you will have to have one thread in a constant wait state if you want your program to be immediately notified when the target process no longer exists.
An alternative would be to call RegisterWaitForSingleObject, which will automatically create a thread for you (or use an existing thread in the thread pool), which will wait on the process and will call the callback function that you specified, as soon as the target process no longer exists.
|
70,808,565 | 74,495,558 | Trying to implement NTP Client using Managed C++ but getting date from 1899 using time.windows.com | I am trying to implement a code to get time from time.windows.com but it returns a weird date (year of the date I get is 1899). Since the same servers work for my unmanaged C++ code using WinSock, I can imagine that something must be wrong with my code itself. Can someone look at my code below and tell me what I am doing wrong?
typedef unsigned int uint;
typedef unsigned long ulong;
long GetTimestampFromServer()
{
System::String^ server = L"time.windows.com";
array<unsigned char>^ ntpData = gcnew array<unsigned char>(48);
ntpData[0] = 0x1B;
array<System::Net::IPAddress^>^ addresses = System::Net::Dns::GetHostEntry(server)->AddressList;
System::Net::IPEndPoint^ ipEndPoint = gcnew System::Net::IPEndPoint(addresses[0], 123);
System::Net::Sockets::Socket^ socket = gcnew System::Net::Sockets::Socket
(
System::Net::Sockets::AddressFamily::InterNetwork,
System::Net::Sockets::SocketType::Dgram,
System::Net::Sockets::ProtocolType::Udp
);
try
{
socket->Connect(ipEndPoint);
socket->ReceiveTimeout = 3000;
socket->Send(ntpData);
socket->Receive(ntpData);
socket->Close();
}
catch (System::Exception^ e)
{
System::Console::WriteLine(e->Message);
return 0;
}
const System::Byte serverReplyTime = 40;
ulong intPart = System::BitConverter::ToUInt32(ntpData, serverReplyTime);
ulong fractPart = System::BitConverter::ToUInt32(ntpData, serverReplyTime + 4);
intPart = SwapEndianness(intPart);
fractPart = SwapEndianness(fractPart);
long long milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
System::DateTime networkDateTime = (gcnew System::DateTime(1900, 1, 1, 0, 0, 0, System::DateTimeKind::Utc))->AddMilliseconds((long)milliseconds);
std::cout << ConvertToTimestamp(networkDateTime);
return 0;
}
static uint SwapEndianness(ulong x)
{
return (uint)(((x & 0x000000ff) << 24) +
((x & 0x0000ff00) << 8) +
((x & 0x00ff0000) >> 8) +
((x & 0xff000000) >> 24));
}
long ConvertToTimestamp(System::DateTime value)
{
System::TimeZoneInfo^ NYTimeZone = System::TimeZoneInfo::FindSystemTimeZoneById(L"Eastern Standard Time");
System::DateTime NyTime = System::TimeZoneInfo::ConvertTime(value, NYTimeZone);
System::TimeZone^ localZone = System::TimeZone::CurrentTimeZone;
System::Globalization::DaylightTime^ dst = localZone->GetDaylightChanges(NyTime.Year);
NyTime = NyTime.AddHours(-1);
System::DateTime epoch = System::DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();
System::TimeSpan span = (NyTime - epoch);
return (long)System::Convert::ToDouble(span.TotalSeconds);
}
| David Yaw pushed me in the right direction. Big thanks to him, I finally got my code to work. There was a lot of incorrectness associated with different statements throughout the method. I have fixed them and posting the new code below.
ref class SNTP
{
public: static DateTime GetNetworkTime()
{
System::String^ ntpServer = "time.windows.com";
auto ntpData = gcnew cli::array<unsigned char>(48);
ntpData[0] = 0x1B; //LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode)
auto addresses = System::Net::Dns::GetHostEntry(ntpServer)->AddressList;
auto ipEndPoint = gcnew System::Net::IPEndPoint(addresses[0], 123);
auto socket = gcnew System::Net::Sockets::Socket
(
System::Net::Sockets::AddressFamily::InterNetwork,
System::Net::Sockets::SocketType::Dgram,
System::Net::Sockets::ProtocolType::Udp
);
socket->Connect(ipEndPoint);
socket->ReceiveTimeout = 3000;
socket->Send(ntpData);
socket->Receive(ntpData);
socket->Close();
const System::Byte serverReplyTime = 40;
System::UInt64 intPart = System::BitConverter::ToUInt32(ntpData, serverReplyTime);
System::UInt64 fractPart = System::BitConverter::ToUInt32(ntpData, serverReplyTime + 4);
intPart = SwapEndianness(intPart);
fractPart = SwapEndianness(fractPart);
auto milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
auto networkDateTime = (System::DateTime(1900, 1, 1, 0, 0, 0, System::DateTimeKind::Utc)).AddMilliseconds((System::Int64)milliseconds);
return networkDateTime.ToLocalTime();
}
private: static System::UInt32 SwapEndianness(System::UInt64 x)
{
return (System::UInt32)(((x & 0x000000ff) << 24) +
((x & 0x0000ff00) << 8) +
((x & 0x00ff0000) >> 8) +
((x & 0xff000000) >> 24));
}
};
|
70,808,793 | 70,809,116 | Can CUDA Kernels Modify Host Memory? | Is there any way to get a kernel to modify an integer via passing a pointer to that integer to the kernel? It seems the pointer is pointing to an address in device memory, so the kernel does not affect the host.
Here's a simplified example with the behavior I've noticed.
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <iostream>
__global__
void change_cuda(int* c);
void change_var(int* c);
int main() {
using namespace std;
int c = 0;
int* ptc = &c;
change_var(ptc); // *ptc = 123
cout << c << endl;
cudaError_t errors;
cudaMallocManaged((void**)&ptc, sizeof(int));
change_cuda<<<1, 1>>> (ptc); // *ptc = 555
errors = cudaDeviceSynchronize();
cudaFree(ptc);
cout << cudaGetErrorString(errors) << endl;
cout << c << endl;
return 0;
}
__global__
void change_cuda(int* c) {
*c = 555;
}
void change_var(int* c) {
*c = 123;
}
Ideally, this would modify c to be 555 at the end, but the output of this example is
123
no error
123
Clearly I am misunderstanding how this works. What is the correct way to get the behavior that I expect?
| Yes, you have a misunderstanding. cudaMallocManaged is an allocator like, for example, malloc or new. It returns a pointer that points to a new allocation, of the size requested.
It is not some method to allow your host stack based variable to be accessed from device code.
However, the allocated area pointed to by the pointer returned by cudaMallocManaged can be accessed either from device code or host code. (It will not point to your c variable.)
You can minimally fix your code by making the following changes. 1. comment out the call to cudaFree. 2. print out the value of *ptc rather than c. Perhaps a more sensible change might be like this:
int main() {
using namespace std;
int* ptc;
cudaMallocManaged((void**)&ptc, sizeof(int));
change_var(ptc); // *ptc = 123
cout << *ptc << endl;
cudaError_t errors;
change_cuda<<<1, 1>>> (ptc); // *ptc = 555
cudaDeviceSynchronize();
errors = cudaGetLastError();
cout << cudaGetErrorString(errors) << endl;
cout << *ptc << endl;
return 0;
}
|
70,808,916 | 70,808,972 | C++ "Exception has occurred" during assignment statement to a double array | I am relatively new to C++, and I'm trying to write a simple code to solve a partial differential equation.
The solution code is repeated a number of times with a different value of a time increment dt. During the fifth iteration (j=4), my IDE throws an error:
Exception has occurred.
EXC_BAD_ACCESS (code=2, address=0x7ffeeecbd490)
when it is trying to assign a value to a double array called u2. The error specifically occurs on the line:
u2[0] = 1;
From some debugging, I noticed that Visual Studio Code does something different during the reinitialization of u2 on the previous line. When j = 0, 1, 2, and 3, the variables list shows u2 as all zero values after
double u2[numTimes[j]];
When j = 4, suddenly u2's elements are shown as "??". This suggested to me that maybe the reinitialization didn't occur as expected. For instance, maybe dt caused the size of u2 to be larger than c++ can handle? Some googling disagrees that I hit a size limit at 1,000,000 elements. What is going on here?
Edit: When I looked into std::vector, the just typing
vector<double> u1[1000000];
caused the exact same error message. It therefore doesn't seem that std::vector is a solution. Should I dynamically update u1 and u2 up to the desired number of elements rather than preallocating? I don't see why that would be any more possible though.
Edit 2:
To preallocate memory for a vector, do this:
std::vector<double> u;
u.reserve(1000000);
Do not do this:
std::vector<double> u[1000000];
The array style memory allocation results in the same problem as the original implementation had because you are creating a million vectors not a vector of 1,000,000.
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
// Global System Parameters
double g = // a real value;
double R = // a real value;
double f_du1dt(double u2)
{
return // some equation;
}
double f_du2dt(double u1)
{
return // some other equation;
}
int main()
{
double dt[] = {1, 0.01, 0.001, 0.0001, 0.00001, 0.000001, 0.0000001, 0.00000001};
int numDts = sizeof(dt) / sizeof(dt[0]);
double tmax = 10;
int numTimes[numDts];
for (int k = 0; k < numDts; k++)
{
numTimes[k] = tmax / dt[k] + 1;
}
// Iterate through all dts
for (int j = 0; j < numDts; ++j)
{
double u1[numTimes[j]];
u1[0] = 0;
double u2[numTimes[j]];
u2[0] = 1; // This is the line where the problem happens
double du1dt;
double du2dt;
// cout << numTimes << endl;
// Euler Integrator
for (int i = 0; i < numTimes[j]; i++)
{
// Integrator here
}
/*
Output to a csv file to plot
*/
}
return 0;
}
| When j is 4, your numTimes[k] should be 100001. You're allocating 2 arrays of double at that size on your stack. That puts it at 1.6MB approx. That may exceed your stack size in some environments. It's going to get worse for higher values of j.
I suggest to not use variable length arrays that are allocated on stack. Use std::vector instead that can automatically allocate and re-allocate memory as needed to fit itself.
|
70,809,087 | 70,809,194 | How can I solve this problem with chain inheritance c++? | Basically I'm studying about Chain Inheritance in my college and I'm expected to build a program with this, the problem I have is in this part:
template <class NUM_TYPE>
class FilterPositiveNumber: public Filtro<NUM_TYPE> {
bool dadoValido(NUM_TYPE& d) const override {
// TODO: Implemente este metodo.
if (d > 0){
return true;
}else{
return false;
}
}
};
class FilterNaturalString: public Filtro<std::string> {
bool dadoValido(std::string& d) const override {
std::string::const_iterator it = d.begin();
while (it != d.end() && std::isdigit(*it)) ++it;
return !d.empty() && it == d.end();
}
};
void convert2int(std::vector<std::string>& in, std::vector<int>& out) {
Filtro<std::string>* new_check;
new_check = new FilterNaturalString;
for(std::string i : in){
if(new_check->dadoValido(i)){
out.push_back(stoi(i));
}
}
}
template <class NUM_TYPE> void test_filter_square_roots() {
std::vector<unsigned> entrada;
std::vector<unsigned> saida;
read_input(entrada);
Filtro<int>* new_check;
new_check = new FilterPositiveNumber;
}
I get this error
error: invalid use of template-name ‘FilterPositiveNumber’ without an argument list
new_check = new FilterPositiveNumber;
I don't understant why I get a error in the second time I try to instantiate a "Filtro" if I called it the exact same way when doing it to FilterNaturalString.
| template <class NUM_TYPE>
class FilterPositiveNumber: public Filtro<NUM_TYPE>
{
...
};
defines a class template, a blueprint for a potential family of classes. To use it you must tell the compiler, or the compiler must be able to infer, what type the template is to be specialized on in order to become a class.
class FilterNaturalString: public Filtro<std::string>
{
...
};
defines a class.
So
new_check = new FilterNaturalString;
is valid but
new_check = new FilterPositiveNumber<int>;
is required to allow the compiler to fill in the blanks and create a class that can be instantiated from the template.
|
70,809,151 | 70,809,538 | Default move constructor failing when used in a constexpr context, | I have an issue with the default move constructor in Visual Studio 2022 (/std:c++latest) in a constexpr context. I do not see the issue in Visual Studio 2019. I have two questions:
Is it my code or Visual Studio 2022 that is incorrect? If my code is incorrect then why?
Are similar issues are seen in gcc or clang? (I do currently have access to those compilers.)
Problem statement
In the code below, I have two true/false switches:
DEFAULT_MOVE and CONSTEXPR, therefore giving me four possible programs.
DEFAULT_MOVE controls whether the default move constuctor or a
home-brew move constructor is used.
CONSTEXPR controls whether an instance of Container is created at
compile-time or run-time.
The code does not compile when both DEFAULT_MOVE and CONSTEXPR are both true, yielding the message:
error C3615: constexpr function 'Containerstd::u8string_view,3::Container' cannot result in a constant expression
However, under any other of the three switch combinations the code compiles successfully.
I would have expected the code to compile in all four cases.
#include <array>
#include <cassert>
#include <string_view>
//switches
#define DEFAULT_MOVE true
#define CONSTEXPR true
template<typename T, size_t N>
struct Container{
std::array<T, N> x;
template<typename... Args>
constexpr explicit Container(Args&&...args) : x{std::forward<Args>(args)...} {}
#if DEFAULT_MOVE
//default move ctor
constexpr Container(Container&&) noexcept = default;
#else
//home-brew move ctor
constexpr Container(Container&& other) noexcept : x{} {
for (size_t n{0} ; T& e : other.x)
x[n++] = std::move(e);
}
#endif
constexpr Container(const Container&) = delete;
constexpr Container& operator=(Container&&) = delete;
constexpr Container& operator=(const Container&) = delete;
constexpr ~Container() = default;
};
using X = Container<std::u8string_view, 3>;
using Y = Container<X, 2>;
int main() {
#if CONSTEXPR
// constexpr creation of a Y object
constexpr Y a{X{u8"a",u8"b"}, X{u8"a"}};
static_assert(a.x[0].x[1] == u8"b");
#else
// runtime creation of a Y object
const Y a{X{u8"a",u8"b"}, X{u8"a"}};
assert(a.x[0].x[1] == u8"b");
#endif
}
| You should use: constexpr Container(Container&&) = default;. The default implementation is already noexcept in most cases.
From cppreference:
default constructors, copy constructors, move constructors that are implicitly-declared or defaulted on their first declaration unless:
a constructor for a base or member that the implicit definition of the constructor would call is potentially-throwing
a subexpression of such an initialization, such as a default argument expression, is potentially-throwing
a default member initializer (for default constructor only) is potentially-throwing
Best way to validate things like this is using https://godbolt.org/. It let's you try out a lot of different compilers quickly.
Add #include <cstddef> to make size_t work without std::size.
Clang/LLVM v13 can build this with -std=c++20, as can Visual C++ as with /std:c++20 (19.30 on godbolt is VS 2022's compiler).
I tried /std:c++latest and it also works.
What is the full set of compiler switches you are using? Also try cl -Bv and see what version of the compiler exactly you are using.
|
70,809,242 | 70,809,274 | Is it possible for an address of an std::array member to be null in C++? | Is it possible to modify a to make the if-statement fail?
std::array<int,4> a = {{1,2,3,4}};
for (int i=0;i<a.size();i++)
{
auto ptr = &a[i];
if (ptr != nullptr)
{
printf("value at %d is %d\n",i,a[i]);
}
else
{
printf("Invalid array\n");
}
}
| The address of an element in a standard library container can't be null, as long as you are using the container's API properly. This is because, assuming you meet all preconditions of the API, the container guarantees that all of its elements are valid objects, and a valid object never has a null address. As soon as you violate the preconditions, however (for example, popping from an empty vector), the entire program has undefined behaviour, and you might end up seeing "impossible" branches of if statements getting executed.
In the snippet shown, for example, attempting to access a[4] will give the program undefined behaviour. It probably will not result in the else branch being taken, but you never know.
|
70,809,725 | 70,809,853 | How do I make my header, function and main file work together, I always get: error: Id returned 1 exit status | I made a very simple C++ program where the goal is to use functions in different files. The function justs prints out a certain message passed in a parameter. After some research, I read that for such project, I need 3 files: the main, the header and the function (apparently I shouldn't put the function code in the header file.) I now have three files:
main.cpp (main file)
simple.h (header file (function definition))
simple.cpp (function file)
Whenever I try to make them work together, I always get the same error:
C:\Users\juuhu\AppData\Local\Temp\ccQRa0R0.o:main.cpp:(.text+0x43): undefined reference to `message(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
collect2.exe: error: ld returned 1 exit status
Here's the code of the three files:
main.cpp
#include <iostream>
#include "simple.h"
using namespace std;
int main(){
message("Hello world!");
return 0;
}
simple.h
#ifndef SIMPLE_H_INCLUDED
#define SIMPLE_H_INCLUDED
#include <string>
void message(std::string message);
#endif
simple.cpp
#include "simple.h"
void message(std::string message){
cout << message;
}
| I was use visual studio 2019 to compile your code. First compile error output:"Error C2065 'cout': undeclared identifier message".
When I add #include<iostream> in simple.h and change simple.cpp message function the cout to std::cout, the program output "Hello world!"
simple.h
#ifndef SIMPLE_H_INCLUDED
#define SIMPLE_H_INCLUDED
#include<iostream>
#include <string>
void message(std::string message);
#endif
simple.cpp
#include "simple.h"
void message(std::string message) {
std::cout << message;
}
you can try again, hope you are successful to compile the code and get your to want.
|
70,810,035 | 70,810,108 | Restarting a loop in C++? | I am in need of assistance with my program. I have to code a three-round word scramble program using 10 keywords that will appear scrambled to the user for them to guess it. My problem is that after one word the code just simply exits the loop. My intention is for the loop to be used again for a second and third time before exiting.
Here is the code:
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <string>
using namespace std;
int main() {
while (true) {
enum fields { KEY, HINT, Locked };
const int NUM_WORDS = 10;
const string WORDS[NUM_WORDS][Locked] = {
{"MITCHELL", "NICKNAME IS MITCH,SO WHAT IS MY NAME?"},
{"PIZZA", "MY FAVORITE FOOD, IS ITALY."},
{"ROYCE", "SOME TUMBLE AND SOME ROLLS...?"},
{"INFINITY", "THE IMAGINARY NUMBER IS?"},
{"AMY", "FAVORITE SONIC CHARACTER IS ?"},
{"FIAT", "CRYPTO OVER; THIS TYPE OF CURRENCY?"},
{"RUSSIA", "SAINT PETERSBURG IS IN ?"},
{"DONETELLO", "TEENAGE MUTANT NINJA TURTLES"},
{"SON", "BROOKLYN PEOPLE SAY THIS WORD"},
{"FUN", "FEELING HAPPY"}
};
srand(static_cast<unsigned int>(time(0)));
int choice = (rand() % NUM_WORDS);
string theWord = WORDS[choice][KEY]; // GUESSING THE WORDS
string theHint = WORDS[choice][HINT]; // Hint for Words
// Randomizing using the string; swapping charcters equal to the length of the words
string Jumble = theWord; // jumbled version of word
int length = Jumble.size();
for (int i = 0; i < length; ++i) {
int index1 = (rand() % length); // Random
int index2 = (rand() % length); // Random
char temp = Jumble[index1];
Jumble[index1] = Jumble[index2]; // Swapping charcters
Jumble[index2] = temp;
}
cout << "\t\t\Welcome to Word Jumble!\n\n"; // USING CARRIAGE RETURN; USING TITLE
cout << "Unscramble the letters to make a word.\n";
cout << "Enter 'hint' for a hint.\n";
cout << "Enter 'quit' to quit the game.\n\n";
cout << "The jumble is:" << Jumble;
string guess;
cout << "\n\nYour guess:";
cin >> guess;
while ((guess != theWord) && (guess != "quit")) {
if (guess == "hint") {
cout << theHint;
} else {
cout << "Sorry, that's not it.";
}
cout << "\n\nYour guess:";
cin >> guess;
}
if (guess == theWord) {
cout << "\nTHat's it! You guessed it!\n";
}
cout << "\nThanks for playing.\n";
return 0;
}
}
| #include <cstdlib>
#include <ctime>
#include <iostream>
#include <string>
using namespace std;
int main() {
while (true) {
enum fields { KEY, HINT, Locked };
const int NUM_WORDS = 10;
const string WORDS[NUM_WORDS][Locked] = {
{"MITCHELL", "NICKNAME IS MITCH,SO WHAT IS MY NAME?"},
{"PIZZA", "MY FAVORITE FOOD, IS ITALY."},
{"ROYCE", "SOME TUMBLE AND SOME ROLLS...?"},
{"INFINITY", "THE IMAGINARY NUMBER IS?"},
{"AMY", "FAVORITE SONIC CHARACTER IS ?"},
{"FIAT", "CRYPTO OVER; THIS TYPE OF CURRENCY?"},
{"RUSSIA", "SAINT PETERSBURG IS IN ?"},
{"DONETELLO", "TEENAGE MUTANT NINJA TURTLES"},
{"SON", "BROOKLYN PEOPLE SAY THIS WORD"},
{"FUN", "FEELING HAPPY"}
};
srand(static_cast<unsigned int>(time(0)));
int choice = (rand() % NUM_WORDS);
string theWord = WORDS[choice][KEY]; // GUESSING THE WORDS
string theHint = WORDS[choice][HINT]; // Hint for Words
// Randomizing using the string; swapping charcters equal to the length of the words
string Jumble = theWord; // jumbled version of word
int length = Jumble.size();
for (int i = 0; i < length; ++i) {
int index1 = (rand() % length); // Random
int index2 = (rand() % length); // Random
char temp = Jumble[index1];
Jumble[index1] = Jumble[index2]; // Swapping charcters
Jumble[index2] = temp;
}
cout << "\t\t\Welcome to Word Jumble!\n\n"; // USING CARRIAGE RETURN; USING TITLE
cout << "Unscramble the letters to make a word.\n";
cout << "Enter 'hint' for a hint.\n";
cout << "Enter 'quit' to quit the game.\n\n";
cout << "The jumble is:" << Jumble;
string guess;
cout << "\n\nYour guess:";
cin >> guess;
while ((guess != theWord) && (guess != "quit")) {
if (guess == "hint") {
cout << theHint;
}
else {
cout << "Sorry, that's not it.";
}
cout << "\n\nYour guess:";
cin >> guess;
}
if (guess == theWord) {
cout << "\nTHat's it! You guessed it!\n";
}
cout << "\nThanks for playing.\n";
}
return 0;
}
|
70,810,045 | 70,815,845 | How to generate a list of unknown number of items without using a loop | Is it possible to generate a list of items if I don't know how many there are in the list, without using a loop?
Here's an example (using a loop):
vector<int> bits(int N) {
vector<int> v;
while (N != 0) {
v.push_back(N & 1);
N >>= 1;
}
return v;
}
In this example, I don't know how many items the returned vector will have beforehand. And while it is totally fine using a loop to implement this function, my question (as I'm trying to learn C++ and STL) is if there's a way to do the same thing but without any loops.
| Something along these lines perhaps, if you absolutely insist on going out of your way to get STL to run loops for you:
class BitIterator {
public:
using value_type = int;
using difference_type = std::size_t;
using pointer = int*;
using reference = int&;
using iterator_category = std::input_iterator_tag;
BitIterator(int n = 0) : n_(n) {}
int operator*() const { return n_ & 1; }
BitIterator& operator++() { n_ >>= 1; return *this; }
bool operator==(const BitIterator& other) const { return n_ == other.n_; }
bool operator!=(const BitIterator& other) const { return n_ != other.n_; }
private:
int n_ = 0;
};
std::vector<int> bits(int N) {
return {BitIterator(N), BitIterator(0)};
}
Demo
|
70,810,602 | 70,811,958 | C++ Container of Pointers/References to Existing Objects | I have an existing container filled with automatically allocated struct objects like so:
std::vector<Object> objectList {obj1, obj2, obj3};
I'm trying to create a new container useObjectList that consists of pointers/references that point to those existing objects so that I am able to access and modify the object member values from either list.
I've tried to achieve this by creating a container of shared pointers
std::vector<std::shared_ptr<Object>> useObjectList {std::make_shared<Object>(objectList[1])};
but it hasn't worked out at all (given my limited knowledge, I assume std::make_shared constructs and/or allocates a new object entirely?).
I'd appreciate any advice I could get.
| To use a "C++ Container of Pointers/References to Existing Objects", or pretty much anything else, you should understand the concept of ownership. Summary: ownership is responsibility for cleanup. You should think which entity should delete your objects. Often, you should rethink this whenever you change your code or add features to it.
std::vector<Object> objectList {obj1, obj2, obj3}; - here, objectList contains copies of objects obj1, obj2 and obj3, and is responsible for deleting them (i.e. owns them). Whichever entity contained the original obj1, obj2 and obj3 retains ownership of these (i.e. will delete them).
A wider context:
void do_stuff()
{
Object obj1;
Object obj2;
Object obj3;
std::vector<Object> objectList {obj1, obj2, obj3};
}
Here, the scope (or "stack frame") of function do_stuff owns the three objects: they will be deleted when control goes out of the scope. This is a situation where something other than an object owns objects.
std::vector<Object*> objectList {&obj1, &obj2, &obj3}; - here, objectList contains pointers to objects obj1, obj2 and obj3. The ownership of objects themselves is not changed - whatever owned them continues owning them. Some comment mentions "always recommend avoiding using raw pointers"; "always" is nonsense, but this is a good example for illustrating that recommendation.
A wider context:
std::vector<Object*> someObjectList;
void do_stuff()
{
Object obj1;
Object obj2;
Object obj3;
std::vector<Object*> objectList {&obj1, &obj2, &obj3};
someObjectList = objectList;
}
Here, the stack frame of function do_stuff owns the three objects. If you have pointers to these objects, it's easy to "send" them to some other entity (someObjectList), which will store the pointers even after the objects have been cleaned up. This is the reason why people "recommend avoiding using raw pointers"; but the real problem here is more fundamental - it's having a "Container of Pointers/References to Existing Objects". This is what people should recommend not doing.
If you really want to reference existing objects, you should make sure your ownership pattern supports this. You can do this in either of these ways:
Use an entity which owns the objects; make sure all lists of pointers to objects get deleted before the "owner of everything" is deleted. Often, the semantics of your application demand this anyway.
Use shared ownership. For that, you should apply shared ownership right at the creation point of your objects.
std::shared_ptr<Object> obj1 = std::make_shared(whatever1);
std::shared_ptr<Object> obj2 = std::make_shared(whatever2);
std::shared_ptr<Object> obj3 = std::make_shared(whatever3);
std::vector<std::shared_ptr<Object>> objectList(obj1, obj2, obj3);
You should think about a situation where the only "link" to the objects is your list of pointers. Does this make sense in your application? If yes, use shared ownership. If not, this is not a good idea, because it hides bugs.
|
70,810,746 | 70,810,771 | how to call overloaded function in the same version of another in c++ | Greetings I have a class with overloaded functions I do not want to re type whole thing again and again so I created function(s) with different parameters see below example and I get compilation errors please help consider below snippet
class A {
public:
inline A();
inline ~A();
QString insert(QString& id, QString& name, QString& email_id, QString& contact_id, QString& reg_num, Address addr, QUrl& urlToLocalFile );
QString insert(QString& id, QString& name, QString& email_id, QString& contact_id, QString& reg_num, Address addr, QString& pathToLocalFile );
}
inline QString insert(QString& id, QString& name, QString& email_id, QString& contact_id, QString& reg_num, Address addr, QUrl& urlToLocalFile ) {
this->insert(id, name, email_id, contact_id, reg_num, addr, urlToLocalFile.toLocalFile()); // throws error no matching member function for call to insert
}
inline QString insert(QString& id, QString& name, QString& email_id, QString& contact_id, QString& reg_num, Address addr, QString& pathToLocalFile ) {
/*some tasks*/
}
Thanks in advance.
| You have to be in the scope of the class A when defining the member functions outside the class. This can be done using A:: as shown below.
class A {
public:
inline A();
inline ~A();
QString insert(QString& id, QString& name, QString& email_id, QString& contact_id, QString& reg_num, Address addr, QUrl& urlToLocalFile );
QString insert(QString& id, QString& name, QString& email_id, QString& contact_id, QString& reg_num, Address addr, const QString& pathToLocalFile ); //note the const added for the last parameter
}; //added missing semicolon here
//note the A:: used below
inline QString A::insert(QString& id, QString& name, QString& email_id, QString& contact_id, QString& reg_num, Address addr, QUrl& urlToLocalFile ) {
this->insert(id, name, email_id, contact_id, reg_num, addr, urlToLocalFile.toLocalFile());
}
//note the const added in the last parameter
inline QString A::insert(QString& id, QString& name, QString& email_id, QString& contact_id, QString& reg_num, Address addr, const QString& pathToLocalFile ) {
/*some tasks*/
}
Additionally you're missing a semicolon ; after class definition.
Also, note that we cannot bind non-const lvalue reference to an rvalue. So the last parameter of the second insert member function should be const QString& pathToLocalFile instead of QString& pathToLocalFile
|
70,810,775 | 70,810,809 | The solution is executed with error 'out of bounds' on the line 7 | I have received this bound error though the sample input and output match. I tried several ways to solve this error, but I couldn't. Please help me to overcome this problem. And also please, explain why? what is the main reason for this error?. My code as follows:
#include <iostream>
using namespace std;
int main(){
int a[4];
for(int i=1; i<=4; i++){
cin >> a[i];
}
string s;
cin >> s;
int sum = 0;
for(int i =0; i<s.size(); i++){
if(s[i]=='1'){
sum=sum+a[1];
}
else if(s[i]=='2'){
sum+=a[2];
}
else if(s[i]=='3'){
sum+=a[3];
}
else if(s[i]=='4'){
sum+=a[4];
}
}
cout << sum << endl;
}
Sample input:
1 2 3 4
123214
Output:
13
| Array indexes start at 0 so a[4] is out of bounds in your case.\
Since we're here I recommend to not use C arrays. Use std::array or std::vector instead.
Also it's better to use the range for.
|
70,811,081 | 70,811,174 | Coufused about using cpp to achieve selection sort | I tried to implement selection sorting in C++,when i encapsulate the swap function, the output shows a lot of zeros.But at beginning of array codes still work.When I replace swap function with the code in the comment, the output is correct.
I am so confused by this result, who can help me to solve it.
#include <iostream>
#include <string>
using namespace std;
template<class T>
int length(T& arr)
{
return sizeof(arr) / sizeof(arr[0]);
}
void swap(int& a, int& b)
{
a += b;
b = a - b;
a = a - b;
}
int main()
{
int array[] = { 2,2,2,2,6,56,9,4,6,7,3,2,1,55,1 };
int N = length(array);
for (int i = 0; i < N; i++)
{
int min = i; // index of min
for (int j = i + 1;j < N; j++)
{
if (array[j] < array[min]) min = j;
}
swap(array[i],array[min]);
// int temp = array[i];
// array[i] = array[min];
// array[min] = temp;
}
for (int i = 0; i < N; i++)
{
int showNum = array[i];
cout << showNum << " ";
}
return 0;
}
| Problem is that your swap function do not work if a and b refer to same variable. When for example swap(array[i], array[i]) is called.
Note in such case, this lines: b = a - b; will set b to zero since a and b are same variable.
This happens when by a chance i array element is already in place.
offtopic:
Learn to split code into functions. Avoid putting lots of code in single function especially main. See example. This is more important the you think.
|
70,811,249 | 70,815,468 | Boost Kruskal minimum spanning tree algorithm -- undirected vs directed graph documentation | Per the documentation, the minimum spanning tree algorithm implemented in boost should work only on undirected graphs. Yet, the following code that provides a directed graph as input to the algorithm seems to work just fine: (while building on MSVC Visual Studio 2019, there are no warnings related to boost)
#include <boost/property_map/property_map.hpp>
#include <boost/config.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/kruskal_min_spanning_tree.hpp>
#include <boost/graph/graph_utility.hpp>
using namespace boost;
typedef adjacency_list <vecS, vecS, directedS, no_property,
property<edge_weight_t, double>>
Graph_vvd_MST;
typedef adjacency_list_traits<vecS, vecS, directedS> Traits_vvd;
property_map<Graph_vvd_MST, edge_weight_t>::type cost;
typedef Traits_vvd::edge_descriptor Edge;
std::vector < Edge > spanning_tree;
int main() {
Graph_vvd_MST g;
add_vertex(g);//0 th index vertex
add_vertex(g);// 1 index vertex
add_vertex(g);// 2 index vertex
cost = get(edge_weight, g);
//Add directed arcs
for(int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) {
if (i == j)
continue;
std::pair<Traits_vvd::edge_descriptor, bool> AE = add_edge(i, j, g);
assert(AE.second);
if (i == 0 && j == 1) cost[AE.first] = 1;
if (i == 0 && j == 2) cost[AE.first] = 2;
if (i == 1 && j == 0) cost[AE.first] = 1;
if (i == 1 && j == 2) cost[AE.first] = 2;
if (i == 2 && j == 0) cost[AE.first] = 1;
if (i == 2 && j == 1) cost[AE.first] = 2;
}
kruskal_minimum_spanning_tree(g, std::back_inserter(spanning_tree));
printf("MST Solution:\n");
for (std::vector < Edge >::iterator ei = spanning_tree.begin();
ei != spanning_tree.end(); ++ei) {
int fr = source(*ei, g);
int to = target(*ei, g);
double cst = cost[*ei];
printf("[%d %d]: %f \n", fr, to, cst);
}
getchar();
}
The code above generates the following bidirectional graph:
The output of the code is correctly:
MST Solution:
[0 1]: 1.000000
[2 0]: 1.000000
Is it the case that the document is not updated and in recent boost versions, the algorithm can actually work with directed graphs?
| I'd simplify the code Live
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/kruskal_min_spanning_tree.hpp>
#include <iostream>
using Graph =
boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS,
boost::no_property,
boost::property<boost::edge_weight_t, double>>;
using Edge = Graph::edge_descriptor;
int main()
{
Graph g(3); // 0..2
/*auto [it, ok] =*/ add_edge(0, 1, {1}, g);
add_edge(0, 2, {2}, g);
add_edge(1, 0, {1}, g);
add_edge(1, 2, {2}, g);
add_edge(2, 0, {1}, g);
add_edge(2, 1, {2}, g);
auto cost = get(boost::edge_weight, g);
std::vector<Edge> spanning_tree;
kruskal_minimum_spanning_tree(g, std::back_inserter(spanning_tree));
std::cout << "MST Solution:\n";
for (auto e : spanning_tree) {
std::cout << e << ": " << cost[e] << "\n";
}
}
If you insist on a loop to insert edges: Live
for (auto [i, j, c] : { std::tuple //
{0, 1, 1.},
{0, 2, 2.},
{1, 0, 1.},
{1, 2, 2.},
{2, 0, 1.},
{2, 1, 2.},
})
{
if (!add_edge(i, j, {c}, g).second)
return 255;
}
The Question
If you don't meet the documented pre-conditions the output is unspecified. Unspecified doesn't mean it throws an exception (that would be specified). It might even accidentally (seem to) do the right thing.
The point is that the algorithm operates under the assumption that edges are - by definition - traversable in the reverse direction at the same cost. As soon as you deviate from that, the algorithm may give incorrect results. In fact, some algorithms might exhibit undefined behaviour (like, a Dijkstra with some weights negative might never complete).
You'd do better to
Either convert your graph to be undirected
satisfy the invariants of undirected graphs and verify that the algorithm works correctly for it
Use an algorithm for MDST (Minimum Directed Spanning Tree), see e.g. Finding a minimum spanning tree on a directed graph
|
70,812,077 | 70,816,363 | How can I correctly create a C++ vector in Python3 by swig? | I try to test swig library 'std_vector.i', but I can't create a vector in Python3 like official demo, Here is some information.
swig_test.i
%module swig_test
%{
#include <vector>
void worker(std::vector<int> &v) {
v.push_back(123);
}
%}
%include <std_vector.i>
%template(MyVector) std::vector<int>;
void worker(std::vector<int> &v);
Then I run:
swig -python -py3 -c++ swig_test.i
It works right.
And then is setup.py
from distutils.core import setup, Extension
test_module = Extension('_swig_test',
sources=['swig_test_wrap.cxx'],
)
setup(name = 'swig_test',
version = '0.1',
author = "SWIG Docs",
description = """Simple swig test from docs""",
ext_modules = [test_module],
py_modules = ["swig_test"],)
And then run:
python setup.py build_ext --inplace
It creates the file '_swig_test.cp38-win_amd64.pyd', I test it in the shell.
>>> import _swig_test
>>> v = _swig_test.MyVector([1,2,3])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module '_swig_test' has no attribute 'MyVector'
It's too strange, it can't be work as normal, then I run dir
>>> dir(_swig_test)
['MyVector___bool__', 'MyVector___delitem__', 'MyVector___delslice__', 'MyVector___getitem__', 'MyVector___getslice__', 'MyVector___len__', 'MyVector___nonzero__', 'MyVector___setitem__', 'MyVector___setslice__', 'MyVector_append', 'MyVector_assign', 'MyVector_back', 'MyVector_begin', 'MyVector_capacity', 'MyVector_clear', 'MyVector_empty', 'MyVector_end', 'MyVector_erase', 'MyVector_front', 'MyVector_get_allocator', 'MyVector_insert', 'MyVector_iterator', 'MyVector_pop', 'MyVector_pop_back', 'MyVector_push_back', 'MyVector_rbegin', 'MyVector_rend', 'MyVector_reserve', 'MyVector_resize', 'MyVector_size', 'MyVector_swap', 'MyVector_swiginit', 'MyVector_swigregister', 'SWIG_PyInstanceMethod_New', 'SwigPyIterator___add__', 'SwigPyIterator___eq__', 'SwigPyIterator___iadd__', 'SwigPyIterator___isub__', 'SwigPyIterator___ne__', 'SwigPyIterator___next__', 'SwigPyIterator___sub__', 'SwigPyIterator_advance', 'SwigPyIterator_copy', 'SwigPyIterator_decr', 'SwigPyIterator_distance', 'SwigPyIterator_equal', 'SwigPyIterator_incr', 'SwigPyIterator_next', 'SwigPyIterator_previous', 'SwigPyIterator_swigregister', 'SwigPyIterator_value', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'delete_MyVector', 'delete_SwigPyIterator', 'new_MyVector', 'worker']
I try to add #define SWIG_FILE_WITH_INIT, but it have no any use, and I try to imitate official demo, it works same result.
How can I deal with it?
| The problem here is how you're importing and using the module you've built.
When you ran SWIG as well as generating some C++ code it also generated some Python too. Rather than directly access the native module you want to access it via the generated python instead, e.g.
import swig_test # Note no leading _
v = swig_test.MyVector([1,2,3])
Which will work just fine then.
Note that you can also ask SWIG to generate native-only module by invoking SWIG with the -builtin flag as well, e.g.:
swig -python -py3 -c++ -builtin swig_test.i
However I wouldn't usually recommend this when getting started as it makes a bunch of common things quite a lot harder.
|
70,812,129 | 70,812,651 | Building multiple binaries in CMake from Zephyr RTOS project, each with different device address | I have a project that consists of nodes in a mesh, that will communicate between each other wirelessly and will identify each other with a use of addresses.
Nodes will be equivalent in their responsibilities so the source code for each them will be identical, except for address which I would like to be specific and unique for each.
This project will be a kind of demo, or technology demonstration so for simplicity I do not want to introduce some address negotiations or anything complex like that.
I was researching and found some suggestions to use target_compile_definitions in CMake but I am not really sure how to apply it to generic Zephyr CMakeLists.txt:
set(BOARD qemu_x86)
find_package(Zephyr)
project(my_zephyr_app)
target_sources(app PRIVATE src/main.c)
So I was wondering what is the best way to do that? Is there a way to do that in CMake (I am quite a noob yet when it comes to CMake)? Or should I tinker with some Python script?
EDIT:
And I was thinking if maybe doing something like #define <device_addr> from level of CMake is possible, and then repeating that X times for the rest of the devices. So in the end I would have X binaries that will differ only in regard to that #define <device_addr>.
Thank You for responses in advance.
| Create a custom ELF section in your project with the address. Use compiler specific syntax. This is for GCC compiler:
// volatile, so that optimizer does not bite us
__attribute__((__section__("myaddress")))
__attribute__((__used__))
volatile const uint8_t _address[20] = {0};
# external API - fetch the address
# remove volatile for usage for optimizations
uint8_t *get_address(uint8_t buffer[20]) {
memcpy(buffer, _address, sizeof(_address));
return address;
}
At best create a linker file so that your section will be placed in .rodata read only memory.
Build one ELF file.
Create a short script. This script will replace the content of the section in the generated ELF file with your custom data - the actual address. Use objcopy --update-section myaddress=filename to update the section, where filename has the binary content of the section. Repeat objcopy for every address. The best would be to write that script in CMake - research CMakeFindBinUtils and add_custom_command + add_custom_target and generator expression with $<TARGET_FILE:app>.
Then use objcopy on generated ELF files to generate bin files.
Overall, this sounds like an odd approach, because every device has some "identification number", "manufacturer number" etc. stored in some read-only device specific memory. Strongly consider reading that number and just using it as an address.
|
70,812,204 | 70,812,241 | Is it possibile to call virtual methods with shared pointers? | class Base {
public:
virtual void f() const { std::cout << "Base::f()" << std::endl; }
};
class Derived : public Base {
public:
void f() const { std::cout << "Derived::f()" << std::endl; }
};
int main()
{
Base* obj = new Derived;
std::shared_ptr<Base> sp = std::make_shared<Base>(*obj);
sp->f(); //prints Base::f()
}
What i expect is that sp->f() prints Derived::f(), just like raw pointers with virtual methods.
What is the correct way to have a polymorphic behaviour with std::shared_ptr?
| sp points to an instance of type Base, not Derived. You can't clone derived classes using a pointer to base like this.
std::shared_ptr<Base> sp = std::make_shared<Derived>(); would work. ... =std::make_shared<Derived>(std::dynamic_cast<Derived&>(*obj)) would also work;
|
70,812,278 | 70,812,391 | reference_wrapper: Is this UB? | I'm curious if this code is UB.
https://wandbox.org/permlink/nU0iPLCrPXwQ7Kor
The code does not crash (in both GCC and Clang, with or without optimization), which makes me more and more baffled..
#include <list>
#include <vector>
#include <iostream>
#include <utility>
#include <queue>
using namespace std;
int main() {
deque<int> l {1, 2, 3, 4, 5};
vector<reference_wrapper<int>> v (l.begin(), l.end());
// v now holds references to 1, 2, 3, 4, 5 in l
cout << v[3] << '\n'; // 4
l.pop_front(); // 1 popped
for (auto num : l) {
cout << num << ' '; // 2 3 4 5
}
cout << '\n';
cout << v[0] << '\n'; // I think this should crash because 1 is dangling reference
l.pop_front(); // 2 popped
for (auto num : l) {
cout << num << ' '; // 3 4 5
}
cout << '\n';
cout << v[1] << '\n'; // I think it should crash but it still outputs 2
}
| The reason why your code does not crash is because you get lucky with regards to implementation details of deque.
A deque allocates memory in blocks of 512 byte. The first and last block in a deque can be partially filled at their front or back, respectively. Pointers mark these locations. A pop_front simply moves that pointer one element forward, as long as the first block does not become completely empty.
In your example, the complete content fits into one block. So you simply keep referencing memory that remains allocated and is just considered empty by the deque. Of course any operation such as push_front or any other resize may change that.
|
70,812,322 | 70,812,494 | When using function calls to template functions, I am faced with an unexpected matching template function for my call | For the following code, why is the compiler matching my function calls with (an unexpected) template function:
First of all here are the function templates available:
// First function template
template <typename T, typename U>
auto sub(T x, U y) {
return x - y;
}
// Second function template
template <typename T>
auto sub(T x, T y) {
return x - y;
}
Now let's say I begin with a template argument deduction statement:
sub(5.2, 2.1);
The above statement should in turn instantiate a function instance (template function) using the second function template provided above, and would end up looking something like this:
template<>
double sub<double>(double x, double y) {
return x - y;
}
The next statement wouldn't instantiate a new template function as it would be able to match with the one created previously.
sub<double>(2.3, 234.2);
Now the statement below is where I am having a bit of confusion.
sub<double>(2.3, 234.0f); // Weird one
Although I had provided a single actual type (double), in the template argument, I was faced with a strange result. I purposefully made the second function argument a float, so as to not perfectly match our previously mentioned function instance (template function), and expected floating-point promotion to happen and for the float to be promoted to a double and then match the template function, that isn't what ended up happening... but instead it created a new function instance (template function) using the first function template provided at the top, and ended up looking like this:
template<>
double sub<double, float>(double x, float y) {
return x - y;
}
What I am confused about is, how I thought that the compiler preferred promotion over something like this, or maybe I am getting it all confused with something else, I am hoping someone could maybe clear it up a bit.
A problem that is also bothering me, is that I don't know how I would then be able to explicitly call the template function I actually want, for example:
sub<double>(2, 2);
What if I wanted it to call the template function with both parameter types being double and just wanted both my arguments to be numerically converted from int to double. By this logic, I wouldn't be able to do that, since the compiler would end up creating a new function instance (template function) that would look something like this:
template<>
double sub<double, int>(double x, int y) {
return x - y;
}
I must mention I am not talking about how to convert my arguments as I very well know I could use static_cast on them, I'm also not talking about doing something like this:
sub<double, double>(2, 2);
As that would of course, use the first function template to create a new function instance (template function), not use the already available template function (which was created through the use of the second function template).
Could someone explain how I would be able to if there really even is a way? All of this, is mostly because I am trying to really understand concepts.
| You can supply a partial list of template parameters. For example, if you have
template <typename A, typename B, typename C>
void foo(A, B, C);
then these calls
foo(1,2,3);
foo<int>(1,2,3);
foo<int, double>(1,2,3);
foo<int, double, float>(1,2,3);
are all good.
So sub<double>(2.3, 234.2f); still matches both the first function template and the instantiation of the second template, and the former one is a better match, since it does not require a conversion. The overload resolution only prefers a non-template over a template1 only when both matches are equally good. If the template is a better match, it is used.
It is possible to force the selection of the second template when the two parameters do not have the same type:
auto x = (static_cast<float(*)(float, float)>(sub))(1, 2.0);
but this of course defeats the purpose. To make it convenient to use, you would need to introduce some other selection mechanism, for example
enum class same { type };
template <typename T, same = same::type>
auto sub(T x, T y)...
... sub<double, same::type>(2.3, 234.0f) ...
1 Or rather, a call where a template argument needs to be deduced vs a call where nothing needs to be deduced.
|
70,812,345 | 70,818,052 | C++ print a structure with cout | I have been trying to find a simple way to return 2 values from a function and found online that creating a structure to store the values was the easiest method of doing so. Now I have written the structure and the function I can not figure out how to actually print the structure. I have seen many other posts about this online, but I don't understand the answers to them. Could anybody please explain to me how I can fix my code without using any technical terms (without explanation). Preferably an addition/modification of my current code with some research material on the subject. I am not experienced in coding at all, nor do I have an education centered around coding. I am just doing this in my spare time for a bit of fun.
#include <iostream>
#include <cmath>
struct values {
float value1;
float value2;
};
values quadratic(int a, int b, int c) {
float d = sqrt(b*b - 4*a*c);
float x1 = (-b + d)/2*a;
float x2 = (-b - d)/2*a;
values result = {x1, x2};
return result;
};
int main() {
std::cout << quadratic(1, 2, -1);
};
| There are at least three ways to do this.
Method 1: Get the struct result and print it
This is the simplest solution.
int main() {
values vs = quadratic(1, 2, -1);
std::cout << vs.value1 << ", " << vs.value2 << "\n";
}
Method 2: Use automatic structured bindings
This requires C++17 minimum (I think, you shouldn’t be using anything less anyway):
int main() {
auto [a, b] = quadratic(1, 2, -1);
std::cout << a << ", " << b << "\n";
}
It’s prettier than Method 1, but basically the same thing.
Method 3: Overload the stream insertion operator
This is where you question was marked as a duplicate and linked to do do exactly this:
std::ostream & operator << (std::ostream & outs, const values & vs) {
return outs << vs.value1 << ", " << vs.value2;
}
int main() {
std::cout << quadratic(1, 2, -1) << "\n";
}
This is perhaps the prettiest at the call site, but does require your values struct to be convertible into a string (which is what the overloaded << operator does).
Method 4: Return a tuple instead of a custom struct
This is basically a rehash of 2.
#include <cmath>
#include <iostream>
#include <tuple>
std::tuple <float, float> quadratic(int a, int b, int c) {
float d = sqrt(b*b - 4*a*c);
float x1 = (-b + d)/2*a;
float x2 = (-b - d)/2*a;
return std::make_tuple(x1, x2);
};
int main() {
auto [a, b] = quadratic(1, 2, -1);
std::cout << a << ", " << b << "\n";
};
That’s all I’m gonna bother with off the top of my head, but I think it covers all the bases.
EDIT: fixed dumb thing I wrote
|
70,812,376 | 70,812,572 | How std::atomic wait operation works? | Starting C++20, std::atomic has wait() and notify_one()/notify_all() operations. But I didn't get exactly how they are supposed to work. cppreference says:
Performs atomic waiting operations. Behaves as if it repeatedly
performs the following steps:
Compare the value representation of this->load(order) with that of old.
If those are equal, then blocks until *this is notified by notify_one() or notify_all(), or the thread is unblocked spuriously.
Otherwise, returns.
These functions are guaranteed to return only if value has changed,
even if underlying implementation unblocks spuriously.
I don't exactly get how these 2 parts are related to each other. Does it mean that if the value if not changed, then the function does not return even if I use notify_one()/notify_all() method? meaning that the operation is somehow equal to following pseudocode?
while (*this == val) {
// block thread
}
| Yes, that is exactly it. notify_one/all simply provide the waiting thread a chance to check the value for change. If it remains the same, e.g. because a different thread has set the value back to its original value, the thread will remain blocking.
Note: A valid implementation for this code is to use a global array of mutexes and condition_variables. atomic variables are then mapped to these objects by their pointer via a hash function. That's why you get spurious wakeups. Some atomics share the same condition_variable.
Something like this:
std::mutex atomic_mutexes[64];
std::condition_variable atomic_conds[64];
template<class T>
std::size_t index_for_atomic(std::atomic<T>* ptr) noexcept
{ return reinterpret_cast<std::size_t>(ptr) / sizeof(T) % 64; }
void atomic<T>::wait(T value, std::memory_order order)
{
if(this->load(order) != value)
return;
std::size_t index = index_for_atomic(this);
std::unique_lock<std::mutex> lock(atomic_mutexes[index]);
while(this->load(std::memory_order_relaxed) == value)
atomic_conds[index].wait(lock);
}
template<class T>
void std::atomic_notify_one(std::atomic<T>* ptr)
{
const std::size_t index = index_for_atomic(ptr);
/*
* normally we don't need to hold the mutex to notify
* but in this case we updated the value without holding
* the lock. Therefore without the mutex there would be
* a race condition in wait() between the while-loop condition
* and the loop body
*/
std::lock_guard<std::mutex> lock(atomic_mutexes[index]);
/*
* needs to notify_all because we could have multiple waiters
* in multiple atomics due to aliasing
*/
atomic_conds[index].notify_all();
}
A real implementation would probably use the OS primitives, for example WaitForAddress on Windows or (at least for int-sized types) futex on Linux.
|
70,812,427 | 70,812,782 | Should warnings about missing typename supressed in c++20? | Warning messages like:
missing 'typename' prior to dependent type name ... [-Wtypename-missing]
and
template argument for template type parameter must be a type; omitted 'typename' is a Microsoft extension [-Wmicrosoft-template]
If I understand right c++20 relaxed the need for typename. Does this mean that these warnings are outdated? Or should I add the (annoying) typename whenever there is warning? (I'm using Visual Studio / Clang12 / std=C++20.)
| No, the warning is useful. Fix your code.
C++20 relaxed the typename rules a little bit. But it's unrelated to this warning.
MSVC considers typename to be (almost?) completely optional, and is non-conforming in this regard. Clang apparently can do that too, for compatibility with MSVC. The warning says that your code is non-conforming, and might not work on other compilers (most notably on GCC).
|
70,812,439 | 70,812,699 | C++: What is the evaluation order of the user-defined comma operator? | I was reading the "C++ 17 Completed Guide" by Nicolai Josuttis and came across the following expression:
foo(arg1), (foo(arg2), foo(arg3));
The author claims that the evaluation order will be left to right for the built-in comma operators, but it can be changed by overloading them. However, I saw the "Order of evaluation" article on cppreference (https://en.cppreference.com/w/cpp/language/eval_order) and came across the following statements:
Every value computation and side effect of the first (left)
argument of the built-in comma operator , is sequenced before every
value computation and side effect of the second (right) argument.
and
Every overloaded operator obeys the sequencing rules of the
built-in operator it overloads when called using operator notation.
So, according to the statement 16, it appears that cppreference claims the overloaded comma operator to have the same evaluation order as its built-in counterpart.
So, what exactly did the author mean by saying that "by overloading the comma operator, you can change its evaluation order" and what exactly behavior is expected?
| Evaluation order was a mess prior to C++17. C++17 made sweeping changes to evaluation order, this is most likely just a mistake by the author.
Prior to C++17, overloaded operators are complete syntax sugar. With any binary operator @, a@b is equivalent to one of
operator@(a, b)
a.operator@(b)
depending on whether it is a member function or free function. Which is to say, a and b are unsequenced relative to each other
In C++17 the evaluation order of a@b is the same as the built-in operators. For the comma operator, a is sequenced before b. In the function call version, a and b are indeterminately sequenced.
|
70,812,481 | 70,813,480 | container iterators - should they be nested? | Should the custom iterator for a customer container be a nested class or a free(for a lack of better word) class? I have seen it both ways, especially in books and online, so not sure if one approach has advantage over other. The two books I am using both have the iterators defined as free classes where as online first few implementations I checked, all were nested.
I personally prefer nested iterator, if the iterator only serves a particular container.
Thanks,
DDG
p.s. - The question is not about preference but about advantages of one approach over others.
| The fact is that an iterator, it is built and used for a specific class, so there is no need for it to be defined outside. Since you only use it in coordination with your container.
Different thing if your iterator it is used by different classes, but I can't really find an example of where it could be useful.
Edit. Finally, to wrap up, both can be done and I don't think there are any advantages in terms of memory used or execution times. For a better understanding of this we should check difference between a nested class and a not-nested class, but I think is off-topic here.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.