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, there... | 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\... |
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:3... | 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 GetSt... |
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.... |
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'... | (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... |
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 by... | 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.
He... |
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(cons... | 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 tha... |
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;
her... | 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 e... |
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 adv... | 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 th... | 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... |
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:
hdGetD... | 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 progr... | 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 wh... |
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... | 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... |
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 (c... | 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 ... |
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 t... | 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 compile... |
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 solv... | 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 inst... |
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;
mess... | 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 wil... | 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 ar... |
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 n... | 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 sam... |
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)
{
swi... | 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,... |
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, wh... | 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(){
a... |
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 <str... | 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 doub... |
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... | 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_prope... |
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:
... |
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 ... |
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.tx... | 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 git... |
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 : ... | 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:
... |
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(VE... | 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 o... |
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 on... | 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}{};
... |
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())
{
ca... | 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 = sceneE... |
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... | 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>
... |
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 AcceptC... | 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";
_ht... |
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... | 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_arr... |
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... | 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;
... | 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<D... |
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** azC... | 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_b... |
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;
in... | 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:
Matri... |
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... | 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... |
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* re... | 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... | 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)
{
... |
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 = {... | 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_at... |
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 ... | 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(d... |
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 <... | 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... |
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;}
... | 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>, KlassCo... |
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::funct... | 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:
#includ... |
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 ... | 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 ch... |
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 {};... | 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 instan... |
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... | 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... |
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
... |
_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_add... |
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());
... | 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 b... |
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... | 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(s... |
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>,st... | 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.firs... |
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 ... | 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... |
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 = (002400AB1... | 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("\... |
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,
#incl... | 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 yo... |
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&Expire... | 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, whe... |
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_uni... | 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:
... | 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 ... |
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 ... | 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 w... |
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):
clas... | 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... |
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... | 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 ta... |
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) {
... | 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 w... |
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++;... |
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(declva... | 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,
typ... |
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 nu... | 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 ... |
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 el... | 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)
{... |
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::r... | 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("re... |
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 th... |
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 outpu... |
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 ... |
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>... | 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:
... |
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)
{
... | 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... |
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, t... | "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"
By... |
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;
... | 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 t... |
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::Vect... | 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 a... |
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 ... | 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 na... |
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::a... | 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'... |
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;
... | 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]){... |
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 ... |
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 c... |
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 ... | 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.
Sin... |
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 ... | 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... |
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 < action... | 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])
s... |
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... | 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... | 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... |
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;
... | 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::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... |
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;
... | 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 reas... |
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 EXPERIMENT... | 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,... |
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 =... | 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 ... |
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 ... | 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 ... |
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 fun... | 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.
Fi... | 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(...) { ... |
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){
... | 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... |
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<SI... | 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 f... |
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 Stac... | 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) {
... |
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 =... | 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::referen... |
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.
Th... | 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... |
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 execu... | 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 d... | 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 ... |
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);
out... | 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.