question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
70,012,280 | 70,171,560 | How to pass a vector by reference in pybind11 & c++ | I try to pass vector/array by reference from python through pybind11 to a C++ library. The C++ library may fill in data. After the call to C++, I hope the python side will get the data.
Here is the simplified C++ code:
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
class Setup
{
p... | Figured out a way:
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include "Calculator.h" // where run_calculator is
namespace py = pybind11;
// wrap c++ function with Numpy array IO
int wrapper(const std::string& input_file, py::array_t<double>& in_results) {
if (in_results... |
70,012,617 | 70,013,948 | Get a parameter pack from variable argument | I'm trying to get a parameter pack from the list of arguments passed to a macro.
template<std::size_t N, class T, class... Ts> ... | Something along these lines, perhaps (not tested):
template <std::size_t N, typename Tuple, size_t... Is>
constexpr bool myFunction1(const char (&fmt)[N], std::index_sequence<Is...>) {
return myFunction<N, std::tuple_element_t<Is, Tuple>...>(fmt);
}
template <std::size_t N, typename Tuple>
constexpr bool myFunction2... |
70,012,648 | 70,023,729 | Recovering pthread_cond_t & pthread_mutex_t after process termination | Hey there!
I have already looked up similiar problems here, but didn't arrive at a final solution.
In my application, I have two processes running concurrently that need to be synchronized via shared-memory. Currently I'm using a pthread_mutex_t & pthread_cond_t for that purpose which are put into shared-memory.
This i... | As far as I am aware, the POSIX API does not define mechanisms sufficient to make your Poller wholly robust against all process-failure scenarios. But you might achieve a situation you consider an improvement by using a SysV semaphore in place of the condition variable and mutex. Here's an outline:
a semaphore can_p... |
70,012,655 | 70,012,701 | How to include multiple header directories in g++ without many -I flags? | I have a project with multiple subfolders under my include folder. For instance:
include/
|-- foo/
|-- foo_header1.h
\-- foo_header2.h
|-- bar/
|-- bar_header1.h
\-- bar_header2.h
|-- root_header1.h
\-- root_header2.h
src/
|-- foo/
|-- foo_source1.cpp
\-- foo_source2.cpp
|-- bar/
|-- bar_sou... | You could just add "-Iinclude" to g++ and include the headers as following
#include <foo/foo_header1.h>
#include <bar/bar_header2.h>
This also eliminates the need to have the foo/bar prefix in the header filename. After renaming, the above simplifies to follows
#include <foo/header1.h>
#include <bar/header2.h>
|
70,012,690 | 70,012,787 | how convert dct = {int : [int, list()]] from Python to C++? | I am re-writing this data structure in Python to c ++.
Writing this code in Python is easy for me, but I have trouble with C ++.
I need to change the "step" in my value and find my pairs through the keys.
In Python, I wrote:
step = 0
dct = {1: [step, list()]}
In c ++, I write like this, but I can not find my pairs wit... | Here's a rough C++11 equivalent to the posted Python code:
#include <iostream>
#include <map>
#include <utility> // for std::pair
#include <vector>
int main(int argc, char ** argv)
{
std::map<int, std::pair<int, std::vector<int> > > dct;
int step = 0;
// insert some empty pairs into (dct)
for (int i=1; ... |
70,012,760 | 70,013,068 | Calling another constructor C++ | I have something like this:
Foo::Foo(vector<item> items) {
// do stuff
}
I'd like to call this constructor from another constructor:
Foo::Foo(char* buf, size_t num) {
// unpack the bytes into vector
Foo::Foo(items);
}
Is this possible in C++ 17+? I know that you can call another constructor using an init... | Simply call a delegating constructor. Use a helper function to construct the vector<item>.
namespace {
vector<item> helper(char*buff, size_t num)
{
/* your implementation for re-packaging the data here */
}
}
Foo::Foo(char*buff, size_t num)
: Foo(helper(buff,num))
{}
|
70,012,841 | 70,013,373 | How are objects from derived classes constructed in C++ | Im not a C++ pro, i've done mostly Java and C#. A teacher said something that confused me today. I've tried to validate the info by doing some research, but i ended up even more confused.
Lets say i have class A and class B. Class A is the base class and B is derived from A.
Now i already know that when an object of cl... | According to http://www.vishalchovatiya.com/memory-layout-of-cpp-object/#Layout_of_C_Object_With_Inheritance
These two classes:
class X {
int x;
string str;
public:
X() {}
virtual ~X() {}
virtual void printAll() {}
};
class Y : public X {
int y;
public:
Y() {}
~Y() {}
void p... |
70,013,032 | 70,014,400 | C vs C++ why is this macro not expanded to a constant? | I am using gcc/g++. The below code compiles fine with gcc -S test.c, however with g++ -S test.cpp I get error: requested alignment is not an integer constant. If I look at the preprocessor output for both it looks identical. So my question is why isn't ALIGN_BYTES being evaluated to the constant 64 by the preprocessor ... | It is not a macro expansion issue. The macro is not expanded to a constant in either C or C++, here. The preprocessor does not do arithmetic, so it simply generates the expression 512 / 8 which isn't a constant, but which the compiler should definitely be able to reduce to one.
The preprocessor generates the same code ... |
70,013,098 | 70,013,155 | C++ template function explicit specialization with multiple template types | I'd like to write a templatized function with two template types: one a bool and one a typename, and I'd like to specialize on the typename.
eg, this is what I want, but specialized on just a couple types for T:
template<bool b, typename T>
void foo(T val)
{
// do different stuff based on b and type of T.
}
without... | template<bool B, typename T>
void foo(T const&)
{
static_assert(false, "not implemented");
}
template<bool B>
void foo(short)
{
printf("it's a short!\n");
}
However, this is not really specialisation, but overloading, which is completely appropriate. In fact, you could omit the general case.
|
70,014,236 | 70,014,369 | Can I create a function which takes any number of arguments of the same type? | So basically, I want to create a function like this:
total_sum(1, 2, 5, 4, 2) // return 14
total_sum(5, 6, 2) // return 13
One way that I can use is ellipsis, something like this:
#include <cstdarg>
int total_sum(int count, ...)
{
int sum{0};
va_list list;
va_start(list, count);
for (int arg{0}; arg < ... | Use C++17 fold expression:
template<class... Args>
constexpr auto total_sum(const Args&... args) {
return (args + ... + 0);
}
static_assert(total_sum(1, 2, 5, 4, 2) == 14);
static_assert(total_sum(3, 5, 6, 2) == 16);
|
70,015,322 | 70,015,821 | Efficient lookup on fixed collection of vectors | I have a fixed number (5) of vectors of structs (structs are inserted at runtime, a number can vary).
And i have a enum class which is used as a key for lookup. E.g.
enum class CountryCode {
kUS,
// ...other 4
};
const std::vector<SomeStruct>& get_by_country_code(CountryCode cc);
I can use std::unordered_map<Cou... |
What would be the most efficient way to store these 5 vectors and do a lookup by the enum value?
An array. The default values of enum are 0,1,... which fit perfectly as the indices of an array.
Only small hurdle is that enum classes must be explicitly converted to the underlying integer.
does array of vectors consid... |
70,015,481 | 70,015,690 | How do I count leading zeros on both mac M1 and x86-64? | Originally I tried lzcnt but that doesn't seem to work on a mac. I'm working with someone who is using the apple M1 CPU which is ARM64v8.4
In this arm document which list ARM 8 it appears clz supports using 0
CLZ Xd, Xm
Count Leading Zeros (64-bit): sets Xd to the number of binary zeros at the most significant end of ... | If C++20 features are available, std::countl_zero<T> solves the problem, and it's up to compiler devs to implement it in a way that compiles efficiently even for an input of zero. (In which case it's required to return the number of value-bits in the integer type you passed, unlike __builtin_clzll)
That's great in the... |
70,015,603 | 70,024,650 | Overloading a parent member function without ref-qualifier with a child member function with ref-qualifier in C++ | In C++ one cannot overload in one class a member function with ref-qualifier with a member function without ref-qualifier. But at the same time it is possible to inherit one member function from a parent class and overload it in a child class as in the example:
struct A {
void f() {}
//void f() & {} //overload ... | GCC is correct to accept this, but the situation changed recently. The current phrasing is that a using-declaration in a class ignores (base-class) declarations that would be ambiguous (in a sense that is more strict than for overload resolution, partly because there is no argument list yet) with other declarations in... |
70,015,825 | 70,016,028 | Copy constructor not used during pass by value in C++ | class A {
int x;
public:
A() { cout << "\t A() \n"; }
A(int _x): x(_x) { cout << "\t A(int) \n"; }
A(const A& other): x(other.x) { cout << "\t A(const A&) \n"; }
A(A&& other): x(std::move(other.x)) { cout << "\t A(A&&) \n"; }
A& operator=(const A& other) { x = other.x; cout << "\t operator=() \n... |
For func_1(A(5));, I expected the output to be A(int) \n A(const A&) \n func_1 because we are passing A(5) by value so the passed object should be copied to the parameter.
You expected wrongly. A(5) is a prvalue of the same type, so the temporary object will not be materialised, and its initialiser is instead used to... |
70,016,007 | 70,019,500 | Inputting multiple integers from lines into a 2d array c++ | I initialized a 2d array and am trying to fill the array respectively. My issue is I cannot get the 2d array to update.
Input is:
0 1 9
0 4 8
1 5 5
2 0 6
3 2 2
1 3 1
2 1 3
4 3 7
5 3 4
My code is:
stringstream s(input);
while(count != numV){
getline(cin, input);
while(s >> u >> v >> weight)
... | Note that you don't have to use arrays for storing the information(like int values) in 2D manner because you can also use dynamically sized containers like std::vector as shown below. The advantage of using std::vector is that you don't have to know the number of rows and columns beforehand in your input file. So you d... |
70,016,284 | 70,023,063 | Make script in Unity to Unreal | Im new to Unreal. I tried to follow the tutorial into making A* pathfinding:
https://www.youtube.com/watch?v=nhiFx28e7JY&t=1252s&ab_channel=SebastianLague
I don't really know how to change the script made in Unity to Unreal.
UnityScript
public class Node {
public bool walkable;
public Vector3 worldPosition... | I guess you cannot create constructors with parameters in such way in UE4. Try define a default constructor.
If you really need to pass parameters to it - check ObjectInitializer constructor here: https://ikrima.dev/ue4guide/engine-programming/uobjects/new-uobject-allocation-flow/
|
70,016,304 | 70,016,391 | In TCP/IP Socket send, Send data still remains in OS Memory | I created a simple chatting client program to communicate with the server.
After the client sent data to the server using the send() function, the data was initialized to memset (buf, 0x00, sizeof(buf)), but after searching OS memory through Dumpit, there are still traces of data sent somewhere.
How can i clear send da... | Your binary program code still contains the string literal thisishell. Most likely, that's what you're seeing, because your other string literals like "connect() error!" can be seen right above it in memory.
|
70,016,345 | 70,018,021 | C# pass struct with interface to unmanaged C++ | I have an unmanaged C++ DLL and some C# code that uses [dllimport] to access it. I have a struct that derives from an interface (say Dog : Animal) and on the C++ side I have a class that derives from an abstract class (say Dog : public Animal). I want to have a C++ function that somehow takes in Animal as a parameter, ... | One option would be to use c++/cli to define your object model. That would make it usable by both c# and c++/cli code.
P/invoke essentially does method calls the same way C does. This means they are highly compatible between different languages, but also that they do not support things like polymorphism.
A struct is es... |
70,016,357 | 70,016,734 | Can you detect template member of a class using std::is_detected | I use std::experimental::is_detected to determine if class has certain member functions:
#include <utility>
#include <experimental/type_traits>
template<typename USC>
class Descriptor
{
private:
template<class T>
using has_member1_t =
decltype(std::declval<T>().member1(std::declval<std::vector<char> ... | If c++20 is an option, this kind of code has been made a lot easier to both read and write by using concepts.
#include <iostream>
#include <vector>
struct Foo {
int member1(int) {
return 1;
}
template <typename T>
double member2(std::vector<T>) {
return 2.5;
}
};
struct Bar {};
t... |
70,016,562 | 70,016,752 | c++ frequently open and close iostream will affect IO performance? | If I want to write into a file frequently like the function of logging, which is the better way?
when I need to write, open iostream and close when it is done
void log(const string& s){
iostream ios(log_path);
ios << s;
ios.close();
}
void main(){
while (need_to_log) {
log(some_string);
}
... | Yes, there will probably be a significant difference – if logging is what your application is spending most of its time on.
To open and close files requires a system call. To close a file, in particular, requires the internal buffer of the ostream to be flushed, which requires another system call, and possibly also wri... |
70,016,665 | 70,016,740 | Doesn't instance call function to variadic template | I have write function to deduce how much parameters I forward to function. Something like this:
template<typename Arg>
constexpr size_t get_init_size(Arg arg, size_t i) {
return i + 1;
}
template<typename T, typename ... Args>
constexpr size_t get_init_size(T First_arg, Args ... args, size_t i) {
return get_in... | You don't need to write a recursive template function to do this, you can use the sizeof...() operator on the type of the parameter pack to get the number of elements directly:
template<typename... Args>
constexpr std::size_t get_init_size(Args&&...) {
return sizeof...(Args);
}
See it in action here.
The reason wh... |
70,016,727 | 70,045,895 | Signal handlers of C++ application within a docker container are not working | I have the following C++ code:
#include <signal>
#include <iostream>
void sig_handler(int signo, siginfo_t *info, void *_ctx) {
cout << "HANDLE AND RESET!!" << endl;
// try to forward the signal.
raise(info->si_signo);
// terminate the process immediately.
puts("watf? exit");
_exit(EXI... | I've been there before. It's a real struggle especially when things work on your device but it's not on other devices.
I'll write the steps I did for my own problem and maybe it can light up some solutions for you.
Things were working perfectly on macOS and I had to compare the docker engine versions between my device ... |
70,016,814 | 70,018,399 | Can two different processes communicate with each other using Windows events in WINAPI? | I am in the midst of developing two applications that communicate using a file. These applications are running on the same machine. To be clear, I have a writer.exe and a reader.exe executables.
The writer.exe constantly writes a random integer to a common file "some_file.bin" and closes the file. It repeats the same p... | Yes, it is possible. When one process creates a handle to an Event object, you have the option of assigning a name to that object in the kernel. The other process can then create/open its own handle to that Event object using the same name.
Note that to accomplish what you want, you actually would need 2 Events, eg:
wr... |
70,016,827 | 70,016,942 | How do I create two classes that refer to each other in different header files? | I have two classes in two different header files. I, as advised in another topic with a similar question, declared class A before class B and declared class B before class A. But it did not help. Seller still can't see the Organization
Seller.h
#ifndef OOP_3_SELLER_H
#define OOP_3_SELLER_H
#include "Organization.h"
cla... | Since you've forward declared the class Organization in Seller.h there is no need to write #include "Organisation.h". Similarly, in Organization.h" since you've forward declared class Seller there is no need to write #include "Seller.h". Also, always take into account cyclic dependency like in your program Organization... |
70,016,851 | 70,016,973 | Thread Sanitizer - How to interpret the Read vs Previous Write warning | I am running a program with thread sanitizers and wonder how to interpret the following warning:
==================
WARNING: ThreadSanitizer: data race (pid=2788668)
Read of size 4 at 0x7f7eefc4e298 by main thread:
[Stacktrace follows...]
Previous write of size 8 at 0x7f7eefc4e298 by thread T27:
[Stacktrace follows... | The warning is a real error (unless it is a false positive).
Thread T27 wrote 8 bytes to address 0x7f7eefc4e298 and main thread read the first 4 bytes of that later without locking (as far as the sanitizer could tell). This is a race condition and undefined behaviour.
In other words, access to 0x7f7eefc4e298 is not pro... |
70,017,743 | 70,021,594 | Pass a template to an async function | I'm trying to run an async function passing to it a function f to execute and a template function f0 as attribute.
This is the function that I create through a template
DivideVerticesInThreads<0> f0(g, {}, {});
The template is
template <int NSegments, int Segment> struct SegmentVertices {
std::hash<Graph::vertex_descr... | I agree somewhat with the commenters, that the problem exposition is needlessly unclear.¹
However, I think I know what's happening is due to a choice I made when presenting this sample code to you in an earlier answer.
It appears I focused on efficiency and it landed you with c++ challenges you didn't know how to handl... |
70,018,040 | 70,018,361 | Template function for random number generation (static assertion failed) | I created a simple template function to generate a random number of type T (I need int or float) in range [low, high) as follows:
template <typename T>
T randm(T low, T high)
{
static std::random_device seeder;
static std::mt19937 gen(seeder());
std::uniform_real_distribution<T> dis(low, high);
return d... | For integral types, there is std::uniform_int_distribution. You have to apply something with if constexpr or to use SFNIAE (with type traits) to handle floating points and integrals separately. Btw. there is a note in std::uniform_real_distribution: The effect is undefined if this is not one of float, double, or long d... |
70,018,274 | 70,018,837 | Out of the switch scope, how can I use the template variable which is defined in switch scope in C++ | The code is as follows:
//template_test.h
enum SnType
{
Sa,
Sb,
Sc
};
//main.cc
#include <iostream>
#include "template_test.h"
using namespace std;
template<SnType _Tsn>
class Test
{
public:
void print()
{
cout << "Type is " << _Tsn << endl;
}
};
int main()
{
... |
How can I use A out of the switch scope?
You can't. It has ceased to exist.
Aside: All names that start with and underscore and are followed by a capital letter are reserved, _Tsn makes your program is ill-formed.
You'll have to do your type-dependant things within the switch, e.g.
#include <iostream>
enum SnType
{
... |
70,018,502 | 70,019,572 | Compiler can't execute constexpr expression | I have code something like this:
template<typename ... Args>
constexpr size_t get_init_size(Args ... args) {
return sizeof...(Args);
}
template<typename ... Args>
constexpr auto make_generic_header(Args ... args) {
constexpr size_t header_lenght = get_init_size(args...);
return header_lenght;
}
constexpr ... | I rewrite the code that will be work and I think will be execute in compile time:
template<typename ... Args>
constexpr auto make_generic_header(const Args ... args) {
std::integral_constant<size_t, sizeof...(Args)> header_lenght;
return header_lenght.value;
}
constexpr auto create_ipv4_header() {
constexp... |
70,019,717 | 70,019,904 | Replace const std::string passed by reference, with std::string_view | I've got the following method which gets std::string as input argument.
int func(const std::string &filename);
From it's signature, the input type refers passed by reference (no copy is made) and shouldn't be changed (by the const prefix).
Would it be equivalent of using std::string_view instead, which is also used for... | No it's not equivalent.
There are two cases where using std::string const& is a better alternative.
You're calling a C function that expects null terminated strings. std::string_view has a data() function, but it might not be null terminated. In that case, receiving a std::string const& is a good idea.
You need to sa... |
70,020,184 | 70,020,684 | how to detect words in an image with OpenCV and Tesseract properly | I'm working on an application which reads an image file with OpenCV and processes the words on it with Tesseract.
With the following code Tesseract detects extra rectangles which don't contain text.
void Application::Application::OpenAndProcessImageFile(void)
{
OPENFILENAMEA ofn;
ZeroMemory(&ofn, sizeof(OPENFIL... | Tesseract is based on character recognition more than text detection. Even there is no text in some areas tesseract can see some features as a text.
What you need to do is that using a text detection algorithm to detect text areas first and then apply tesseract. Here is a tutorial for a dnn model for text detection whi... |
70,020,343 | 70,020,510 | Alternative to template ADL for GCC <= 10 | Consider the following valid C++20 code:
#include <utility>
namespace foo
{
template<typename... Args>
struct tuple : Args... { };
template<std::size_t N, typename... Args>
auto get(tuple<Args...>) { return 0; }
}
namespace bar
{
template<typename... Args>
struct tuple : Args... { };
template<std::siz... | You can add a dummy function and leave it without definition to make the compiler happy.
When the template is instatiated the right methods will be found through ADL.
#include <utility>
#include <tuple>
namespace foo
{
template<typename... Args>
struct tuple : Args... { };
template<std::size_t N, typename... Ar... |
70,020,593 | 70,021,054 | std::make_from_tuple doesn't compile without constructor | I have a simple struct:
struct A
{
int a;
int b;
int c;
// A(int a, int b, int c) : a{a}, b{b}, c{c} { }
};
The constructor is commented for now. I am trying to create object of type A in a such way:
auto t = std::make_tuple(1, 2, 3);
A a = std::make_from_tuple<A>(std::move(t));
but it doesn't co... | If you look closely at the implementation of make_from_tuple in the standard:
namespace std {
template<class T, class Tuple, size_t... I>
requires is_constructible_v<T, decltype(get<I>(declval<Tuple>()))...>
constexpr T make-from-tuple-impl(Tuple&& t, index_sequence<I...>) {
return T(get<I>(std::forward<... |
70,020,637 | 70,020,818 | The pointer changes the value of the address it points to | I would expect pFirst to always point to the same place in the address. However it looks like pFirst moves along with pCurrent even though the function only entered the Else statement once.
Note:code is creating a linked list .
void Push(T data) {
++_size;
Data d = Data(data);
if (_pCurrent != nullptr) _pCu... | d is created locally, so it does not exist after the function is over. Debug error is a little bit strange, because the program initializes a new element at the same address, so I did not immediately understand exactly what is happening.
This is the working version:
void Push(const T data) {
Data*d = new Data(data);
++... |
70,020,760 | 70,020,797 | How to make a class variable in one line? | In C++ how make a class variable in one line?
For example:
I have a class:
class point{
public:
int x;
int y;
};
How to make a variable in one line like java you can do new point(x, y), currently I do make a tmp and then push back to vector or something, are the simply way like java can do what I do in one line?
| For creating a variable of type point on the stack you can use:
point myVariable{5,6};//this creates a point type variable on stack with x=5 and y=6;
So the complete program would look like:
#include <iostream>
class point{
public:
int x;
int y;
};
int main()
{
point myVariable{5,6};
retu... |
70,020,887 | 70,054,848 | How cmake judging target_link_libraries item is a library name or a target? | I have some troubles in cmake target_link_libraries function.
In my case,there are three projects like this,which means A depends on B,B depends on C
A(exec) --> B(static library) --> C(static library alias C::C)
I write a CMakeLists.txt for B like this:
find_package(C REUQIRED)
add_library(B ...)
target_link_librarie... | I solved this problem finally.
In my case,B using C's funtion in template code,and B does not instantiate this template,so C::C would not link into B's static library.But A would instantiate B's template,so A need C::C,that's why B's PRIVATE flag was useless.
In order to help A found the C::C,I should use find_depecncy... |
70,021,319 | 70,397,628 | How do I know when X server has completed the drawing? | Suppose I want to draw rectangles one after another. How do I know when X server has completed drawing one rectangle? Is there a way to get any confirmation from X server?
In the following code I draw the first rectangle at 500,500 and redraw the same rectangle in the expose handler. After that I draw a new rectangle a... | It seems you are expecting XDrawRectangle() to generate Expose events, but it will never happen, because this is not how it works. Expose events are generated when a window is mapped, resized, moved or when an obscuring window is unmapped, but not when drawing into a window. Actually, the only Expose event you are inte... |
70,022,433 | 70,022,800 | How to solve the Visual Studio problem at the execution of a program | I need to solve an error that says "Please Select a Valid Startup Item" when i try to execute a program in Visual Studio. I am working with C++.
| Dou you have the c++ compiler pluing for VS? you can install it from the extensions panel in VS
The file is in a project? try putting it in one.
Are you sure you have a method int main(){reutrn 0;}?
Maybe whit more info i can help you more :)
|
70,022,460 | 70,825,558 | Do libraries compiled with MinGW work with MSVC? | Problem:
I would use a MinGW library in Visual Studio project.
How my system is built:
I downloaded ZBar library for my Windows 10 system ( zbar-0.23.91-win_x86_64-DShow.zip
This is the link: https://linuxtv.org/downloads/zbar/binaries/).
I have these files in the folder of lib and bin:
libzbar.a
libzbar.dll.a
libzb... | No, libraries compiled on MinGW can't be used with MSVC. The main reasons are:
Lack of ABI compatibility. That is to say that in binary, the way things can be laid out are different depending on the compiler.
Difference in how the standard library is implemented. The standard library can be implemented in many ways. T... |
70,022,701 | 70,043,893 | Basler's Pylon SDK, on memory Image saving | I am working on a Pylon Application where performance is crucial , saving images directly to the disk might throttle the performance, so I want to allocate a memory buffer where I can store an array of Pylon Images, and save them to disk later, what is the best approach I could take?
| I have managed to solve it by making an array of type (Pylon::CPylonImage) and save the captured images on it using a converter (Pylon::CImageFormatConverter) like the following code block
Pylon::CImageFormatConverter::Convert(Pylon::CPylonImage[i],Pylon::CGrabResultPtr)
|
70,022,947 | 70,072,828 | TouchGFX gui automated testing | Checking for feasibility of automated UI testing for TouchGFX. Is there a library that helps in identifying the application window handle and use it to choose UI elements and drive the operations in each window?
| I work as part of the TouchGFX team on a daily basis.
We have a test-framework, only for internal use currently, that we plan to share with the public at some point. It uses the CubeProgrammer API to, through UnitTest++, step an application x number of times, dump the frame-buffer and do comparisons against golden imag... |
70,023,071 | 70,023,348 | C++ cannot call set_value for promise move-captured in a lambda? | I'm trying to write a fairly simple method that returns a future. A lambda sets the future. This is a minimal example. In reality the lambda might be invoked in a different thread, etc.
#include <future>
std::future<std::error_code> do_something() {
std::promise<std::error_code> p;
auto fut = p.get_future();
aut... | By default lambda stores all its captured values (non-references) as const values, you can't modify them. But lambda supports keyword mutable, you can add it like this:
[/*...*/](/*...*/) mutable { /*...*/ }
This will allow inside body of a lambda to modify all its values.
If for some reason you can't use mutable, the... |
70,023,172 | 70,023,318 | When does "requires" cause a compiler error | Consider this code:
struct Bad {};
int main() {
static_assert(requires(int n, Bad bad) { n += bad; });
}
Compiling with Clang 13 and -std=c++20, I get the following error:
<source>:5:48: error: invalid operands to binary expression ('int' and 'Bad')
static_assert(requires(int n, Bad bad) { n += bad; });
... | A notation from the standard:
If a requires-expression contains invalid types or expressions in its requirements, and it does not appear within the declaration of a templated entity, then the program is ill-formed.
So requires only gains this capability when it is in a template.
|
70,023,236 | 70,023,337 | delete a double pointer | How to properly delete a double-pointer array? when I tried this code, memcheck told me that "Use of the uninitialized value of size 8" and "Invalid write of size 4". I couldn't figure out where I did wrong.
struct Node
{
int value;
Node* next;
};
int main()
{
Node** doublePtrNode= new Node* [10];
... | You are already deallocating what you have allocated but doublePtrNode[i]->value=i; assumes that you've allocated a Node there, but you haven't so the program has undefined behavior.
If you are going to use raw owning pointers, you could fix it like this:
Node** doublePtrNode = new Node*[10];
// now allocate the actual... |
70,023,321 | 70,024,660 | get value of postfix experssion from number more than one digit | #include <iostream>
#include <string>
#include <stack>
using namespace std;
float postix_evalute(string expr)
{
stack<float> stk;
for (int x = 0; x < expr.length(); x++)
{
if (isdigit(expr[x]))
{
stk.push((expr[x] - '0'));
}
else
{
float val;
... | You need a way to differentiate the tokens of your postfix expressions. For example, if the input is 213+, a parser would typically read that as 213 and +. For these simple expressions, you could separate the different tokens with whitespaces, as in 21 3 +. Then, having that input in a string, you could read each token... |
70,023,711 | 70,025,365 | Upper-triangle matrix looping | If I have the following matrix for example:
enter image description here
The values in the tables are an index of the elements.
for (int count =0; index<9; count++) {
//row = function of index
//column = function of index
}
In other words, how can I get the row and column from the index of an upper triangle ... | row_index(i, M):
ii = M(M+1)/2-1-i
K = floor((sqrt(8ii+1)-1)/2)
return M-1-K
column_index(i, M):
ii = M(M+1)/2-1-i
K = floor((sqrt(8ii+1)-1)/2)
jj = ii - K(K+1)/2
return M-1-jj
where M is the size of the matrix
Here's a link algorithm for index numbers of triangular matrix coefficients
which gives more details about ... |
70,023,790 | 70,023,874 | Control flow with iterators | Say I have something like this:
void myFunk(std::vector<T>& v, std::vector<T>::iterator first, std::vector<T>::iterator last) {
while (first != last) {
if ((*first) > (*last)) {
T someT;
v.push_back(someT);
}
first++;
}
}
int main(){
std::vector<T> foo = {som... |
Would this lead to an infinite loop, or would it end after foo.size() iterations?
Neither. What you are doing is undefined behavior, for a couple of reasons:
You are modifying the vector while iterating through it.
If the vector reallocates its internal storage when pushing a new item, all existing iterators into th... |
70,023,798 | 70,027,578 | Armadillo Sparse Matrix Size in Bytes | I would like to assess how large Armadillo sparse matrices are. The question is related to this answer regarding dense matrices.
Consider the following example:
void some_function(unsigned int matrix_size) {
arma::sp_mat x(matrix_size, matrix_size);
// Steps entering some non-zero values
std::cout << sizeof(x) ... | There are three key properties:
n_rows
n_cols and
n_nonzero
The last value represents the number of cells 0 <= n_nonzero <= (n_rows*n_cols) which have a value.
You can use this to know the density (which is also displayed as a percentage with .print, e.g.
[matrix size: 3x3; n_nonzero: 4; density: 44.44%]
(1, 0)... |
70,023,880 | 70,024,290 | How to return an array in method decleration using C++? | I am trying to write C++ code suitable for object oriented programming.
I have two classes, namely, Student and Course. In the Student class, I have quiz_scores which is a 1-D array of 4 integers. I need both set and get methods, both are used in natural common way.
In the following, I implement setQuizScores method:
v... | Just as setQuizScores() is able to take a pointer to an array, so too can getQuizScores() return a pointer to the quiz_scores member array, eg:
const int* Student::getQuizScores() const {
// do something...
return quiz_scores;
}
The caller can then access the array elements as needed, eg:
Student s;
...
const in... |
70,024,312 | 70,024,460 | Using accumulate method but can't the first element is always shown as 0 | I am trying to write a programm which returns a list whose n-th element is the sum of the first n Values of the transferred list.
list<int> summe(list<int> liste) {
list<int> neueListe;
list<int>::iterator itr;
itr = liste.begin();
int sum = 0;
int n = 0;
cout <... | You are using a wrong algorithm. For this task there already exists the appropriate algorithm std::partial_sum declared in the header <numeric>.
Here is a demonstration program.
#include <iostream>
#include <list>
#include <iterator>
#include <numeric>
std::list<int> summe( const std::list<int> &liste )
{
std::li... |
70,024,327 | 70,024,368 | C++ Strange Results of String Range Constructor | I have some code similar to this:
std::istringstream iss{"SomeChars"};
// Some read ops here (though the problem stays even without them)
std::string reconst(iss.str().cbegin(), iss.str().cbegin() + iss.tellg());
std::cout << reconst << std::endl;
The result is always some garbled string. Here is a program demonstrati... | The str function returns the string by value. That means each call to str gives you a new string object, and your iterators are pointing to those temporary strings, not the string that is the buffer for the stringstream. This cant work, because the iterators need to point into the same object, not different objects t... |
70,024,770 | 70,024,967 | Why is my loop not restarting to the first iteration? C++ | I'm making a Dice Game in C++. I was wondering why it doesn't restart the loop. The game is Best of 3. It's supposed to restart the loop as long as the player wants to keep playing. However it only restarts the loop once. The second time I press 'Y' or yes in this case it just exits the program.
I've tried putting the ... | First, is this all your code? I noticed most of your variables seem to be declared outside of the provided code block. If so, is your "Y" being declared as a char and not a string type to match your condition type?
It looks like you are failing to set your pWin and cWin back to zero when it returns to the top. You can ... |
70,024,894 | 70,027,936 | How to make my program ask for administrator privileges on execution | I have searched and wondered how certain programs ask you to let them have administrator permissions when you start them up normally but haven't really found any good answer, I suppose they use something in Windows API but I haven't found anything that would help me.
| Add a manifest file into your EXE as described here:
http://msdn.microsoft.com/en-us/library/bb756929.aspx
|
70,025,215 | 70,026,402 | How is the lvalue problem solved for SIMD inline asm with memory output operands in a 2D array? | I am trying to write a function that will fill my float matrix with zeros using ymm registers.
After not a long time I wrote this function:
void fillMatrixByZeros(float matrix[N][N]){
for (int k = 0; k < N; k += 8){
for (int i = 0; i < N; ++i){
asm volatile (
"vxorps %%ymm0, %%ym... | You cannot assign to matrix[i] + k, so it is not an lvalue. The m constraint expects an object in memory, not its address. So to fix this, supply the object you want to assign to instead of its address:
void fillMatrixByZeros(float matrix[N][N]){
for (int k = 0; k < N; k += 8){
for (int i = 0; i < N; ++i)... |
70,025,772 | 70,026,136 | How to find the closest palindrome to an integer? | I'm trying to write a program which can find the closest palindrome to an user-input integer
For example:
input 98 -> output 101
input 1234 -> output 1221
I know i have to transform the integer into string and compare the both halves but i have a hard time trying to start writing the code
I would appreciate any help!
T... | I think this is an acceptable solution:
#include <iostream>
#include <string>
int main( )
{
std::string num;
std::cout << "Enter a number: ";
std::cin >> num;
std::string str( num );
bool isNegative { };
if ( str[0] == '-' )
{
isNegative = true;
str.erase( str.begin( ) );... |
70,025,846 | 70,026,689 | How to add new object to the array of objects in C++? | I have two classes, namely Players and Team In the Team class, I have array of Players instances, and the MAX_SİZE = 11
#define MAX 11
class Players{
// Some private and public members
};
class Team {
private:
Players players[MAX];
// Some other private and public members
};
I want to implement the addNewPl... | players array is defined within Team class. To assign it a size; you use the variable MAX, if this variable uses an appropriate value, suppose one different from its maximum capacity that depends on the hardware, you can try creating a new array replacing the one of the class with a new length and element:
void Team::... |
70,026,936 | 70,027,746 | Can an overloaded member function of a class depend on the outcome of an overloaded constructor of that class? | I have a class with an overloaded constructor where each version of the constructor initializes a different set of private attributes for that class. I also have a public member function of that class that will perform some operation based on the private attributes of that class. I want to overload the member function ... | For me, this looks like inheritance with a virtual function.
struct someClass {
virtual ~someClass() {}
virtual double calcVal() = 0;
};
struct classWithVar1 : someClass {
double var1;
classWithVar1(double in1) : var1(in1) {}
double calcVal() override { return var1; }
};
struct classWithVar2 : s... |
70,027,226 | 70,027,299 | C++ ensure object exists while executing a function | I have a function foo. During the execution of foo, I want to be certain that an object of type Bar exists. Let’s call whatever object that happens to be “bar.”
I cannot copy or move bar, and bar can have any storage duration. The one thing I do know about bar is that it is an empty object.
foo doesn't need to do anyth... |
the calling environment could pass a dangling reference into foo
It really couldn't. Dangling references are not legal, so the only way for this to happen is by the caller violating the language rules. I don't find this a compelling concern.
pass a shared_ptr to bar in. But this would require bar to have dynamic s... |
70,027,304 | 70,028,829 | Is the following case an issue with the new C++ concept standard? | Consider this program which uses the curiously recurring template pattern:
template <typename T>
concept Frobulates = requires (T t) { t.frobulate(); };
template <typename Derived>
struct S {
int sidefumble() requires Frobulates<Derived> {
Derived::frobulate();
}
};
struct K: public S<K> {
void fr... | Looks like this is a bug.
Though this other question (thanks @T.C.) seems to outline slightly different scenario, the underlying bug seems to be the same.
This comment in a clang bug thread contains almost exactly the same repro.
|
70,027,356 | 70,159,228 | mutltithreading in C++ does not work with pybind11 to Python | I am having this difficulty to utilize the multithreading capability of C++ through python's pybind11 plugin system. I am aware of the notorious GIL issue and try to release it but no avail. Following is my C++ code:
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include "Calcula... | This is a false alarm. The multithreading is working on the C++ side. GIL has nothing to do with that as long as the threading is not on the python side.
|
70,027,525 | 70,027,628 | Undefined reference to initialized static member variable with make_shared | Compiling with -std=c++14 the following code:
#include <memory>
class A
{
public:
static constexpr int c = 0;
std::shared_ptr<int> b;
A() {
b = std::make_shared<int> (c);
}
};
int main () {
A a;
return 0;
}
Gives a linker error "undefined reference to `A::c'", while using "A::c"... | Since C++17 the first code should work correctly: a static constexpr class member variable is implicitly inline which means the compiler takes care of making sure a definition exists .
Prior to C++17 the code has undefined behaviour (no diagnostic required) due to ODR violation. A static class member that is odr-used ... |
70,027,785 | 70,038,621 | Error build skia: machine type x64 conflicts with x86 | I'm trying to build Skia as per the instructions here https://skia.org/docs/user/build/. I install the C++ clang tools for Windows using the Visual Studio Installer and then configured skia as follows:
bin/gn gen out/Shared --args='clang_win="C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\Llvm"... | Ok so it turns out that for some reason (not sure what), Skia has a problem with the LLVM version installed using the Visual Studio Installer. I downloaded LLVM directly from their official website and then ran:
bin/gn gen out/Shared --args='clang_win="C:\Program Files\LLVM" is_component_build=true is_debug=false is_o... |
70,028,017 | 70,030,357 | Exception has occured, unknown signal error when using class object again inside each function | I'm trying to write a C++ code for a course I'm enrolled in, where I keep the information of the students enrolled in the course.
I should be able to add a student to the classrrom in the user interface written in main , by calling the function void addNewStudent(int ID, string name, string surname), where I create ... | To make the menu more interactive you could add a do while statement that would accept 3 options:
register
show data
exit
int main(){
Course ECE101;
int x;
int ID;
string name, surname;
string option_1 = "1) Add a student\n";
string option_2 = "2) Search a student by ID\n";
cout << "Welcome to... |
70,028,107 | 70,028,206 | In C++, is "const_iterator" the same as "const iterator"? | Is a const_iterator the same as const iterator? if not what's the difference? if yes why does standard use const_iterator when const iterator is already meaningful?
For example, are these two declarations exactly the same ?
string& replace (const_iterator i1, const_iterator i2, const string& str);
string& replace (cons... | No, they are not the same.
Like any const object, you can not make changes to a const iterator:
// ++it gives error below since we try to change it:
for(const std::vector<int>::iterator it = vec.begin(); it != vec.end(); ++it) {}
You are, however, allowed to change the value of the object a const iterator is pointing ... |
70,028,724 | 70,028,869 | C++ size_t in mixed arithmetic and logical operations | Currently using WSL2, g++, with -std=c++20 -Wall -Wextra -Wvla -Weffc++ -Wsign-conversion -Werror.
In the program I'm building, because I utilize several STL containers such as std::vector, std::array, std::string, etc, I've come across many situations involving integer arithmetic or logical comparisons between size_t ... | Instead of calling the member function size(), you can use C++20 std::ssize() to get the signed size for comparison and operation with signed integers.
std::vector v{42};
auto size = std::ssize(v); // get signed size
|
70,028,924 | 70,028,963 | How is access of an index more than string's size in c++ allowed? | #include <iostream>
using namespace std;
int main() {
// your code goes here
string g = "12345";
cout << g[10] << endl; // Prints an empty character
return 0;
}
Reference: https://ideone.com/rpCWm2
This surprisingly works and doesn't throw an error! Can somebody explain how this is happening? Tha... | std::string g = "12345";
std::cout << g[10] << std::endl;
Your access is out-of-bounds, which makes it an undefined behaviour. Undefined behaviour can do anything, from running normally to crashing the program.
If you use the at() function instead(which does bound-checking), you will see that this will throw an std::o... |
70,028,944 | 70,031,180 | How to handle runtime errors in C++? | So, I'm kinda new to C++ and I wanted to know what are the good practices or even how do I handle runtime errors when programming, here is an example:
State s_toState(std::string state){
if (state == "MG")
return State::MG;
else if (state == "PR")
return State::PR;
else if (state == "SP")
return State... | Generally speaking, the way to handle such errors (like any errors) depends on the needs of your program as a whole - and you have not specified that. So there is no one-size-fits-all "general rule".
There are options and trade-offs.
One option is for your State enumerated type to provide an enumerator value that rep... |
70,029,205 | 70,029,273 | Declare a variable and return it in the same line C++ | I have code that does
if(x>5){
vector<int> a;
return a;
}
But i'm curious if theres a way to do this return in one line such like:
if(x>5){
return vector<int> a;
}
| This will work as expected:
return vector<int>();
This creates an object and returns one at the same time. Since the object has not been created without any name, it is known as anonymous object.
Hence you can modify your code, without assigning a name to the variable, like this:
if(x>5){
return vector<int>();
}
|
70,029,743 | 70,030,360 | Overload inherited methods in an Rcpp class | I have two classes A, the parent and B, the child.
B overloads a method from A. The problem is that the method getval is not overloaded when exposing class B in an RCPP module, despite explicitly exposing it again a second time with a pointer to B::getval.
Is it due to a bug in Rcpp, a limitation or something I just do... | If I use my basic example above (in the question) in a simple C++ program as follows:
int main()
{ ... |
70,029,939 | 70,030,057 | Set the working directory when starting a process with boost | I am looking for a way to specify the working directory when starting a process with boost::process::system or boost::process::child. In the docs https://www.boost.org/doc/libs/1_77_0/doc/html/boost_process/tutorial.html are some useful examples, but nothing on the subject of my interest.
The child constructor looks li... | #include <boost/process/start_dir.hpp>
namespace bp = boost::process;
int result = bp::system("/usr/bin/g++", "main.cpp", bp::start_dir("/home/user"));
bp::child c(bp::search_path("g++"), "main.cpp", bp::start_dir("/home/user"));
c.wait();
See boost::process::start_dir and the complete Reference.
Args are program n... |
70,030,015 | 70,030,033 | Why does an error occur when I modulus the value in array? | may i know what exactly have gone wrong in this code? cause the output of the even number is not what i expected if i input the value in the comment
//int number[10]={0, 2, 5, 8, -2, 0, 6, 4, 3, 1};
int number[10], divided_number[10], total_odd_numbers, total_even_numbers, a;
for(int i=0;i<=9;i++){
a=i+1;
cout<... | The problem is that total_odd_numbers and total_even_numbers are not initialized before being accessed. This is called undefined behavior. In this case, the program will take whichever trash data is already in the memory assigned to those variables and just use it as-is (and so, of course, the output may or may not be ... |
70,030,906 | 70,031,122 | I want my zeros to be some other number/character (C++) | double floaty=36.6736872;
cout<<fixed<<setprecision(10)<<floaty;
My output is "36.6736872000";
I want my zeros to be some other number.
Eg: If I want zeros to be ^.
then the output should be 36.6736872^^^
I don't have any idea other than using setw and setfill to get my desired output in single line of code
| You can use std::ostringstream, and change the resulting string in any way you see fit:
#include <iostream>
#include <sstream>
#include <string>
#include <iomanip>
int main()
{
double floaty=36.6736872;
std::ostringstream strm;
// Get the output as a string
strm << std::fixed << std::setprecision(10... |
70,030,927 | 70,031,130 | How to generate program code from ui-forms? | I have a UI, generated with Qt Designer. It's generates me a XML code like these:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ColorDialog</class>
<widget class="QDialog" name="ColorDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
and etc
I want to remove this UI and e... | If you want to generate code using the .ui information then you must use uic tool:
uic filename.ui -g cpp -o filename_ui.h
|
70,030,985 | 70,031,263 | How to pass the target function of std::thread constructor as an argument | I can do this to start my thread:
int main_test() {
// do something...
return 0;
}
std::thread* myThread;
void myFunction() {
myThread = new std::thread(main_test);
}
How do I pass main_test as an argument to myFunction, so the same function can be used to start the thread using different target functions? Wha... |
How do I pass main_test as an argument to myFunction, so the same function can be used to start the thread using different target functions?
You can pass the poiter to your function as an argument
void myFunction(int (*func)()) {
myThread = new std::thread(func);
}
int callSelector(int someCriteria)
{
if (someCr... |
70,031,324 | 70,031,422 | Difference between char in C and C++? | I know that C and C++ are different languages.
Code - C
#include <stdio.h>
int main()
{
printf("%zu",sizeof('a'));
return 0;
}
Output
4
Code- C++
#include <iostream>
int main()
{
std::cout<<sizeof('a');
return 0;
}
Output
1
https://stackoverflow.com/a/14822074/11862989 in this answer user Kerrek SB... |
is char in C++ is integral type or strict char type ?
Character types, such as char, are integral types in C++.
The type of narrow character constant in C is int, while the type of narrow character literal in C++ is char.
|
70,031,459 | 70,031,805 | Error when trying to serialize std::wstring with boost::serialization | I'm trying to serialize a class with a std::wstring variable, but what I'm getting are multiple undefined reference to ~ errors.
I don't seem to be missing any headers or libraries & from what I've read from the boost::serialization documents, std::wstring seems to be a primitive type that doesn't need any overriding.... | The serialization objects are split into two libraries: boost_serialization (which you are linking against) and the corresponding objects for wchar etc. in boost_wserialization. So, you need to add -lboost_wserialization to your linker flags.
|
70,031,982 | 70,032,089 | My Bubble Sort Program worked for one case but not for other. How this is Possible? | #include<iostream>
using namespace std;
int main(){
int n;
cout<<"Enter size of array-";
cin>>n;
int arr[n];
cout<<"Enter all elements"<<endl;
for(int i=0;i<n;i++){
cin>>arr[i];
}
cout<<"Your Entered elements are"<<endl;
for(int i=0;i<n;i++){
cout<<arr[i]<<",";
}
... | You are trying to access arr[i+1]. When i = n-1, arr[i+1] = arr[n], so your access is out-of-bounds.
Also, int arr[n] isn't valid C++. You should use std::vector<int> instead.
|
70,032,111 | 70,032,496 | How to pass and start multiple threads within a function? | I want to pass in an arbitrary number of functions together with their arguments to a function called startThread so that it can run them concurrently.
My code is below but obviously, it has syntactic errors:
#include <iostream>
#include <thread>
#include <chrono>
#include <vector>
#include <exception>
int test1( in... | This is how I would do it, using a recursive template function.
And std::async instead of std::thread
#include <future>
#include <chrono>
#include <thread>
#include <iostream>
void test1(int /*i*/, double /*d*/)
{
std::cout << "Test1 start\n";
std::this_thread::sleep_for(std::chrono::milliseconds(300));
st... |
70,032,585 | 70,032,678 | Using a method in the created Window in QT | Right now, there is a button for activating the function, like:
Window {
id: window
width: Screen.width
height: Screen.height
visible: true
property alias originalImage: originalImage
title: qsTr("Window1")
Button{
id: startButton
x: 50
y:100
text: "Open"... | You can use Component.onCompleted signal to do things right after component is created.
The onCompleted signal handler can be declared on any object. The order of running the handlers is undefined.
Window {
id: window
width: Screen.width
height: Screen.height
visible: true
property alias originalIma... |
70,032,640 | 70,032,840 | How to check the value of a bit in C++ | I would like to check the value of the 5th and the 4th bit starting from the left in this strings like this one:
value: "00001101100000000000000001000110"
value: "00000101100000000000000001000110"
value: "00010101100000000000000001000110"
The value is generated as a string in this way:
msg.value = bitset<32... | You don't have a bitset, you have a string, in which each "bit" is represented by a char.
To check the 4th and 5th "bits", just use:
msg.value[3] != '0' and msg.value[4] != '0'
msg.value[3] & 1 and msg.value[4] & 1
#2 might be faster; it exploits the fact that '0' and '1' differ in the lowest bit only.
|
70,032,994 | 70,037,065 | CMake - 3rdparty folder and mulit module project | What is good practice to create 3rdparty folder?
I have a project with multiple modules that are in scope of project, some of those modules are depending on 3rdpartys. Currently I have single 3rdparty folder in root. On top of that I've created cmake folder with Find<package>.cmake files. Then each module just call fin... | I would say that what you have done is the cleanest possible way of managing 3rd party dependencies in a multi-component project.
What you presented matches perfectly the "external" directory of the Pitchfork proposal (which aims to establish/standarize typical C/C++ project structure).
|
70,033,024 | 70,033,478 | leetcode 295 median in stream, runtime error? | Leetcode 295 is to find median in a data stream.
I want to use two heaps to implement it. which can make add a data from stream in O(logn), get the percentile in O(1).
left_heap is a min_heap which used to save the left data of requied percentile.
right_heap used to save data which is larger than percentile.
In class S... | You have one minor problem
In the line
double left_top = left_data_.back();
At the very beginning, the std::vector "left_data" will be empty. If you try to access the last element of an empty vector, you will get an runtime error.
If you modify this line to for example:
double left_top = left_data_.empty()?0.0:left_da... |
70,033,277 | 70,033,621 | How to use modulo 10^9+7 | I am trying to write a code for sum of square of natural numbers but with mod it's giving wrong answer. What would be the correct way here?
#include <bits/stdc++.h>
using namespace std;
#define mod 1000000007
int main()
{
int N;
cin>>N;
cout<< (((N) * (N+1) * (2*N+1))/6)%mod;
return 0;
}
| (N) * (N+1) * (2*N+1) can be, even if N is less than 1000000007, too large. Namely up to 2000000039000000253000000546, which is an 91-bit number. It is not likely that int on your system is capable of containing such large numbers.
As usual with this type of question, the work-around is a combination of:
Using a large... |
70,033,337 | 70,033,462 | Retrieve first key of std::multimap, c++ | I want to retrieve just the first key of a multimap. I already achieved it with iterating through the multimap, taking the first key and then do break. But there should be a better way, but I do not find it.
int store_key;
std::multimap<int, int> example_map; // then something in it..
for (auto key : example_map)
{
... | Your range based for loop is more or less (not exactly but good enough for this answer) equivalent to:
for (auto it = example_map.begin(); it != example_map.end(); ++it) {
auto key = *it;
store_key = key;
break;
}
I hope now it is clear that you can get rid of the loop and for a non-empty map it is just:
... |
70,033,455 | 70,034,522 | Devlop programme by Qt LGPL 4d1,must by section 6 of the GNU GPL. So that must provide All Source Code? | I want develop a gratis software use Qt,I read the LPGL. I want by 4d1.But must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. If by GNU GPL 6, must provide All Source Code.
Just dynamically link to Qt. If you dynamically link to LGPL libra... | LGPL 4e says
If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.
Section 6 defines "installation information" as follows:
“Installation Information” for a User Product means any methods, procedures, authorization... |
70,033,985 | 70,035,718 | How does .Byte[] function on a specific byte? | I am working on the following lines of code:
#define WDOG_STATUS 0x0440
#define ESM_OP 0x08
and in a method of my defined class I have:
bool WatchDog = 0;
bool Operational = 0;
unsigned char i;
ULONG TempLong;
unsigned char Status;
TempLong.Long = SPIReadRegisterIndirect (WDOG_STATUS,... | Your ULONG must be defined somewhere.
Else you'd get the syntax error 'ULONG' does not name a type
Probably something like:
typedef union {unsigned long Long; byte Byte[4];} ULONG;
Check union ( and typedef ) in your C / C++ book, and you'll see that
this union helps reinterpreting the long variable as an array of by... |
70,034,027 | 70,175,629 | How do I read data via i2c from a MAX11613 chip using C++ on a RPI 3B+ | I'm trying to write a driver for a MAX11613 ADC chip (MAX11613 Datasheet) in c++. I think I've got the write code correct for the setup and config, but I'm having some trouble with the read code. I am setting the chip up to read using the internal clock in Unipolar mode and the internal voltage reference, then writing... | It appears that I am now able to read data from the device after some more review. Here's the final code that works, for anyone else that might be interested.
static void writeMAXRegister(uint8_t i2cAddress, uint8_t reg, uint8_t value) {
beginMAXTransmission(i2cAddress);
i2c_smbus_write_word_data(i2cMAXHandle,... |
70,034,244 | 70,034,322 | Reading dynamic matrix from file with unspecified number of columns | This method is creating my dynamic allocated matrix that I have to read it from a file. I managed finding the columns for every row from the file and initialize my matrix, but I don't know how to read now the values and introduce them into the matrix.
The number of neighbourhoods(noCartiere) is generated random from 2 ... | The solution is to use vectors. More specifically a vector of vectors of integers: std::vector<std::vector<int>>.
Using vectors, you can also skip the inner reading loop completely, and instead use std::istream_iterator to initialize (and add) the inner vector directly.
Something like this:
std::vector<std::vector<int>... |
70,034,503 | 70,034,590 | How to build a class in C++ to use in Python? | PyMethodDef from Python.h allows to specify Cpp-built functions to use in Python. However, there is much doubt if this can be applied for Cpp-built classes and I can't find anything like PyClassDef which could presumably help me to do so. All I've managed to find concerns class methods, but not the class itself. Is it ... | You can use pybind11 to implement python call c++ native class.
Link here pybind11 class
it's easier use than cpython.
|
70,034,513 | 70,034,558 | move from unique_ptr to stack variable | Is it possible to create a stack variable (of type T with a move constructor) from a std::unique_ptr<T>?
I tried something like
std::unique_ptr<T> p = ext_get_my_pointer(); // external call returns a smart pointer
T val{std::move(*p.release())}; // I actually need a stack variable
but it looks ugly, a... | It is a memory leak because you have decoupled the allocated memory from the unique_ptr, but it is still allocated.
Assuming you have a functioning move constructor, why not:
std::unique_ptr<T> p = ext_get_my_pointer();
T val{std::move(*p)};
// p goes out of scope so is freed at the end of the block, or you can call `... |
70,034,915 | 70,035,014 | Is it necessary to check range in bit representation C++ | Some data are stored in a 64 bit integer. As you can see, inside the getDrvAns function I check if the bit in the position drvIdx-1 is 0 or 1. One cannot be sure if the drvIdx will have a value in the right range (1-64). However, I noticed that if we put a value higher that 64, we have a wrap-around effect as demonstr... | According to the documentation, out of bounds access using operator[] is Undefined Behaviour. Don't do it.
If you don't want to check the bounds yourself, call test() instead, and be prepared to handle the exception if necessary.
|
70,035,020 | 70,035,021 | Compiler variance in function template argument deduction | The following program:
#include <type_traits>
template<typename T, bool b>
struct S{
S() = default;
template<bool sfinae = true,
typename = std::enable_if_t<sfinae && !std::is_const<T>::value>>
operator S<T const, b>() { return S<T const, b>{}; }
};
template<typename T, bool b1, bool b2>... | This is governed by [temp.deduct.call], particularly /4:
In general, the deduction process attempts to find template argument values that will make the deduced A identical to A (after the type A is transformed as described above). However, there are three cases that allow a difference: [...]
In the OP's example, A is... |
70,035,099 | 70,035,957 | How to extract requires clause with a parameter pack whose parameters are related to each other into a concept? | I've got such a set of toy functions:
template <typename... Args>
requires std::conjunction_v<std::is_convertible<Args, int>...>
void test(Args...) { std::cout << "int"; }
template <typename... Args>
requires std::conjunction_v<
std::disjunction<std::is_convertible<Args, int>,
std::is_converti... | There is no need to use std::conjunction and std::disjunction in such a case since it makes the code verbose and difficult to read. Using fold expressions will be more intuitive.
template <typename... Args>
requires (std::is_convertible_v<Args, int> && ...)
void test(Args...) { std::cout << "int\n"; }
template <type... |
70,035,653 | 70,035,812 | c++ return two arrays from the function | I find a solution to the equation using the bisection method.
And I need to find the value of a and b on some iterations. Therefore, I made two arrays for these points, respectively.
in order to "pull out" the number of iterations from the function, I had no problems. They are displayed on the screen. But how do I "pul... | In your case, you should take the arrays by reference:
double dihotom(double a, double b, double e, double (*fp)(double), int &iter,
double (&points_a)[3], double (&points_b)[3]) {
// ^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^
You could also let the arrays decay into pointers:
double dihot... |
70,035,959 | 70,036,183 | How can I create an instance from a UObject class? | I have a DataTable with a list of items that can be dropped by enemies, along with their rarities and min/max quantities:
USTRUCT(BlueprintType)
struct FItemDropRow : public FTableRowBase
{
GENERATED_BODY()
UPROPERTY(EditAnywhere, BlueprintReadOnly)
TSubclassOf<UBattleItemBase> DropItemClass;
UPROPERT... | DropItemClass is only the class of the item, not an instance of it.
If you want to create an instance from that class you can use NewObject() or one of the more advanced versions (NewNamedObject() / ConstructObject(), CreateObject(), etc...)
e.g.:
TArray<UBattleItemBase*> ItemsToReturn;
for(int i = 0; i < DropQuantity;... |
70,036,511 | 70,037,021 | How to delete column in 2d array c++ with dynamic array? | I want to delete column with max integer in 2d array, I do it in this way, but why is deleting the column and also row? Can I fix that and delete only column? The task was do it with delete command, but now I think it's impossible
#include <iostream>
using namespace std;
int main()
{
int row = 3, col = 3;
int** arr ... | For starters the variable index is set to a row number
index = i;
Then this row is deleted
delete [] arr[index];
But you are going to remove a column instead of a row. So this code does not make a sense.
Also you are incorrectly searching the maximum element. If the user will enter all negative values then the maximu... |
70,037,105 | 70,038,230 | Get byte representation of C++ class | I have objects that I need to hash with SHA256. The object has several fields as follows:
class Foo {
// some methods
protected:
std::array<32,int> x;
char y[32];
long z;
}
Is there a way I can directly access the bytes representing the 3 member variables in memory as I would a struct ? Th... | Most Hash classes are able to take multiple regions before returning the hash, e.g. as in:
class Hash {
public:
void update(const void *data, size_t size) = 0;
std::vector<uint8_t> digest() = 0;
}
So your hash method could look like this:
std::vector<uint8_t> Foo::hash(Hash *hash) const {
hash-... |
70,037,239 | 70,037,294 | unusual switch statement label - why isn't this a syntax error? | I've inherited a very old (+15 years old) C++ program currently running on AIX using IBM's xlc compiler. I came across a switch statement and I don't understand how this ever worked.
Below is a minimal example that shows the situation.
#include <iostream>
using namespace std;
int main()
{
int i=5;
sw... | A label can occur on any statement. That the statement happens to be inside of a switch block doesn't matter. This label can be jumped to from anyplace inside the current function.
A case label or default can only appear inside of a switch, but that doesn't prevent other labels from appearing there as well.
Section 9... |
70,037,430 | 70,263,559 | Qt: How to implement Panning/Zooming in QGraphicsScene with two finger gestures on laptop trackpad (win/mac)? | I have a Qt 6.2 Application (Windows/Mac) using QGraphicsScene and want to use 2 fingers on the touch pad of my laptop for panning - as many other applications do.
Zooming in/out works fine, but using 2 fingers for panning always results in zoom out.
I found a number of questions and some fragmentary samples. But no ha... | I finally manged to get this work. What i found out:
Pan Gestures (in Qt) are converted to Mouse Wheel messages which can have a y and also a x offset. This seems strange to me, as there is no Mouse with a horizontal Wheel.
Even more confusing, by MS definition Pan events are converted to WM_VSCROLL/WM_HSCROLL events (... |
70,037,538 | 70,037,831 | Using template function for accessing the raw bytes of POD data type and strings | I'm trying to make a function template that lets me process the raw bytes of a POD data type and strings.
I came up with this somewhat naive approach (I'm not using template a lot, and I'm able to write them use them only for very simple cases):
#include <cstdio>
template<typename T>
void PrintBytes(T object)
{
unsi... | You can use C++17 if constexpr to perform the corresponding address and size method according to the type of T, something like this:
#include <cstdio>
#include <cstring>
#include <utility>
#include <type_traits>
template<typename T>
void PrintBytes(T object)
{
auto [p, size] = [&] {
if constexpr (std::is_same_v<... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.