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 |
|---|---|---|---|---|
71,583,366 | 71,592,113 | XCode C++, how to use boost dependency from cocoapods? | I'm creating a C++ library for iOS and React-Native. I need to access some helper code from the boost framework, which React-Native itself already has as a dependency.
However, when I try to include the header Xcode tells me it cannot be found:
My library itself is meant to be packaged as a Cocoapods dependency, therefore, I've tried adding the boost dependency to the .podspec but that doesn't seem to do anything to expose the headers.
require "json"
package = JSON.parse(File.read(File.join(__dir__, "package.json")))
Pod::Spec.new do |s|
s.name = "react-native-wallet-core"
s.version = package["version"]
s.summary = package["description"]
s.homepage = package["homepage"]
s.license = package["license"]
s.authors = package["author"]
s.platforms = { :ios => "14.0" }
s.source = { :git => "---.git", :tag => "#{s.version}" }
s.source_files = "ios/**/*.{h,m,mm}", "cpp/**/*.{h,cpp}"
s.dependency "React-Core"
s.dependency "TrustWalletCore", '~>2.7.2'
# Doesn't seem to do anything
s.dependency "boost"
# doesn't work cannot use path in a podspec
# s.dependency "boost", path: "../node_modules/react-native/third-party-podspecs/boost.podspec"
end
Any idea what do I need to do to be able to use boost code inside my own C++ code?
| I got it working, apparently even though the dependency is declared and it is part of react-native, the header path is not immediately available, one needs to add header search paths as part of the podspec itself:
s.pod_target_xcconfig = {
"HEADER_SEARCH_PATHS" => "\"$(PODS_TARGET_SRCROOT)\" \"$(PODS_ROOT)/boost\" \"$(PODS_ROOT)/DoubleConversion\" \"$(PODS_ROOT)/libevent/include/\""
}
s.user_target_xcconfig = {
"HEADER_SEARCH_PATHS" => "\"$(PODS_ROOT)/boost\""
}
|
71,583,479 | 71,583,715 | initial value of reference to non-const must be an lvalue, Passing an object type by reference error | I get the following error when I try to pass a Point object by reference by keeping Point x and y member variables as private, which is why I get x and y by function GetX() and GetY()
how do I resolve the error and get it to work as I expect it to.
error log :
CppReview.cpp: In function 'int main()':
CppReview.cpp:92:30: error: cannot bind non-const lvalue reference of type 'Point&' to an rvalue of type 'Point'
92 | v.OffSetVector(v.GetStart(),1,3);
| ~~~~~~~~~~^~
CppReview.cpp:79:34: note: initializing argument 1 of 'void Vector::OffSetVector(Point&, int, int)'
79 | void Vector::OffSetVector(Point& p,int xoffset,int yoffset){
code :
class Point{
private:
int x,y;
public:
Point(){
x = y = 0;
}
Point(int x,int y){
this->x = x;
this->y = y;
}
Point(float x,float y){
this->x = x;
this->y = y;
}
void SetX(int x){
this->x = x;
}
void SetY(int y){
this->y = y;
}
void Display(){
cout<<"("<<this->x<<','<<this->y<<")\n";
}
void move(int i=0,int j=0){
this->x+=i;
this->y+=j;
}
int& GetX(){
return (this->x);
}
int& GetY(){
return this->y;
}
};
class Vector{
Point start,end;
public:
Vector(){
this->start = Point(0,0);
this->end = Point(1,1);
}
Vector(int sx,int sy,int ex,int ey){
this->start = Point(sx,sy);
this->end = Point(ex,ey);
}
float ComputeDistance(Point,Point);
Point GetStart();
Point GetEnd();
void OffSetVector(Point&,int,int);
void Show();
};
float Vector::ComputeDistance(Point p1,Point p2){
int p1x = p1.GetX();
int p1y = p1.GetY();
int p2x = p2.GetX();
int p2y = p2.GetY();
float dist = sqrt((p1x-p2x)*(p1x-p2x)+(p1y-p2y)*(p1y-p2y));
return dist;
}
Point Vector::GetStart(){
return this->start;
}
Point Vector::GetEnd(){
return this->end;
}
void Vector::OffSetVector(Point& p,int xoffset,int yoffset){
p.GetX()+=xoffset;
p.GetY()+=yoffset;
}
void Vector::Show(){
cout<<this->GetStart().GetX()<<','<<this->GetStart().GetY()<<" : "<<this->GetEnd().GetX()<<','<<this->GetEnd().GetY()<<"\n";
}
int main(){
Vector v(1,1,3,3);
v.Show();
v.OffSetVector(v.GetStart(),1,3);
return 0;
}
| The function GetStart returns a temporary object of the type Point:
Point GetStart();
while the function OffsetVector excepts a non-constant reference to an object:
void OffSetVector(Point&,int,int);
You may not bind a temporary object with a non-constant lvalue reference.
Change the declaration of the function GetStart like:
Point & GetStart();
Also at least the function GetEnd should be changed like:
Point & GetEnd();
You could overload the functions for constant and non-constant objects:
Point & GetSgtart();
cosnt Point & GetStart() const;
Point & GetEnd();
const Point & GetEnd() const;
|
71,584,088 | 71,613,779 | how to deal with this assertion debug failure | I am debugging a code that generates five dxf files. Everything works correctly for the first generation. As soon as I start creating the second dxf file I get this error.
Could someone help me and explain me the problem. I am not able to post the whole code because the code is very big.
thanks in advance
| The reason for this failure was that I used these two data types in the wrong way:
const wchar_t*
wstring
class KDXFDWGWRAPPERTEIG_API K_ArcParameter {
private:
struct K_2DPoint { double m_point_1; double m_point_2; };
K_Teigha3DPoint m_arcCenter{ 0.0, 0.0, 0.0 };
K_Teigha3DPoint m_arcNormal{ 1.0, 1.0, 0.0 };
K_2DPoint m_arcAngleParameter{ 0.0, 3.14 };
K_DxfDwgColor m_defColor;
double m_radius = 1.0;
double m_thickness = 0.5;
const wchar_t* m_layerName = L""; // error is here
const wchar_t* m_lineType = L"";// error is here
public:
// C-Tor
K_ArcParameter(K_Teigha3DPoint pArcCenter, K_Teigha3DPoint pArcNormal, K_2DPoint pArcAngleParameter, double pRadius) :
m_arcCenter(pArcCenter), m_arcNormal(pArcNormal), m_arcAngleParameter(pArcAngleParameter), m_radius(pRadius), m_defColor(0x000000ff) {};
K_ArcParameter(K_Teigha3DPoint pArcCenter, K_Teigha3DPoint pArcNormal,K_2DPoint pArcAngleParameter, double pRadius, double pThickness, wstring& pLayerName, wstring& pLineType) :
m_arcCenter(pArcCenter), m_arcNormal(pArcNormal), m_arcAngleParameter(pArcAngleParameter), m_radius(pRadius), m_thickness(pThickness), m_layerName(pLayerName), m_lineType(pLineType), m_defColor(0x000000ff) {};
K_ArcParameter(K_Teigha3DPoint pArcCenter, K_Teigha3DPoint pArcNormal, K_2DPoint pArcAngleParameter, K_DxfDwgColor pDefColor, double pRadius, double pThickness, wstring& pLayerName, wstring& pLineType) :
m_arcCenter(pArcCenter), m_arcNormal(pArcNormal), m_arcAngleParameter(pArcAngleParameter), m_defColor(pDefColor), m_radius(pRadius), m_thickness(pThickness), m_layerName(pLayerName), m_lineType(pLineType) {};
//methods
K_Teigha3DPoint getArcCenterPoint() const { return m_arcCenter; }
K_Teigha3DPoint getArcNormal() const { return m_arcNormal; }
K_2DPoint getArcAngleParameter() const { return m_arcAngleParameter; }
K_DxfDwgColor getColor() const { return m_defColor; }
double getRadius() const { return m_radius; }
double getThickness() const { return m_thickness; }
wstring getLayerName() const { return m_layerName; }
wstring getLineTypeName() const { return m_lineType; }
bool IsLineTypeByLayer() const { return false; }
};
The layer name and linetype name must be wstring. The const wchar_t* is not allowed and crashes my debugger. I'm sorry I didn't post the code as it's very extensive and I wasn't able to see the specific error location.
I hope this can help you guys.
|
71,584,632 | 71,585,185 | Why is the efficiency worse when I use c++ addon to iterate an array in node.js |
I'm a beginner at node.js c++ addon, and I'm trying to implement a c++ addon that does the same thing as Array.prototype.map function.
But after I finished this, I benchmarked my addon and found it's 100 times worse than the Array.prototype.map function. And it's even worse than I used for loop directly in js.
Here's my code:
// addon.cc
#include <napi.h>
Napi::Value myFunc(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::Array arr = info[0].As<Napi::Array>();
Napi::Function cb = info[1].As<Napi::Function>();
// iterate over array and call callback for each element
for (uint32_t i = 0; i < arr.Length(); i++) {
arr[i] = cb.Call(env.Global(), {arr.Get(i)});
}
return arr;
}
Napi::Object Init(Napi::Env env, Napi::Object exports) {
return Napi::Function::New(env, myFunc);
}
NODE_API_MODULE(addon, Init)
var addon = require("bindings")("addon")
for (let i = 0; i < 10; i++) {
const arr1 = [];
while (arr1.length < 10000000) {
arr1.push(Math.random());
}
const arr2 = [];
while (arr2.length < 10000000) {
arr2.push(Math.random());
}
const arr3 = [];
while (arr3.length < 10000000) {
arr3.push(Math.random());
}
console.time("map");
const a = arr1.map((cur) => cur * 2);
console.timeEnd("map");
console.time("myAddon");
const b = addon(arr2, (i) => i * 2);
console.timeEnd("myAddon");
const c = [];
console.time('for');
for (let i = 0; i < arr3.length; i++) {
c.push(arr3[i] * 2);
}
console.timeEnd('for');
console.log('--------------')
}
And my benchmark result:
map: 411.9ms
myAddon: 3.220s
for: 218.143ms
--------------
map: 363.966ms
myAddon: 2.841s
for: 86.077ms
--------------
map: 481.605ms
myAddon: 2.819s
for: 75.333ms
--------------
I tried to time my addon and return the execution time during the for loop in the c++ code, return it to js and output the value.
It's really that the for loop cost a long time, but why? Shouldn't c++ faster than js?
And is there any way to improve my addon efficiency?
| (V8 developer here.)
This is expected. The reason is that crossing the boundary between C++ and JavaScript (in either direction) is comparatively expensive. That's why in V8, we don't implement Array.map and similar built-in functions in C++; however the internal techniques we use to accomplish that ("CodeStubAssembler", "Torque") aren't available to Node addons.
It's really that the for loop cost a long time, but why?
It's not the for-loop itself, it's the cb.Call(...) expression.
Shouldn't c++ faster than js?
No, not necessarily. Optimized JS can be just as fast. In very rare cases it can even be faster, when you create a scenario where dynamic optimizations are more powerful than static optimizations. In the case at hand, it's not about which language is faster though, it's about the cross-language function calls.
And is there any way to improve my addon efficiency?
Write it in JavaScript. Or find a way to have fewer invocations of any callbacks in either direction (i.e. neither calling JS from C++ for every array element nor calling C++ from JS for every array element). For numerical code, TypedArrays can sometimes be useful for this, depending on your use case.
Side note: for a fairer comparison, the third case based on a plain old JavaScript for loop should preallocate the result array, i.e. replace const c = [] with const c = new Array(arr3.length), and c.push with c[i] = . It'll be twice as fast that way.
|
71,584,735 | 71,585,294 | sending 0 byte values from c++ to python via protocoll buffers | I'm trying to send image data in a bytes field from a c++ library i built to a python program. The problem is that 0 byte values seem to mess up the protocol buffer parsing. When using values other than 0 everything works fine.
image_buffer.proto
syntax = "proto3";
package transport;
message Response{
repeated bytes img_data = 1;
}
test.cpp
extern "C" void* calculate()
{
transport::Response response;
unsigned char* data = new unsigned char [3];
data[0] = 11;
data[1] = 0; // this breaks the code, if other than 0 everything works fine
data[2] = 120;
response.add_img_data(data, 3);
size_t out_size = response.ByteSizeLong();
out = malloc(out_size);
response.SerializeToArray(out, out_size);
return out;
}
test.py
lib = ctypes.util.find_library("myLib")
libc = ctypes.cdll.LoadLibrary(lib)
calculate = libc.calculate
calculate.restype = c_char_p
result = calculate()
response = img_buf.Response()
response.ParseFromString(result) # i get a failed parse error here when using 0 values
for idx,img in enumerate(response.img_data):
print("num pixels:",len(img))
for pix in img:
print(int(pix))
I'm struggling with this for a few days now so if anyone has a hint i'd be super grateful!
| Don't use .restype = c_char_p for binary data. c_char_p is by default handled as a null-terminated byte string and converted to a Python bytes object. Instead, use POINTER(c_char) which will return the data pointer that can then be processed correctly. You'll need to know the size of the returned buffer, however.
Here's an example:
test.cpp
#ifdef _WIN32
# define API __declspec(dllexport)
#else
# define API
#endif
extern "C" API char* calculate(size_t* pout_size)
{
// hard-coded data with embedded nulls for demonstration
static char* data = "some\0test\0data";
*pout_size = 14;
return data;
}
test.py
import ctypes as ct
dll = ct.CDLL('./test')
dll.calculate.argtypes = ct.POINTER(ct.c_size_t),
dll.calculate.restype = ct.POINTER(ct.c_char)
def calculate():
out_size = ct.c_size_t() # ctypes storage for output parameter
result = dll.calculate(ct.byref(out_size)) # pass by reference
return result[:out_size.value] # slice to correct size and return byte string
result = calculate()
print(result)
Output:
b'some\x00test\x00data'
|
71,585,084 | 71,592,614 | A class with a pointer pointing to another class as a member variable and pushing it into vector | using namespace std;
class B {
public:
B() :m_i(0), m_Name("") {};
B(const int num, const string& name) :m_i(num), m_Name(name) {};
void showInfo() {
cout << this->m_i << ", " << this->m_Name << endl;
}
friend class A;
private:
int m_i;
string m_Name;
};
class A {
public:
A(const int num, const string& name) :m_i(num), m_Name(name), ptr(nullptr) {};
A(const A& orig) {
m_i = orig.m_i;
m_Name = orig.m_Name;
ptr = new B;
ptr = orig.ptr;
}
void showInfo() {
cout << this->m_i << " " << this->m_Name << endl;
if (ptr) {
cout << ptr->m_i << " " << ptr->m_Name << endl;
}
}
~A() {
delete ptr;
}
friend class C;
private:
int m_i;
string m_Name;
B* ptr;
};
class C {
public:
void function() {
A instanceA1(10, "Hello");
A instanceA2(11, "Hello");
A instanceA3(12, "Hello");
{//another scope
B* instanceB1 = new B(10, "Bye");
instanceA1.ptr = instanceB1;
B* instanceB2 = new B(11, "Bye");
instanceA2.ptr = instanceB2;
B* instanceB3 = new B(12, "Bye");
instanceA3.ptr = instanceB3;
}
DB.push_back(instanceA1);
DB.push_back(instanceA2);
DB.push_back(instanceA3);
DB[0].showInfo();
DB[1].showInfo();
DB[2].showInfo();
};
private:
vector<A> DB;
};
int main(void) {
C console;
console.function();
}
I had to build a copy constructor of A since there is a pointer as a member variable and as far as I know push_back() only does a 'shallow copy' of an object.
However, although my desired output is
10 Hello
10 Bye
11 Hello
11 Bye
12 Hello
12 Bye
it prints nothing.
And if I delete delete ptr; in A's destructor, it prints what I wanted but I'm pretty
sure there is a memory leak.
What did I do wrong here?
| Here's your copy constructor:
A(const A& orig) {
m_i = orig.m_i;
m_Name = orig.m_Name;
ptr = new B;
ptr = orig.ptr;
}
You assign ptr to a new B but then you turn around and trash it so it points to the original B. I don't think that's what you want. How about this:
ptr = new B(*orig.ptr);
Does that help?
|
71,585,174 | 71,585,205 | convert vector of 4 bytes into int c++ | my function read_address always returns a vector of 4 bytes
for other usecases it is a vector and not const array
in this use case I always return 4 bytes
std::vector<uint8_t> content;
_client->read_address(start_addr, sizeof(int), content);
uint32_t res = reinterpret_cast<uint32_t>(content.data());
return res;
here is the vector called content
it is always the same values
however the value of "res" is always changing to random numbers
Can you please explain my mistake
| Your code is casting the pointer value (random address) to an integer instead of referencing what it points to. Easy fix.
Instead of this:
uint32_t res = reinterpret_cast<uint32_t>(content.data());
This:
uint32_t* ptr = reinterpret_cast<uint32_t*>(content.data());
uint32_t res = *ptr;
The language lawyers may take exception to the above. And because there can be issues with copying data on unaligned boundaries on some platforms. Hence, copying the 4 bytes out of content and into the address of the 32-bit integer may suffice:
memcpy(&res, content.data(), 4);
|
71,585,568 | 71,616,578 | How to alias pair member-data in C++? | How to alias pair member-data in C++ ?
I have a container of std::pair<int,int> to store master-slave pairs.
For better readability I want to use something like:
using Master = std::pair<int,int>::first;
std::pair<int,int> myPair;
auto myMaster = myPair.Master;
What would be the correct syntax here?
Thank you, in advance.
| An alternative would be to use the tuple-like get access to std::pair with a self-defined constant:
const std::size_t Master = 0;
std::pair<int,int> myPair;
auto myMaster = std::get< Master >( myPair );
Somewhat cleaner and more readable than pointered access IMHO.
|
71,585,913 | 71,585,943 | The second letter 't' in 'tt' is a little bigger than the first one | I develop an application in Qt/C++ with Qt 5.12.12 on Windows 10.
I have some *.ui files including simple QLabel widgets to display text in Calibri font, with 16 points size.
Here is an example of what is displayed on screen when "tt" is present in a word:
This is only cosmetic issue, but I did not find anything on the web about this kind of issue. I really need to keep the Calibri font.
When I use Calibri font, 16 points, in Word or any other text editor, I do not see this issue. I am getting really crazy...
Can someone help me please ?
| Maybe you find that it's actually a single character instead of two. It's called a ligature. If you don't like it, try deleting it and re-type the two Ts. But actually, typographists do that to make the font prettier, not uglier. So maybe it's something you may want to get used to and actually start liking.
There are a lot of other ligatures as well, not only for TT. Most of which I know are combinations with F:
You may not get ligatures in Word because the default seems to be "no ligatures". You can find it in the advanced text properties:
If someone wants to replace the German screnshot by an English one, please do so
|
71,585,951 | 71,599,847 | Phantom Omni angular velocities are 0 | I'm trying to build my application using the Phantom Omni haptic device and in order to get the angular velocity of the device, I'm using a function from its library (OpenHaptics):
hdGetDoublev(HD_CURRENT_ANGULAR_VELOCITY, ang_vel);
but it returns [0,0,0]. I'm using the same function to get the linear velocity:
hdGetDoublev(HD_CURRENT_VELOCITY, lin_vel);
and it's working fine. (Both lin_vel and ang_vel are defined as hduVector3Dd)
What am I missing?
| I asked directly to Open Haptics support and this was the answer: "This is not a bug, HD_CURRENT_ANGULAR_VELOCITY doesn't apply to Touch/Omni model, because its gimbal encoder wouldn't be sufficient for accurate angular velocity calculation".
I hope it can save you some time.
|
71,587,205 | 71,587,875 | How does compiler/stdlib determine what policy to use for default std::async | Edit: Sorry that I did something stupid. This question is wrong. Just go ahead to the answer or vote to close this question in case of wasting other's time.
I know that compilers and/or standard libaray are free to choose what policy to use for std::async with default policy. But how do they determine that?
This program has really confusing behavior.
// extern.cpp
#include <future>
extern std::future<void> a;
void task(int t);
void extern_func1() {
a.get();
}
void extern_func2() {
task(2);
}
// main.cpp
#include <chrono>
#include <future>
#include <thread>
#include <iostream>
#include <sstream>
#include <mutex>
std::mutex m;
auto now_sec() {
using namespace std::chrono;
auto t = system_clock::now().time_since_epoch();
return duration_cast<seconds>(t).count();
}
template<class...Args>
void log(Args&&...args) {
std::ostringstream oss;
oss << "thread#" << std::this_thread::get_id() << " "
<< "time:" << now_sec() << " ";
(..., (oss << args << " "));
oss << "\n";
std::string msg = oss.str();
std::unique_lock l{m};
std::cout << msg;
std::cout.flush();
}
void task(int t) {
log("task", t, "begin");
using namespace std::chrono_literals;
std::this_thread::sleep_for(3s);
log("task", t, "end");
}
std::future<void> a;
void extern_func1();
void extern_func2();
int main() {
auto t1 = now_sec();
a = std::async(task, 1);
#if 1
extern_func1(); // <---- This order uses "deferred" policy(See below)
extern_func2();
#else
extern_func2(); // <---- This order uses async policy
extern_func1();
#endif
auto t2 = now_sec();
log("total", t2 - t1, "secs");
}
If extern_func1 is called before extern_func2, the program use "deferred" policy and outputs
thread#0x16da17000 time:1648037227 task 1 begin
thread#0x16da17000 time:1648037230 task 1 end
thread#0x1026e0580 time:1648037230 task 2 begin
thread#0x1026e0580 time:1648037233 task 2 end
thread#0x1026e0580 time:1648037233 total 6 secs
It's not the standard deferred policy because a new thread is spawned. But it starts when result is requested.
If If extern_func2 is called before extern_func1, the program use async policy and outputs
thread#0x102970580 time:1648037352 task 2 begin
thread#0x16d80f000 time:1648037352 task 1 begin
thread#0x102970580 time:1648037355 task 2 end
thread#0x16d80f000 time:1648037355 task 1 end
thread#0x102970580 time:1648037355 total 3 secs
The order is the only diference. Why the order of calling external functions of exactly same signature change the used policy or the thread scheduling? How is this possible?
Originall there's only one translation unit. In order to rule out compiler's optimization, I moved the two functions into another translation unit and compiled them with -fno-lto to disable link-time optimization. But still, both GCC and Clang gives this confusing behavior.
Clang's version:
Homebrew clang version 13.0.1
Target: arm64-apple-darwin21.1.0
Thread model: posix
InstalledDir: /opt/homebrew/opt/llvm/bin
GCC's version
g++ (Homebrew GCC 11.2.0_3) 11.2.0
Copyright (C) 2021 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
| There is no policy change. Look at extern_func1/2 again:
void extern_func1() {
a.get();
}
void extern_func2() {
task(2);
}
It's simply that when you call extern_func1 first you are running:
a = std::async(task, 1); // start task 1
a.get(); // wait for task 1 to finish
task(2); // run task 2 on main thread
and when you call extern_func2 first you are running:
a = std::async(task, 1); // start task 1
task(2); // run task 2 on main thread
a.get(); // wait for task 1 to finish
When you call extern_func1 first, you are preventing both tasks from running at the same time! You are telling the computer not to run task 2 until task 1 finishes, and the computer is doing exactly what you tell it to. No weirdness here!
|
71,587,241 | 71,587,485 | How do i make this sorting algorythm work? | Im trying to experiment with some iterative sorting algorythms, im trying hard to make this one work. It is actually fine when i use it on small lists of 20 or less, but when i go up to 200 or more elements it gives me a runtime error (exception not handled). I guess it's a memory problem, but i dont really know how to proceed.
The result that i would like to get is a function that takes a list, splits it in two part depending if the elements are bigger or smaller than the average. Then the function is called again on both the new lists created.
When it takes a list that is either empty, with a single element, or already sorted, it should do nothing.
The error: Unhandled exception at 0x00007FFF05EE5469 (ucrtbased.dll) in ConsoleApplication4.exe: 0xC00000FD: Stack overflow (parameters: 0x0000000000000001, 0x000000B0AB403FF8).
#include <list>
#include <iostream>
void mySort(std::list<int>& input_list) {
if (input_list.begin() != input_list.end()) {
std::list<int> listaMin;
std::list<int> listaMaj;
std::list<int>::iterator it;
bool alreadySorted = true;
int previousValue = 0;
int avg = 0, counter = 0;
for (it = input_list.begin(); it != input_list.end(); it++) {
if (*it >= previousValue)previousValue = *it;
else alreadySorted = false;
avg += *it;
counter++;
}
if (alreadySorted == false) {
for (it = input_list.begin(); it != input_list.end(); it++) {
if (*it < (avg / counter)) { listaMin.push_front(*it); }
else listaMaj.push_front(*it);
}
mySort(listaMin);
mySort(listaMaj);
input_list.clear();
input_list.merge(listaMaj);
input_list.merge(listaMin);
}
}
}
Later:
int main() {
srand(time(NULL));
std::list<int> mainList;
for (int i = 0; i < 100; i++) mainList.push_back(rand() % 100);
mySort(mainList);
return 0;
}
Also, im relatively new to coding, so if you have suggestions on something i could change in way the code is written i'll happily take it. Thank you all!
| Your problem is that you are using integer division in calculating the average used to split your list into 2 parts.
Consider elements a list of 3 elements { 1, 2, 1 }.
This results in avg = 4 and counter = 3.
You then split the list into two depending on whether each element is < or >= avg / counter.
In this case, avg / counter = 4 / 3 = 1 (using integer division)
With all 3 elements being >= 1, you end up with listaMaj containing all 3 elements and listaMin containing 0.
The call to mysort(listaMaj) then results in infinite recursion as the same list is effectively passed on unchanged forever.
Defining your avg variable as double instead of int, would fix this.
|
71,587,381 | 71,588,850 | Apply template function depending on runtime parameter | Is there a way to instance the function depending on runtime parameters?
Something like this:
#include <string>
#include <iostream>
#include <exception>
using namespace std;
enum class EType{
INT,
DOUBLE,
STRING
}
template<typename T>
void print (const T& val){
cout << val << endl;
}
template<typename T>
void sum (const T& l, const T& r){
cout << l + r;
}
template typename<T> load_parameter (const string& path, const string& name){
const T arg = // read this parameter
cout << arg;
}
template<typename F<typename P>, typename... Args>
void apply_type_template_func(const EType e_type, F* function, Args... args){
switch (type){
case EType::INT:
*F<int>(std::forward<Args>(args)...);
case EType::DOUBLE:
*F<double>(std::forward<Args>(args)...);
case EType::STRING:
*F<string>(std::forward<Args>(args)...);
default:
throw runtime_error("Unsupported Param Type");
}
}
int main()
{
auto e_type = EType::INT;
apply_type_template_func(e_type, print);
e_type = EType::DOUBLE;
apply_type_template_func(e_type, sum, 0.1, 0.2);
}
And can I make it somehow without using type deduction? For example, consider function that load parameter from yaml by it's name?
| Syntax template<typename F<typename P>> is wrong.
Moreover, you cannot pass template function (I mean print and set T afterward).
But you can for class:
template <typename T>
struct printer
{
void operator()(const T& val) const
{
cout << val << endl;
}
}
template <template <typename> class C>
void apply_type_template_func()
{
C<int>{}(42);
C<float>{}(4.2f);
C<std::string>{}("Hello world");
}
That is why a way to pass template function is to wrap them in class or lambda:
auto lambda = [](const auto& arg){ print(arg); };
Note: Here, class (lambda) is not template, but its operator() is.
And indeed, to transform a runtime value into compile time value/type,
you have to dispatch at runtime (so with limited set of values) to compile time value.
As with switch:
template <template <typename> class C>
void apply_type_template_func(EType type)
{
switch (type)
{
case EType::INT: C<int>{}(42); break;
case EType::Double: C<double>{}(4.2); break;
case EType::STRING: C<std::string>{}("Hello world"); break;
}
}
Note that each branch should be valid, even if branch is not taken, so your variant with forwarding argument would be wrong, as all of C<int>{}(arg), C<double>{}(arg), C<std::string>{}(arg) should be valid (which is not the case for regular argument).
|
71,588,152 | 71,588,438 | Is the c++ code in standard library all valid c++? | Just out of curiosity, I looked at how std::is_pointer is implemented and saw stuff like this (one of multiple overloads):
template <class _Ty>
_INLINE_VAR constexpr bool is_pointer_v<_Ty*> = true;
which if I copy and paste into my code and compile says constexpr is not valid here. What is happening?
Is it possible to implement structs like std::is_pointer and std::is_reference by us? (Not that I would, just curious so please don't come at me)
MRE with msvc 2019:
template <class _Ty>
inline constexpr bool is_pointer_v<_Ty*> = true;
int main()
{
}
--
Error: error C7568: argument list missing
after assumed function template 'is_pointer_v'
| To answer the question in the title:
No, standard library code does not need to adhere to the language rules for user code. Technically it doesn't even need to be implemented in C++, but could e.g. be directly integrated into the compiler.
However, practically the standard library code is always compiled by the compiler just as user code is, so it will not use any syntax constructs that the compiler would reject for user code. It will however use compiler-specific extensions and guarantees that user code should not generally rely on. And there are also some reservations made specifically to the standard library implementation in the standard.
For example, the snippet you are showing from the standard library implementation is not valid user code, because _Ty is a reserved identifier that may not be used by user code, because it starts with an underscore followed by an uppercase letter. Such identifiers are specifically reserved to the standard library implementation. For this reason alone most standard library code will not be valid user code.
|
71,588,672 | 71,590,162 | In symbol table how to mark variable out of scope? | I am writing a toy compiler, which compile a c/c++ like language to c++.
I am using bison, but in this structure is hard to handle when variable became out of scope.
In the source lanugage in the whole main function there can be only one variable with the same name, it is good, but there is a problem what I cannot solve.
I cannot make c++ code like this, because c++ compiler throw semantical error:
'var' was not declared in this scope.
int main()
{
if (true)
{
int var = 4;
}
if (true)
{
var = 5;
}
}
The source language has while, if and if/else statements.
I have to throw semantical error if a declared variable is assinged in out of scope.
For example:
This should be semantical error, so I cannot generetad this code:
int main()
{
while(0)
{
int var = 1;
}
if (1)
{
var = 2;
}
}
This also have to be semantical error:
int main()
{
if (0)
{
int var = 1;
}
else
{
if (1)
{
var = 5;
}
}
}
And this is allowed, I can generate this code:
int main()
{
if (0)
{
}
else
{
int var = 1;
if (1)
{
while (0)
{
while (0)
{
var = 2;
}
}
}
}
}
I tried lot of things, but I cannot solve when there is nested if, if/else or while.
I read tons of tutorials about symbol table, but none of them can explain properly how to manage a variable if it is become out of scope.
If you familiar with this topic and with bison, please do not just give me hints, like "use stack, and mark a variable if it become out of scope". I found lot of article about it.
Instead of please give me pseudocode or concrate implementation sketch.
I think it cannot be so much difficult, because in the whole main function there can be one variable with the same name as I wrote.
Symbol table:
struct SymbolType
{
int lineNumber;
std::string identifier;
int identifierValue;
Type type;
int functionArgumentNumber;
Type functionReturnType;
Type markType;
bool outOfScope;
};
class Symbol
{
public:
void AddVariable(int _lineNumber, std::string _identifier, int _identifierValue, Type _type, int _functionArgumentNumber, Type _functionReturnType, Type _markType, bool _outOfScope);
void AddMarker(int _lineNumber, std::string _scopeName, Type _markType);
bool FindVariable(std::string _identifier);
int FindVariableValue(std::string _identifier);
void Remove();
void Print();
std::vector<SymbolType> symbolTable;
private:
int lineNumber;
std::string identifier;
int identifierValue;
Type type;
int functionArgumentNumber;
Type functionReturnType;
Type markType;
bool outOfScope;
};
| Now let's assume the following: While you are in a nested scope you cannot add a variable to a parent scope. So we can work e.g. with a stack like structure (push/pop at the end only suffices, but with read access to all entries – the latter requirement disqualifying std::stack, so we'd operate e.g. on std::vector instead).
Encountering the declaration of a new variable:Run up the entire stack to see if that variable exists already. If so, issue an error ('duplicate declaration/definition').
Encountering accessing a variable: Run up the entire stack to see if that variable exists; if not, issue an error ('not declared/defined' – I wouldn't differentiate between the variable not having been defined ever or having left the scope).
On leaving a scope, run up the stack and remove any variable that resides in that scope.
To be able to do 3. you have (at least) two options:
With every stack entry provide an identifier for the respective scope, could be simple counter. Then delete all those variables that have the same counter value. If you fear the counter might overflow, then reduce it by 1 as well (then it would always represent current scope depths).
Have a sentinel type – that one would be pushed to the stack on opening a new scope, compare unequal to any variable name, and on leaving a scope you'd delete all variables until you encounter the sentinel – and the sentinel itself.
This processing makes your outOfScope member obsolete.
Your addVariable function takes too many parameters, by the way – why should a variable need a return type, for instance???
I recommend adding multiple functions for every specific semantic type your language might provide (addVariable, addFunction, ...). Each function accepts what actually is necessary to be configurable and sets the rest to appropriate defaults (e.g. Type to Function within addFunction).
Edit – processing the example from your comment:
while(condition)
{ // opens a new scope:
// either place a sentinel or increment the counter (scope depth)
int var = 1; // push an entry onto the stack
// (with current counter value, if not using sentinels)
if (true)
{ // again a new scope, see above
var = 2; // finds 'var' on the stack, so fine
} // closes a scope:
// either you find immediately the sentinel, pop it from the stack
// and are done
//
// or you discover 'var' having a counter value less than current
// counter so you are done as well
} // closing next scope:
// either you find 'var', pop it from the stack, then the sentinel,
// pop it as well and are done
//
// or you discover 'var' having same counter value as current one,
// so pop it, then next variable has lower counter value again or the
// stack is empty, thus you decrement the counter and are done again
|
71,589,010 | 71,691,131 | How to use a c++ type (struct) in inet packet definition | I want to create an inet packet and the packet content needs to be of c++ type struct which is defined outside the message file.
I have done this earlier to define a .msg file derived from cMessages in OMNeT like this:
cplusplus{{
#include "util/DataTypes/StateDataTypes.h"
}};
struct StateWithCovariance;
message WirelessMsg
{
StateWithCovariance VehicleLocation;
}
Now I am working with simu5g and want to send the same msg content as an inet packet. I know the inet Packet data structure builds on top of the data structure chunks. Thus I followed how it's done in inet and when I try to create the packet I can't use the same above format to define the packet because then
cplusplus{{
#include "inet/common/INETDefs"
#include "inet/common/packet/chunk/chunk"
}}
class WirelessAppPacket extends inet::FieldsChunk
{
simtime_t payloadTimestamp;
StateWithCovariance VehicleLocation;
}
wouldn't work and gives me the error:
modules/communication/NR/App/WirelessAppPacket.msg:34: Error: 'WirelessAppPacket': unknown base class 'inet::FieldsChunk',
available classes' (inet::StateWithCovariance:1)' ,'(omnetpp::cMessage:4)', '(omnetpp::cNamedObject:5)','(omnetpp::cObject:3)','(omnetpp::cOwnedObject:4)','(omnetpp::cPacket:4)'
if I give it as
import inet.common.INETDefs;
import inet.common.packet.chunk.Chunk;
class WirelessAppPacket extends inet::FieldsChunk
{
simtime_t payloadTimestamp;
StateWithCovariance VehicleLocation;
}
it wouldn't give any error with regards to chunks, if I change the message complier to --msg6 in project properties as follows
MSGC:=$(MSGC) --msg6
But it gives me an error with respect to the data type definition as:
modules/communication/NR/App/WirelessAppPacket.msg:28: Error: Type declarations are not needed with imports, try invoking the message compiler in legacy (4.x) mode using the --msg4 option
modules/communication/NR/App/WirelessAppPacket.msg:32: Error: unknown type 'StateWithCovariance' for field 'VehicleLocation' in 'WirelessAppPacket'
The entire code I used look like this
import inet.common.INETDefs;
import inet.common.packet.chunk.Chunk;
cplusplus{{
#include "util/DataTypes/StateDataTypes.h"
#include "modules/vehicle/CommunicationCoordinator.h"
}};
struct StateWithCovariance;
class WirelessAppPacket extends inet::FieldsChunk
{
simtime_t payloadTimestamp;
StateWithCovariance VehicleLocation;
}
If I change the message compiler to --msg4 then I can't define my packet from chunk base class in INET framework and with --msg6 I can't use the data type I want to use.
Is there a way to rectify this issue?
I use OMNeT++ version 5.6.2, INET version 4.2.2 and Simu5G version 1.1.0
| This thread explains what to do. Basically you need to change the line
struct StateWithCovariance;
from your last code snippet into
struct StateWithCovariance {
@existingClass;
}
This works with the --msg6 message compiler, so that you can still import INET classes.
|
71,589,042 | 71,591,352 | How to understand "a given random-number generator always produces the same sequence of numbers" in C++ primer 5th? | Title "Engines Generate a Sequence of Numbers" in section 17.4.1 has following Warring.
A given random-number generator always produces the same sequence of numbers. A function with a local random-number generator should make that generator (both the engine and distribution objects) static. Otherwise, the function will generate the identical sequence on each call.
"A given random-number generator always produces the same sequence of numbers." What kind of given generator does it refer to?
If I give a random number engine and a random number distribution, they form a given random number generator.
Will it always produce a fixed sequence of values given a seed?
Won't it change because of different compilers or system environments?
So I compiled and ran the following code on different compilers.
#include <iostream>
#include <random>
using namespace std;
minstd_rand0 dre1(13232);
minstd_rand0 dre2(13232);
int main()
{
uniform_int_distribution<unsigned> h1(0,10);
uniform_int_distribution<unsigned> h2(0,10);
unsigned t=100;
while(t--){
cout << "dre1:" << h1(dre1) << endl;
cout << "dre2:" << h2(dre2) << endl;
}
}
For it's easy to watch, I won't release all the results.
//in gcc and clang:
dre1:1
dre2:1
dre1:5
dre2:5
dre1:1
dre2:1
dre1:9
dre2:9
dre1:6
dre2:6
//in msvc
dre1:0
dre2:0
dre1:0
dre2:0
dre1:3
dre2:3
dre1:2
dre2:2
dre1:0
dre2:0
Why did this happen?
| The random-number facilities that were introduced in C++11 have two categories of things: generators and distributions. Generators are sources of pseudo-random numbers. A distribution takes the results of a generator as input and produce values that meet the statistical requirements for that distribution.
Generators are tightly specified: they must use a particular algorithm with a particular set of internal values. In fact, the specification in the C++ standard includes the 10,000th value that each default-constructed generator will produce. As a result, they will have the same behavior on all platforms.
Distributions are not tightly specified; their behavior is described in terms of the overall distribution that they provide; they are not required to use any particular algorithm. Code that uses them is portable across all platforms; the values that they produce from the same generator will not necessarily be the same.
A newly-constructed generator object will produce a particular sequence of values as specified by its algorithm. Another newly-constructed generator object will produce exactly the same sequence. So, in general, you want to create one generator object and one distribution object, and use the pair to produce your desired pseudo-random sequence.
|
71,589,107 | 71,590,127 | How to set expectation on the function calls inside the constructor? | I am using google test(gtest/gmock) to add a couple of tests for the program(C++). For one of the class, I have to add a test to make sure the class is calling a function(let's say an important function I don't want to miss) in its constructor.
For example:
class foo
{
foo()
{
bar();
}
};
Here, I need to add a test to make sure bar() is called in the foo instantiation. As the expectation should be added before the action, I am finding it difficult to add such test:
For example:
foo f; // here the bar is called, so we need to set expectation before it but we got the object at this moment only
I want to use EXPECT_CALL() for this task. I am new to google test. Let me know if I am thinking clearly and what needs to be done here?
Update: bar() is an inherited member function of the foo class. I need the test to never miss that call in the further changes. That test will make sure the call is always present even after several new modifications of the source code.
| Usually you test a class (which is not mocked) and mock the collaborators of that class (i.e. the classes that interact with it). The class being tested should not be mocked at the same time.
In your use case, however, it looks like you are trying to test a class AND mock the same class (or the parent class) at the same time.
I don't think you can do this with GMock specially if you want to test if something is called in the constructor because EXPECT_CALL requires an object of the mocked class, and by the time you create that object, the constructor is called and finished. So, you need to make a clear distinction between the class-under-test and the collaborator classes that are mocked.
Interestingly if you try to do this here you will get a warning for an uninteresting call to bar, which is a sign that bar was called, but it's not that useful because while you get the warning, your test will fail.
Instead, rather than using mocks and EXPECT_CALL, I suggest you create and test a side effect of bar(). To do this, you will have to slightly modify your class definitions. For example, you can write:
class base {
void bar(){
//...
bar_was_called = true;
}
public:
bool bar_was_called=false;
};
class foo : public base
{
public:
foo()
{
bar();
}
};
TEST(foo, barWasCalled){
foo f;
EXPECT_TRUE(f.bar_was_called);
}
|
71,589,791 | 71,589,921 | Can I use SFINAE to compare enum class Value? | Live On Coliru
struct Banana : public FruitBase
{
Banana(Fruit fruit, int price, std::string name, int length):
...
};
struct Apple : public FruitBase
{
Apple(Fruit fruit, int price, std::string name):
...
};
template<typename... Ts>
std::unique_ptr<FruitBase> makeFruits(Fruit fruit, Ts&&... params)
{
switch(fruit)
{
case Fruit::APPLE:
return std::make_unique<Apple>(Fruit::APPLE, std::forward<Ts>(params)...);
break;
case Fruit::BANANA:
return std::make_unique<Banana>(Fruit::BANANA, std::forward<Ts>(params)...);
break;
}
return nullptr;
}
int main()
{
auto apple_ptr = makeFruits(Fruit::APPLE, 10, "gala");
print_fruit(apple_ptr.get());
auto banana_ptr = makeFruits(Fruit::BANANA, 20, "plantains", 123);
print_fruit(banana_ptr.get());
}
main.cpp:37:5: note: candidate: 'Apple::Apple(Fruit, int, std::string)'
37 | Apple(Fruit fruit, int price, std::string name):
| ^~~~~
main.cpp:37:5: note: candidate expects 3 arguments, 4 provided
main.cpp:26:5: note: candidate: 'Banana::Banana(Fruit, int, std::string, int)'
26 | Banana(Fruit fruit, int price, std::string name, int length):
| ^~~~~~
main.cpp:26:5: note: candidate expects 4 arguments, 3 provided
Question> The issue is that the compiler has problems choosing which constructor for Apple and which one for Banana. I assume I could use SFINAE(i.e. with help of std::enable_if) to help compiler deduce the correct function. However, I didn't find an example where the checking is for VALUE instead of TYPE. Can someone give me a little hint here?
| Even if not taken, all branches should be valid
If argument is passed as template parameter (so known at compile time), you might do
template<Fruit fruit, typename... Ts>
std::unique_ptr<FruitBase> makeFruits(Ts&&... params)
{
if constexpr (fruit == Fruit::APPLE)
return std::make_unique<Apple>(Fruit::APPLE, std::forward<Ts>(params)...);
else if constexpr (fruit == Fruit::BANANA)
return std::make_unique<Banana>(Fruit::BANANA, std::forward<Ts>(params)...);
else
return nullptr;
}
int main()
{
auto apple_ptr = makeFruits<Fruit::APPLE>(10, "gala");
auto banana_ptr = makeFruits<Fruit::BANANA>(20, "plantains", 123);
}
Demo
You can still add SFINAE on top of that.
|
71,590,029 | 71,590,143 | Can type be created(or template instantiated) by object known at compile time? | Suppose I have a template function:
template <typename T, T value>
auto foo(std::integral_constant<T, value>)
{
if constexpr (value == 0)
{
return int{};
}
else
{
return float{};
}
}
And I want to call it using a number constant:
foo(4);
Can it be implemented? If no, why?
I see that I can create std::integral_constant on my own, but I'm interested in the idea of creating a type from an object. In the example above, I have 4 as the object and std::integral_constant as the type.
Declaring some define which will do if or switch is not a solution - it will be a lot of code and slow.
| I absolutely do not recommend this, but you could use a macro to achieve the syntax you're after:
template <auto value>
auto foo_impl()
{
if constexpr (value == 0)
{
return int{};
}
else
{
return float{};
}
}
#define foo(constant) foo_impl<constant>()
int main(){
auto should_be_int = foo(0);
static_assert(std::is_same_v<int, decltype(should_be_int)>);
auto should_be_float = foo(1);
static_assert(std::is_same_v<float, decltype(should_be_float)>);
}
Demo
Ultimately you're better sticking to bolov's answer for now until constexpr function parameters (P1045) is standardized (or something similar to it).
|
71,590,337 | 71,590,435 | Why did my shared_ptr turn into an invalid pointer? | I am trying to store in a map some derived classes.
I store them using share_ptr to avoid unexpected deallocation.
Unfortunately, in my attempt it is working-ish: the program compiles and execute but I get an error message.
I obtained the following MWE:
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <typeindex>
#include <typeinfo>
using namespace std;
class DataInOut {
public:
std::shared_ptr<void> data = nullptr;
std::type_index type = typeid(nullptr);
bool initialized = false;
bool optional = false;
// template <class Archive>
virtual bool dummy_funct(int &ar, const char* charName){
cout<< "serialize_or_throw from DataInOut address is an empty function." << endl;
return true;
}
DataInOut *clone() const { return new DataInOut(*this); }
~DataInOut(){}; // Destructor
};
template <typename T>
class DataInOutType : public DataInOut {
public:
// template <class Archive>
bool dummy_funct(int &ar, const char* charName){
cout<< "serialize_or_throw from DataInOutTYPE is an FULL function." << endl;
return true;
}
};
class mapClass {
private:
std::map<std::string, std::shared_ptr<DataInOut> > _m;
public:
template<typename T>
void set(string key, T* var, bool optional = false) {
cout << "set entry with " << var << endl;
std::shared_ptr<DataInOutType<T>> dataIO_ptr (new DataInOutType<T>);
dataIO_ptr->type = typeid(*var) ;
dataIO_ptr->data.reset( var ) ;
dataIO_ptr->optional = optional ;
dataIO_ptr->initialized = true ;
_m.insert( std::pair<std::string, std::shared_ptr<DataInOutType<T>>>(key, dataIO_ptr) );
int toto= 1;
// dataIO_ptr.get()->dummy_funct(toto, key.c_str());
// cout << "set EXIT" << endl;
}
void call_dummy(string key){
int dummyArchive= 1;
_m.at(key).get()->dummy_funct(dummyArchive, key.c_str());
}
};
int main(int argc, const char *argv[]) {
cout << "Hello World!" << endl;
mapClass mapTest;
double length = 1.0;
mapTest.set("length", &length);
cout << "mapTest is out of set" << endl;
mapTest.call_dummy("length");
cout << "ByeBye!" << endl;
return 0;
}
Then using the compilation line:
g++ -std=c++17 ./test.cpp -o prog && ./prog
I obtain the following output:
Hello World!
set entry with 0x7ffcda122318
mapTest is out of set
serialize_or_throw from DataInOutTYPE is an FULL function.
ByeBye!
free(): invalid pointer
Abandon
So my question is how to prevent from the invalid pointer ?
| On this line:
mapTest.set("length", &length);
You are calling set() with a raw double* pointer to a local variable length that was not allocated with new. Internally, set() is assigning that raw pointer as-is to a shared_ptr in the map. When that shared_ptr is destroyed later, it will try to call delete on that double* pointer, but since the double it points to was not allocated with new to begin with, you get the runtime error.
This is why mixing raw pointers with smart pointers without clear ownership semantics is very dangerous. Use raw pointers only for non-owning views into existing data. Use smart pointers when allocating data dynamically. For example:
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <typeindex>
#include <typeinfo>
using namespace std;
class DataInOut {
public:
shared_ptr<void> data = nullptr;
type_index type = typeid(nullptr);
bool initialized = false;
bool optional = false;
// template <class Archive>
virtual bool dummy_funct(int &ar, const char* charName){
cout<< "serialize_or_throw from DataInOut address is an empty function." << endl;
return true;
}
virtual shared_ptr<DataInOut> clone() const { return make_shared<DataInOut>(*this); }
virtual ~DataInOut() = default; // Destructor
};
template <typename T>
class DataInOutType : public DataInOut {
public:
// template <class Archive>
bool dummy_funct(int &ar, const char* charName){
cout << "serialize_or_throw from DataInOutTYPE is an FULL function." << endl;
return true;
}
shared_ptr<DataInOut> clone() const override { return make_shared<DataInOutType<T>>(*this); }
};
class mapClass {
private:
map<string, shared_ptr<DataInOut> > _m;
public:
template<typename T>
void set(const string &key, shared_ptr<T> var, bool optional = false) {
cout << "set entry with " << var.get() << endl;
auto dataIO_ptr = make_shared<DataInOutType<T>>();
dataIO_ptr->type = typeid(T);
dataIO_ptr->data = var;
dataIO_ptr->optional = optional;
dataIO_ptr->initialized = true;
_m[key] = dataIO_ptr;
int toto = 1;
// dataIO_ptr->dummy_funct(toto, key.c_str());
// cout << "set EXIT" << endl;
}
void call_dummy(const string &key){
int dummyArchive = 1;
_m.at(key)->dummy_funct(dummyArchive, key.c_str());
}
};
int main() {
cout << "Hello World!" << endl;
mapClass mapTest;
auto length = make_shared<double>(1.0);
mapTest.set("length", length);
cout << "mapTest is out of set" << endl;
mapTest.call_dummy("length");
cout << "ByeBye!" << endl;
return 0;
}
Online Demo
|
71,590,400 | 71,592,949 | how to link to a lib and create a shared .so file at the same time using g++ or CMake | File structure under folder /home/cyan/proj
fst
| -- include
| |-- fstlib
| |-- fst_row_reader.h
| |-- fst
| |-- interface
| |-- fststore.h
|
| -- lib
|-- libfst.so
test.cc
CMakeLists.txt
fst folder is a library I added and used in test.cc.
test.cc
#include <iostream>
#include <fstlib/fst_row_reader.h>
class Add{
public:
double add2num(int a, double b){
return a + b;
}
};
extern "C"
{
Add* test_new(){
return new Add;
}
int my_func(Add* t, int a, double b){
return t->add2num(a, b);
}
}
*Note: In my actual test.cc I used some functions in fst library. Here is just a sample for simplicity.
Problem
Previously, I can simply use g++ test.cc -fPIC -shared -o test.so to get the .so file. However, since I included the fst lib, I got the following error:
In file included from /home/cyan/proj/fst/include/fstlib/fst_row_reader.h:7:0,
from read_fst.cc:1:
/home/cyan/proj/fst/include/fstlib/fst_reader.h:6:10: fatal error: fstlib/fst/interface/fststore.h: No such file or directory
#include <fstlib/fst/interface/fststore.h>
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
compilation terminated.
My attempt:
$ g++ -L/home/cyan/proj/fst/lib -l:libfst.so
/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/Scrt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status
---------------------------------------------------------
$ g++ read_fst.cc -L /home/cyan/proj/fst/lib/libfst.so -fPIC -shared -o test.so
In file included from /home/cyan/proj/fst/include/fstlib/fst_row_reader.h:7:0,
from read_fst.cc:1:
/home/cyan/proj/fst/include/fstlib/fst_reader.h:6:10: fatal error: fstlib/fst/interface/fststore.h: No such file or directory
#include <fstlib/fst/interface/fststore.h>
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
compilation terminated.
I also tried CMakeLists.txt to link the fst library as well as create a .so file under the path /home/cyan/proj/build/lib. But I am very new to CMake. Here is my attempt:
cmake_minimum_required(VERSION 3.0.0)
project(MY_PROJ VERSION 0.1.0)
set(mylibSRCS test.cc)
message(STATUS "Build test.so")
include_directories(${CMAKE_SOURCE_DIR}/fst/include)
link_directories(${CMAKE_SOURCE_DIR}/fst/lib)
add_library(MY_PROJ SHARED ${mylibSRCS})
set_target_properties(MY_PROJ PROPERTIES
LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib)
target_link_libraries(MY_PROJ ${CMAKE_SOURCE_DIR}/fst/lib/libfst.so) # link to my fst lib
target_link_libraries(MY_PROJ)
But I can't find any files under the /home/cyan/proj/build/lib. I guess this is my CMake command issue.
Could you please help me with this problem?
| The most convenient way of using a library located on the file system imho associating the info with a imported library target which allows you to just link it using target_link_libraries:
add_library(fst SHARED IMPORTED)
target_include_directories(fst INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/fst/include)
set_target_properties(fst PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/fst/lib/libfst.so)
...
target_link_libraries(MY_PROJ PRIVATE fst)
this way the info is easy to reuse and it listed in a single place instead of spreading it into different target properties of the linking target.
A bit more advanced, but even better would be to write fst-config.cmake and fst-config-version.cmake files and putting them in the "installation directory" of the library which would allow you to use find_package(fst) to execute the logic creating the imported library which makes the library simple to reuse across multiple cmake projects, but this is beyond the scope of this answer.
The find_package documentation provides more info about how to do this.
Btw: Note the use of CMAKE_CURRENT_SOURCE_DIR instead of CMAKE_SOURCE_DIR. If you're specifying absolute paths inside the directory containing the CMakeLists.txt file containing the variable reference, since CMAKE_SOURCE_DIR refers to the toplevel source dir which may be different, if you're including the CMakeLists.txt using add_subdirectory.
|
71,590,445 | 71,590,723 | How to access a derived class member from const base class reference? | class Base1{
public:
Base1(){};
virtual ~Base1() = 0;
}
class Derived1 : public Base1{
public:
Derived1(int a) : a(a){};
~Derived1();
int a;
}
class Base2{
public:
Base2(){};
virtual ~Base2() = 0;
}
class Derived2 : public Base2{
public:
Derived2(int b) : b(b){};
~Derived2();
int b;
void func(const Base1 &base1); // How to access Derived1::a here?
}
Given the above class definition, how can I access Derived1::a in void func(const Base1 &base1)? I am still new to polymorphism. I tried to use different static_cast or dynamic_cast methods but none of them works. What should I do inside the function so I can access a derived class member from a base class reference?
FYI I can't change the class definition for my coursework requirement, and that is what given to me. I understand that it is simpler to just pass Derived1 as parameter but I am not allow to do so.
|
Given the above class definition, how can I access Derived1::a in void func(const Base1 &base1)? ... FYI I can't change the class definition for my coursework requirement, and that is what given to me.
Ideally, you should expose a virtual method in Base1 that returns an int (or int&), and then have Derived1 override that method to return its a member.
But, given that you are not allowed to change the class definitions, that is not an option.
You need a pointer or reference to a Derived1 object in order to access its a member directly. Which really leaves you with only 1 choice - you can use dynamic_cast to typecast the base class reference to the derived class type, eg:
void Derived2::func(const Base1 &base1)
{
// this will raise an exception if the cast fails at runtime
const Derived1 &d = dynamic_cast<const Derived1&>(base1);
// use d.a as needed...
}
Alternatively:
void Derived2::func(const Base1 &base1)
{
// this will return null if the cast fails at runtime
const Derived1 *d = dynamic_cast<const Derived1*>(&base1);
if (d) {
// use d->a as needed...
} else {
// do something else...
}
}
|
71,590,689 | 71,609,128 | How to properly handle windows paths with the long path prefix with std::filesystem::path | std::filesystem::path doesn't seem to be aware of the windows long path magic prefix.
Is this per design or is there a mode/flag/compiler switch/3rd party library which can be used?
f.e.
for a path like C:\temp\test.txt, the root_name is C: and the root_path is C:\ which are both valid paths but
for \\?\C:\tmp\test.txt they are \\? and \\?\
I hoped that they would be C: and C:\ as well because \\?\ is not a path but just a tag used to work around the legacy windows 260 char path limit.
See a complete example on compilerexplorer.
| As mentioned in the comments above, the source code of the Microsoft STL shows that the current behavior is intentional for UNC (Uniform Naming Convention) paths and that there is no "magic compiler switch" to change this. Moreover, it seems that UNC paths should not be used with std::filesystem, as implied by this github post. There is also an open issue that requests a change of behavior.
Since the OP is ok with 3rd party libraries: boost::filesystem has special code on Windows builds for UNC paths and gives results that are closer to what is expected.
Trying it out with the following code (adapted from the original post):
#include <filesystem>
#include <iostream>
#include <string>
#include <vector>
#include <boost/filesystem.hpp>
int main()
{
std::vector<std::string> tests = {
R"(C:\temp\test.txt)",
R"(\\?\C:\temp\test.txt)",
};
for (auto const & test : tests) {
std::filesystem::path const p(test); // or boost::filesystem::path
std::cout << std::endl << test << std::endl;
std::cout << "root_name\t" << p.root_name().string() << std::endl;
std::cout << "root_directory\t" << p.root_directory().string() << std::endl;
std::cout << "root_path\t" << p.root_path().string() << std::endl;
std::cout << "relative_path\t" << p.relative_path().string() << std::endl;
std::cout << "parent_path\t" << p.parent_path().string() << std::endl;
std::cout << "filename\t" << p.filename().string() << std::endl;
std::cout << "stem\t" << p.stem().string() << std::endl;
std::cout << "extension\t" << p.extension().string() << std::endl;
}
}
For std::filesystem on MSVC I get
C:\temp\test.txt
root_name C:
root_directory \
root_path C:\
relative_path temp\test.txt
parent_path C:\temp
filename test.txt
stem test
extension .txt
\\?\C:\temp\test.txt
root_name \\?
root_directory \
root_path \\?\
relative_path C:\temp\test.txt
parent_path \\?\C:\temp
filename test.txt
stem test
extension .txt
For boost::filesystem I get:
C:\temp\test.txt
root_name C:
root_directory \
root_path C:\
relative_path temp\test.txt
parent_path C:\temp
filename test.txt
stem test
extension .txt
\\?\C:\temp\test.txt
root_name \\?\C:
root_directory \
root_path \\?\C:\
relative_path temp\test.txt
parent_path \\?\C:\temp
filename test.txt
stem test
extension .txt
|
71,590,740 | 71,591,918 | Is there a way to get collision results in the context of the plant? | I'm a bit unfamiliar with Drake and I've been trying to write a function to return the body indices involved in collisions in my MultibodyPlant. I'm having some trouble getting the correct collision results. I'm currently trying to get the contact results from the plant using a LeafSystem:
class ContactResultsReader : public drake::systems::LeafSystem<double> {
public:
ContactResultsReader() : drake::systems::LeafSystem<double>() {
contact_results_input_port = &DeclareAbstractInputPort("contact_results_input_port", *drake::AbstractValue::Make<drake::multibody::ContactResults<double>>());
};
drake::systems::InputPort<double> & get_contact_results_input_port() {
return *contact_results_input_port;
}
private:
drake::systems::InputPort<double> *contact_results_input_port = nullptr;
};
connecting the contact results output port into this
builder->Connect(plant->get_contact_results_output_port(), contact_results_reader->get_contact_results_input_port());
and reading the contact results from the input port in the LeafSystem:
const drake::systems::InputPortIndex contact_results_input_port_index = contact_results_reader->get_contact_results_input_port().get_index();
const drake::AbstractValue* abstract_value =
contact_results_reader->EvalAbstractInput(*contact_results_reader_context, contact_results_input_port_index);
const drake::multibody::ContactResults<double> &contact_results = abstract_value->get_value<drake::multibody::ContactResults<double>>();
For some reason, I'm not reading a collision between two bodies that I load into the plant directly on top of each other. Is there something wrong with this method?
I've also tried getting the QueryObject from the plant and using query_object.ComputePointPairPenetration();, but that returns the bodies themselves and I would like to get the body indices. Thank you!
| From some application code (e.g., not within your own custom LeafSystem), it would look like this:
Say we have a const drake::multibody::MultibodyPlant<double>& plant reference along with a const drake::systems::Context<double>& plant_context matching context reference. To access its contact results would be like so:
const drake::multibody::ContactResults<double>& contact_results =
plant.get_contact_results_output_port().
Eval<drake::multibody::ContactResults<double>>(context);
BodyIndex a = contact_results.point_pair_contact_info(...).bodyA_index();
BodyIndex b = contact_results.point_pair_contact_info(...).bodyB_index();
If you need to do it from within a LeafSystem function, then the code would be a mix of what you posted above, and this answer.
Something like
const drake::multibody::ContactResults<double>& contact_results =
this->get_input_port(0).
Eval<drake::multibody::ContactResults<double>>(context);
BodyIndex a = contact_results.point_pair_contact_info(...).bodyA_index();
BodyIndex b = contact_results.point_pair_contact_info(...).bodyB_index();
|
71,591,043 | 71,824,486 | LCOV File has strange Paths at "SF:" | i am testing my cpp Application with googletest and these part runs very good.
To build and start the Unit-Tests i run a small Powershell Skript.
cmake -G "Unix Makefiles" -S . -B ${BUILD_PATH}
cmake --build $BUILD_PATH
Set-Location $BUILD_PATH
./UnitTests
The CMakeLists.txt looks like this:
cmake_minimum_required(VERSION 3.14)
project(exampleProject)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_FLAGS --coverage)
# GoogleTest
include(FetchContent)
FetchContent_Declare(
googletest
URL https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip
)
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest)
enable_testing()
# Testsources
file(GLOB_RECURSE TEST_SOURCES "./test/*.cc")
# Linking
# Add here the "inc" and "src" folder from the features
include_directories(
"./Example/inc"
"./Example/src"
"./test/Example/mock"
)
add_executable(
unittests
${TEST_SOURCES}
)
target_link_libraries(
unittests
gtest_main
gmock_main
)
include(GoogleTest)
# Run
gtest_discover_tests(unittests)
The following Line of Code in my .sh Script works on MacOs perfectly.
lcov --directory ${TEST_SOURCE_PATH} --capture --output-file ${LCOV_PATH_INFO} -rc lcov_branch_coverage=1
The same i will do on the Windows Machine with this Code in a another Powershell Script:
$LCOV = "C:\ProgramData\chocolatey\lib\lcov\tools\bin\lcov"
perl $LCOV --capture --directory ${TEST_SOURCE_PATH} --output-file ${LCOV_PATH_INFO}
When i run these Script then the .info File has strage Path at the SF-Tag For Example:
SF:C:\dev\exampleProject\build\test\CMakeFiles\unittests.dir\test\Example\C:/Strawberry/c/lib/gcc/x86_64-w64-mingw32/8.3.0/include/c++/ext/alloc_traits.h
The geninfo at the Powershell says me that he cant open these Files, which is logical.
So why i became these stange Paths?
Thank you. Best Guards
Daniel
I read many stuff about this but i found no Solution.
| So I found a Solution with a Powershell Script.
At first I create a lcov.info file.
After that the created File will be clean about the File Extensions.
At last I clean the strange Path with the replace Command.
So it works well.
|
71,591,055 | 71,591,152 | Understanding behavior of trivial constructors in C++ | I'm trying to understand how the following construction behaves differently across C++ standards, and what the guarantees are on elements a and b.
struct X {
int a;
int b;
};
void func() {
X x(1); // (1) Works in c++2a only
X y{1}; // (2) Works in c++1z
}
| This has nothing to do with the default constructor being trivial, or really with the default constructor at all.
X y{1}; does aggregate-initialization which doesn't use any constructor, but instead initialized members of an aggregate (which your class is since it doesn't explicitly declare any constructors) directly one-by-one from the braced initializer list. The remaining members which are not explicitly given a value are value-initialized, which here means that b will be zero-initialized.
X x(1); can also initialize aggregates in the same way (with minor differences not relevant here) since C++20. Before that, non-empty parenthesized initializers would only try constructors. But there is no constructor that takes a single argument of type int in your class. There is only an implicitly-declared default constructor which takes no arguments and implicitly-declared copy and move constructors, which take references to a X as argument.
|
71,591,385 | 71,591,444 | Why do I get a "no matching constructor error? | I want my code to take a name, mail and car as argument types, and I try to do so in a class named Person. In main(), I try to give that class a variable a which I can call later in cout. However, I get this exact error:
no matching constructor for initialization of "Person"
How can I fix this?
The h. file
#pragma once
#include <iostream>
#include "car.h"
#include <string>
class Person{
private:
std::string name;
std::string mail;
Car* car;
public:
Person(std::string name, std::string mail);
Person(std::string name, std::string, Car* car);
void setMail(std::string mail);
std::string getMail() const;
std::string getName() const;
bool hasAvailableFreeSeats();
friend std::ostream& operator <<(std::ostream& os, const Person& person);
};
The cpp file:
#include "person.h"
std::string Person:: getMail() const{
return mail;
}
std:: string Person:: getName() const{
return name;
}
void Person:: setMail(std::string mail){
this -> mail = mail;
}
Person:: Person(std::string name, std::string mail) : Person(name, mail, nullptr){};
Person::Person(std::string name, std::string, Car* car) : name{name}, mail{mail}, car{car}{};
bool Person:: hasAvailableFreeSeats(){
if (car != nullptr){
return car-> hasFreeSeats();
}
}
std::ostream& operator <<(std::ostream& os, const Person& person){
return os << person.name << ": " << person.mail << "\n";
}
main:
#include "person.h"
int main(){
std::string name{"Ola Normann"};
std::string mail{"ola.normann@norge.no"};
std::unique_ptr<Car> car{new Car{5}};
Person a{name, mail, std::move(car)};
};
| First off, you have a typo in your 3-parameter Person constructor. The 2nd parameter has no name assigned to it, so you end up initializing the mail class member with itself, not with the caller's input:
Person::Person(std::string name, std::string, Car* car) : name{name}, mail{mail}, car{car}{};
^ no name here! ^ member!
That should be this instead:
Person::Person(std::string name, std::string mail, Car* car) : name{name}, mail{mail}, car{car}{};
^ has a name now! ^ parameter!
Now, that being said, your main() code is passing 3 values to the Person constructor:
Person a{name, mail, std::move(car)};
Your Person class only has 1 constructor that accepts 3 parameters:
Person(std::string name, std::string, Car* car);
In main(), your name and mail variables are std::string objects, which is fine, but your car variable is a std::unique_ptr<Car> object, not a Car* pointer. std::move(car) will return a std::unique_ptr<Car>&& rvalue reference, which Person does not accept, hence the compiler error. std::unique_ptr is not implicitly convertible to a raw pointer. You would have to use its get() method instead:
Person a{name, mail, car.get()};
Which defeats the purpose of using std::unique_ptr in the first place. You should instead change the Person class to hold a std::unique_ptr object instead of a raw pointer, eg:
.h
#pragma once
#include <iostream>
#include <string>
#include <memory>
#include "car.h"
class Person{
private:
std::string name;
std::string mail;
std::unique_ptr<Car> car;
public:
...
Person(std::string name, std::string mail);
Person(std::string name, std::string mail, std::unique_ptr<Car> car);
...
};
.cpp
#include "person.h"
...
Person::Person(std::string name, std::string mail) : Person(name, mail, nullptr){};
Person::Person(std::string name, std::string, std::unique_ptr<Car> car) : name{name}, mail{mail}, car{std::move(car)}{};
...
main
#include "person.h"
int main(){
std::string name{"Ola Normann"};
std::string mail{"ola.normann@norge.no"};
std::unique_ptr<Car> car{new Car{5}};
Person a{name, mail, std::move(car)};
// alternatively:
// Person a{name, mail, std::make_unique<Car>(5)};
};
|
71,592,769 | 71,596,213 | QGraphicsScene::itemAt() not working properly | I am trying to find out the QGraphicsItem under the mouse (when mouse hover over the item). For that I am using itemAt() method but itemAt() is not returning QGraphicsItem.
I tried this way:
bool myViewer::eventFilter(QObject *watched, QEvent *event)
{
bool fEvent = false;
switch(event->type())
{
case QEvent::MouseButtonPress:
{....}
case QEvent::MouseButtonRelease:
{...}
case QEvent::Enter:
{
QMouseEvent * mouseEvent = static_cast<QMouseEvent *>(event);
qDebug()<<"Event points = "<< mouseEvent->pos(); // showing points properly
QPointF po = _view->mapToScene(mouseEvent->pos());
QGraphicsRectItem* rItem = qgraphicsitem_cast<QGraphicsRectItem*>(_scene->itemAt(po,QTransform()));
if(rItem)
{
// some logic
}
}
return true;
default:
break;
}
return fEvent;
I tried with QGraphicsView::itemAt() also. But still it did not work.
Note: In both way following lines works fine.
QMouseEvent * mouseEvent = static_cast<QMouseEvent *>(event);
qDebug()<<"Event points = "<< mouseEvent->pos();
Where am I wrong?
| May be you can try handling QEvent::GraphicsSceneMousePress
And then get the position as said below (pseudo code. Not tetsted.)
//Get the scene event object.
QGraphicsSceneMouseEvent* sceneEvent = dynamic_cast<QGraphicsSceneMouseEvent*>(qevent);
//From the scene event object get the scene position.
QPointF po = sceneEvent->scenePos();
Use that position to find the item.
|
71,593,055 | 71,593,543 | Detect the existence of a template instantiation for a given type | I'm using templates to explicitly declare and allow read access to specific data.
#include <type_traits>
template <typename T>
struct Access
{
template <typename U>
void Read()
{
static_assert(std::is_same_v<T, U>);
}
};
Normally T would be a set of types, but I've simplified it here.
I'd like to ensure that any access that gets declared actually gets used. If a user declares Access<int> I want to check to see that there is a corresponding Read<int> somewhere.
Give that context, what I'm currently trying to do is detect whether Access<int>::Read<int> ever gets instantiated. Is this possible?
I tried using extern template to prevent implicit instantiations. The main problem here is that you have to explicitly write out every possible type at namespace scope. I don't see a way to do this systemically.
extern template void Access<int>::Read<int>();
int main()
{
auto IsIntReadUsed = &Access<int>::Read<int>; // Linker error, yay!
return 0;
}
Being able to detect this at compile time, link time, or run time is acceptable. The solution does not need to be portable across compilers. A solution that works on any single compiler is sufficient. Any C++ version is acceptable.
Here is a sandbox for experimenting
https://godbolt.org/z/d5cco989v
// -----------------------------------------------------------
// Infrastructure
#include <type_traits>
template <typename T>
struct Access
{
template <typename U>
void Read()
{
static_assert(std::is_same_v<T, U>);
}
};
int main()
{
return 0;
}
// -----------------------------------------------------------
// User Code
using UserAccess = Access<int>;
void UserUpdate(UserAccess access)
{
// Oh no, access.Read<int> is never used!
(void) access;
}
// -----------------------------------------------------------
// Validation
template <typename TDeclared>
void ValidateAccess(Access<TDeclared>)
{
// Write something here that can tell if Access<TDeclared>::Read<TDeclared> has been
// used when this is called with UserAccess (i.e. ValidateAccess(UserAccess())).
// This could also be implemented inside the Access class.
}
| Here's a link-time solution. Works on GCC, Clang, and MSVC.
One template (impl::Checker<T>) declares a friend function and calls it.
Another template (impl::Marker) defines that function. If it's not defined, the first class gets an undefined reference.
run on gcc.godbolt.org
#include <cstddef>
#include <type_traits>
namespace impl
{
template <typename T>
struct Checker
{
#if defined(__GNUC__) && !defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wnon-template-friend"
#endif
friend void adl_MarkerFunc(Checker<T>);
#if defined(__GNUC__) && !defined(__clang__)
#pragma GCC diagnostic pop
#endif
static std::nullptr_t Check()
{
adl_MarkerFunc(Checker<T>{});
return nullptr;
}
inline static const std::nullptr_t check_var = Check();
static constexpr std::integral_constant<decltype(&check_var), &check_var> use_check_var{};
};
template <typename T>
struct Marker
{
friend void adl_MarkerFunc(Checker<T>) {}
};
}
template <typename T, impl::Checker<T> = impl::Checker<T>{}>
struct Access
{
template <typename U>
void Read()
{
static_assert(std::is_same_v<T, U>);
(void)impl::Marker<U>{};
}
};
int main()
{
Access<int> x;
x.Read<int>();
[[maybe_unused]] Access<float> y; // undefined reference to `impl::adl_MarkerFunc(impl::Checker<float>)'
using T [[maybe_unused]] = Access<double>; // undefined reference to `impl::adl_MarkerFunc(impl::Checker<double>)'
}
Had to introduce a dummy template parameter to Access, since I couldn't think of any other way of detecting it being used in a using.
|
71,593,271 | 71,593,744 | Poco::Net::HTTPRequest is unable to resolve host | I have written a code in poco c++ library that is supposed to send a request to the server to get some data. The is running from inside a docker container. And I am getting a "hostname not resolved" error. The sample code is as follow
//initialize session
Poco::SharedPtr<InvalidCertificateHandler> ptrCert = new AcceptCertificateHandler(false);
_ptrContext = new Context(Context::TLSV1_2_CLIENT_USE, "", "", "", Context::VERIFY_RELAXED, 9, false, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
_ptrContext->enableSessionCache(true);
// Disable SSL versions 2 & 3 and TLS versions 1.0 & 1.1
_ptrContext->disableProtocols(Poco::Net::Context::PROTO_SSLV2 | Poco::Net::Context::PROTO_SSLV3 | Poco::Net::Context::PROTO_TLSV1 | Poco::Net::Context::PROTO_TLSV1_1);
SSLManager::instance().initializeClient(0, ptrCert, _ptrContext);
_httpsession_secure = new HTTPSClientSession(_hostname, _port);
//build request
Poco::Net::HTTPRequest req(Poco::Net::HTTPRequest::HTTP_POST, uri, Poco::Net::HTTPMessage::HTTP_1_1);
req.setContentLength(http_body.length());
req.setContentType("application/x-www-form-urlencoded");
// Send request
std::ostream &os = _httpsession_secure->sendRequest(req);
os << http_body;
// Wait for response
Poco::Net::HTTPResponse res;
std::istream &rs = _httpsession_secure->receiveResponse(res);
I have run a curl command as the CMD entry in the docker container, and the command is executing properly and giving the result. so that means the host is accessible inside the container. When I execute the code inside the container, it is failing. So I am surely missing something in the code. Please guide.
| As per your answer to a my question in the comments, you are using:
_httpsession_secure = new HTTPSClientSession(_hostname, _port);
where _hostname is of the form to https://somehost.somedomain.
This is wrong, you must not pass an URI there, you just have to pass the domain name.
_hostname = "somehost.somedomain";
_httpsession_secure = new HTTPSClientSession(_hostname, _port);
|
71,593,633 | 71,593,852 | c++ check if a type is a fixed char array in a template | I need to do some special handling of string types in a template I'm writing, but I'm running into a problem with fixed size char arrays. I'm aware I can write code like mentioned in this answer to create a wrapper: Const char array with template argument size vs. char pointer
But I was wondering if there was a way to test if this is a const char array from within a templated function with a static assert, something like this:
template<typename T>
void f(T& val /* a handful of other params */ )
{
static_assert(
std::is_same_v < T, const char* > ||
std::is_same_v < T, char[N] > || // how do I get/discard N here?
std::is_same_v < T, std::string >
, "Unsupported type" );
}
My motivation for this is to avoid having a ton of function signatures for all valid type combinations, while still ensuring only valid types are allowed. Writing all those type declarations and definitions is a nightmare for a few reasons. But as strings can come in various fixed size arrays, I'm unsure how to check them without a wrapper to peel off the length data, but then I am back to writing a ton of wrappers which is exactly what I'm trying to avoid (if there is some way to write a simple reusable test using a single wrapper that would be ok, but I haven't been able to figure one out). And for each string like this, if I was to manually add a wrapper for each time a string param appears in a param list, it will obviously double the number of declarations and definitions I need to write, creating a lot of redundant code. So is there any way to determine if a type is a fixed array type, and only then extract the pointer without the length so I can check it against a const char*? Or someway to ignore the array length and just check if it's a char type array in my assert?
| You cannot determine whether a T is an array like that directly, but the standard library provides traits for determining whether a given type is an array already: std::is_array.
Though std::is_array also accepts char[], which may be undesirable. In that case if you have access to C++20, you can use std::is_bounded_array. If you don't have access to C++20, implementing one is rather trivial, or if you want to only check for char[N]:
template <class> struct is_bounded_char_array : std::false_type {};
template <size_t N>
struct is_bounded_char_array<char[N]> : std::true_type {};
template <class> struct is_bounded_array : std::false_type {};
template <class T, size_t N>
struct is_bounded_array<T[N]> : std::true_type {};
static_assert(!is_bounded_array<char>{});
static_assert(!is_bounded_array<char[]>{});
static_assert(is_bounded_array<char[42]>{});
Then, instead of std::is_same_v < T, char[N] >, you can say is_bounded_array<T>.
To get a const char* from any of your types, you could use std::string_view(t).data() instead of handling each case yourself.
|
71,594,009 | 71,594,083 | How to insert a line every 10 numbers displayed in C++? | I am trying to insert a line every 10 numbers displayed but when I run this and enter -29 and 29, not a single line shows. Please help and thank you
int start;
int end;
do
{
cout << "Please enter a number between -30 and 0: ";
cin >>start;
} while(start > 0 || start < -30);
do
{
cout << "Pleaes enter a number between 15 and 30: ";
cin >> end;
} while(end < 15 || end > 30);
for (int i = start; i <= end; i++)
{
if (i++ % 10 == 0)
{
cout << "----------"<<endl;
}
else
cout << start << " " << end <<endl;
}
| i is incremented twice. Do not increment it again in the if condition, and just use the following:
if (i % 10 == 0)
|
71,594,502 | 71,594,547 | insert an element into container without changing its original adress in C++ | I have 2 classes. The class Covid has a list of Deviant.
I need to add an Deviant to the list .
class Deviant : public Individu{
public:
Deviant();
Deviant(const Personne& );
Deviant(const Personne&, const std::string& );
~Deviant();
const std::string& getObs() const;
void setObs(const std::string&);
std::vector<Personne> p;
std::string obs;
};
class Covid{
public:
Covid();
~Covid();
void push(const Deviant&);
const Deviant& top() const;
std::list<Deviant > d;
};
I need to implement methods push() that pushes a Deviant into list d and top() that returns the first element in the list d.
I need to pass this test
TEST_CASE("COVID") {
Deviant zz[] = { Deviant(Personne("bruno") , "19980930"),
Deviant(Personne("alexis"), "20160930"),
Deviant(Personne("loic") , "19990930"),
Deviant(Personne("jeremy"), "20210930")
};
Covid c;
for (int i=0; i< 4; ++i)
c.push(zz[i]);
std::cout << c.top().getObs() << std::endl;
std::cout << zz[3].getObs() << std::endl;
CHECK(&c.top() == &zz[3]);
/*c.pop();
CHECK(&c.top() == &zz[1]);
c.pop();
CHECK(&c.top() == &zz[2]);
c.pop();
CHECK(&c.top() == &zz[0]);*/
}
but the first check does pass
tests.cpp:225: FAILED:
CHECK( &c.top() == &zz[3] )
with expansion:
0x000055bded197be0 == 0x00007fffad1896a8
what is the best container to store objects without changing their original addresses ?
| Your test will always fail, because std::list makes a copy of whatever is pushed into it. You are testing the copy's address against the original's address, which will never match. The only way to push an object into a container without copying/moving it is to push a pointer to the object instead. IOW, use std::list<Deviant*> and c.push(&zz[i]);, and then adjust top() and your tests accordingly, eg:
class Covid{
public:
Covid();
~Covid();
void push(Deviant*);
const Deviant* top() const;
std::list<Deviant*> d;
};
TEST_CASE("COVID") {
Deviant zz[] = { Deviant(Personne("bruno") , "19980930"),
Deviant(Personne("alexis"), "20160930"),
Deviant(Personne("loic") , "19990930"),
Deviant(Personne("jeremy"), "20210930")
};
Covid c;
for (int i=0; i< 4; ++i)
c.push(&zz[i]);
std::cout << c.top()->getObs() << std::endl;
std::cout << zz[3].getObs() << std::endl;
CHECK(c.top() == &zz[3]);
/*c.pop();
CHECK(c.top() == &zz[1]);
c.pop();
CHECK(c.top() == &zz[2]);
c.pop();
CHECK(c.top() == &zz[0]);*/
}
|
71,594,722 | 71,595,007 | How to work with the 4th argument of the sqlite3_exec function? | I want to pass a std::list to my callback function. I understand that I have to work with void* in my callback function, but how exactly do I insert objects to my list while working with void*?
//function will insert to a list of albums (data) a new album
int callbackAlbums(void* data, int argc, char** argv, char** azColName)
{
Album album;
for(int i = 0; i < argc; i++)
{
if (std::string(azColName[i])) == "NAME")
{
album.setName(std::string(argv[i]));
}
else if (std::string(azColName[i])) == "CREATION_DATE")
{
album.setCreationDate(std::string(argv[i]));
}
else if (std::string(azColName[i])) == "USER_ID")
{
album.setOwner(atoi(argv[i]));
}
}
data.push_back(album);
return 0;
}
//function will return a list of all albums.
const std::list<album> DatabaseAccess::getAlbums()
{
const char* sqlStatement = "SELECT * FROM ALBUMS;";
std::list<Album> albums;
char* errMessage = "";
int res = sqlite3_exec(this->_db, sqlStatement, callbackAlbums, (void*)&albums, &errMessage);
}
I tried changing the void* in my callback function to std::list<Album> and expected sqlite3_exec() to work with that callback function.
| You already know how to cast a list* to a void* (which BTW, that explicit cast is redundant). Simply do the opposite cast inside the callback, eg:
int callbackAlbums(void* data, int argc, char** argv, char** azColName)
{
Album album;
...
std::list<Album>* albums = (std::list<Album>*)data;
albums->push_back(album);
...
}
And don't forget to actually return your std::list from getAlbums():
const std::list<album> DatabaseAccess::getAlbums()
{
std::list<Album> albums;
...
int res = sqlite3_exec(..., callbackAlbums, &albums, ...);
...
return albums;
}
|
71,594,756 | 71,594,870 | Can't fill dynamic array | I'm learning C++ now and I have some misunderstandings
I've created 2d dynamic array, but I can't fill it
I've got error in 44 line like: Access violation writing location 0xFDFDFDFD.
This is my code:
#include <iostream>
#include <cmath>
using namespace std;
class Matrix
{
private:
int row;
int column;
int** M;
public:
Matrix();
void setRow(int row) {
this->row = row;
}
void setColumn(int column) {
this->column = column;
}
int getRow() {
return row;
}
int getColumn() {
return column;
}
void setMat();
void printMat();
~Matrix();
};
Matrix::Matrix() {
M = new int* [row];
for (int i = 0; i < row; i++) {
M[i] = new int[column];
}
cout << "Constructor called";
}
//filling matrix
void Matrix::setMat() {
for (int i = 0; i < row; i++) {
cout << "Enter the first row";
for (int j = 0; j < column; j++) {
M[i][j]=j;
}
}
}
void Matrix::printMat() {
for (int i = 0; i < row; i++) {
cout << endl;
for (int j = 0; j < column; j++) {
cout<< M[i][j];
}
}
}
Matrix::~Matrix() {
for (int i = 0; i < row; i++) {
delete[] M[i];
}
delete[] M;
cout << "constructor cancelled";
}
int main(){
int numC, numR;
Matrix a;
cout << "Enter the number of column: ";
cin>>numC;
a.setColumn(numC);
cout << "Enter the number of rows: ";
cin >> numR;
a.setRow(numR);
int col = a.getRow();
cout << col;
a.setMat();
a.printMat();
}
I think that the problem is with dynamic array, but I don't know how to fix it. I hope you'll help me. Also about column and row, I know about vector, but the task is to create row and column.
| Your constructor is allocating the arrays before the row and column members have been initialized yet. You need to re-think your design.
Try something more like this instead:
#include <iostream>
#include <cmath>
using namespace std;
class Matrix
{
private:
int row;
int column;
int** M;
public:
Matrix(int row, int column);
~Matrix();
int getRow() const {
return row;
}
int getColumn() const {
return column;
}
void setMat();
void printMat() const;
};
Matrix::Matrix(int row, int column) : row(row), column(column) {
M = new int* [row];
for (int i = 0; i < row; i++) {
M[i] = new int[column];
}
cout << "Constructor called";
}
Matrix::~Matrix() {
for (int i = 0; i < row; i++) {
delete[] M[i];
}
delete[] M;
cout << "Destructor called";
}
void Matrix::setMat() {
for (int i = 0; i < row; i++) {
cout << "Enter the first row";
for (int j = 0; j < column; j++) {
M[i][j] = j;
}
}
}
void Matrix::printMat() const {
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
cout << M[i][j] << ' ';
}
cout << endl;
}
cout << endl;
}
int main(){
int numR, numC;
cout << "Enter the number of rows: ";
cin >> numR;
cout << "Enter the number of column: ";
cin >> numC;
Matrix a(numR, numC);
cout << a.getRow();
a.setMat();
a.printMat();
return 0;
}
If you really want to use separate setters for the row and column members, then try something more like this instead:
#include <iostream>
#include <cmath>
using namespace std;
class Matrix
{
private:
int row;
int column;
int** M;
void checkMat();
public:
Matrix();
~Matrix();
void setRow(int row);
void setColumn(int column);
int getRow() const {
return row;
}
int getColumn() const {
return column;
}
void setMat();
void printMat() const;
};
Matrix::Matrix() : row(0), column(0), M(NULL) {
cout << "Constructor called";
}
Matrix::~Matrix() {
for (int i = 0; i < row; i++) {
delete[] M[i];
}
delete[] M;
cout << "Destructor called";
}
void Matrix::setMat() {
for (int i = 0; i < row; i++) {
cout << "Enter the first row";
for (int j = 0; j < column; j++) {
M[i][j] = j;
}
}
}
void Matrix::setRow(int row) {
this->row = row;
checkMat();
}
void Matrix::setColumn(int column) {
this->column = column;
checkMat();
}
void Matrix::checkMat() {
if ((!M) && (row > 0) && (column > 0)) {
M = new int*[row];
for (int i = 0; i < row; i++) {
M[i] = new int[column];
}
}
}
void Matrix::printMat() const {
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
cout << M[i][j] << ' ';
}
cout << endl;
}
cout << endl;
}
int main(){
int numR, numC;
Matrix a;
cout << "Enter the number of rows: ";
cin >> numR;
a.setRow(numR);
cout << "Enter the number of column: ";
cin >> numC;
a.setColumn(numC);
cout << a.getRow();
a.setMat();
a.printMat();
return 0;
}
|
71,594,902 | 71,595,195 | C++ char array seems to not pass full array | I would like to preface this with I am a junior but relatively experienced developer, but with very little C++ experience.
I have this test method that is supposed to pass an array of characters to find the "O".
TEST(MyTest, ReturnIndexOfO)
{
Widget unitUnderTest;
char x = 'X';
char o = 'O';
char *row[4] = {&o, &x, &x, &x};
char *row2[4] = {&x, &o, &x, &x};
EXPECT_EQ(unitUnderTest.findEmptySpace(*row, 4), 0);
EXPECT_EQ(unitUnderTest.findEmptySpace(*row2,4 ), 1);
}
And this has properly invoked my findEmptySpace method, which is:
#define WHITE_SPACE 'O'
int Widget::findEmptySpace(char row[], int size)
{
cout << "The row under test is:\n";
for(int i = 0; i < size; i++) {
cout << row[i];
}
cout << "\n";
for(int i = 0; i < size; i++) {
if(row[i] == WHITE_SPACE) {
return i;
}
}
return -1;
}
But unfortunately, my output seems indicate that not all of the characters are being read by my findEmptySpace method:
The row under test is:
OX
The row under test is:
X
So even with the truncated data, my first test case passes, but the second test case fails. Any idea why I am not seeing the data correctly?
| When you call
unitUnderTest.findEmptySpace(*row, 4)
the expression row will decay to a pointer to the first element of row, i.e. to &row[0]. Therefore, the expression *row is equivalent to row[0], which is a pointer to the variable o, i.e. a pointer to a single character.
In the function Widget::findEmptySpace, in the following loop, you use this pointer to a single character as if it were a pointer to 4 characters:
for(int i = 0; i < size; i++) {
cout << row[i];
}
Since the function argument row (in contrast to the original array with that name) is a pointer to a single character, the only valid index for row would be row[0]. However, you are using the indexes row[0] to row[3], so you are accessing the object out of bounds, causing undefined behavior.
The function signature
int Widget::findEmptySpace(char row[], int size)
is probably not what you want. If you want to pass a pointer to the entire array row from the functon TEST to the function findEmptySpace, then you should pass a pointer to the first element of the array as well as its length. You are already doing the latter properly, but you are not doing the former properly. Since every element of the array is of type char *, a pointer to the first element of the array would be of type char **, i.e. a pointer to a pointer. Therefore, you should change the function signature to the following:
int Widget::findEmptySpace( char **row, int size )
Or, if you prefer, you can use this equivalent, to make it clear that the higher level pointer points to an array:
int Widget::findEmptySpace( char *row[], int size )
Of course, you will have to rewrite your function findEmptySpace to adapt to the different parameter type, so that it dereferences the pointer:
int Widget::findEmptySpace( char *row[], int size )
{
cout << "The row under test is:\n";
for( int i = 0; i < size; i++ ) {
cout << *row[i];
}
cout << "\n";
for( int i = 0; i < size; i++ ) {
if( *row[i] == WHITE_SPACE ) {
return i;
}
}
return -1;
}
Now, in the function TEST, you must change the way you are calling the function findEmptySpace, due to the changed function parameter. You should change the lines
EXPECT_EQ(unitUnderTest.findEmptySpace(*row, 4), 0);
EXPECT_EQ(unitUnderTest.findEmptySpace(*row2,4 ), 1);
to:
EXPECT_EQ(unitUnderTest.findEmptySpace( row, 4), 0);
EXPECT_EQ(unitUnderTest.findEmptySpace( row2, 4 ), 1);
Now you are no longer passing the value of the first array element, but you are instead passing a pointer to the first array element, so that the function findEmptySpace can access the entire array properly.
|
71,595,114 | 71,595,255 | How to solve this problem trying to iterate a string? | I'm trying to invert the case of some strings, and I did it, but I have some extra characters in my return, is it a memory problem? Or because of the length?
char* invertirCase(char* str){
int size = 0;
char* iterator = str;
while (*iterator != '\0') {
size++;
iterator++;
}
char* retorno = new char[size];
for (int i = 0; i < size; i++) {
//if capital letter:
if (str[i] < 96 && str[i] > 64) {
retorno[i] = str[i] + 32;
}
// if lower case:
else if (str[i] > 96 && str[i] < 123) {
retorno[i] = str[i] - 32;
}
//if its not a letter
else {
retorno[i] = str[i];
}
}
return retorno;
}
For example, if I try to use this function with the value "Write in C" it should return "wRITE IN c", but instead it returns "wRITE IN cýýýýÝݱ7ŽÓÝ" and I don't understand where those extra characters are coming from.
PS: I know I could use a length function, but this is from school, so I can't do that in this case.
| add +1 to the size of the char array.
char* retorno = new char[size+1];
add a null-terminated string before returning retorno.
retorno[size] = '\0';
|
71,595,421 | 71,595,700 | Generating all set of permutations | Recently in an interview, I was asked the following question:
Given a list of pairs of numbers, like (2, 6)(4, 5)(1, 5), generate all numbers of the form 241,242,243,244,245,251.... Note that the length of list of pairs is variable, i.e., we could have more than 3 pairs of numbers. Each pair represents an "inclusive interval". Each of the numbers generated, for e.g., 241 should come from each of the intervals: 2 from the first, 4 from the second, 1 from the third and so on. Duplicates are not to be treated any specially, i.e., 555 is valid and should be part of the output sequence.
I came up with the simple brute force logic:
#include <iostream>
#include <vector>
using namespace std;
vector<int> res;
void helper(pair<int,int>& interval) {
int start=interval.first;
int end=interval.second;
vector<int> ans;
for(int i=0; i<res.size(); i++) {
for(int j=start; j<=end; j++) {
ans.push_back(res[i]*10+j);
}
}
res=ans;
}
vector<int> generatePermutation(vector<pair<int,int>>& intervals) {
if(intervals.empty()) return res;
pair<int, int> firstInt=intervals[0];
for(int i=firstInt.first; i<=firstInt.second; i++) {
res.push_back(i);
}
for(int i=1; i<intervals.size(); i++) {
helper(intervals[i]);
}
return res;
}
int main() {
vector<pair<int,int>> v;
v.push_back({2,6});
v.push_back({4,5});
v.push_back({1,5});
vector<int> ans=generatePermutation(v);
for(auto& each: ans) cout<<each<<" ";
return 0;
}
Which generates the answer as needed. But I was curious to know if there is some efficient algorithm to this problem? The interviewer did not have any time complexity on mind, although he said he was looking for a recursive solution making me think if we could perhaps solve it by backtracking in a more efficient manner.
| The only practical solution here is the one your interviewer hinted at you: recursion.
#include <iostream>
#include <vector>
void genperms(std::vector<int> &res, int n,
std::vector<std::pair<int, int>>::const_iterator b,
std::vector<std::pair<int, int>>::const_iterator e)
{
if (b == e)
{
res.push_back(n);
return;
}
n *= 10;
for (int i=b->first; i <= b->second; ++i)
genperms(res, n+i, b+1, e);
}
std::vector<int> genperms(const std::vector<std::pair<int, int>> &pairs)
{
std::vector<int> res;
if (!pairs.empty())
genperms(res, 0, pairs.begin(), pairs.end());
return res;
}
int main()
{
auto res=genperms({{2,6}, {4, 5}, {1, 5}});
for (auto n:res)
std::cout << n << std::endl;
return 0;
}
Resulting output (truncated for brevity):
241
242
243
244
245
251
252
(snippola)
652
653
654
655
|
71,596,406 | 71,596,612 | Swap the value of two pointers atomically | I've learnt that semaphore can act as an atomic lock that can perform two function: down and up.
Is there any way, to swap the value of two pointers atomically, avoiding race condition and deadlock.
I first came up with the 'solution', suppose both pointers has :
Item a = { value = "A", lock = Semaphore(1) }
Item b = { value = "B", lock = Semaphore(1) }
void atomic_swap(Item* a, Item* b) {
a->lock.down(); // acquire
b->lock.down(); // acquire
non_atomic_swap(&a.value, &b.value);
b->lock.up(); // release
a->lock.up(); // release
}
But if I am not wrong, it will result to deadlock if two atomic_swap is called using same pointers: eg.
Item a = ...;
Item b = ...;
thread_start(atomic_swap, {&a, &b}); // start a thread running atomic_swap(&a, &b);
thread_start(atomic_swap, {&b, &a}); // start a thread running atomic_swap(&b, &a);
On the code above, if both call to atomic_swap arrive the first down simultaneously, the next down will block forever, which results to deadlock.
One of the solution I can think about to avoid deadlock is assign a 'group' to them, only item in the same group can perform atomic_swap safely (without deadlock):
Group g = { lock = Semaphore(1) };
Item a = { value = "A", group = g };
Item b = { value = "B", group = g };
void atomic_swap(Item* a, Item* b) {
// assume a->group == b->group
a->group.down() // b->group.down()
non_atomic_swap(&a.value, &b.value);
a->group.up(); // b->group.up();
}
But this of course require every item to carry a group, and unrelated items might wait for the group because of other calls.
Is there any good way to perform the atomic_swap theoretically using semaphore?
| You can use std::less to compare the pointers to ensure that all users acquire the locks in the same order:
void atomic_swap(Item* a, Item* b) {
std::less<Item *> cmp;
if (cmp(a, b)) {
a->lock.down();
b->lock.down();
} else {
b->lock.down();
a->lock.down(); }
non_atomic_swap(&a->value, &b->value);
b->lock.up(); // release
a->lock.up(); // release
}
|
71,596,899 | 71,602,718 | How do you pass an array by reference from python to a C++ function using CTypes? | As the title says I have been trying for the last 48 hours to pass vectors from a python project to a set of C++ functions I have written. Eventually I came to the conclusion it might be easier using arrays instead of vectors based on some reading around of past posts on here. This led to me trying this tutorial below BUT it was originally only for exemplifying passing in an integer and returning it too. I tried changing the code so it would pass by reference a 3 number long list/array from python, and then add 1 to each of the numbers in it. However, when I run this, I can see it is getting the array no problem and printing the values modified in the c++ function, but it's not modifying the original python variable. In fact what I get "<class 'main.c_double_Array_3'>" back when I try to print output of the wrapper function. Below is the code I've tried so far (in its current state). If anyone could provide some direction regarding a resource for a good clear tutorial on how to do this, OR some help regarding what to do I would greatly appreciate it.
Simple_calculations C++ file
extern "C" void our_function(double * numbers) {
numbers[0] += 1;
numbers[1] += 1;
numbers[2] += 1;
std::cout << numbers[0] << std::endl;
std::cout << numbers[1] << std::endl;
std::cout << numbers[2] << std::endl;
}
Python file
import os
import ctypes
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
os.system('g++ -dynamiclib -shared -o simple_calculations.dylib simple_calculations.cpp -std=c++17')
_sum = ctypes.CDLL('simple_calculations.dylib')
_sum.our_function.argtypes = (ctypes.POINTER(ctypes.c_double),)
def our_function(numbers):
array_type = ctypes.c_double * 3
_sum.our_function(array_type(*numbers))
return array_type
z = our_function([0, 1, 2])
print(z)
Output
1
2
3
<class '__main__.c_double_Array_3'>
| You are returning array_type. That’s a type, not an instance of the type. The instance is your array_type(*numbers) passed to the function, but it is not preserved. Assign it to a variable and return that, or better yet convert it back to a Python list as shown below:
test.cpp
#ifdef _WIN32
# define API __declspec(dllexport)
#else
# define API
#endif
extern "C" API void our_function(double * numbers) {
numbers[0] += 1;
numbers[1] += 1;
numbers[2] += 1;
}
test.py
import ctypes
_sum = ctypes.CDLL('./test')
_sum.our_function.argtypes = ctypes.POINTER(ctypes.c_double),
def our_function(numbers):
array_type = ctypes.c_double * 3 # equiv. to C double[3] type
arr = array_type(*numbers) # equiv. to double arr[3] = {...} instance
_sum.our_function(arr) # pointer to array passed to function and modified
return list(arr) # extract Python floats from ctypes-wrapped array
z = our_function([0, 1, 2])
print(z)
Output:
[1.0, 2.0, 3.0]
|
71,597,537 | 71,598,175 | Why my destructor shows that pointer being freed was not allocated c++ | I want to implement 2 array addition, but when a destructor to the class SList
void operator+(SList list2) {
int totalLen = this->len + list2.len;
char** temp = new char* [totalLen];
for(int i = 0; i < len; i++) {
temp[i] = this->list[i];
}
for(int i = len, j = 0; i < totalLen; i++, j++) {
temp[i] = list2.get(j);
}
delete[] this->list;
this->list = temp;
this->len = totalLen;
cout << len << endl << endl;
}
Here are the get method that just return the dynamic array of char:
char* get(int i) {
if (i >= len) {
return "";
} else {
return list[i];
}
}
here are my class SList private variables:
private:
char** list;
int len;
char* generateString(){
char* str;
int n = rand() % 20 + 1;
str = new char[n + 1];
for(int i = 0; i < n; i++) {
str[i] = 'a' + rand()%26;
}
str[n] = '\0';
return str;
};
~SList() {
delete[] list;
}
It always shows malloc error on the destructor.
malloc: *** error for object 0x105007410: pointer being freed was not allocated
malloc: *** set a breakpoint in malloc_error_break to debug
Please help! I have carefully checked my delete method on the dynamic allocated array, but it always shows this error.
I have tried to check other delete from the other function, but none of them make the same malloc error. I have tried to commented the destructor method and everything work fine. But i really need to have destructor method here. I hope someone with more expertise on c++ can help me fix this malloc error and gave an explanation on which part i made a mistake.
| Regardless what are other details of implementation, the destructor is not correct while you're using a data structure known as a "ragged array", i.e. list is a pointer to an array of pointers. delete[] would free the pointer array, but not char arrays pointed by its elements. You have to do something like this:
~SList() {
if(!list) return; // if we cannot guarantee that list isn't
// nullptr we have to check it,
// or result of list[i] would be undefined.
for(int i = 0; i < len; i++)
delete[] list[i];
delete[] list;
}
and you have to make sure that any of those pointers is either initialized by new expression or is equal nullptr.. It doesn't happen on its own. You have to make sure during construction and all operations. You didn't show any. Look for faults there.
The method get() is a disaster waiting to happen and is ill-formed, i.e. it doesn't follow C++ rules. The string literal "" returns const char*, always the same one and the statement return ""; is incorrect - some compilers only warn about it though. It cannot be deallocated by delete.
char* get(int i) {
if (i >= len) {
return nullptr; // "" - is not safe
} else {
return list[i];
}
}
Deleting a nullptr is a safe no-op. Deleting something that was't returned by new is a disaster.
The addition operator is taking list2 by value, which means that proper copy operations have to be implemented. You didn't show them either. Default implementation would just copy a pointer and destruction of local copy would deallocate memory used by original via ~SList() above. The operator have to return resulting object and should not modify one pointed by this. You had implemented an operator+=. The way you did it, it would work as
a+b; // a now contains result of concatenation.
It's simply weird to use. Proper operator would be
SList operator+(SList& list2);
In general, an object that deals with ownership of some resource, dynamic memory in our case, have to implement certain set of special member functions:
~SList();
SList(const SList& other);
SList(SList&& other); // move copy, source is a temporal.
SList& operator=(const SList& other);
SList& operator=(SList&& other); // move assignment
If that is done right, you can safely do the c = a + b; assignment.
Note that if you pass argument by reference you have to take in account that arguments of assigning operators aren't referencing the object pointed by this and act accordingly if they are. Otherwise you would destroy it and loose original data. On other hand copying argument is excessive and user-unfriendly due to increased cost and memory footprint. Concatenation of n-element and m-element array is expected to have memory footprint of n+m elements , not n+2*m.
|
71,598,474 | 71,599,608 | C++ how to declare an array of priority_queue with customed comparator | With the idea from:
declaring a priority_queue in c++ with a custom comparator ,
I tried to use lambda as comparator for the priority_queue, but when I tried to declare an array of it, error comes.
codes:
`
class Klass{public:int raw_hash;int name;};
bool PriorByRaw(Klass a, Klass b){return a.raw_hash > b.raw_hash;}
auto prior = [](Klass a, Klass b){return PriorByRaw(a, b);};
//here comes the error before "[10]": expected a ';'
priority_queue<Klass, vector<Klass>, decltype(prior)> pq(prior)[10];
`
The question is how can I declared an array of priority_queue in this manner? Or is there any other solution?
As one day I may need a priority que which use other functions as comparator (say "PriorByName"), overriding the less function for the "Klass" looks not good.
I've tried but didn't work:
priority_queue<Klass, vector<Klass>, decltype(prior)> pq(prior)[10];
priority_queue<Klass, vector<Klass>, decltype(prior)> (pq(prior))[10];
| You can do the following to achieve what you want:
bool PriorByRaw(Klass const & a, Klass const & b) { return a.raw_hash > b.raw_hash; }
class KlassCompare
{
public:
bool operator() (Klass const & a, Klass const & b) const
{
return PriorByRaw(a, b);
}
};
priority_queue<Klass, vector<Klass>, KlassCompare> pq[10];
Several comments:
I replaced passing the Klass objects by const& instead of by value, since this is more efficient. Is there any reason you passed it by value ?
The main issue is to replace the lambda with a comparator class with operator(). Using the lambda and decltype(prior) requires the compiler to construct a new instance of a lambda which is not allowed.
MSVC gives the following error for using the lambda:
"error C3497: you cannot construct an instance of a lambda"
You can look C3497 up if you'd like to get more info.
|
71,598,718 | 71,598,883 | Timer with std::thread | I'm working on a timer class to perform operations on a different thread, sample code below is a copy from another SO question HERE
#include <thread>
#include <chrono>
#include <functional>
class Timer
{
public:
~Timer();
Timer() noexcept;
typedef std::chrono::milliseconds Interval;
typedef std::function<void(void)> Timeout;
public:
void start(const Interval& interval, const Timeout& timeout);
void stop();
private:
std::thread mThread; /** Timer thread */
bool mRunning = false; /** Timer status */
};
Implementation with a comment where the problem will occur:
Timer::~Timer()
{
}
Timer::Timer() noexcept
{
}
void Timer::start(const Interval& interval, const Timeout& timeout)
{
mRunning = true;
mThread = std::thread([&]()
{
while (mRunning == true)
{
std::this_thread::sleep_for(interval);
// std::abort will be called here
timeout();
}
});
}
void Timer::stop()
{
mRunning = false;
mThread.join();
}
Sample to test the timer:
#include <iostream>
int main()
{
Timer tm;
tm.start(std::chrono::milliseconds(1000), []
{
std::cout << "Hello!" << std::endl;
});
std::this_thread::sleep_for(std::chrono::seconds(4));
tm.stop();
}
I'm not able to understand why std::abort is called while executing the std::function within lambda and how do I resolve this?
| Arguments to your start function are passed by reference. In your lambda, you capture them by reference. By the time you come around calling that lambda, everything you've captured is destroyed, thus you're causing undefined behavior.
Additionally, make sure to either use atomic<bool> instead of a regular bool:
#include <thread>
#include <chrono>
#include <functional>
#include <cstdio>
#include <atomic>
class Timer {
public:
~Timer() {
if (mRunning) {
stop();
}
}
typedef std::chrono::milliseconds Interval;
typedef std::function<void(void)> Timeout;
void start(const Interval &interval, const Timeout &timeout) {
mRunning = true;
mThread = std::thread([this, interval, timeout] {
while (mRunning) {
std::this_thread::sleep_for(interval);
timeout();
}
});
}
void stop() {
mRunning = false;
mThread.join();
}
private:
std::thread mThread{};
std::atomic_bool mRunning{};
};
int main() {
Timer tm;
tm.start(std::chrono::milliseconds(1000), [] {
std::puts("Hello!");
});
std::this_thread::sleep_for(std::chrono::seconds(4));
}
P.S. you might want to look into coroutines depending on where this idea is going.
|
71,598,964 | 71,599,499 | Given that I have a list of vector <1, 2, 3, 4>, can next_permutation in algorithm library help me arrange 4P2 arrangement? In C++ | can next_permutation avoid the duplication as what I want is to skip 2th and 4th as only change in first 2 character is important to me.
do {
//Do something
} while(next_permutation(s.begin(), s.end()));
this will get 4! = 24 solution, while I only wanted 4P2 = 12 solution.
The above coding will give me.
1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 2 3
1 4 3 2
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 1 3
2 4 3 1
3 1 2 4
3 1 4 2
3 2 1 4
3 2 4 1
3 4 1 2
3 4 2 1
4 1 2 3
4 1 3 2
4 2 1 3
4 2 3 1
4 3 1 2
4 3 2 1
While actually I only want
1 2
1 3
1 4
2 1
2 3
2 4
3 1
3 2
3 4
4 1
4 2
4 3
| do {
// Do something with the first two entries of `s`.
std::prev_permutation(s.begin()+2, s.end());
} while(std::next_permutation(s.begin(), s.end()));
This will essentially skip all permutations of the last two items, so it won't iterate all permutations unnecessarily and be relatively efficient even if you change the length of the vector or the number of items you are interested in (the magic number 2 in the code above).
|
71,599,952 | 71,600,195 | explicit template specialization with no explicit specialization declaration | I have small example code:
file foo.h:
#pragma once
template <typename T> class FooNoDef {
public:
void foo(const T& value); // declared and not defined
};
class FooUser {
public:
template <typename T> static void useFoo(const T& value) {
FooNoDef<T>{}.foo(value);
}
};
file xy.h:
#pragma once
struct X {};
struct Y {};
file xy.cpp:
#include "foo.h"
#include "xy.h"
#include <iostream>
template <> void FooNoDef<X>::foo(const X& value) {
std::cout << "x" << std::endl;
}
template <> void FooNoDef<Y>::foo(const Y& value) {
std::cout << "y" << std::endl;
}
and finally main.cpp:
#include "foo.h"
#include "xy.h"
int main() {
FooUser::useFoo(X{});
FooUser::useFoo(Y{});
return 0;
}
This code compiles with gcc 11 and clang 13. I suspect my code is ill-formed, but I can't find a definite answer from reading the standard:
Section 13.9.4 [temp.expl.spec] (emphasis mine):
If a template, a member template or a member of a class template is
explicitly specialized, a declaration of that specialization shall be
reachable from every use of that specialization that would cause an
implicit instantiation to take place, in every translation unit in
which such a use occurs; no diagnostic is required. If the program
does not provide a definition for an explicit specialization and
either the specialization is used in a way that would cause an
implicit instantiation to take place or the member is a virtual member
function, the program is ill-formed, no diagnostic required. An
implicit instantiation is never generated for an explicit
specialization that is declared but not defined.
Section 13.9.2 [temp.inst] (emphasis mine):
[Example 5:
template<class T> struct Z {
void f();
void g();
};
void h() {
Z<int> a; // instantiation of class Z<int> required
Z<char>* p; // instantiation of class Z<char> not required
Z<double>* q; // instantiation of class Z<double> not required
a.f(); // instantiation of Z<int>::f() required
p->g(); // instantiation of class Z<char> required, and
// instantiation of Z<char>::g() required
}
Nothing in this example requires class Z, Z::g(), or Z::f() to be implicitly instantiated.** — end example]
I think FooUser::useFoo() does not cause implicit instantiation of FooNoDef::foo() as the example from the standard discussed, but still I never provided a declaration for my explicit specialization of FooNoDef<X> and FooNoDef<Y>. Which rule of C++, if any, do I violate with my example? Would I have to provide explicit specialization declaration template <> void FooNoDef<X>; and template <> void FooNoDef<Y>; strictly before the body of FooUser::useFoo()?
| As far as I can see, you are right, though you've put emphasise on the wrong line of the standard:
[...] a declaration of that specialization shall be reachable from every use of that specialization [...]
Within main, both of FooUser::useFoo<X> and FooUser::useFoo<Y> need to be instantiated. These then need to instantiate FooNoDef<X>::foo and FooNoDef<Y>::foo – and here an implicit instantiation would be caused, if no explicit instantiation was available.
However, there only exists a definition within xy.cpp, and that's not visible to main.cpp, and there's no visible declaration – violating above cited phrase, thus your programme indeed is ill-formed.
To fix, you'd need to add a declaration, e.g. in xy.h (note: the header that is included by main.cpp):
template <> void FooNoDef<X>::foo(X const& value);
template <> void FooNoDef<Y>::foo(Y const& value);
|
71,600,037 | 71,600,261 | error: no match for 'operator>>' (operand types are 'std::istream' {aka 'std::basic_istream<char>'} and 'Oper') | Task is to load complex number from a file. When code was written without classes, using stuctures and specified functions only it didn't show that error. Functions (>> overlading) were completely the same.
Class
#ifndef WYRAZENIE_ZESPOLONE_HH
#define WYRAZENIE_ZESPOLONE_HH
#include "liczbaZespolona.hh"
enum Oper {op_plus, op_minus, op_razy, op_dziel};
class WyrazenieZespolone {
private:
LiczbaZespolona lz1;
LiczbaZespolona lz2;
Oper op;
public:
WyrazenieZespolone() = default;
WyrazenieZespolone(const LiczbaZespolona, const LiczbaZespolona, Oper);
LiczbaZespolona oblicz() const;
friend std::ostream& operator << (std::ostream&, const WyrazenieZespolone&);
friend std::istream& operator >> (std::istream&, WyrazenieZespolone&);
friend std::istream& operator >> (std::istream&, Oper&);
};
#endif
Operators overloading implementation
std::istream& operator >> (std::istream& strm, WyrazenieZespolone& wz){
strm >> wz.lz1 >> wz.op >> wz.lz2;
return strm;
}
std::istream& operator >> (std::istream& strm, Oper& t_op){
char znak;
strm >> znak;
switch(znak){
case '+': {t_op = op_plus; break;}
case '-': {t_op = op_minus; break;}
case '*': {t_op = op_razy; break;}
case '/': {t_op = op_dziel; break;}
default : {strm.setstate(std::ios::failbit);}
}
return strm;
}
I'm getting such error during compilation, even though vs code doesn't show any mistakes
error: no match for 'operator>>' (operand types are 'std::istream' {aka 'std::basic_istream<char>'} and 'Oper')
strm >> wz.lz1 >> wz.op >> wz.lz2;
~~~~~~~~~~~~~~~^~~~~~~~
| The problem is that at the point when you wrote:
strm >> wz.lz1 >> wz.op >> wz.lz2;
compiler do not have the definition of the overloaded std::istream& operator >> (std::istream& strm, Oper& t_op) since it is defined afterwards.
So to solve this just move the definition of std::istream& operator >> (std::istream& strm, Oper& t_op) before the definition of std::istream& operator >> (std::istream& strm, WyrazenieZespolone& wz) as shown below. That is for strm >>wz.op to work, define the corresponding overloaded operator>> before its use.
Similarly, for strm >> wz.lz1 to work, define the corresponding overloaded operator>> before its use. This is shown in the below snippet Working demo.
//this comes first so that it can be used in strm >>wz.op
std::istream& operator >> (std::istream& strm, Oper& t_op){
char znak;
strm >> znak;
switch(znak){
case '+': {t_op = op_plus; break;}
case '-': {t_op = op_minus; break;}
case '*': {t_op = op_razy; break;}
case '/': {t_op = op_dziel; break;}
default : {strm.setstate(std::ios::failbit);}
}
return strm;
}
//similarly this comes before so that it can be used in strm >> wz.lz1
std::istream& operator>>(std::istream& strm, LiczbaZespolona&)
{
//do something here
return strm;
}
std::istream& operator >> (std::istream& strm, WyrazenieZespolone& wz){
strm >> wz.lz1 >> wz.op >> wz.lz2;
return strm;
}
Demo
|
71,600,474 | 71,600,996 | Difference between __builtin_addcll and _addcarry_u64 | Good morning (or good evening),
I was reading some legacy code in my company and I found the following intrinsic was used:
_addcarry_u64
However, I have to port this code on a platform that does not support it.
After some research, I stumbled upon a Clang builtin that seemed to do the exact same job:
__builtin_addcll
It has the same arguments (not in the same order but still), however, since there is little to no documentation about it even on Clang website, I have no clue if they truly are the same or not, especially since return types or argument order is not the same.
I tried to use a macro to remap already used arguments however it did not work (I know it's dirty).
#define _addcarry_u64(carryIn, src1, src2, carryOut) __builtin_addcll(src1, src2, carryIn, carryOut)
I feel I will have to wrap it in a function for it to work correctly (still I'm not sure it would work)
Can anyone point me to a documentation or to anything that could solve my problem?
|
_addcarry_u64 is the official intrinsic name from Intel for all Intel platforms
__builtin_addcll is the intrinsic from Clang for all platforms supported by Clang
The __builtin_uaddll_overflow family is the equivalent in GCC for all platforms supported by GCC
The signature for Clang is
unsigned long long __builtin_addcll(unsigned long long x,
unsigned long long y,
unsigned long long carryin,
unsigned long long *carryout);
and the Intel version is
unsigned char _addcarry_u64 (unsigned char c_in,
unsigned __int64 a,
unsigned __int64 b,
unsigned __int64 * out)
So your macro is incorrect. _addcarry_u64 adds 2 number and returns the carry, and the sum is returned via a pointer as stated by Intel
Add unsigned 64-bit integers a and b with unsigned 8-bit carry-in c_in (carry flag), and store the unsigned 64-bit result in out, and the carry-out in dst (carry or overflow flag).
__builtin_addcll OTOH returns the sum directly and the carry out is returned via a pointer as you can see right from your Clang documentation link
Clang provides a set of builtins which expose multiprecision arithmetic in a manner amenable to C. They all have the following form:
unsigned x = ..., y = ..., carryin = ..., carryout;
unsigned sum = __builtin_addc(x, y, carryin, &carryout);
So the equivalent to
int carryOut = _addcarry_u64(carryIn, x, y, &sum);
in Clang is
auto sum = __builtin_addcll(x, y, carryIn, &carryOut);
|
71,600,538 | 71,602,522 | What is the difference between captures and parameters in a C++ laambda expression? | https://en.cppreference.com/w/cpp/algorithm/sort
std::array<int, 10> s = {5, 7, 4, 2, 8, 6, 1, 9, 0, 3};
auto print = [&s](std::string_view const rem) {
for (auto a : s) {
std::cout << a << ' ';
}
std::cout << ": " << rem << '\n';
};
std::sort(s.begin(), s.end());
print("sorted with the default operator<");
For example, in this code, why is the capture "s" and the parameter "sorted with the default operator<"?
Why is the capture "sorted with the default operator<" and not the parameter "s"?
| The captured values stay with the lambda object while the function arguments exist only for the call. As with any function you can call the lambda function several times, each with a different argument list to its parameter list. The lambda object, however, is constructed exactly once, at which point the captures are bound to the internal members of the lambda.
If you throw your code into https://cppinsights.io, you get an idea of what the compiler does with your lambda function:
std::array<int, 10> s = {{5, 7, 4, 2, 8, 6, 1, 9, 0, 3}};
class __lambda_7_18
{
public:
inline /*constexpr */ void operator()(const std::basic_string_view<char, std::char_traits<char> > rem) const
{
{
std::array<int, 10> & __range1 = s;
int * __begin1 = __range1.begin();
int * __end1 = __range1.end();
for(; __begin1 != __end1; ++__begin1) {
int a = *__begin1;
std::operator<<(std::cout.operator<<(a), ' ');
}
}
std::operator<<(std::operator<<(std::operator<<(std::cout, ": "), std::basic_string_view<char, std::char_traits<char> >(rem)), '\n');
}
private:
std::array<int, 10> & s;
public:
__lambda_7_18(std::array<int, 10> & _s)
: s{_s}
{}
};
__lambda_7_18 print = __lambda_7_18{s};
print.operator()(std::basic_string_view<char, std::char_traits<char> >("sorted with the default operator<"));
As you can see, your print lambda is an object that holds a reference to the captured array: s. When you call it, its operator() member function is invoked with the arguments you pass to it, here an std::string_view with the value "sorted with the default operator<". You'd be free to call it again with a different value.
|
71,600,573 | 71,600,911 | how to return multi values from function in Armadillo? | I'm new to c++ and Armadillo. I've written a function as follows:
mat solver(mat charge)
{
mat x = regspace(0, mesh_num - 1);
mat xx = reshape(x, 1, mesh_num);
mat xxx = repmat(xx, mesh_num, 1);
mat y = regspace(0, mesh_num - 1);
mat yy = reshape(y, mesh_num, 1);
mat yyy = repmat(yy, 1, mesh_num);
mat green_func = -0.5 * log(square(step_xc * xxx) + square(step_yc * yyy));
green_func(0, 0) = 0;
mat temp_1 = fliplr(green_func);
mat temp_2 = temp_1.cols(0, mesh_num - 2);
mat temp_3 = flipud(green_func);
mat temp_4 = temp_3.rows(0, mesh_num - 2);
mat temp_5 = fliplr(temp_4);
mat temp_6 = temp_5.cols(0, mesh_num - 2);
mat temp_7 = join_horiz(temp_6, temp_4);
mat temp_8 = join_horiz(temp_2, green_func);
mat green_fun_expand = join_vert(temp_7, temp_8);
return green_fun_expand;
}
I'd like to return more-than-one matrix, e.g. green_func_expand and temp_8. How to achieve this?
| use a Tuple STL
tuple <mat, mat> solver(mat charge)
{
mat x = regspace(0, mesh_num - 1);
mat xx = reshape(x, 1, mesh_num);
mat xxx = repmat(xx, mesh_num, 1);
mat y = regspace(0, mesh_num - 1);
mat yy = reshape(y, mesh_num, 1);
mat yyy = repmat(yy, 1, mesh_num);
mat green_func = -0.5 * log(square(step_xc * xxx) + square(step_yc * yyy));
green_func(0, 0) = 0;
mat temp_1 = fliplr(green_func);
mat temp_2 = temp_1.cols(0, mesh_num - 2);
mat temp_3 = flipud(green_func);
mat temp_4 = temp_3.rows(0, mesh_num - 2);
mat temp_5 = fliplr(temp_4);
mat temp_6 = temp_5.cols(0, mesh_num - 2);
mat temp_7 = join_horiz(temp_6, temp_4);
mat temp_8 = join_horiz(temp_2, green_func);
mat green_fun_expand = join_vert(temp_7, temp_8);
return make_tuple( green_fun_expand,temp_8 ) ;
}
while recieving this , try
mat ret1, ret2;
tie(ret1, ret2) = solver(mat, change);
then you can directly use ret1 and ret2
Alternatively , you can use a class and add whatever you want to return as class variables, create object of class inside your function, populate the variables and return the object
|
71,600,589 | 71,603,132 | How can I create a priority queue of pairs that's sorted by the first element and then by the second? | I created a lambda comp according to what I use in vectors, but it doesn't work, I would like to know why it doesn't work and how to do it properly.
CODE:
auto cmp=[](const std::pair<int,int>& a,const std::pair<int,int>& b){
return (b.first>a.first)||(b.second>a.second);
};
std::priority_queue<std::pair<int,int>,std::vector<std::pair<int,int>>,decltype(cmp)> q(cmp);
| As you mentioned in the comments: std::greater<std::pair<int, int>> works just fine, and yours not working because the comparison equation isn't 'strict enough' - right.
Lets take two pairs p1 = (3,5) and p2 = (4,2), if we comapre p1 and p2 according to your function, it will output cmp(p1, p2) = true because of b.first > a.first // 4 > 3.
Also, if we compare p2 and p1 the same way(the only difference is the order of p1 and p2), it will output cmp(p2, p1) = true because of b.second > a.second // 5 > 2.
Not saying anything, when a == b, if we compare some pair to itself it will be false.
So the compiler has to have problems while comparing the same pairs one more time, but this time with the reverse order.
Since the question doesn't contain many details about how you use the queue, the problem has to be this. That's why greater working and not this one.
If you want to make work yours, you should try a more specific and strict equation, try to use the && operator instead of || and consider the equal variant too.
Hope it helps, I had similar problems a few years ago, while I was trying to sort vector of pairs by my way.
|
71,600,685 | 71,601,038 | Cannot define aclass property array from brace-encasing initialiser in C++ | This does not compile, I am obliged to set 3 within the [].
Is there a way to let the compiler computes the exact length of the array based on literals?
class Foo {
const uint8_t commands[] = {
0x90,
0x91,
0x92,
};
}
| compiler can deduce and know command's size. you don't need to pass command's size.
from c++11 you can use constexpr with static to declare const inside a class
class Foo {
constexpr static int commands[] = {
0x90,
0x91,
0x92,
};
};
https://godbolt.org/z/cnh4o37Pq
|
71,600,972 | 71,601,738 | When multiple a relative big floating point value with two relative small floating point value, what's the best order of arithmetic to eliminate error | The question description itself is pretty simple, let's say i have two variable, the big and scale, all i want to do is calculating:
float res = big * scale * scale;
As you can see, there exists two arithmetic order:
// #1
float res = (big * scale) * scale;
// #2
float res = big * (scale * scale);
Due to the fact of IEEE754 single precision standard, it is natural that the above two line will give different result.
Now i have some priori knowledge that big might vary from 0 to ~1000, scale might vary from 0 to 2^-10. The big is not that "big" that might "eat the small". And the scale is not that "small" to cause underflow when multiply themselves. That leaves my question is, which arithmetic order should i adopt to get a "smaller error", compared with the "real" value?
| Order makes a possible small difference
Since the concern is precision and not range:
Consider the number of non-zero significant bits in big and scale. Each as floats may have up to 24 significant binary digits.
The idea is to perform the 2 multiplications and avoid 2 rounding. If possible, do multiplication exactly first. If big has fewer non-zero significant binary digits, then do big * scale first, else scale * scale.
As OP question hints that scale may be a power-of-2, then since that have only 1 significant binary digit, and if that holds for OP's code, then the order is irrelevant.
The exponent is irrelevant given OP's "scale is not that "small" to cause underflow when multiply themselves"
Since these are float, check FLT_EVAL_METHOD as the issue may be moot as intermediate calculations may occur with wider math.
|
71,601,152 | 71,602,599 | QByteArray to short Int array in QT C++ | I am receiving a QByteArray from UDP Socket. The QByteArray is of 52 elements each containing values from 0 to 9 - A to F. Now, I want to convert this QByteArray into a short int array of 13 elements such that first 4 elements of the QByteArray are stored in first element of short int array.
Eg. QByteArray = (002400AB12CD) -> ShortINT = [0024,00AB,12CD]
I have tried concatenating 4 elements and then convert them to Short INT.
| You can use QByteArray::data() and QByteArray::constData() to access pointer to stored data and use c cast or reinterp_cast to cast specific type. Also you need to know endianness of data is it big-endian or little endian.
#include <QByteArray>
#include <QDebug>
#include <QtEndian>
void test() {
QByteArray data("\x00\x24\x00\xAB\x12\xCD", 6);
qint16_be* p = (qint16_be*) data.data();
int l = data.size() / sizeof(qint16_be);
for (int i=0; i<l; i++) {
qDebug() << i << hex << p[i];
}
}
Qt 4 does not have _be types. You can use qFromBigEndian or qbswap to swap bytes.
#include <QByteArray>
#include <QDebug>
#include <QtEndian>
void test() {
QByteArray data("\x00\x24\x00\xAB\x12\xCD", 6);
qint16* p = (qint16*) data.data();
int l = data.size() / sizeof(qint16);
for (int i=0; i<l; i++) {
qDebug() << i << hex << qFromBigEndian(p[i]);
}
}
|
71,601,234 | 71,602,346 | warning: 'void operator delete(void*, std::size_t)' called on unallocated object | I am just playing with the placement-new operator. below code compiles and runs without any error on gcc version 11.2.But I am getting one warning as,
warning: 'void operator delete(void*, std::size_t)' called on unallocated object 'buf' [-Wfree-nonheap-object]x86-64 gcc 11.2 #1
Please see the code which I tried,
#include<iostream>
class sample
{
public:
sample()
{
std::cout<<"entered constructor"<<std::endl;
}
~sample()
{
std::cout<<"entered destructor"<<std::endl;
}
};
int main()
{
unsigned char buf[4];
sample* k = new(buf) sample;
delete k;
return 0;
}
Output as follows(I am using compiler explorer for the same)
Program returned: 139
Program stdout
entered constructor
entered destructor
Program stderr
free(): invalid pointer
| Using delete on anything other than pointer returned by an allocating new expression results in undefined beheaviour.
Placement-new doesn't allocate anything. You may not delete a pointer returned by placement new. In order to destroy an object created using placement new, you must call the destructor explicitly, or you can use std::destroy_at:
sample* k = new(buf) sample;
std::destroy_at(k);
// or
// k->~sample();
|
71,601,575 | 71,602,292 | which part of code is creating Segmentation Fault in hackerrank? | I am trying to solve this problem in hackerrank.
https://www.hackerrank.com/challenges/circular-array-rotation/problem
Every other test is fine but one test is creating Segmentation Fault. This is the test case:
https://hr-testcases-us-east-1.s3.amazonaws.com/1884/input04.txt?AWSAccessKeyId=AKIAR6O7GJNX5DNFO3PV&Expires=1648127766&Signature=a0c1UvQ4t9DBn%2Fkr02ZnLUurhjk%3D&response-content-type=text%2Fplain
I wish to what part of my code is creating Segmentation Fault and I want to know the way to solve it with code and some explanation well as I believe my code should not have created any. Here is my code:
vector<int> circularArrayRotation(vector<int> a, int k, vector<int> queries) {
rotate(a.begin(),a.begin()+a.size()-k,a.end());
vector<int> result;
cout<<result.size()<<endl;
for(auto x:queries) result.push_back(a[x]);
return result;
}
This is the code I am submitting in the hackerrank solution. Please help me to pass the test.
| The problem is:
rotate(a.begin(),a.begin()+a.size()-k,a.end());
According to the problem statement, the constraints are:
1 <= n <= 10^5
1 <= k <= 10^5
There is no constraint that k <= n, and the test case you got there is exactly the hit, n = 515, k = 100000.
So the problem is:
a.begin()+a.size()-k // a.size()-k, when k > n, is negative
So the hackerrank compiler has a problem while it's doing a.begin() - negative num.
For fixing that you should make sure it won't go in negative bounds, and since it's a circular rotation one full rotation or 1000 full rotations won't change anything, only the remainder matters:
rotate(a.begin(), a.begin() + a.size() - (k % a.size()), a.end());
It passes all the test cases.
|
71,601,920 | 71,613,635 | In boost::multi_index, will modifying a field, which is a key in another index, cause that index to reshuffle? | The situation is as follows:
I'm having a bmi, indexed by hashed_unique over a name field of the struct and ordered_non_unique, over the status field of the same struct. The question is: if I invoke modify() on the hashed_unique index and modify a status field with it, will this cause a rebalance on the ordered_non_unique index? Or should I explicitly use modify() on the ordered_non_unique index while altering status in order to keep it updated?
| modify will cause all indices to reorder as necessary regardless of which index it is called on.
|
71,602,135 | 71,602,375 | Are class arguments stored after function execution? | I am brand new to C++ and trying to better how understand memory is allocated and stored in class methods.
Lets say I have the following code:
#include <iostream>
using namespace std;
class ExampleClass {
public:
void SetStoredAttribute(int Argument);
int GetStoredAttribute(void);
private:
int StoredAttribute;
};
void ExampleClass::SetStoredAttribute(int Argument) {
StoredAttribute = Argument;
};
int ExampleClass::GetStoredAttribute(void) {
return StoredAttribute;
};
int main() {
ExampleClass Object;
Object.SetStoredAttribute(1);
cout << Object.GetStoredAttribute();
return 0;
};
What does C++ do with the argument once my SetStoredAttribute method is finished? Does it free that memory or do I need to do this manually?
| Function arguments, including those in member functions, always have automatic storage duration. They start to exist at the beginning of the function scope, and cease to exist at the end of the function scope, and the implementation deals with ensuring they are "allocated" and "deallocated".
On most platforms, this is implemented in two ways.
Firstly by a stack, often called The Stack, because it is unique to the thread of execution, with a special purpose register in the CPU pointing to the top.
Secondly, the arguments are directly assigned to registers in the CPU.
|
71,602,590 | 71,603,436 | TCP need to discard info on the buffer or make it faster | I am making a 3d application that works with the data of the accelerometer and gyroscope of the mobile. The problem is that the mobile sends data faster than the computer reads. The application increasingly makes the movements of the mobile with more delay as time passes. For example, at the beginning 2~3s is faithful to what the mobile does in reality, but over 10s it is making the movements that I did 6 seconds before.
I understand that it is reading data from the beginning buffer while the front of the most current data grows and never reaches it. I think the problem is how I read the data that comes to me.
Here is an example code that is implemented in the application. What could I do?
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#include <fcntl.h>
#include <algorithm>
#define PORT 8080
int main(int argc, char const *argv[])
{
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};
const char *ACK = "ACKDAT\n";
std::string data;
socklen_t len;
char *error;
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,&opt, sizeof(opt)))
{
perror("setsockopt");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address))<0)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 3) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
}
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0)
{
perror("accept");
exit(EXIT_FAILURE);
}
fcntl(new_socket, F_SETFL, O_NONBLOCK);
while(true){
valread = read( new_socket , buffer, 1024);
for(int i = 0;i < 1024 ; i++){
if(buffer[i]!=0){
data = data + buffer[i];
}
buffer[i]=0;
}
if(!data.empty()){
//remove /n from data
data.erase(std::remove(data.begin(), data.end(), '\n'), data.end());
std::cout<<"#"<<data<<"#"<<std::endl;
send(new_socket , ACK , strlen(ACK) , 0 );
}
data.clear();
}
return 0;
}
| While Sam Varshavchik's suggestion of using a thread is good, there's another option.
You already set your socket to non-blocking with fcntl(new_socket, F_SETFL, O_NONBLOCK);. So, at each loop you should read everything there is to read and send everything there is to send. If you don't tie one-to-one the reading and writing, both sides will be able to catch up.
The main hint that you need to fix this is that you don't use the read return value, valread. Your code should look like:
while(true){ // main loop
...
valread = read( new_socket , buffer, 1024);
while(valread > 0)
{
// deal with the read values.
// deal with receiving more than one packet per iteration
}
// send code done a single time per loop.
There still plenty of architecture you need to have a clean resilient main loop that sends and receives, but I hope that points you in a useful direction.
|
71,603,050 | 71,608,899 | How to create/destroy objects in "modern" C++? | I am porting C# app into C++ linux app. I am confused with construction and destruction in "modern" (C++11 ?). I always thought you have to use new/delete but now it appears C++ recommendation is not to do so (is this correct or I read a wrong blog?).
What I have roughly (there are 6 subclasses of B and BRec atm):
class ARec : public BRec
class A : public B
. . .
class Factory
BRec GetRecord(WrapperStruct s)
{
if(s.Type == 'A')
{
A* a = (A*)s.Data;
auto rec = ARec((ushort)a->Num);
rec.OtherField = a.OtherField;
return rec;
}
. . .
main
// separate pthread
void* Logger(void* arg) {
int* thread_state = (int*)arg;
auto f = Factory();
WrapperStruct item;
while (true)
{
q->try_dequeue(item);
auto rec = f.GetRecord(item);
auto bytes = f.GetBytes(rec);
// write bytes to file ...
delete bytes;
if(*thread_state == -1)
pthread_exit(0);
}
Question - how does compiler would know when to delete s.Data in factory method? Same - rec if it was created in a class method and then crossed to other method (while in Logger)? Is there a simple guide how to manage variables' memory in C++11 ?
EDIT: s.Data contains ref to an object created in a 3rd party dll and can be of different types hence the s.Type field
| Smart pointers are the key.
std::shared_ptr<Foo> foo = std::make_shared<Foo>();
std::unique_ptr<Foo> bar = std::make_unique<Foo>();
Shared pointers can be copied. They do reference counting. When the reference count drops to zero, they'll delete their contents automatically.
Unique pointers can't be copied. They can be copied by reference. When the unique pointer goes out of reference, it frees the object for you.
So it works a lot like Java now.
void notAMemoryLeak() {
std::shared_ptr<Foo> foo = std::make_shared<Foo>();
}
Other than that, you treat them like pointers. The syntax for their use at this point is identical, except you're passing smart pointers, not Foo *.
void myFunct(std::unique_ptr<Foo> &foo) {
cout << "Foo: " << foo->getName() << "\n";
}
The make_shared and make_unique can take the same arguments as any of your Foo's constructors, so feel free to pass stuff.
I do one more thing:
class Foo {
public:
typedef std::shared_ptr<Foo> Pointer;
...
};
Foo::Pointer foo = std::make_shared<Foo>();
Sometimes I also create static methods to make it even cleaner. This is stylistic and not necessary. Some people might fault me. But it's clean and easy to read.
|
71,603,389 | 71,872,132 | CMenu not receiving Windows touch messages | In my application when I receive an ON_WM_RBUTTONDOWN() message in a certain window I create a CMenu, populated with some items, and then displayed with TrackPopupMenu(xxx). It has no other interaction with Windows messages to be created. It defaults to accepting left clicks to select items and I can see these messages coming in when I use the mouse.
I'm trying to allow use of this context menu on a touch screen - the parent window can receive WM_GESTURENOTIFY messages (for other functionality) and in all other aspects of my app, such as other windows and dialogs, it handles touch gestures fine - Spy++ shows gesture messages and a WM_LBUTTONDOWN which gives me normal behaviour across the app. I CAN touch select menu items when this menu is opened with a physical mouse right click, with the touch input coming through as a WM_LBUTTONDOWN.
I've tried creating and displaying this menu by calling that same creation code again from a touch message, or just sending the window an ON_WM_RBUTTONDOWN() message manually after a touch, with the same flags. This is created fine and works as normal with a mouse, and as far as the app is concerned nothing is different. However, the CMenu is not receiving any touch messages at all - I get the touch-style cursor showing where I'm tapping, but nothing is being piped through to the menu.
I've tried changing from gestures to registering touch while this interaction happens and ensuring the original gesture handle is closed in case it was blocking for whatever reason.
My assumption is that Windows is doing something additional behind the scenes beyond what my app is aware of to allow these messages to be sent through, so I'm a bit stuck for a solution.
| I was able to get around this issue by enabling the tablet press-and-hold gesture (it's normally disabled) which serves the purpose of being treated as a right click and having a properly interactable context menu, rather than sending the right click message myself. Works on desktop with a touch screen and a Windows tablet.
https://learn.microsoft.com/en-us/troubleshoot/developer/visualstudio/cpp/language-compilers/mfc-enable-tablet-press-and-hold-gesture
Adding
ULONG CMyView::GetGestureStatus(CPoint /*ptTouch*/) { return 0; } was what enabled this to work.
|
71,603,462 | 71,603,616 | putting function inside a namespace breaks use of std::vector | I have written a function that does the element-wise square root of a std::vector<double>
#include <cmath>
#include <vector>
namespace pcif {
std::vector<double> sqrt(const std::vector<double>& d) {
std::vector<double> r;
r.reserve(d.size());
for (size_t i{ 0 }; i < r.size(); ++i) {
r.push_back(sqrt(d[i]));
}
return r;
}
}
I am getting the error (all pointing to the r.push_back line):
cannot convert from 'const _Ty' to 'const std::vector<double,std::allocator>'
error C2664: 'std::vector<double,std::allocator> pcif::sqrt(const std::vector<double,std::allocator> &)': cannot convert argument 1 from 'const _Ty' to 'const std::vector<double,std::allocator> &'
Constructor for class 'std::vector<double,std::allocator>' is declared 'explicit'
If I remove the namespace, it all compiles with no dramas.
What am I doing wrong? Is there a better way to do this?
I am working in Visual Studio 2019, C++17.
.
Follow-up question:
Using the fully qualified std::sqrt() solves this. Why did it work in my original case with no namespace? I can't just call vector<double>, why can I call sqrt?
| As already mentioned in comments, you should explicitly call ::sqrt() (or from std namespace, std::sqrt()) instead, otherwise you are recursively calling your own sqrt() function with the wrong arguments.
The reason is that in the global namespace, there already exists a matching function called sqrt() (that's why it worked outside of the pcif namespace).
Once you are inside the pcif namespace, there are no other sqrt() overloads defined except the one you are writing, hence the recursion with the wrong arguments (Overloads are looked up in the same scope).
To solve this, you can explicitly call either the function of the global namespace ::sqrt() or the one defined in the std namespace std::sqrt().
Moreover, you should also change your loop condition from i < r.size() to i < d.size() instead, since r is empty.
Keep in mind that reserve(n) does not change the size of the container, it only allocates the necessary space for being able to store at least n elements without the need of reallocations (i.e. only the capacity is changed).
You may be interested to have a look at the documentation.
|
71,603,923 | 71,604,204 | Particle Pool Performance Optimization In C++ | I have a particle pools which stored particle pointers
It has a large number of particles
Every particle has the IsActive variable
When partitioning the vector every frame according to their active state, there is high cpu usage
So instead is it a good way to partition the vector every few seconds on a worker thread?
| Since the order of the active doesn't matter, and they don't become active or inactive very often, you can use a trick to keep the active particles at the front:
Suppose that nActive is the number of active particles.
When an inactive particle becomes active, do std::swap(vector[nParticle], vector[nActive]); nActive++; i.e. make it be the last active particle - and whatever inactive particle was already in that slot, goes to where the particle used to be, and we don't care, because we don't care about the order.
When an active particle becomes inactive, do nActive--; std::swap(vector[nParticle], vector[nActive]); i.e. make it be the first inactive particle - and whatever active particle was already in that slot, goes to where the particle used to be, and we don't care, because we don't care about the order.
You can remember this trick by remembering that it's easy to make a particle active or inactive - if we don't care which one it is - because we just add or subtract 1 from nActive. But then we don't know which particle we just changed. So we swap that particle with the one we meant to change, and we don't care where that particle goes, as long as it stays inactive or stays active (doesn't change).
Like this:
+-----------+-----------+-----------+-----------+
| Particle0 | Particle1 | Particle2 | Particle3 |
| active | active | inactive | inactive |
+-----------+-----------+-----------+-----------+
^
|
nActive==2
make particle 3 active: swap particle 3 and 2, then increment nActive:
+-----------+-----------+-----------+-----------+
| Particle0 | Particle1 | Particle3 | Particle2 |
| active | active | active | inactive |
+-----------+-----------+-----------+-----------+
^
|
nActive==3
make particle 0 inactive: decrement nActive, then swap particle 3 (in slot 2) and 0.
+-----------+-----------+-----------+-----------+
| Particle3 | Particle1 | Particle0 | Particle2 |
| active | active | inactive | inactive |
+-----------+-----------+-----------+-----------+
^
|
nActive==2
The particle order is all jumbled up now, but you don't care about that, right?
|
71,604,607 | 71,604,836 | C++ template type_trait enable_if a class is a map | #include <iostream>
#include <any>
#include <vector>
#include <map>
#include <unordered_map>
#include <string>
using namespace std;
// enable_if_t = MapType implements .find(KeyType key), .begin(), .end(), and .begin()
// and MapType::iterator it has it->first and it->second
template<typename MapType>
decltype(declval<MapType>().begin()->second) MapGetOrDefault(
MapType mymap,
decltype(declval<MapType>().begin()->first) key,
decltype(declval<MapType>().begin()->second) defaultValue = decltype(declval<MapType>().begin()->second){}
)
{
auto it = mymap.find(key);
if (it!=mymap.end()) return it->second;
else return defaultValue;
}
int main()
{
map<string, int> a;
unordered_map<int, string> b;
a["1"] = 2;
cout << MapGetOrDefault(a, "1") << " " << MapGetOrDefault(a, "2") << " " << MapGetOrDefault(a, "2", -1) << "\n";
b[1] = "hello";
cout << MapGetOrDefault(b, 1) << " " << MapGetOrDefault(b, 2) << " " << MapGetOrDefault(b, 3, "world") << "\n";
return 0;
}
I'm trying to make a generic get_or_default() function that can be used with all types of map. There are 4 conditions that a class must meet to be counted as map, like shown in the code comment.
How can I do this using C++ type traits? Also, how to change decltype(declval<MapType>().begin()->first) into something more clean?
Edit: is enable_if_t even needed in this case? My goal is to just prevent compilation
| Maps have member aliases mapped_type and key_type (and value_type) that you can use :
#include <iostream>
#include <any>
#include <vector>
#include <map>
#include <unordered_map>
#include <string>
using namespace std;
template<typename MapType>
typename MapType::mapped_type MapGetOrDefault(
MapType mymap,
typename MapType::key_type key,
typename MapType::mapped_type defaultValue = typename MapType::mapped_type{}
)
{
auto it = mymap.find(key);
if (it!=mymap.end()) return it->second;
else return defaultValue;
}
int main()
{
map<string, int> a;
unordered_map<int, string> b;
a["1"] = 2;
cout << MapGetOrDefault(a, "1") << " " << MapGetOrDefault(a, "2") << " " << MapGetOrDefault(a, "2", -1) << "\n";
b[1] = "hello";
cout << MapGetOrDefault(b, 1) << " " << MapGetOrDefault(b, 2) << " " << MapGetOrDefault(b, 3, "world") << "\n";
return 0;
}
Template aliases can help for more terse syntax:
template <typename T> using mapped_type = typename T::mapped_type;
template <typename T> using key_type = typename T::key_type;
template<typename MapType>
mapped_type<MapType> MapGetOrDefault(
MapType mymap,
key_type<MapType> key,
mapped_type<MapType> defaultValue = mapped_type<MapType>{}
)
{
auto it = mymap.find(key);
if (it!=mymap.end()) return it->second;
else return defaultValue;
}
PS: I didnt change it because it wasn't part of the question, but you should not make a copy of the map when passing it to the function, rather use const MapType& mymap for the argument.
PPS: As mentioned by Caleth in a comment, with a transparent comparator, ie one that has a Comparator::is_transparent member type, you might want to support the overload (4) listed here: https://en.cppreference.com/w/cpp/container/map/find by introducing another template argument KeyType that can be deduced from the key paramter.
|
71,604,883 | 71,606,691 | Code not working trying to do bubble sort in different way | #include <iostream>
using namespace std;
int main() {
int n, arr[n];
cin >> n;
int i, j;
int counter = 1;
for (i = 0; i < n; i++) {
cin >> arr[i]; // taking arr inputs
}
while (counter < n) {
for (i = 0; i < n - counter; i++) {
if (arr[i] > arr[i + 1]) {
j = arr[i]; // swapping numbers
arr[i] = arr[i + 1];
arr[i + 1] = j;
}
}
counter++;
}
}
my code is simply exiting it isnt taking any inputs or giving any outputs or errors.
i just want to do it this way lemme know what are the mistakes dont change the method
I tried changing conter into loop but it didnt work
tryin bubble sort
| We beginners need to hold together.
There are some very minor problems in your code.
Your variable "n" is uninitialized. So it has an indeterminate value. So, something. Then you try to set the size of your array with this "something". And after that, you read the size from the user.
Additionally. VLA (Variable length Arrays), so something like "array[n]", with "n" not being a compile time constant is illegal. It is not part of C++. Some compiler are allowing it as an extension, but it is illegal C++ code. But the good message is: There is a drop in replacement: The std::vector
And last but not least, if you want to see some output, then you need to output something. So, for example with "std::cout << something".
With above changes, your code coul look like:
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n = 0;
cin >> n;
std::vector<int> arr(n);
int i = 0, j = 0;
int counter = 1;
for (i = 0; i < n; i++) {
cin >> arr[i]; // taking arr inputs
}
while (counter < n) {
for (i = 0; i < n - counter; i++) {
if (arr[i] > arr[i + 1]) {
j = arr[i]; // swapping numbers
arr[i] = arr[i + 1];
arr[i + 1] = j;
}
}
counter++;
}
for (int k : arr) std::cout << k << ' ';
}
Still not perfect, but OK for the beginning.
|
71,605,228 | 71,605,977 | Unite elements that share the same value of a variable in a vector of structs | For example, I have this struct :
struct Time
{
char Day[10];
int pay;
int earn;
}
And suppose that the vector of this Time struct has the following elements:
vector<Time> mySelf = ({"Monday", 20, 40}, {"Tuesday", 15, 20}, {"Monday", 30, 10}, {"Tuesday", 10, 5});
So is there any algorithm to unite the data so that elements with the same day name will appear once and the other variables of those elements will combine together to form a new vector like this :
vector<Time> mySelf = ({"Monday", 50, 50}, {"Tuesday", 25, 25});
| You can try to insert your elements to unordered_map, and then reconstruct a vector. Search and insertion to the map have constant-time complexity, so all the operation will be O(n), because we need to iterate over a vector twice.
std::unordered_map<std::string, Time> timeMap;
for (const auto& t : mySelf)
{
if (timeMap.count(t.day) == 0)
{
timeMap[t.day] = t;
}
else
{
timeMap[t.day].pay += t.pay;
timeMap[t.day].earn += t.earn;
}
}
or shorter version, since insert already checks if the element exists and will not overwrite it:
for (const auto& t : mySelf)
{
timeMap.insert({t.day, {t.day,0,0}});
timeMap[t.day].pay += t.pay;
timeMap[t.day].earn += t.earn;
}
and then the vector reconstruction:
std::vector<Time> result;
result.reserve(timeMap.size());
for (const auto&[key, val] : timeMap)
{
result.push_back(val);
}
Alternatively you could use std::unordered_set but then you need some hash function for your struct. Probably you could improve it further with move semantics.
live demo
|
71,605,246 | 71,605,437 | GoogleTest: How to catch a generic exception in EXPECT_THROW? | Hi i want to catch a generic exception in function EXPECT_THROW GoogleTest ,which can catch all the type of exception thrown, irrespective of exception type.
Is their any similar way as we used to catch in try-catch block.
catch (...) {
}
| EXPECT_ANY_THROW is for this purpose.
See Advanced googletest topics.
|
71,605,280 | 71,662,744 | How to import basic functions like len() or help() in C++ with pybind11 | I'm quite new to pybind11 and I was trying to import/borrow simple Python functions like len() or especially help() inside my C++ code.
Note that I don't want to use pybinds.doc() inside C++ since I want to extract names and types of the parameters passed to Python functions.
I'm already familiar with:
auto fnc = py::reinterpret_borrow< py::function >(
py::module::import( "sys" ).attr( "path" ).attr( "append" ) );
But I can't find any definition of how to import functions outside of specific python modules.
| Thanks to @unddoch for mentioning the buitlins module.
Unfortunately help() is using sys.stdout by default. Therefore I switched to using pydoc.render_doc() to catch it as a string.
My working code looks like this:
py::function helpFnc = py::reinterpret_borrow< py::function >(
py::module::import( "pydoc" ).attr("render_doc") );
auto helpResult = helpfunc(pyExecute,"%s",0,py::module::import( "pydoc" ).attr("plaintext"));
std::cout << "Help in C++: " << helpResult.cast<std::string>() << std::endl;
|
71,605,355 | 71,605,553 | Array dimension in C++ | I know that arrays need to be defined with a size that cannot be modified, but in this code, the counter i exceeds the size of the array (because of the 2 in "i<sz+2" in the for loop) but the code don't give any errors, why?
another question: is it correct to use std::cin to assign the value to sz or should I assign the value of sz when I declare the variable?
#include <iostream>
int main() {
int sz;
std::cin >> sz;
int v[sz];
std::cout << "i" << " " << "v[i]" << std::endl;
for(int i=0;i<sz+2;i++){
std::cin >> v[i];
std::cout << i << " " << v[i] << std::endl;
}
return 0;
}
|
the counter i exceeds the size of the array (because of the 2 in "i<sz+2" in the for loop) but the code don't give any errors, why?
Going out of bound of the array(as you're doing) is undefined behavior.
Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior.
So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash.
So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.
Additionally, in Standard C++ the size of an array must be a compile time constant. So when you wrote:
int sz;
std::cin >> sz;
int v[sz]; //NOT STANDARD C++
The statement int v[sz]; is not standard C++ because sz is not a constant expression.
1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.
|
71,605,613 | 71,605,839 | How to find minimum even number from a vector using comparator | Eg: 2,3,4,5,6.
The expected output should be 2.
How can I write comparator func for min_element func to get the smallest even number.
auto mini_even=*min_element(vec.begin(),vec.end(),cmp);
| You can use a comparator that puts all even numbers before odd ones, ie any even number compares less than any odd, while all other comparisons are as usual:
#include <iostream>
#include <algorithm>
#include <vector>
int main()
{
std::vector<int> vec{1,2,3};
auto cmp = [](int a,int b){
if (a%2 == b%2) return a < b;
if (a%2) return false; // a odd b even
return true; // a even b odd
};
auto mini_even=*min_element(vec.begin(),vec.end(),cmp);
std::cout << mini_even;
}
To handle the case of a vector that only contains odd numbers you should check if the result is even or not.
The same effect can be achieved with a more elegant way of defining the comparator, as suggested by Jarod42 in a comment:
const auto projection = [](int n) { return std::make_pair(is_odd(n), n); };
const auto comp = [=](int lhs, int rhs){ return projection (lhs) < projection (rhs); };
std::pairs have an operator< that will, same as the above, place all even numbers (the ones where is_odd is false) before the odd ones.
And if you want to follow common practice to return vec.end() when the desired element cannot be found, you can wrap it in a function:
template <typename IT>
IT min_even(IT first, IT last) {
if (first == last) return last;
auto cmp = .... see above ...
auto it = min_element(first,last,cmp);
if (*it % 2) return last;
return it;
}
Which can be generalized to work for any predicate:
template <typename IT, typename Predicate>
IT min_proj(IT first,IT last,Predicate pred){
if (first == last) return last;
const auto projection = [pred](int n) { return std::make_pair(!pred(n), n); };
const auto cmp = [=](int lhs, int rhs){ return projection (lhs) < projection (rhs); };
auto it = min_element(first,last,cmp);
if (!pred(*it)) return last;
return it;
}
Live Demo
|
71,605,870 | 71,607,098 | Is it possible to deduct the template type of a templated parameter in C++? | I have a template class, with an internal method that is itself templated.
Consider the following minimal working example
#include <functional>
template<typename T>
class P{
public:
template <typename U>
P<U> call(std::function< P<U> (T)> f){
return f(return_value);
}
T return_value;
};
P<int> foo() {
P<int> value = P<int>();
return value;
}
P<float> bar(int arg) {
return P<float>();
}
int main()
{
auto res = foo().call<float>(bar);
return 0;
}
As you can see in the main function, the compiler forces me to to specify the float type for calling the call() function, eventhough the type should be obvious from passing over the bar() function, that specifies the float type.
Is it somehow possible to deduct the type so that the code in the main function can be simplified to the following statement:
auto res = foo().call(bar);
| std::function is not the type that you should use whenever you want to pass a function around. std::function is a type that uses type erasure to be able to store different types of callables in one type. If you don't need that then you need no std::function:
#include <functional>
template<typename T>
class P{
public:
template <typename F>
auto call(F f){
return f(return_value);
}
T return_value{}; // don't forget to initialize !
};
P<int> foo() {
P<int> value = P<int>();
return value;
}
P<float> bar(int arg) {
return P<float>();
}
int main()
{
auto res = foo().call(bar);
return 0;
}
Using partial specializatzion you can get the return type of bar and you can get the float from P<float>:
#include <type_traits>
#include <iostream>
template <typename T> class P;
// get return type from function
template <typename T> struct return_type;
template <typename R,typename...args>
struct return_type<R(args...)> { using type = R; };
// get T from P<T>
template <typename P> struct P_arg;
template <typename T> struct P_arg< P<T> > { using type = T; };
// combine both
template <typename F>
struct get {
using type = typename P_arg<typename return_type<F>::type >::type;
};
template<typename T>
class P{
public:
template <typename F>
auto call(F f){
return f(return_value);
}
T return_value{};
};
P<float> bar(int arg) {
return P<float>();
}
int main()
{
std::cout << std::is_same_v< get<decltype(bar)>::type,float>;
return 0;
}
Though that does not really help here, because you cannot use it to decalre the return type of P::call, as it requires P<float> to be already complete.
|
71,606,074 | 71,606,781 | How do I copy values from one stack to another? | I am stuck after popping the values from stack1 then trying to push those values back into stack1, to later push back into stack2 in order. I'm not sure if I need another loop to make it nested loops or if I should switch to for loops as they are counting loops.
void copyStack(stack<int>& stack1, stack<int>& stack2)
{
int size = stack1.size();
while(size > 0)
{
stack2.push(stack1.top());
stack1.pop();
stack1.push(stack2.top());
--size;
}
}
Example:
Stack1: 4 3 2 1
Stack2: (empty)
(after running the function...)
Stack1: (empty)
Stack2: 4 3 2 1
| I'm a bit confused, why don't you just use this:
void copyStack(stack<int>& stack1, stack<int>& stack2) {
stack2 = stack1;
}
It's C++ ;)
Or, if you want to swap elements of these two stacks, instead of copying, you can use:
stack1.swap(stack2);
EDIT: if you want to do it by yourself and looking for an interesting solution, you can try these links:
Clone a stack without extra space
Clone a stack without using extra space | Set 2
|
71,606,116 | 71,639,438 | Loading a custom kernel causes VM to constantly reboot | I am working on a custom 32-bit OS, and i have coded a bare bones bootloader. I am trying to make it load a simple kernel that puts a char onto the screen, however, instead of getting the char i get a triple fault (maybe?)
I've tried increasing the number of sectors read, the number of 'db 0's in my extended program, tampering with the compilation script...
Nothing, however, my OS also prints the letter 'H' if it succeeds to read the disk, and sometimes when I increase the number of sectors to something exponential, the vm doesn't restart, but the disk isn't read successfully.
Github: https://github.com/Nutty000/Broken-OS
| "BROKEN-OS", you say?
Your GitHub ldr.asm file has many errors.
The Boot Sector and BPB Structure uses all the wrong data sizes! No wonder your VM gets all confused.
should be
---------
OEMIdentifier db "POSv0.10"
BytesPerSector dd 512 DW
SectorsPerCluster db 1
ReservedSectors db 32 DW
NumberOfFATs db 2
NUmberOfRootDirEntries db 224 DW
NumberOfSectors dd 2880 DW
MediaDescriptorType db 0xf0
SectorsPerFAT db 9 DW
SectorsPerTrack db 18 DW
NumberOfSides db 2 DW
HiddenSectors db 0 DD
LargeSectorCount db 0 DD
DriveNumber db 0x00
db 0
Signature db 0x29
VolumeID db 0x00, 0x00, 0x00, 0x00
VolumeLabel db "POSBOOTDSK "
SystemIdentifier db "FAT12 "
jmp short mbrcodestart
This short jump is encoded with 2 bytes, but the above mentioned structure must begin at offset 3 in your bootsector. You need to pad with a nop instruction, or force a near (non-short) jmp.
jmp short mbrcodestart
nop
The fact of storing a capital "H" as the first byte of your [ExtendedSpace] that you later jump to was a bad idea, but luckily for you that will not pose a problem as that particular encoding 72 happens to correspond to a valid one-byte instruction dec ax.
There's also:
not setting up the segment registers yourself
not setting up a stack in a safe place where the additional sectors can't overwrite it
ignoring the BH and BL parameters of the BIOS.Teletype call
not inspecting the carry flag that you get from the int 13h call
reading many sectors at once instead of the more reliable method of using a loop of reading individual sectors. (Some real-world BIOSes are somewhat broken; using only the simplest functionality will let your bootloader work even on such machines. See also Michael Petch's general tips for bootloaders.)
...
All of this happens even before diving into protected mode. First make sure the real mode part works fine before attempting to go further.
There are many good answers on this forum that deal with these issues:
Bootloader doesn't jump to kernel code
My OS is showing weird characters
Your current ldr.asm for reference:
[org 0x7c00]
jmp short mbrcodestart
OEMIdentifier db "POSv0.10"
BytesPerSector dd 512
SectorsPerCluster db 1
ReservedSectors db 32
NumberOfFATs db 2
NUmberOfRootDirEntries db 224
NumberOfSectors dd 2880
MediaDescriptorType db 0xf0 ;3.5 Inch Double-Sided HD Floppy disk(1.44MB or 2.88MB) should work with single-sided ones as well, maybe even 5.25 inch diskettes
SectorsPerFAT db 9
SectorsPerTrack db 18
NumberOfSides db 2
HiddenSectors db 0
LargeSectorCount db 0
;EBPB
DriveNumber db 0x00 ;Floppy Disk
db 0 ;Reserved
Signature db 0x29
VolumeID db 0x00, 0x00, 0x00, 0x00
VolumeLabel db "POSBOOTDSK "
SystemIdentifier db "FAT12 "
mbrcodestart:
mov bx, POSBL_WelcomeString
call print16
call read16
mov ah, 0x0e
mov al, [ExtendedSpace]
int 0x10
jmp ExtendedSpace
POSBL_WelcomeString:
db "PlanetOS BootLoader (POSBL) v0.1 (limited compatability)",0
print16:
mov ah, 0x0e
loop:
mov al, [bx]
cmp al, byte 0
je exit
int 0x10
inc bx
jmp loop
exit:
ret
ExtendedSpace equ 0x7e00
read16:
mov ah, 0x02
mov al, 20
mov bx, ExtendedSpace
mov ch, 0x00
mov cl, 0x02
mov dh, 0x00
mov dl, 0x00
int 0x13
ret
times 510-($-$$) db 0
dw 0xaa55
|
71,606,664 | 71,606,761 | Compiler casts derived instance as parent abstract class | I have a bug in a project I am making where I am trying to use abstract classes.
I have an abstract class defined as follows:
class BoundingVolume: public Displayable{
public:
virtual bool intersects(BoundingVolume const& bv) const noexcept = 0;
virtual bool intersects(Sphere const& sp)const noexcept = 0;
virtual bool intersects(AABB const& aabb) const noexcept= 0;
virtual float getVolume() = 0;
virtual std::tuple<std::vector<std::array<float,3>>, std::vector<std::vector<unsigned int>>> &toMesh() = 0;
};
I am using it as a member of another class because in that class I don't know what derived class of it I want to use:
class Object{
public :
explicit Object(std::vector<Point> const& vertices) noexcept;
std::vector<Point> m_vertices;
BoundingVolume *m_bounding_volume;
};
The code of my constructor for Object :
m_vertices = vertices
AABB aabb(points); // AABB is a derived class of BoundingVolume
auto aabb_pt = (AABB*) malloc(sizeof(AABB));
*aabb_pt = aabb;
m_bounding_volume = aabb_pt;
The problem is that when I construct an instance of Object and call toMesh on its BoundingVolume member, the program crashes (exit code 139). And while debugging it seems that it is because at the last line of my constructor the compiler makes a cast which does not allow it to understand later that m_bounding_volume is an instance of a derived class.
What am I doing wrong? Am I understanding everything correctly? What should be changed?
| You should not be using malloc to allocate memory for this class. In C++, objects might need additional logic to construct that isn't encapsulated by malloc, and this is especially, extremely true for objects that have inheritance, since [in most common implementations] the compiler has to do hidden work to construct the extra member data required to hold its type information.
In C++, you should be using the new keyword instead:
m_vertices = vertices
AABB aabb(points); // AABB is a derived class of BoundingVolume
auto aabb_pt = new AABB(aabb); //Assuming that you do intend to allocate a copy of aabb, and not merely point to it
//If you just wanted a pointer to aabb, this would be more appropriate
//auto aabb_pt = &aabb;
m_bounding_volume = aabb_pt;
It's also good practice in C++ to prefer using smart pointers, like std::unique_ptr or std::shared_ptr/std::weak_ptr, as these allow you to express ownership semantics and will help prevent these kinds of mistakes.
|
71,606,856 | 71,623,757 | Eigen matmul runtime depending on order of multiplication | I having problems where the runtime of a function involving some matrix multiplication changes depending on the order of the multiplication and the intermediate saved values. These are the variables...
Eigen::SparseMatrix<double> C; \\ = a sparse matrix (NxM)
Eigen::MatrixXd M_inv; \\ = a dense matrix (NxN)
Eigen::VectorXd v; \\ = a dense vector (dim M)
and N << M. This is fast,
Eigen::VectorXd alpha = M_inv * C * v;
Eigen::VectorXd v_n = v - C.transpose() * alpha;
and these are very slow (don't finish),
Eigen::MatrixXd D = C.transpose() * M_inv * C;
Eigen::VectorXd v_n = v - D * v;
Eigen::VectorXd v_n = v - C.transpose() * M_inv * C * v;
Does this have to do with memory usage or something with sparse and dense matmul?
Edit: N is of order 10, M is of order 10^6
| A (matrix * matrix) * vector product will almost certainly evaluate slower than matrix * (matrix * vector). Even in your fast version, you should make sure that you evaluate the product from right to left:
Eigen::VectorXd alpha = M_inv * (C * v);
Eigen::VectorXd v_n = v - C.transpose() * alpha;
And if you don't need alpha afterwards, you can also write this in one line:
Eigen::VectorXd v_n = v - C.transpose() * (M_inv * (C * v));
|
71,607,148 | 71,607,287 | Why are standard library types accessible inside `std` despite being nested in implementation-defined namespaces? | I was browsing the implementation of the <optional> header for GCC 11.2 (which can be found here), and I noticed something I'm struggling to understand. Here's the header with (hopefully) only the important bits left out:
#ifndef _GLIBCXX_OPTIONAL
#define _GLIBCXX_OPTIONAL 1
#pragma GCC system_header
#if __cplusplus >= 201703L
/* Includes of various internal and library headers */
namespace std _GLIBCXX_VISIBILITY(default)
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION
#if __cplusplus == 201703L
# define __cpp_lib_optional 201606L
#else
# define __cpp_lib_optional 202106L
#endif
/* Implementation */
template<typename _Tp>
class optional;
/* Implementation */
template<typename _Tp>
class optional: /* Implementation */
{ /* Implementation */ };
/* Implementation */
_GLIBCXX_END_NAMESPACE_VERSION
} // namespace std
#endif // C++17
#endif // _GLIBCXX_OPTIONAL
I found that _GLIBCXX_BEGIN_NAMESPACE_VERSION and _GLIBCXX_END_NAMESPACE_VERSION expand to namespace __8 { and }, respectively (there's no inline before namespace __8).
Therefore, it looks like std::optional is actually defined inside the non-inline namespace std::__8, but despite that, I can obviously reference std::optional in my programs as if it was located directly within std.
I don't think there are any using directives in effect, first because I haven't found any, and second because it should be allowed to specialize std::optional for custom types without opening implementation-defined namespaces ([namespace.std#2], [temp.spec.partial.general#6]).
The _GLIBCXX_VISIBILITY(default) macro expands to __attribute__ ((__visibility__ ("default"))), but I think it's unrelated (documentation). I couldn't find system_header in the list of pragmas in the documentation.
Therefore, I don't understand the reason why I should be able to reference the optional class as std::optional and not std::__8::optional. What am I missing here?
| The config.h in libstdc++ that defines these macros also initially declares the version namespace as inline here:
// Defined if inline namespaces are used for versioning.
#define _GLIBCXX_INLINE_VERSION
// Inline namespace for symbol versioning.
#if _GLIBCXX_INLINE_VERSION
# define _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace __8 {
# define _GLIBCXX_END_NAMESPACE_VERSION }
namespace std
{
inline _GLIBCXX_BEGIN_NAMESPACE_VERSION
#if __cplusplus >= 201402L
inline namespace literals {
inline namespace chrono_literals { }
inline namespace complex_literals { }
inline namespace string_literals { }
#if __cplusplus > 201402L
inline namespace string_view_literals { }
#endif // C++17
}
#endif // C++14
_GLIBCXX_END_NAMESPACE_VERSION
}
And once a namespace is declared inline, it's always inline. For instance:
namespace A {
inline namespace B {
struct X { };
}
}
namespace A {
namespace B {
struct Y { };
}
}
A::X x; // ok
A::Y y; // still ok
clang warns on this even if gcc doesn't, but also it's a system header so even if gcc wanred on it it wouldn't matter.
Still, not sure why not just add inline to the macro definition. We're probably not at the point where the additional 7 characters per header is a significant detriment to compile time?
|
71,607,609 | 71,607,882 | Why is double free called in this situation? | I've come about with the following situation that I fortunately solved by refactoring some other code, not related to the actual issue which I managed to capture below.
The code:
#include <boost/asio.hpp>
void passIocPtr(__attribute__((unused)) std::shared_ptr<boost::asio::io_context> iocPtr)
{}
void makeptr(boost::asio::io_context* ioc)
{
std::shared_ptr<boost::asio::io_context> iocPtr = std::make_shared<boost::asio::io_context>();
iocPtr.reset(ioc);
passIocPtr(iocPtr);
}
void makeptr2(boost::asio::io_context* ioc)
{
std::shared_ptr<boost::asio::io_context> iocPtr(ioc);
passIocPtr(iocPtr);
}
int main()
{
boost::asio::io_context ioc;
// makeptr(ioc);
makeptr2(ioc);
}
Both functions (makeptr and makeptr2) would result in:
double free or corruption (out) / free(): invalid pointer
The code I was working on had to use a pointer to a io_context.
Not entirely sure if the issue I had is specifically related to the ioc, I think it's pretty much my bad usage of smart pointers.
Maybe someone can give me some insight on how I should approach this better.
| shared_ptr is exclusively for managing heap objects
here:
int main()
{
boost::asio::io_context ioc;
// makeptr(ioc);
makeptr2(ioc);
}
you are passing a stack object to shared_ptr (eventually in make_ptr2). All bets are off after that. The double free message really means 'whoa - you have trashed your heap'
If you want this to work put ioc on the heap
int main()
{
boost::asio::io_context *ioc = new boost::asio::io_context;
// makeptr(ioc);
makeptr2(ioc);
}
|
71,608,535 | 71,608,731 | How to reduce the amount of checks of similar code blocks? | I do not seem able to improve the following code:
if(state[SDL_SCANCODE_M]){
if(_ball.velocity.x < 0)
_ball.velocity.x -= 20;
else
_ball.velocity.x += 20;
if(_ball.velocity.y < 0)
_ball.velocity.y -= 20;
else
_ball.velocity.y += 20;
}
if(state[SDL_SCANCODE_L]){
if(_ball.velocity.x < 0)
_ball.velocity.x += 20;
else
_ball.velocity.x -= 20;
if(_ball.velocity.y < 0)
_ball.velocity.y += 20;
else
_ball.velocity.y -= 20;
}
They are pretty similar, but the operations are the opposite.
Is there any best practice or technique that allows to improve these kind of situations?
| You can pre-compute some factor so to inverse the sign regarding the conditions.
Here is an example:
int xCoef = (_ball.velocity.x < 0) ? -1 : 1;
int yCoef = (_ball.velocity.y < 0) ? -1 : 1;
if(state[SDL_SCANCODE_M]){
_ball.velocity.x += xCoef * 20;
_ball.velocity.y += yCoef * 20;
}
if(state[SDL_SCANCODE_L]){
_ball.velocity.x -= xCoef * 20;
_ball.velocity.y -= yCoef * 20;
}
A more compact (branch-less) version that is a bit less clear (but probably more efficient) is the following:
int xCoef = (_ball.velocity.x < 0) ? -1 : 1;
int yCoef = (_ball.velocity.y < 0) ? -1 : 1;
int mPressed = state[SDL_SCANCODE_M] ? 1 : 0;
int lPressed = state[SDL_SCANCODE_L] ? 1 : 0;
_ball.velocity.x += (mPressed - lPressed) * xCoef * 20;
_ball.velocity.y += (mPressed - lPressed) * yCoef * 20;
Note that if state is a boolean array, you do not even need to use a ternary since booleans can be directly converted to 0-1 integer values.
|
71,608,557 | 71,610,461 | How can I use FFTW with the Eigen library? | I'm trying to learn how to use the FFTW library with Eigen. I don't want to use Eigen's unsupported module since I'd eventually like to incorporate FFTW's wisdom features into my code. However, I'm struggling on implementing a very basic example. Here is my code so far:
void fft(Eigen::Ref<Eigen::VectorXcd> inVec, int N) {
fftw_complex *in, *out;
fftw_plan p;
in = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N);
out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N);
p = fftw_plan_dft_1d(N, in, in, FFTW_FORWARD, FFTW_ESTIMATE);
in = reinterpret_cast<fftw_complex*>(inVec.data());
fftw_execute(p);
fftw_destroy_plan(p);
// reassign input back to inVec here
fftw_free(in); fftw_free(out);
}
This is essentially copied from chapter 2.1 in fftw's documentation. The documentation seems to say that its basic interface can't operate on different datasets, but you also have to initialize the data after creating a plan. I don't understand this point. Why not simply overwrite the data you initialize the first time with new data and execute the plan again?
Also, I've tried to cast an Eigen vector to fftw_complex, but I suspect I've made a mistake here. In Eigen's unsupported FFTW module, there is also a const_cast call. Why would that be there, and is that necessary since my underlying data is not const here?
Finally, if in is a pointer to fftw_complex data, how can I reassign it to my inVec and then free in?
|
I don't understand this point. Why not simply overwrite the data you initialize the first time with new data and execute the plan again?
Yes, that is exactly what fftw wants you to do. The line in = reinterpret_cast<fftw_complex*>(inVec.data()); just sets a pointer. It doesn't copy the array. You need to memcpy the content over, meaning memcpy(in, invec.data(), N * sizeof(fftw_complex));
What you want (and that is somewhat hidden in the FFTW documentation), is the "new-array execute function" that allows you to specify a different array for the call. However, note this line in the documentation:
The alignment issue is especially critical, because if you don’t use fftw_malloc then you may have little control over the alignment of arrays in memory. For example, neither the C++ new function nor the Fortran allocate statement provide strong enough guarantees about data alignment. If you don’t use fftw_malloc, therefore, you probably have to use FFTW_UNALIGNED (which disables most SIMD support). If possible, it is probably better for you to simply create multiple plans (creating a new plan is quick once one exists for a given size), or better yet re-use the same array for your transforms.
When you use Eigen, that is probably not an issue because Eigen also aligns its arrays. GCC also uses 16 byte alignment, so you are probably fine, even when calling malloc, but that depends on your platform. Your function interface doesn't guarantee alignment, though, because an Eigen::Ref may be a segment of a larger array. But you can check at runtime. Something like this:
unsigned flags = FFTW_ESTIMATE;
if(reinterpret_cast<size_t>(invec.data()) % 16)
flags |= FFTW_UNALIGNED;
p = fftw_plan_dft_1d(..., flags);
The warning about loss of vectorization may be outdated. Proper alignment is less crucial today (especially on anything supporting AVX) and I suspect (but have not verified) that FFTW will vectorize with unaligned memory access, too.
Side note: In the line p = fftw_plan_dft_1d(N, in, in, FFTW_FORWARD, FFTW_ESTIMATE);, the third argument should be out, not in; unless you want an in-place transformation, in which case you don't need to allocate the out array.
EDIT: The check for alignment may break. I've just checked the source code and FFTW may define different alignments depending on compile flags. I don't see a good way to figure out what alignment it uses. It may be 32 byte for AVX or 64 byte for AVX-512.
On the other hand, the fftw_alignment_of function that is provided to check for this kind of stuff does a simple modulo 16 like my code above. So I don't know. Breakage should be very obvious. It will just crash, not result in invalid results.
|
71,608,605 | 71,608,689 | Calling boolean function without an argument inside of an if-statement in C++ | I was wondering, why is there no error when the block of code below is executed? The error should come from the func1 block, because we are calling func2 without an argument. What is being passed in the argument to func2?
I also realized this only happens when func2 is a boolean function, and if it is called inside an if statement. I know that "-4" is not passed from the main function, because the output is "1" when it should be "0".
#include <iostream>
bool func2(int b) {
return b>0;
}
int func1(int a) {
if (func2) return 1;
else return 0;
}
int main() {
std::cout << func1(-4);
return 0;
}
| The reason the code doesn't fail to compile is because of function-to-function-pointer decay.
When you use just the name of a function, it will decay into a pointer to that function. The pointer can then be converted to a bool that will be true if the pointer points to something, and false if it is a null pointer.
Since the pointer is pointing to a function, it will have a non-null value, and that means the expression will evaluate to true.
|
71,609,061 | 71,609,354 | How To Use Nested-Function-Type As The Function Parameter? C++ | The Problem
void function(InnerType const& inputs) {
struct InnerType {
// All the function required parameters
};
}
It's possible to fix the compiler error about the function parameter type?
Possible Solution
struct InnerType;
void function(InnerType const& inputs) {
struct InnerType {
};
}
But it fails with the 'Incomplete Type' error when we try to use it.
Usage
In my recent project, I have to deal with a lot of C APIs including the third-party libraries and the Kernel APIs.
First I tried to wrap those functions but soon I come up with a lot of duplicate codes to handle trivial things(like checking the API preconditions that some of them have the same code under different name/context),
Then I tried to use Template Programming to hide the logic of the conditions under templates.
And that didn't take a long time before I come up with a lot of unreadable templates code only just for a single task(removing the duplication).
So I think that if we could have a Nested-Function-Type, we could easily wrap the API parameter in the C++ function to avoid a whole new class with duplicate codes.
My Restrictions
I can't define the struct in the same namespace of the function. Because all of the API handlers are defined in the same file and it's hard to choose unique names.
I can't create a file per handler, because we already have a lot of files.
My Priorities
Readbility
Maintainability
Strong Typing(for dealing with the C APIs)
Example
Expected<ReturnType> GetDataFrom(FunctionParamType const& inputs) {
struct FunctionParamType {
String string;
Integer index;
};
ThrowExceptionOnEmptyString(inputs.string, "Missed Something");
ThrowExceptionOnZeroInteger(inputs.index, "Wrong Index");
// Call The API
}
// Usage
auto const result = GetDataFrom({.string = "something", .index = 1});
Instead of:
class DataApi {
public:
void setString(String const& string) {
ThrowExceptionOnEmptyString(string, "Missed Something");
string_ = string;
}
void setInteger(Integer const& interger) {
ThrowExceptionOnZeroInteger(integer, "Wrong Index");
integer_ = integer;
}
String getString() const noexcept { return string_; }
Integer getInteger() const noexcept { return integer_; }
DataApi(String const& string, Integer const& integer)
: string_(string), integer_(integer) {
ThrowExceptionOnEmptyString(string, "Missed Something");
ThrowExceptionOnZeroInteger(integer, "Wrong Index");
}
DataApi() = default;
Expected<ReturnType> execute() {
// Call The API
}
private:
String string_;
Integer integer_;
};
// Usage
auto const result = DataApi("Something", 1).execute();
| How about this approach:
namespace some_api_function {
struct parameter_type {
...
};
struct return_type {
...
};
return_type call(parameter_type p) {
...
}
}
The only name that changes is that of the surrounding namespace. parameter_type, call and return_type remain the same throughout the various API wrappers.
BTW: Your approach with validating setters for the parameter structs is flawed. In particular, you don't guarantee that the parameter is correct if you don't establish that guarantee from the constructor on. Also, if two parameters' correctness depend on each other, that approach doesn't work with separate setters.
Instead, consider writing two more functions validate() that you call first hand on the parameters and finally on the results. That is also a good way to clearly document these requirements in code.
|
71,609,213 | 71,609,868 | Why cannot I use [] operator on std::shared_ptr<unsigned char[]>? | I'm writing an application for Arduino (more precisely, Teensy). While compiling the following code (last pasted line):
void executeActions(std::shared_ptr<unsigned char[]> actionData, const unsigned short actionBytes)
{
unsigned short modifier = 0;
Keyboard.set_modifier(modifier);
int i = 0;
while (i < actionBytes)
{
unsigned char action = actionData[i];
I'm getting the following error:
no match for 'operator[]' (operand types are 'std::shared_ptr<unsigned char []>' and 'int')
For reference, mentioned actionData is initialized in the following way (then passed a couple of times):
this->actionData = std::make_shared<unsigned char[]>(new unsigned char[this->actionBytes]);
What am I doing wrong?
| In C++17 and later, std::shared_ptr has an operator[] (only when T is an array type). This operator does not exist in C++11..14, which is apparently what you are compiling for, or at a cursory glance, Arduino does not fully support C++17.
Also:
std::make_shared<unsigned char[]>(new unsigned char[this->actionBytes])
should be:
std::make_shared<unsigned char[]>(actionBytes)
But that is only available in C++20 and later.
In this situation, I would suggest using std::vector<unsigned char> instead of unsigned char[] (you should not be using new manually anyway), eg:
actionData = std::make_shared<std::vector<unsigned char>>(actionBytes);
void executeActions(std::shared_ptr<std::vector<unsigned char>> actionData)
{
unsigned short modifier = 0;
Keyboard.set_modifier(modifier);
for(size_t i = 0; i < actionData->size(); ++i)
{
unsigned char action = (*actionData)[i];
...
}
/* simpler:
for (auto action : *actionData)
{
...
}
*/
...
}
|
71,609,216 | 71,879,764 | Add and subtract integers of arbitrary size | I am tasked to implement from scratch addition and subtraction of signed integers of arbitrary size. Such an integer is stored in an array of 64-bit unsigned integers. The least significant bit of the array's first element is the least significant bit of the whole integer. An array of size d represents a signed integer of at most 64 * d - 1 bits. Format of the integer should not be changed.
I came up with the following:
// Add huge integers: z[] = x[] + y[]
template<typename ing>
inline void addHint(uint64_t *z, uint64_t *x, uint64_t *y, ing d)
{
uint64_t carry = 0;
for (ing i = 0; i < d; ++i)
{
uint64_t zi = x[i] + y[i];
// uint64_t carryNew = zi < x[i] or zi < y[i];
uint64_t carryNew = zi < x[i]; // zi < y[i] unnecessary.
z[i] = zi + carry;
carry = carryNew or z[i] < zi;
}
}
// Subtract huge integers: x[] = z[] - y[]
template<typename ing>
inline void subHint(uint64_t *x, uint64_t *z, uint64_t *y, ing d)
{
uint64_t carry = 0;
for (ing i = 0; i < d; ++i)
{
uint64_t xi = z[i] - y[i];
// uint64_t carryNew = z[i] < y[i];
uint64_t carryNew = z[i] < xi; // Somehow x86-64 g++ 8.3 -O2 dumps fewer assembly lines than the above according to godbolt.org
x[i] = xi - carry;
carry = carryNew or xi < x[i];
}
}
My team is unsatisfied with the speed. Can it be improved?
Thanks!
| mp_limb_t mpn_add_n (mp_limb_t *rp, const mp_limb_t *s1p, const mp_limb_t *s2p, mp_size_t n)
and
mp_limb_t mpn_sub_n (mp_limb_t *rp, const mp_limb_t *s1p, const mp_limb_t *s2p, mp_size_t n)
in GMP are what you were looking for.
|
71,610,020 | 72,490,406 | Debugger doesn't locate symbols in source when INTERPROCEDURAL_OPTIMIZATION is enabled | I've been switching a project to CMake and VSCode on my Mac, and encountered a baffling problem: when I enable LTO/IPO, VSCode's C++ debugger doesn't highlight the execution line when breaking. This appears to affect any build target for which I enable IPO.
Here's a minimum example demonstrating the problem:
[main.cpp]
#include <iostream>
int main()
{
std::cout << "This is some text!" << std::endl;
__asm__("int $3"); // Alternatively, use a breakpoint
return 0;
}
[CMakeLists.txt]
cmake_minimum_required(VERSION 3.23.0)
project(TestLTODebugging)
include(CheckIPOSupported)
check_ipo_supported()
add_executable(example main.cpp)
set_target_properties(example PROPERTIES
INTERPROCEDURAL_OPTIMIZATION TRUE
)
I'm using Clang and Ninja, using quick-debugging via VSCode's CMake Tools extension. When run, the app appears to pause as expected, but the line is not highlighted:
And if all I do is turn off IPO/LTO, the issue goes away:
Anyone know where to look for the problem? I'm new to CMake and using VSCode for C++, but this seems super basic and I can't find anything online about this problem. I've had no problems with this when generating an Xcode project with the same source.
While I'm primarily going to be debugging without optimizations, the project I'm working on requires working with optimizations enabled a lot of the time, and I want the debugger to work. I appreciate any help or advice.
EDIT: I've confirmed that this issue does not occur on my PC, where I also tested with Ninja, Clang, and the VSCode debugger. So the problem is either with my Mac environment or is Mac-specific?
EDIT 2: I've now confirmed this affects me with both Ninja and Make files on my Mac. Additionally, both Ninja.build and compile_commands.json (when using Make) show that the only difference between enabling and disabling IPO is the addition of the -flto=thin flag. The -g flag is never removed, and using nm in Terminal shows that the debug symbols are still being generated. I'm now more confident that this is a bug with VS Code or CMake Tools.
| I faced a similar problem -- in my case I source annotations for Instruments were missing.
From here:
Note
On Darwin, when using -flto along with -g and compiling and linking in separate steps, you also need to pass -Wl,-object_path_lto,<lto-filename>.o at the linking step to instruct the ld64 linker not to delete the temporary object file generated during Link Time Optimization (this flag is automatically passed to the linker by Clang if compilation and linking are done in a single step). This allows debugging the executable as well as generating the .dSYM bundle using dsymutil(1).
Additional information here.
TL;DR: just add -Wl,-object_path_lto,lto.o to your linker options -- e.g. for CMake: add_link_options(-Wl,-object_path_lto,lto.o).
|
71,610,522 | 71,610,579 | What causes __detail::__can_reference to fail? | Consider the following code.
#include <iterator>
struct Node {
static Node mNode;
};
Node Node::mNode;
struct DeepNodeRange {};
class DeepNodeIter
{
public:
using iterator_category = std::forward_iterator_tag;
using value_type = Node*;
using difference_type = std::ptrdiff_t;
DeepNodeIter() = default;
DeepNodeIter(DeepNodeRange& deepNodeRange, bool end = false) :
mDeepNodeRange(&deepNodeRange), mEnd(end) {}
auto operator*() const { return &Node::mNode; }
auto& operator++()
{
mIdx++;
mEnd = (mIdx > 10);
return *this;
}
auto operator++([[maybe_unused]] int val)
{
auto tmp(*this);
operator++();
return tmp;
}
auto operator==(const DeepNodeIter& iter) const
{ return iter.mEnd == mEnd; }
protected:
DeepNodeRange* mDeepNodeRange;
int mIdx;
bool mEnd;
static_assert(std::forward_iterator<DeepNodeIter>);
};
int main() {
}
I'm getting the following error.
b.cpp:51:22: error: static assertion failed
51 | static_assert(std::forward_iterator<DeepNodeIter>);
| ~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
b.cpp:51:22: note: constraints not satisfied
In file included from include/c++/11.1.0/bits/stl_iterator_base_types.h:71,
from include/c++/11.1.0/iterator:61,
from b.cpp:1:
include/c++/11.1.0/bits/iterator_concepts.h:612:13: required for the satisfaction of 'input_or_output_iterator<_Iter>' [with _Iter = DeepNodeIter]
include/c++/11.1.0/bits/iterator_concepts.h:634:13: required for the satisfaction of 'input_iterator<_Iter>' [with _Iter = DeepNodeIter]
include/c++/11.1.0/bits/iterator_concepts.h:613:9: in requirements with '_Iter __i' [with _Iter = DeepNodeIter]
include/c++/11.1.0/bits/iterator_concepts.h:613:33: note: the required expression '* __i' is invalid
613 | = requires(_Iter __i) { { *__i } -> __detail::__can_reference; }
| ^~~~
cc1plus: note: set '-fconcepts-diagnostics-depth=' to at least 2 for more detail
What is causing this error?
| Move the static_assert after the class body.
You cannot pass an incomplete type to std::forward_iterator and the class isn't complete yet at the point where you put the assertion.
|
71,610,824 | 71,612,481 | Why does reference_wrapper<string> comparison not work? | int main()
{
int x = 1;
auto ref = std::ref(x);
if (x < ref)
{
...
}
}
In the above code, I made an int variable and a reference_wrapper<int> variable, and then compared them, and it works well.
However, If I change the type int to string, It raises a compile error like this.
binary '<': 'std::string' does not define this operator or a conversion to a type acceptable to the predefined operator
I thought that reference_wrapper<string> would be implicitly converted to string, but wouldn't.
Are there any rules that prevent implicit conversion from reference_wrapper<string> to string?
| std::reference_wrapper<> more or less supports only one operation: an implicit type conversion back to the original type (which is std::string in your case).
But the problem is that the compiler has to know that an implicit conversion back to the original type is necessary.
That is why your example works with the built-in type int, while not with the class template instantiation std::string of the basic_string class template.
The situation is similar to the below given example:
template<typename T>
struct MyWrapper
{
operator T()
{
return T{};
}
};
int main()
{
int x = 1;
MyWrapper<int> ref;
if(x < ref) //WORKS WITH INT
{
}
std::string x2 = "f";
MyWrapper<std::string> ref2;
if(x2 < ref2) //WON'T WORK WITH STD::STRING
{
}
}
To solve this problem, we need to explicitly say that we want the original type, which we can do by using the get() member function, as shown below:
std::string x = "hi";
auto ref = std::ref(x);
//----------vvvvv------->get() member function used here
if (x < ref.get())
{
}
|
71,610,856 | 71,610,986 | What is the best place for a static_assert? | Consider the following code:
#include <iterator>
struct Node {
static Node mNode;
};
Node Node::mNode;
struct DeepNodeRange {};
class DeepNodeIter
{
public:
using iterator_category = std::forward_iterator_tag;
using value_type = Node*;
using difference_type = std::ptrdiff_t;
DeepNodeIter() = default;
DeepNodeIter(DeepNodeRange& deepNodeRange, bool end = false) :
mDeepNodeRange(&deepNodeRange), mEnd(end) {}
Node* operator*() const { return &Node::mNode; }
DeepNodeIter& operator++()
{
mIdx++;
mEnd = (mIdx > 10);
return *this;
}
DeepNodeIter operator++([[maybe_unused]] int val)
{
auto tmp(*this);
operator++();
return tmp;
}
bool operator==(const DeepNodeIter& iter) const { return iter.mEnd == mEnd; }
protected:
DeepNodeRange* mDeepNodeRange;
int mIdx;
bool mEnd;
static_assert(std::forward_iterator<DeepNodeIter>);
};
int main() {
}
I get the following error:
In file included from include/c++/11.1.0/bits/stl_iterator_base_types.h:67,
from include/c++/11.1.0/iterator:61,
from b.cpp:1:include/c++/11.1.0/type_traits: In instantiation of 'struct std::is_nothrow_destructible<DeepNodeIter>':
include/c++/11.1.0/type_traits:3166:35: required from 'constexpr const bool std::is_nothrow_destructible_v<DeepNodeIter>'
include/c++/11.1.0/concepts:134:28: required from here
include/c++/11.1.0/type_traits:900:52: error: static assertion failed: template argument must be a complete class or an unbounded array
900 | static_assert(std::__is_complete_or_unbounded(__type_identity<_Tp>{}),
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
include/c++/11.1.0/type_traits:900:52: note: 'std::__is_complete_or_unbounded<std::__type_identity<DeepNodeIter> >((std::__type_identity<DeepNodeIter>{}, std::__type_identity<DeepNodeIter>()))' evaluates to false
b.cpp:50:22: error: static assertion failed
50 | static_assert(std::forward_iterator<DeepNodeIter>);
| ~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
b.cpp:50:22: note: constraints not satisfied
It seems, if I move the static_assert outside the class then it compiles fine but inside the class it does not. Conversely, if the class has a template type then the reverse is true.
Why am I getting the error here and why do I not get it when DeepNodeIter is a template class?
| It doesn't actually compile when you make DeepNodeIter a template either: https://godbolt.org/z/W9jf94xPn
The reason it may have looked like it worked is if you did not instantiate the template, the compiler will not proactively fail to compile since you might specialize the template before you instantiate it.
The reason this does not work is, a type is considered incomplete until it's closing brace is reached. Until then, it is as if you only have a declaration of the type, i.e. class DeepNodeIter;. There are exceptions to this rule like member functions defined within the definition being compiled as if they were right after the class definition, but apparently not for static_asserts.
|
71,610,886 | 71,610,991 | Reading input from command line, separated by whitespace, into array of objects | I am experimenting with reading input from command line and successfully store them in objects attributes.
Example of input (./(nameOfExecutable) < (sourceText) in the command line)
20 5
1 5
28 5
2 5
20 5
4 5
22 5
88 3
27 5
34 5
I want to read and store them into object attributes.
experimentClass.h
#ifndef EXPERIMENTCLASS_H
#define EXPERIMENTCLASS_H
#pragma once
class experimentClass
{
public:
experimentClass(int x, int y);
~experimentClass();
private:
int age;
int favoriteNumber;
};
#endif
experimentClass.cpp
#include "experimentClass.h"
experimentClass::experimentClass(int x, int y)
{
age = x;
favoriteNumber = y;
}
experimentClass::~experimentClass()
{
}
main.cpp
#include <iostream>
#include "experimentClass.h"
using namespace std;
int main(){
int age;
int favoriteNumber;
std::cin >> age;
std::cin >> favoriteNumber;
experimentClass a(age, favoriteNumber);
}
In this case, I am able to store 20 into a's age, 5 into a's favoriteNumber.
However, I want to do this process until it hits the end of input.
So, in this case, I want to create 10 objects with given input, using iteration, and store these object into an array or something.
How can I read them properly so that I can achieve this?
| Simply take the logic you already have and put it inside a loop, eg:
#include <iostream>
#include <vector>
#include "experimentClass.h"
using namespace std;
int main() {
int age;
int favoriteNumber;
vector<experimentClass> vec;
while (cin >> age >> favoriteNumber) {
experimentClass a(age, favoriteNumber);
vec.push_back(a);
}
// use vec as needed...
}
Then you can take this a step further by implementing an operator>> for your class, eg:
#ifndef EXPERIMENTCLASS_H
#define EXPERIMENTCLASS_H
#include <istream>
#pragma once
class experimentClass
{
public:
experimentClass(int x = 0, int y = 0);
friend std::istream& operator>>(std::istream &is, experimentClass &cls);
private:
int age;
int favoriteNumber;
};
std::istream& operator>>(std::istream &is, experimentClass &cls);
#endif
#include "experimentClass.h"
experimentClass::experimentClass(int x, int y)
{
age = x;
favoriteNumber = y;
}
std::istream& operator>>(std::istream &is, experimentClass &cls)
{
return is >> cls.age >> cls.favoriteNumber;
}
#include <iostream>
#include <vector>
#include "experimentClass.h"
using namespace std;
int main() {
experimentClass a;
vector<experimentClass> vec;
while (cin >> a) {
vec.push_back(a);
}
// use vec as needed...
}
|
71,611,300 | 71,611,368 | why does the local array has extra empty location at the end(c/c++/gcc)? | Check below program,
int main()
{
short int data1[]={1,2,3,4,5,6,7,8,9,10};
short int data2[]={1,2,3,4,5,6,7,8,9,10};
short int *ptr = data1;
cout<<"data1 start addr = "<<data1<<endl;
cout<<"data2 start addr = "<<data2<<endl;
for (int i=0;i<20;i++, ptr++)
cout <<"Data = "<<*ptr<<" Addr = "<<ptr<<endl;
return 0;
}
In the above program, even though array size is 10, after the first array there is exactly 6 extra locations reserved in the stack (12bytes), I am wondering why this extra space got reserved? and this extra space size is varying for different size(Its not 12 for size 20).
Can anybody explain the concept behind these allocations?
Output of above program using g++/gcc is,
data1 start addr = 0x7ffc87350920
data2 start addr = 0x7ffc87350940
Data = 1 Addr = 0x7ffc87350920
Data = 2 Addr = 0x7ffc87350922
Data = 3 Addr = 0x7ffc87350924
Data = 4 Addr = 0x7ffc87350926
Data = 5 Addr = 0x7ffc87350928
Data = 6 Addr = 0x7ffc8735092a
Data = 7 Addr = 0x7ffc8735092c
Data = 8 Addr = 0x7ffc8735092e
Data = 9 Addr = 0x7ffc87350930
Data = 10 Addr = 0x7ffc87350932
Data = 32629 Addr = 0x7ffc87350934
Data = 0 Addr = 0x7ffc87350936
Data = 9232 Addr = 0x7ffc87350938
Data = 12176 Addr = 0x7ffc8735093a
Data = 22064 Addr = 0x7ffc8735093c
Data = 0 Addr = 0x7ffc8735093e
Data = 1 Addr = 0x7ffc87350940
Data = 2 Addr = 0x7ffc87350942
Data = 3 Addr = 0x7ffc87350944
Data = 4 Addr = 0x7ffc87350946
| You can't expect the order that items will be allocated on the stack matches the order they are defined in code unless you explicitly specify a structure for how fields should be stored relative to each other. The compiler can and does reorder elements for performance or other reasons.
There is no way to tell for sure what those items are without checking the assembly to see how they get used. Reading them is undefined behavior since you can't tell at compile time what they will be, or if they will even represent valid memory since it is outside of the bounds of any of the variables you defined. Odds are, they are just other variables in your program though.
|
71,611,923 | 72,637,258 | How to run code on start of yylex and when token is matched in RE-flex | I was using RE-flex to generate a c++ Scanner for a project. I wanted to run code when a token is matched and I followed the Flex way of doing, but that ended up putting the code outside the function. How can I put it at the end, when a token is matched? Also, I want to run code at the beginning of yylex. When I do it the Flex way, it puts the code inside a switch statement based on the start condition. How can I run this code regardless of the start condition? The scanner file is given here.
%top {
#include "driver.h"
#include "y.tab.hh"
std::string buffer_2;
bool actionReturned = false, typeReturned = false, headerReturned;
int actionCount = 0, typeCount = 0;
%}
%{
#undef YY_USER_ACTION
%}
%option noyywrap nounput noinput batch debug
%option params="driver &drv"
%x HEADER ACTION TYPE
blank [ \t\r]+
newline \n+
id [a-zA-Z_][a-zA-Z0-9_]*
%{
#define YY_USER_ACTION loc.columns(yyleng);
%}
%%
yy::location &loc = drv.location;
loc.step();
if(actionReturned) {
actionReturned = false;
buffer_2.clear();
return yy::parser::make_ACTION_CLOSE(loc);
}
if(typeReturned) {
typeReturned = false;
buffer_2.clear();
return yy::parser::make_TYPE_CLOSE(loc);
}
if(headerReturned) {
headerReturned = false;
buffer_2.clear();
return yy::parser::make_HEADER_CLOSE(loc);
}
<INITIAL>{blank} loc.step();
<INITIAL>{newline} loc.lines(yyleng); loc.step();
<INITIAL>"%empty" return yy::parser::make_EPSILON(loc);
<INITIAL>"%type" return yy::parser::make_TYPE(loc);
<INITIAL>"%union" return yy::parser::make_UNION(loc);
<INITIAL>"%token" return yy::parser::make_TOKEN(loc);
<INITIAL>"%%" return yy::parser::make_DELIMITER(loc);
<INITIAL>";" return yy::parser::make_SEMICOLON(loc);
<INITIAL>"*" return yy::parser::make_KLEENE_STAR(loc);
<INITIAL>"+" return yy::parser::make_ZERO_MORE(loc);
<INITIAL>"?" return yy::parser::make_OPTIONAL(loc);
<INITIAL>"/" return yy::parser::make_PRODUCTION_OR(loc);
<INITIAL>"<-" return yy::parser::make_RULE_OPEN(loc);
<INITIAL>"%{" BEGIN(HEADER); return yy::parser::make_HEADER_OPEN(loc);
<INITIAL>"<" BEGIN(TYPE); ++typeCount; return yy::parser::make_TYPE_OPEN(loc);
<INITIAL>"{" BEGIN(ACTION); ++actionCount; return yy::parser::make_ACTION_OPEN(loc);
<INITIAL>{id} return yy::parser::make_ID(yytext, loc);
<INITIAL>. {
throw yy::parser::syntax_error(loc, "Unexpected character: " + std::string(yytext));
}
<INITIAL><<EOF>> return yy::parser::make_YYEOF(loc);
<HEADER>"}" {
loc.step();
if(buffer_2[buffer_2.length() - 1] == '%') {
// end has been matched
buffer_2.pop_back();
headerReturned = true;
return yy::parser::make_HEADER_CODE(buffer_2, loc);
}
buffer_2 += '}';
}
<HEADER>(.|\n) buffer_2 += yytext[0]; loc.step();
<ACTION>"{" ++actionCount; buffer_2 += '{'; loc.step();
<ACTION>"}" {
--actionCount;
loc.step()
if(!actionCount) {
actionReturned = true;
BEGIN(INITIAL);
return yy::parser::make_ACTION_CODE(buffer_2, loc);
}
buffer_2 += '}';
}
<ACTION>\n buffer_2 += yytext[0] loc.lines(yyleng); loc.step();
<ACTION>. buffer_2 += yytext[0]; loc.step();
<TYPE>"<" ++typeCount; buffer_2 += '}'; loc.step();
<TYPE>">" {
--typeCount;
loc.step();
if(!typeCount) {
typeReturned = true;
BEGIN(INITIAL);
return yy::parser::make_TYPE_CODE(loc);
}
buffer_2 += '>';
}
<TYPE>\n buffer_2 += yytext[0]; loc.lines(yyleng); loc.step();
<TYPE>. buffer_2 += yytext[0]; loc.step();
%%
void driver::scanBegin() {
yy_flex_debug = traceScanning;
if(file.empty() || file == "-") {
fprintf(stderr, "Could not open file\n");
exit(1);
}
if(!(yyin = fopen(file.c_str(), "r"))) {
fprintf(stderr, "Could not open file\n");
exit(1);
}
}
void driver::scanEnd() {
fclose(yyin);
}
| Use the YY_USER_INIT macro to inject code that executes the first time yylex() is called. This is a flex macro supported by RE-flex In addition, RE-flex has a new code section %begin{ ... } specifically for this purpose to define code that should be executed before scanning starts, but after the scanner is initialized (i.e. at the same spot as flex YY_USER_INIT). See the Lexer/yyFlexLexer class structure in RE-flex to quickly understand what the generated scanner's code structure will look like.
There are also definitions for initial code blocks in flex and RE-flex, which are executed in yylex() just before a pattern is matched.
|
71,611,939 | 71,611,987 | C++ template result_of_t no type named 'type' when trying to find return value of function | I'm trying to get the return type of a function template. One solution I saw uses result_of_t:
#include <iostream>
#include <vector>
#include <string>
#include <type_traits>
#include <map>
#include <unordered_map>
#include <any>
using namespace std;
using MapAny = map<string, any>;
template <typename num_t>
num_t func1_internal(const vector<num_t> &x, int multiplier) {
num_t res = 0;
for (int i=0; i<x.size(); i++)
res += multiplier * x[i];
return res;
}
template <typename num_t>
class Func1 {
using ResultType = num_t; // std::result_of_t<decltype(func1_internal<num_t>)>;
//using ResultType = std::result_of_t<decltype(func1_internal(const vector<num_t>&, int))>;
private:
vector<int> multipliers;
public:
Func1(const vector<MapAny> ¶ms) {
for (const auto& param : params) {
multipliers.push_back(any_cast<int>(param.at("multiplier")));
}
}
any operator()(const vector<double> &x) {
vector<ResultType> res;
for (int multiplier : multipliers)
res.push_back(func1_internal(x, multiplier));
return res;
}
};
int main()
{
Func1<float> func1({});
return 0;
}
However, it gives me an error:
/usr/include/c++/10/type_traits: In substitution of ‘template<class _Tp> using result_of_t = typename std::result_of::type [with _Tp = float(const std::vector<float, std::allocator<float> >&, int)]’:
fobject.cpp:21:7: required from ‘class Func1<float>’
fobject.cpp:45:23: required from here
/usr/include/c++/10/type_traits:2570:11: error: no type named ‘type’ in ‘class std::result_of<float(const std::vector<float, std::allocator<float> >&, int)>’
2570 | using result_of_t = typename result_of<_Tp>::type;
What's the correct way to do this in C++20? Also, I heard that std::result_of is deprecated, so I'm looking for the best way possible.
| You can use C++17 std::invoke_result, where the first argument is the callable type, followed by arguments type
using ResultType = invoke_result_t<
decltype(func1_internal<num_t>), const vector<num_t>&, int>;
decltype(func1_internal<num_t>) will get the function type of int(const std::vector<int>&, int).
|
71,612,780 | 71,612,825 | How I can determine the "nearest" exception handler | From [except.throw]/2:
When an exception is thrown, control is transferred to the nearest
handler with a matching type ([except.handle]); “nearest” means the
handler for which the compound-statement or ctor-initializer following
the try keyword was most recently entered by the thread of control and
not yet exited.
First of all, I really can't understand this quote properly, and how it is applied in a particular code. So any understandable explanations, with simple words, will be very appreciated.
Consider this two code snippets:
/ * code A */
try
{
throw 1;
}
catch (int) // nearest handler for throwing 1. #first_handler
{
}
-----------------------------------------------
/* code B */
try
{
try
{
throw 1;
}
catch (int) // nearest handler for throwing 1. #second_handler
{
throw 2;
}
}
catch (int) // nearest handler for throwing 2
{
}
Because I cannot understand the above quote, I don't know how I can determine the nearest handler, and I cannot apply [except.throw]/2 in the above examples. My question is just how does [except.throw]/2 is applied in the above code? or in other words, why first_handler and second_handlerare nearest handlers?
| Exceptions travel upwards, hence you can look for the next try then see if it has a matching catch, if not continue. For example
try { // 4
try { // 2
throw "foo"; // 1
} catch(int) { } // 3
} catch(...) { // 5
std::cout << "hello exception";
}
When the excpetion is thrown in 1 then control flow goes backwards and the first try is the one in 2. It does not have a matching catch, it only catches int (3). Hence, you look further upwards to find the try in 4. It has a catch that catches any exception 5 and that is the "nearest".
[...] "“nearest” means the handler for which the compound-statement following the try keyword was most recently entered by the thread of control and not yet exited." What that's "not yet exited"? I can't get the bold part.
Thats the second example:
try // try 2
{
try // try 1
{
throw 1;
} // <---- the try block is exited here
catch (int) // catch 1
{
throw 2;
}
}
catch (int) // catch 2
{
}
throw 2 will be handled by catch 2 because thats the nearest handler. The nearest handler is not catch 1 because that belongs to try 1. And when throw 2 is executed then the try 1 block is already exited.
|
71,612,853 | 71,613,094 | How to read the JSON Error response returned from Server using Libcurl | I have a requirement where I have to read the error response from backend server which returns 500 Internal Server error. The error response is in JSON Format.
Below is the code snippet used in our application
INT CCurlHTTP::HTTPSPost(const CString& endPointUrl, const CString& urlparam,const CString& cookie){
CURL *curl;
CURLcode res;
struct curl_slist *headers=NULL;
char errbuf[CURL_ERROR_SIZE];
curl = curl_easy_init();
get_request req;
req.buffer =0;
req.len =0;
req.buflen =0;
if(curl)
{
//add url, headers, and parameters to the request
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_easy_setopt(curl, CURLOPT_URL, endPointUrl);
curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
headers = curl_slist_append(headers, m_httpHeadAccept);
headers = curl_slist_append(headers, m_httpContentType);
//callback function used to save response
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWrite_CallbackFunc_String);
req.buffer = (unsigned char*) malloc(CHUNK_SIZE);
req.buflen = CHUNK_SIZE;
req.len = 0;
curl_easy_setopt(curl,CURLOPT_WRITEDATA, (void *)&req);
if (!cookie.IsEmpty())
{
headers = curl_slist_append(headers, m_DBAuthCertficate); //What is difference between this and line no 118?
CString pCookie = "DBAuthTicket=" + cookie;
curl_easy_setopt(curl,CURLOPT_COOKIE, pCookie);
}
else
{
headers = curl_slist_append(headers, m_OAuthToken);
}
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, urlparam);
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errbuf);
errbuf[0] = 0;
curl_easy_setopt(curl, CURLOPT_BUFFERSIZE, 512000);
curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L);
res = curl_easy_perform(curl);
if(res != CURLE_OK)
{
/* if errors have occured, tell us wath's wrong with 'result'*/
m_response.Format("%s", curl_easy_strerror(res));
return res;
}
m_response = (char*)req.buffer;
m_errDescription = errbuf;
len = req.len;
buflen = req.buflen;
curl_easy_cleanup(curl);
free(req.buffer);
}
return res;
}
/****************************************************************************
Function: CurlWrite_CallbackFunc_String
Description: Read data from the connected URL
Return: String of data and size
****************************************************************************/
size_t CCurlHTTP::CurlWrite_CallbackFunc_String(void *contents, size_t size, size_t nmemb, void *userdata)
{
size_t rLen = size*nmemb;
get_request* req = (get_request*)userdata;
while(req->buflen < req->len + rLen + 1)
{
req->buffer = (unsigned char*)realloc(req->buffer,req->buflen + CHUNK_SIZE);
req->buflen += CHUNK_SIZE;
}
memcpy(&req->buffer[req->len], contents, rLen);
req->len += rLen;
req->buffer[req->len] = 0;
return rLen;
}
The above code works fine for the Success 200 OK Requests. It reads the JSON Response just fine. However, when I get a 500 Internal Server error, it does not read the JSON Error response that comes along with it. How do I read the JSON response in this scenario?
| By setting the CURLOPT_FAILONERROR option to TRUE, you are telling curl_easy_perform() to fail immediately with CURLE_HTTP_RETURNED_ERROR on any HTTP response >= 400. It will not call the CURLOPT_WRITEFUNCTION callback, as it will simply close the connection and not even attempt to read the rest of the response.
To get the response data you want, simply remove the CURLOPT_FAILONERROR option. Curl's default behavior is to deliver the response data to you regardless of the HTTP response code. In which case, curl_easy_perform() will return CURLE_OK, and you can then retrieve the response code using curl_easy_getinfo(CURLINFO_RESPONSE_CODE) to check if the HTTP request was successful or not.
On a side note, since the code shown is written in C++, I would strongly advise you NOT to use a dynamic char[] buffer for get_request::buffer. Not only because you are not handling malloc()/realloc() failures at all, but also because manual memory management should be avoided in C++ in general. Use std::string or std::vector<char> instead, in which case you can eliminate get_request in this code altogether, eg:
INT CCurlHTTP::HTTPSPost(const CString& endPointUrl, const CString& urlparam,const CString& cookie){
...
std::string resp;
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &resp);
...
//curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L);
res = curl_easy_perform(curl);
if (res != CURLE_OK)
{
/* if errors have occured, tell us what's wrong with 'result'*/
m_response.Format("%s", curl_easy_strerror(res));
curl_easy_cleanup(curl);
return res;
}
m_response = resp.c_str();
m_errDescription = errbuf;
len = resp.size();
buflen = resp.capacity();
curl_easy_cleanup(curl);
return res;
}
size_t CCurlHTTP::CurlWrite_CallbackFunc_String(void *contents, size_t size, size_t nmemb, void *userdata)
{
size_t rLen = size * nmemb;
static_cast<std::string*>(userdata)->append(static_cast<char*>(contents), rLen);
return rLen;
}
|
71,613,207 | 71,613,423 | Why does Dev C++ stop working before running the whole code in finding highest and lowest number between 10 elements? | This is the code that I made to find the highest and lowest number between 10 elements:
#include <iostream>
using namespace std;
#define SIZE 10
void acceptNumbers (int Numbers[SIZE]);
int High(int Numbers[SIZE]);
int Low(int Numbers[SIZE]);
void acceptNumbers(int Numbers[SIZE])
{int i, *max, *min;
for (i=0; i<SIZE; i++)
cin>>Numbers[i];
max = Numbers;
min = Numbers;
}
int High(int Numbers[SIZE])
{int i, *max;
for (i = 0; i < SIZE; i++)
{
if (*(Numbers+i) > *max)
max = (Numbers+i);
}
cout<<*max;
}
int Low(int Numbers[SIZE])
{int i, *min;
for (i = 0; i < SIZE; i++)
{
if (*(Numbers+i) < *min)
min = (Numbers+i);
}
cout<<*min;
}
int main()
{
int arr[SIZE];
cout<<"Enter Elements: \n";
acceptNumbers(arr);
cout<<"Highest Number: ";
High(arr);
cout<<endl;
cout<<"Lowest Number: ";
Low(arr);
cout<<endl;
}
On my PC, it doesn't run the whole program. It just stops right when it reaches the code for finding the highest and lowest number
This is homework I'm working on and I can't use any shortcuts and whatnots since there is a required line of code to be used that is given. And so I tried running this code on another PC and it worked just fine:
I also tried running it on online c++ compiler and it still doesn't work. I can't find solution online so this is my last resort please help me
| Your code exhibits undefined behavior.
In each of your functions, you are declaring min and max as local variables. Thus, when you initialize min/max in acceptNumbers(), they are only initialized in that function. You are not initializing the min/max variables in High()/Low() at all. Your code is crashing when those functions try to dereference those uninitialized variables.
Also, your High()/Low() functions have non-void return types, but are not actually return'ing any values.
Try this instead:
#include <iostream>
using namespace std;
#define SIZE 10
void acceptNumbers (int Numbers[SIZE]);
int High(int Numbers[SIZE]);
int Low(int Numbers[SIZE]);
void acceptNumbers(int Numbers[SIZE])
{
for (int i=0; i<SIZE; i++)
cin>>Numbers[i];
}
int High(int Numbers[SIZE])
{
int *max = Numbers;
for (int i = 1; i < SIZE; i++)
{
if (*(Numbers+i) > *max)
max = (Numbers+i);
}
return *max;
}
int Low(int Numbers[SIZE])
{
int *min = Numbers;
for (int i = 1; i < SIZE; i++)
{
if (*(Numbers+i) < *min)
min = (Numbers+i);
}
return *min;
}
int main()
{
int arr[SIZE];
cout<<"Enter Elements: \n";
acceptNumbers(arr);
cout<<"Highest Number: ";
cout<<High(arr);
cout<<endl;
cout<<"Lowest Number: ";
cout<<Low(arr);
cout<<endl;
}
|
71,613,938 | 71,614,488 | How to print all nodes at the same level in one group? | I am working on the LeetCode problem 102. Binary Tree Level Order Traversal:
Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).
I want to print all nodes at a given level in one group. I have found a way to do this in this answer on Stack Overflow.
But this answer uses recursion while my code does not. I would like to know where I am going wrong in my approach.
For example given input : [1,2,3,4,null,null,5]
My output : [[1],[4],[5]]
Expected output: [[1],[2,3],[4,5]]
#include <iostream>
#include <vector>
#include <map>
#include <deque>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
vector<vector<int>> levelOrder(TreeNode *root) {
deque<TreeNode *> queue;
map<int, vector<int>> myMap;
vector<vector<int>> retvector;
vector<int> addvector;
int level = 0;
if (root != nullptr) {
queue.push_back(root);
addvector.push_back(root->val);
//retvector.push_back(addvector);
myMap.insert(pair<int, vector<int>>(level, addvector));
}
while (!queue.empty()) {
TreeNode *ptr = queue.front();
queue.pop_front();
addvector.clear();
if (ptr->left != nullptr) {
addvector.push_back(ptr->left->val);
queue.push_back(ptr->left);
}
if (ptr->right != nullptr) {
addvector.push_back(ptr->right->val);
queue.push_back(ptr->right);
}
if (!addvector.empty()) {
//retvector.push_back(addvector);
myMap.insert(pair<int, vector<int>>(level, addvector));
level++;
addvector.clear();
}
}
for (int i = 0; i < level; i++) {
retvector.push_back(myMap[i]);
}
return retvector;
}
int main() {
TreeNode root, left1, left2, right1, right2;
left2 = TreeNode(4);
left1 = TreeNode(2, &left2, nullptr);
right2 = TreeNode(5);
right1 = TreeNode(3, nullptr, &right2);
root = TreeNode(1, &left1, &right1);
vector<vector<int>> v = levelOrder(&root);
for (auto &i: v) {
for (auto &j: i)
cout << j << " ";
cout << endl;
}
}
| You don't need a map, nor a queue, nor a level number.
Instead alternate with 2 vectors that have the nodes of 2 consecutive levels.
Also, in your logic, addvector can at the most have 2 entries, which shows why this approach cannot work.
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<TreeNode *> parentLevel, childLevel;
vector<vector<int>> retvector;
vector<int> addvector;
if (root != nullptr) {
parentLevel.push_back(root);
}
while (!parentLevel.empty()) {
addvector.clear();
childLevel.clear();
for (auto parent : parentLevel) {
addvector.push_back(parent->val);
if (parent->left != nullptr) {
childLevel.push_back(parent->left);
}
if (parent->right != nullptr) {
childLevel.push_back(parent->right);
}
}
retvector.push_back(addvector);
parentLevel = childLevel;
}
return retvector;
}
};
Explanation
Let's take the example tree:
1
/ \
2 3
/ \
4 5
parentLevel starts out with [1] (actually the TreeNode having 1).
Then the outer loop starts, where the inner loop will take every node in that parentLevel vector and put its value in addvector. So in this iteration, addvector will be [1].
In the same process all direct children of these nodes are collected in childLevel, so there we will have the nodes [2, 3].
The inner loop then finishes, and addvector is appended to the result. So retvector will be [[1]].
Now the same should happen with the children, so we promote childLevel to be the parentLevel for the next iteration of the outer loop.
And so we start the next iteration of the outer loop with parentLevel having [2, 3]. Again, the corresponding values get pushed to an empty addvector, which will then have [2, 3]. At the same time childLevel gets populated with the child nodes [4, 5].
The second iteration of the outer loop will end by extending retvector to [[1],[2,3]], and so the process continues level by level...
|
71,614,144 | 71,614,216 | C++ "const std::any &" more copy constructor call than without std::any | #include <iostream>
#include <vector>
#include <string>
#include <any>
using namespace std;
template <typename T>
class MyVector {
private:
int n;
T* data;
public:
MyVector() {
n = 0;
data = nullptr;
cout << "MyVector default constructor\n";
}
MyVector(int _n) {
n = _n;
data = new T[n];
cout << "MyVector param constructor\n";
}
MyVector(const MyVector& other) {
n = other.n;
data = new T[n];
for (int i=0; i<n; i++) data[i] = other.data[i];
cout << "MyVector copy constructor\n";
}
MyVector(MyVector&& other) {
n = other.n;
data = other.data;
other.n = 0;
other.data = nullptr;
cout << "MyVector move constructor\n";
}
MyVector& operator = (const MyVector& other) {
if (this != &other) {
n = other.n;
delete[] data;
data = new T[n];
for (int i=0; i<n; i++) data[i] = other.data[i];
}
cout << "MyVector copy assigment\n";
return *this;
}
MyVector& operator = (MyVector&& other) {
if (this != &other) {
n = other.n;
delete[] data;
data = other.data;
other.n = 0;
other.data = nullptr;
}
cout << "MyVector move assigment\n";
return *this;
}
~MyVector() {
delete[] data;
cout << "MyVector destructor: size = " << n << "\n";
}
int size() {
return n;
}
};
template <typename T>
any func_any(const any &vec) {
cout << "\nBefore func_any assignment\n";
MyVector<T> res = any_cast<MyVector<T>>(vec); // I want res to const reference MyVector<T> vec, not copy
cout << "\nAfter func_any assignment\n";
return res;
}
template <typename T>
MyVector<T> func(const MyVector<T> &vec) {
cout << "\nBefore func assignment\n";
MyVector<T> res = vec;
cout << "\nAfter func assignment\n";
return res;
}
int main()
{
MyVector<int> a(5);
MyVector<int> a2(6);
cout << "-----------";
cout << "\nBefore func_any call\n";
auto b = func_any<int>(a);
cout << "\nAfter func_any call\n";
cout << "--------------";
cout << "\nBefore func call\n";
auto c = func<int>(a2);
cout << "\nAfter func call\n";
cout << "-----------------";
cout << "\nBefore exit\n";
return 0;
}
I am trying to make a function-executor base class with Python like interface (use std::any as input and output). In each child class, the actual type input type is known at compile time, so I wish to cast std::any to a specific type. In the example above I just use a function to make it simple.
However, the function with std::any call constructors and destructors many times more than the function without. The above program give the following input:
MyVector param constructor
MyVector param constructor
-----------
Before func_any call
MyVector copy constructor
Before func_any assignment
MyVector copy constructor
After func_any assignment
MyVector move constructor
MyVector destructor: size = 0
MyVector destructor: size = 5
After func_any call
--------------
Before func call
Before func assignment
MyVector copy constructor
After func assignment
After func call
-----------------
Before exit
MyVector destructor: size = 6
MyVector destructor: size = 5
MyVector destructor: size = 6
MyVector destructor: size = 5
So the function version that uses std::any needs 3 constructor + 2 destructor calls. While the normal version needs just 1 constructor call. I assume the return statement in func is copy elision.
How can I improve this? The most important thing I need is below, if it's impossible with std::any then please provide a possible solution with std::variant.
MyVector<T> res = any_cast<MyVector<T>>(vec); // I want res to const reference MyVector<T> vec, not copy
| An object needs to be copied into the std::any, so trying to call func_any<int>(a) will copy a.
You can instead hold a std::reference_wrapper<T> or a T* pointer in the std::any:
template <typename T>
any func_any(const any &vec) {
cout << "\nBefore func_any assignment\n";
MyVector<T> res = any_cast<std::reference_wrapper<const MyVector<T>>>(vec);
cout << "\nAfter func_any assignment\n";
return res;
}
auto b = func_any<int>(std::cref(a));
Since you already know what types are actually being used, you might be better off making your base class use void* as input and output.
You can also any_cast to a reference type:
const MyVector<T>& res = std::any_cast<const MyVector<T>&>(vec)
This will be a reference to the value held in vec (so no constructors involved). This will not reduce the overall number of copies, but it will get rid of one move due to NRVO.
|
71,614,279 | 71,686,064 | Is it safe to change the reactor's state using the async API without manual synchronization? | Hey
I'm using gRPC with the async API. That requires constructing reactors based on classes like ClientBidiReactor or ServerBidiReactor
If I understand correctly, the gRPC works like this: It takes threads from some thread pool, and using these threads it executes certain methods of the reactors that are being used.
The problem
Now, the problem is when the reactors become stateful. I know that the methods of a single reactor will most probably be executed sequentially, but they may be run from different threads, is this correct? If so, then is it possible that we may encounter a problem described for instance here?
Long story short, if we have an unsynchronized state in such circumstances, is it possible that one thread will update the state, then a next method from the reactor will be executed from a different thread and it will see the not-updated value because the state's new value has not been flushed to the main memory yet?
Honestly, I'm a little confused about this. In the grpc examples here and here this doesn't seem to be addressed (the mutex is for a different purpose there and the values are not atomic).
I used/linked examples for the bidi reactors but this refers to all types of reactors.
Conclusion / questions
There are basically a couple of questions from me at this point:
Are the concerns valid here and do I properly understand everything or did I miss something? Does the problem exist?
Do we need to manually synchronize reactors' state or is it handled by the library somehow(I mean is flushing to the main memory handled)?
Are the library authors aware of this? Did they keep this in mind while they were coding examples I linked?
Thank you in advance for any help, all the best!
| You're right that the examples don't showcase this very well, there's some room for improvement. The operation-completion reaction methods (OnReadInitialMetadataDone, OnReadDone, OnWriteDone, ...) can be called concurrently from different threads owned by the gRPC library, so if your code accesses any shared state, you'll want to coordinate that yourself (via synchronization, lock-free types, etc). In practice, I'm not sure how often it happens, or which callbacks are more likely to overlap.
The original callback API spec says a bit more about this, under a "Thread safety" clause: L67: C++ callback-based asynchronous API. The same is reiterated a few places in the callback implementation code itself - client_callback.h#L234-236 for example.
|
71,615,353 | 71,615,602 | C++ template specialization changes constexpr rules? | I am using g++ (GCC) 11.2.0.
The following piece of code
#include <vector>
#include <iostream>
template<int size>
constexpr std::vector<int> get_vector() {
return std::vector<int> (size);
}
int main() {
std::cout << get_vector<5>().size() << std::endl;
}
compiles successfully and outputs 5 when executed. Just as I expected.
However, if I add specialization
#include <vector>
#include <iostream>
template<int size>
constexpr std::vector<int> get_vector() {
return std::vector<int> (size);
}
template<>
constexpr std::vector<int> get_vector<2>() {
return std::vector<int> (2);
}
int main() {
std::cout << get_vector<5>().size() << std::endl;
}
it fails to compile and produces the error
another.cpp: In function ‘constexpr std::vector<int> get_vector() [with int size = 2]’:
another.cpp:10:28: error: invalid return type ‘std::vector<int>’ of ‘constexpr’ function ‘constexpr std::vector<int> get_vector() [with int size = 2]’
10 | constexpr std::vector<int> get_vector<2>() {
| ^~~~~~~~~~~~~
In file included from /usr/include/c++/11.2.0/vector:67,
from another.cpp:1:
/usr/include/c++/11.2.0/bits/stl_vector.h:389:11: note: ‘std::vector<int>’ is not literal because:
389 | class vector : protected _Vector_base<_Tp, _Alloc>
| ^~~~~~
/usr/include/c++/11.2.0/bits/stl_vector.h:389:11: note: ‘std::vector<int>’ has a non-trivial destructor
Why does it happen?
| If you take a look at compiler support you will find out that gcc supports constexpr std::vector from version 12. As you tell us you use gcc 11.2 it simply is not implemented in the library.
You can see it working as expected on godbolt with trunk versions of gcc and clang. For gcc it will be part of gcc 12.x versions.
|
71,615,362 | 71,661,012 | terminate called after throwing an instance of 'std::bad_alloc' during initialization | header
struct Date
{
int year;
int month;
int day;
};
enum Department
{
Game,
FrontEnd,
Backend,
Operation,
HumanResource
};
class Employee
{
protected:
int id;
string name;
char gender;
Date entry_date;
string post;
Department dept;
int salary;
public:
Employee();
Employee(int id, const string& name, char gender, const Date& entry_date, string post, Department dept);
virtual ~Employee();
};
class Manager : public Employee
{
private:
int num_staff;
Employee** staffs;
public:
Manager();
Manager(int id, const string& name, char gender, const Date& entry_date, Department dept);
~Manager();
};
cpp
Manager::Manager(int id, const string &name, char gender, const Date &entry_date, Department dept) : Employee(id, name, gender, entry_date, post, dept), num_staff(0), staffs(NULL) {}
The program crashes here with complaint terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Manager *pm1 = new Manager(101, "Bruce Wayne", 'M', Date{2016, 05, 10}, HumanResource);
I've spent tons of time solving it but failed.
Anyone can help? thx in advance.
Update:
Employee::Employee(int id, const string& name, char gender, const Date& entry_date, string post, Department dept)
: id(id), name(name), gender(gender), entry_date(entry_date), post(post), dept(dept){};
| The problem is likely because you have undefined behavior.
With your Manager constructor definition:
Manager::Manager(int id, const string &name, char gender, const Date &entry_date, Department dept)
: Employee(id, name, gender, entry_date, post, dept), num_staff(0), staffs(NULL) {}
you are first initializing the parent Employee class part, which is good. But when you do that, you pass the uninitilized post member variable as an argument to the Employee constructor.
Because post is uninitialized that will lead to the above mentioned undefined behavior.
This is exactly like initializing any variable with itself:
std::string post = post; // Makes no sense, and leads to UB
As for how to solve this, that really depends on your requirements. A simple solution would be to pass an empty string instead:
Manager::Manager(int id, const string &name, char gender, const Date &entry_date, Department dept)
: Employee(id, name, gender, entry_date, "", dept), num_staff(0), staffs(NULL) {}
If you enable more and extra warnings (for GCC and Clang I always recommend at least -Wall and -Wextra, for MSVC /W4) and treat them as errors you might even get a warning about using the uninitialized member variable.
I also suggest you make all member variables private.
|
71,615,456 | 71,615,918 | ofstream::write writes zeros for part of the file | I would like to write the contents of a vector< int> to a binary file. This current program is supposed to save the integers 0 to 99 in the file, but it only saves the first 26 integers.
std::vector<int> vector;
for (int i = 0; i < 100; i++) vector.push_back(i);
std::ofstream outfile("file.bin", std::ios::binary);
outfile.write(reinterpret_cast<const char *>(&vector[0]), sizeof(int)*vector.size());
outfile.close();
std::ifstream file("file.bin");
file.seekg(0, std::ios_base::end);
std::size_t size = file.tellg();
file.seekg(0, std::ios_base::beg);
std::vector<int> vectorRead(size / sizeof(int));
file.read((char*)&vectorRead[0], size);
file.close();
for (int i = 0; i < vector.size(); i++) {
if (vector.at(i) != vectorRead.at(i)) std::cout << vector.at(i) << ", " << vectorRead.at(i) << std::endl;
}
The output of the code is:
26, 0
27, 0
...
99, 0
How can I write the whole vector to a file?
| As user253751 and Marek R pointed out, the issue was I was not reading in binary mode.
Before:
std::ifstream file("file.bin");
Corrected:
std::ifstream file("file.bin", std::ios::binary);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.