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 |
|---|---|---|---|---|
73,396,664 | 73,397,005 | Data structure/algo for fast insertion and counting | I'm looking for a data structure/algorithm that allows both logarithmic insertion of elements into data structure, and logarithmic counting of elements in data structure that are smaller than a given value.
For instance, std::set<int> allows logarithmic insertion, and logarithmic iter = std::upper_bound(..., value) but... | There is a way, unfortunately only for GNU C++. Called Policy based data structure.
I'll show basics of usage.
#include <ext/pb_ds/assoc_container.hpp>
#include <iostream>
using namespace __gnu_pbds;
using namespace std;
typedef tree<int, null_type, less<int>, rb_tree_tag,
tree_order_statistics_node_updat... |
73,396,880 | 73,399,081 | C++ if, else if, else statement is not printing cout result | I'm struggling with this code. Been working at these if, else if, else statements for a few hours now.
void metric()
{
double mWeight;
double mHeight;
double mAge;
char mExercise;
bool mCorrectExercise = true;
int metricResult;
cout << "Please type in your age: ";
cin >> mAge;
cout... | You forgot to add single quotation marks (i.e. '') to your values. For instance, this '1' is a character literal but this 1 is not a character literal (it's an integer literal). You need to compare a value of char type with values of char type.
Also, you better use a switch statement instead of the if else if structure... |
73,396,946 | 73,399,292 | OpenCV Mat data address shows weird value | I'm suffered by using OpenCV Mat due to unexpected results.
There is an example code:
cv::Mat local_mat = cv::Mat::eye(cv::Size(1000, 1000), CV_8UC1);
qDebug() << "1. local_mat.data: " << local_mat.data;
cv::Mat sobel_img_ = cv::Mat::eye(cv::Size(1000, 1000), CV_8UC1);
qDebug() << "2. sobel_img_.data: " << sobel_img_.... | Initializing of matrix is a form of matrix expression.
cv::Mat has overloads of operator=. One of them handles MatExpr as its argument:
Assigned matrix expression object. As opposite to the first form of
the assignment operation, the second form can reuse already allocated
matrix if it has the right size and type to f... |
73,397,226 | 73,397,594 | C++ Can't print certain words from Char array | Not sure how to phrase the question, but I'm making a program for an assignment, which we're not allowed to use pre-existing libraries besides input/output. We also can only use primitive data-types. I have to read a text file with words, remove all punctuation from the word, and then store those words in a 2D array of... | The simplest fix is to change:
stack[top][i] = word[i];
To:
stack[top][j] = word[i];
^ j not i here
This will ensure that the 'Twas ends up as twas and not \0twas.
Also, formatCharacter() should call isAlphabet() rather than repeat the condition.
|
73,398,329 | 73,400,179 | QT signal slot behavior with respect to const ref arguments | I am working on some code where I see the following:
In header file:
private slot:
void OnNotifySomeSlot(const QList<bool>& someList); // Note the argument is pass by const ref
In implementation file:
connect(&m_serviceObj,SIGNAL(NotifySomeSlot(QList<bool>)), this, SLOT(OnNotifySomeSlot(QList<bool>)); // Note that a... | Answering your questions in order:
The Qt macro machinery canonicalizes signal and slot names so they "fit". If you use the modern connection approach you do not have to worry about this:
QObject::connect(m_serviceObj, &SomeServiceObjectClass::NotifySomeSlot, this, &ThisObjectClassOnNotifySomeSlot)
Yes, even though... |
73,401,155 | 73,401,181 | Why do i can't add an string to an letter of another string? | Consider the following code:
#include <iostream>
#include <typeinfo>
int main(){
std::string word = "This is string";
std::string word1 = "a" + word[0];
std::cout << word1;
}
As you can see, i heve a string with the name word and i want to add first letter of it to another string and store them to string ... | "a" is not a string (well, its a c-string, but not a std::string, and a c-string is just an array). Its a const char[2] and decays to a pointer when + is applied. There is an operator+ for std::string though:
std::string word1 = std::string("a") + word[0];
or
std::string word1 = "a"s + word[0];
|
73,401,495 | 73,402,028 | Is there such a C++ feature: "const scope" in method definitions? | I was wondering if there is a safety feature to restrict a scope of a class method definition to allow disallow modifying access to *this. See this pseudo-code:
class C{
void method();
void const_method() const {
// do const stuff here
}
};
void C::method(){
const_method();
}
Now instead of calling const_... | You can use a immediately invoked lambda, though you still have to capture the local variables explicitly:
#include <iostream>
struct foo {
int member = 42;
void bar() {
int local_var = 42;
[const_obj=const_cast<const foo&>(*this),&local_var](){
//member = 2; // error: thi... |
73,401,506 | 73,401,851 | Copy vector of object to vector of shared_ptrs | I have a simple struct and vector of its objects.
And I want to move all objects to the vector of shared_ptrs.
I don't need the initial vector anymore.
I presented you with my situation.
Is my approach correct? I want to do this the most effective way:
struct MyStruct
{
int i_;
std::string s_;
};
void copyVect... | Yes, that's correct. You might want to reserve the size of the destination beforehand though:
#include <algorithm>
#include <cstdio>
#include <iterator>
#include <memory>
#include <string>
#include <utility>
#include <vector>
template <class T>
auto transform_vector(std::vector<T>&& src) -> std::vector<std::shared_ptr... |
73,401,560 | 73,401,753 | c++ bubble sort routine with template functions doesn't work with string literals | I have a bubble sort algorithm to order integers in a descending order. Next I am asked to implement a template specialization for type char* in which I replace the arithmetic operator between two integers (>) with (strcmp). The code seems to work, as I print out the number of successful swaps, but my output just shows... | You have const char *str[n], but your template specialisation takes char *, so as the compiler will not automatically cast away constness the compiler will select the default class T template.
You should also refactor the code so that for instance a baseSort() function takes a pointer to a comparison function so you do... |
73,402,616 | 73,402,746 | Run-Time Check Failure #2 - Stack around the variable 'arr' was corrupted. I tried to find it but still can't find where i got out of bounds array | what was i trying to do is a recursion of first 40 fibonacci numbers, when tried to launch a program, it's stopped at return 0;.
#include <stdio.h>
#define SIZE 40
void sum(int arr[], int n1, int n2, int offset);
int main(void)
{
int arr[SIZE] = { 0, 1 };
printf("%d\n", arr[0]);
printf("%d\n", arr[1]);
... | Look at this check:
if (offset > SIZE)
return;
That means if offset is equal to SIZE, it passes.
arr[offset] with offset being equal to SIZE refers to the 41 nth element.
This array only have 40 element, hence the corruption.
If you run your program in a debugger, it should stop at the crash and you would be able ... |
73,402,996 | 73,403,193 | Should you use std::unique_ptr alongside std::function? | I'm having trouble figuring out the best way to deal with allocation and deallocation of std::function.
Of course the underlying function is never going to be deallocated, but the captured variables etc. need to be deallocated.
I presume that this is deallocated inside the destructor of std::function.
Does this mean th... | Remember that std::function is not a lambda. A std::function don't have captures. It's a polymorphic wrapper around a function like object like a lambda.
A (extremely rough and incomlete and incorrect) representation of std::function looks like this:
template<typename R, typename... Args>
struct function {
function... |
73,403,115 | 73,403,426 | Linux perf not resolving some symbols with high addresses starting with 0xffffffff | g++ -std=c++17 -fno-omit-frame-pointer -O0 -g3 -o main main.cpp
perf stat ./main 5
perf report
20.98% main [unknown] [k] 0xffffffffb1077f22 ◆
19.11% main main [.] func ▒
17.96% main ... | I did not give attention to the warning message of perf report.
It says:
WARNING: Kernel address maps (/proc/{kallsyms,modules}) are restricted,
check /proc/sys/kernel/kptr_restrict and /proc/sys/kernel/perf_event_paranoid.
So it seemed that I should set a proper value in /proc/sys/kernel/kptr_restrict.
sudo echo 0 > ... |
73,403,427 | 73,403,525 | How to scan for a letter in c++ instead of a number? | My code prompts the user to input 0 or 1 as an integer in answer to one of the questions. I want the user to type Y or N. I tried to create a char variable, but I am not getting it right. It says y and n is not declared. I know it's a basic question, but I have just started learning c++.
Here is my code and below that ... | Try using char:
char m;
std::cin >> m;
if (m == 'y')
// do something
else if (m == 'n')
// do something else
|
73,404,182 | 73,404,416 | glBufferSubData() and glBindArray() | I have two methods:
opengl_init()
opengl_draw()
In the first one I initialize an empty GL_ARRAY_BUFFER because I want to update my point coordinates each frame.
Everything works if in opengl_draw() method I keep commented out //glBindBuffer(GL_ARRAY_BUFFER, 0)
Normally I use this function when I draw elements statica... | glBufferSubData requires that GL_ARRAY_BUFFER is bound to a buffer. glBindBuffer(GL_ARRAY_BUFFER, 0); binds it to nothing.
Assuming nothing else in this code touches GL_ARRAY_BUFFER, commenting that line leaves it bound to vbo, which means that the glBufferSubData call knows which buffer to update.
It is best to be exp... |
73,404,774 | 73,404,822 | sorting a list of tuple by second element but if the second element of mutiple tuple matches then sort using the first element | Given a list of tuples where first and second elements are integer. Sort them using the second element but if the second element matches sort them using first element. Basically, I am trying to convert c++ pair<int, int> type comparison to python code. This is the c++ version.
bool cmp(const pair<int,int>& a, const pai... | You can specify both the elements in the key -
inp = [(2, 5), (3, 6), (1, 5), (8, 10), (6, 9)]
sorted(inp, key=lambda x: (x[1], x[0]))
Output
[(1, 5), (2, 5), (3, 6), (6, 9), (8, 10)]
|
73,405,112 | 73,405,197 | Optimizing bug in ARM Apple Clang on implicit casting double to byte | I found a nasty bug in our C++ iOS application, which I suspect to be caused by a compiler bug on ARM based Apple Clang.
I was able to reproduce the bug in a MRE on a Mac M1 machine.
#include <cstdio>
int main(int argc, const char** argv)
{
int total = 0;
for(double a=1000; a<10000; a*=1.1)
{
unsig... | Your code does have undefined behavior. When you do
unsigned char d = a / 0.1;
you are doing floating point to integer conversion which means [conv.fpint]/1 applies and it states:
A prvalue of a floating-point type can be converted to a prvalue of an integer type. The conversion truncates; that is, the fractional pa... |
73,405,297 | 73,405,441 | Semi-private enum values | Is it possible to have an enumeration where (some) members are accessible from user-code and others are reserved for the implementation?
Here is a minified example of the situation I'm trying to handle: I have a benchmarking framework where I instrument the functions given by a user. To check the sanity of execution th... | You could use a class with static members as the enumeration. This lets you have public and private members. The only catch is you would need to grant friendship to all of the things that need access to those private variables. That could look like:
struct return_code
{
constexpr static int ok = 0;
constexpr... |
73,405,440 | 73,406,604 | Initialization by conversion function for direct reference binding | I found out the rules for determining the candidate conversion functions, for direct reference binding, are not described clearly by the standard at least for me.
The rules are found in [over.match.ref]
Under the conditions specified in [dcl.init.ref], a reference can be
bound directly to the result of applying a conv... |
Why do we even need a conversion function to convert from cv2 T2 to cv1 T even though “cv1 T” is reference-compatible with “cv2 T2”?
Because only after the conversion is done(using the conversion function), the result is of type cv2 T2. In other words, the result of using/calling the conversion function is cv2 T2 and... |
73,405,684 | 73,406,157 | How would one specify a custom deleter for a shared_ptr constructed with an aliasing constructor? | How would one specify a custom deleter for a shared_ptr constructed with an aliasing constructor?
struct Bar {
// some data that we want to point to
};
struct Foo {
Bar bar;
};
shared_ptr<Foo> f = make_shared<Foo>(some, args, here);
shared_ptr<Bar> specific_data(f, &f->bar);
// ref count of the object point... | It doesn't really make sense to add a custom deleter in the construction of the aliasing shared_ptr.
The deleter is associated with the managed object, not the specific shared_ptr instance that will actually call it. The deleter is stored together with the object in the shared control block.
So once all aliasing and no... |
73,405,703 | 73,405,954 | Confused by local scope and function Parameters | Hello im confused by function parameters.
I've had a guy try and help me but i struggle to understand. I've been following learncpp
And local scope confuses me when it comes to parameters.
It says on learncpp, That if you declare a function
int foo(int x, int y) // int x and y are local
So How then can i access those ... | From main's perspective, the function is a black box. The box has two holes labeled Speed and max. main inserts two int's and lets the box do its thing. Then the box spits out an int at the end for main. At no point can main see into that box to access Speed or max (those are local only to the box). main can only feed ... |
73,406,458 | 73,413,966 | Is there an idiomatic way to solve small isolated independent task with CUDA? | I wrote my first CUDA program which I am trying to speed up. I ask myself if this is possible since the problem is not really appropriate for SMID-Processing (Single instruction, multiple data). It is more a "single function, multiple data" problem. I have many similar tasks to be solved independently.
My current appro... |
I have 512 CUDA cores.
Remember "CUDA cores" is just NVIDIA marketing speech. You don't have 512 cores. A Quadro P620 has 4 cores; and on each of them, multiple warps of 32 threads each can execute the same instruction (for all 32). So, 4 warps, each executing an instruction, on each of 4 cores, makes 512. In practic... |
73,407,650 | 73,407,991 | Unexpected page fault when writing return value from assembly procedure | I am experimenting mixing assembly(x86) and C++.
I wrote a procedure in assembly and then called it from C++.
However, when writing the returned value to a local variable I get a write permission violation error.
#include <iostream>
// will return 1 if all ok and 0 if b is 0
extern "C" int integerMulDiv(int a, int b,... | The following section of code stands out to me.
idiv dword ptr[ebx + 12]
mov ebx, [ebp + 20] ; get address of quo
mov [ebp], eax ; write quo
mov ebx, [ebp + 24] ; get address of rem
mov [ebp], edx ; write rem
I am not sure you are wanting to divide by the contents of memory 12 bytes after the address of the... |
73,407,671 | 73,407,910 | Cannot find boost shared library files in Android application | For Intellij (and Android Studio) I built a JNI shared library that links to boost libraries that I'd link to include in my Android app. I called System.loadLibrary on my .so file but it fails to find boost libraries when I run it. I get the following error:
java.lang.UnsatisfiedLinkError: dlopen failed: library "libbo... | Android's install process will not extract libraries that don't have the suffix .so. You have to remove the version suffix of the library (which serves no purpose on Android anyway, because libraries are not all installed to a single common path).
|
73,408,359 | 73,408,426 | What message is sent when user is trying to close window? | What message do i need to listen into my window procedure to close the GUI
when right-clicking into her taskbar button and clicking on X Close window?
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case ???:
{
//...
}
break;
}
Note: Im no... | It's the same message you get when the user presses the [X] button in the caption bar, or chooses Close from the system menu: WM_CLOSE.
The documentation contains useful information. In particular:
An application can prompt the user for confirmation, prior to destroying a window, by processing the WM_CLOSE message and... |
73,408,490 | 73,409,109 | CMake: Properly setting up a multi-directory project with a library and executable project | I'm struggling with properly setting up my CMake project. I've been trying to fix this error for the past 2 days. I'm currently learning CMake so please, pardon a "nooby" question.
I have a library, let's call it "InternalLibrary" and an executable project, called "App". InternalLibrary uses a static library, let's cal... | The parameters passed to the target_link_library command as any parameter other than the first one can be:
A library target name
A full path to a library file
A plain library name
[other stuff for different use cases]
Given the parameter you're passing in
target_link_libraries(InternalLibrary PUBLIC ${CMAKE_CURRENT_S... |
73,408,517 | 73,409,143 | Function that takes array of strings and returns the longest one | Trying to get this to work, but CodeBlocks gives me this error:
error: no matching function for call to 'max(char[4][10], int)'
Tried getting rid of template <>, made function to receive char*, nothing works.
How do I make this function to receive an array of strings (char[]), and spit out the longest one?
EDIT: Yeah... | If we simplify your code a lot we can boil it down to this:
#include <cstring>
char* max(char** strings, int n) { return nullptr; }
int main() {
char strings [4][10] = {"Cat","Dog","CANNIBALS","Witch"};
max(strings, 4);
return 0;
}
As Avi Berger pointed out char[4][10] isn't convertible to char**. The fo... |
73,408,931 | 73,411,150 | SWIG Converting a vector of vectors to a list of lists for Python, 'x' was not declared in this scope | I have a short c++ function that populates a vector of vectors when given inputs a,b which are rows and columns, like this
vec_of_vec.cpp
#include <iostream>
#include "vec_of_vec.h"
#include <vector>
std::vector<std::vector<int>> f(int a, int b) {
std::vector<std::vector<int>> mat;
for (int i = 0; i < a; i++)... | You were close, although the error message doesn't agree with the code shown or the error in the title. Code shown is for(int x = 0...) but error message is for(x = 0...). In the code shown you are missing the marked curly braces below in the %typemap(out) implementation:
%typemap(out) std::vector<std::vector<int>> (... |
73,409,118 | 73,409,378 | std::enable_if_t and std::array implementation | How can I use this function? (syntax)
template<typename T, typename = std::enable_if_t<std::is_array_v<T>>>
void foo(T&& a)
{
std::cout << a.size() << std::endl;
}
because this is error
std::array<std::string, 3> arr { "1", "2", "3" };
foo<std::array<std::string, 3>>(arr);
this error too
std::array<std::string, 3> ... | That function is (almost[1]) uncallable as written:
std::is_array_v is only true for built-in C-style arrays. That is std::is_array_v<int[10]> is true, but std::is_array_v<std::array<int, 10>> is false.
Built-in C-style arrays do not have a size member function.
That means that for any parameter type that will satis... |
73,409,581 | 73,409,650 | TMP using using-directives | Today I played around and tried to achieve template-meta-programming using using-directives.
So far I managed to write simple function calls, but nothing more.
#include <iostream>
template< int value_ > struct int_type { static constexpr int value = value_; operator int() { return value; } };
template< class lhs, cla... | [temp.alias]/4 forbids this sort of thing.
The defining-type-id in an alias template declaration shall not refer to the alias template being declared. The type produced by an alias template specialization shall not directly or indirectly make use of that specialization.
So no, alias templates alone can't be recursive... |
73,409,797 | 73,409,876 | Why do I get 0xC0000374 (STATUS_HEAP_CORRUPTION) error when using qsort() function of std in C++, and how do I fix it? | It's a simple C++ test code, it will just sort the student structs by their studentId which is an integer:
#include <iostream>
using namespace std;
struct student {
int grade;
int studentId;
string name;
};
int studentIdCompareFunc(const void * student1, const void * student2);
int main()
{
const i... | qsort(studentArray, ARRAY_SIZE, sizeof(student), studentIdCompareFunc);
qsort is a C library function and it knows absolutely nothing, whatsoever, about C++ classes. Like that std::string object in the structure this code is trying to sort. Undefined behavior, and hillarity, ensues.
If the intent here is to write C++ ... |
73,410,284 | 73,410,376 | Why do I get weird stray errrors with cxxopts.hpp and meson + ninja build? | I'm currently working on this project. I'm using cxxopts.hpp in order to parse cli options but since I added it I get some error that I now list how to reproduce:
Build the project
$ meson build
$ cd build
$ ninja
Everything good so far, it builds without any errors.
I can change anything other than test/vector.cpp... | As pointed out by @KamilCuk in their comment, this error emerged from a name collision between the standard library #include <vector> and the binary vector I was creating from vector.cpp.
Changing the name of my binary solves the issue.
EDIT:
The desired behavior can be also achieved by setting the option implicit_incl... |
73,410,421 | 73,410,515 | Moving a vector of unique_ptrs bug | I've always used std::move to move a std::vector into an empty one in member initialization lists like this:
class Bar{};
class Foo
{
public:
Foo(std::vector<std::unique_ptr<Bar>>&& t_values)
: m_Values{ std::move(t_values) }
{
}
private:
std::vector<std::unique_ptr<Bar>> m_Values{};
};
I tho... | A move results in a "valid but unspecified state":
Moved-from state of library types [lib.types.movedfrom]
Objects of types defined in the C++ standard library may be moved from.
Move operations may be explicitly specified or implicitly generated. Unless
otherwise specified, such moved-from objects... |
73,410,428 | 73,484,006 | Within qmake how can I get the full path to static library created by a subproject? | I am currently using qmake to build an application. The project is structured to have some sub libraries. So my project looks like this:
--root project (.pro file)
--app
|_ pro file and cpp/h files
--core
|_ pro file and cpp/h files
--gui
|_ pro file and cpp/h files
W... | In my projects I use the solution as you suggested:
I can turn "debug" into a variable that is populated based off the config in order to dynamically build this path to be either debug or release.
The .pro file code example:
CONFIG(debug, debug|release) : BUILD_TYPE = debug
CONFIG(release, debug|release) : BUILD_TYPE... |
73,411,110 | 73,670,742 | MPI Matrix Multiplication - Task sharing when size(of procs) < rows of matrix | I am trying to perform matrix-matrix multiplication in MPI using c++.
I have coded for the cases where number_of_processes = number_of_rows_of_matrix_A (so that rows of matrix_A is sent across all processes and matrix_B is Broadcasted to all processes to perform subset calculation and they are sent back to root process... | From getting suggestion from people here, I came to the below solution.
floor(N * (j + 1)/P) - floor(N * j/P)
Where :
N : Number of rows in matrix
P : Total number of processes available
j : jth process. (i.e if P = 4, j = 0,1,2,3)
|
73,411,359 | 73,411,416 | Why am I unable to use my increment operator overload? [C++] | I have the following struct:
struct sequence_t {
uint8_t val;
explicit sequence_t(uint8_t value) : val(value) {}
sequence_t() : sequence_t(0) {}
auto operator++() -> sequence_t& { // prefix
val = (val + 1) % 16;
return *this;
}
auto operator++(int) -> sequence_t { // postfix
... | auto messenger::make_message(uint8_t const* data, const uint8_t data_size) const
That const keyword at the end signifies that this is a const class method. A const class method:
Can only call other const class methods
Cannot modify any class members
If any class members are objects, only their const methods can be ca... |
73,411,437 | 73,440,182 | Accessing Function from a Nested Include in C++ | Trying to understand more complex project structure in C++. This is for an nrf52840 (embedded 2.4Ghz radio device). But the question is about C++ but using it for an example.
Say I have 5 files I created:
1) main.cpp
2) mouse.cpp
3) mouse.h
4) radio_controls.cpp
5) radio_controls.h
There is also a .h I included:
1) es... | @Steve4879, yes, There's a way to use structures from the esb.h. You can use forward declaration for it. Take a look:
#pragma once
#include <memory>
class ClassFromLibrary;
struct StructFromLibrary;
namespace controls::radio {
std::shared_ptr<ClassFromLibrary> makeClassFromLib(const StructFromLibrary &data);
// he... |
73,411,698 | 73,412,242 | OpenMP parallel iteration over STL unordered_map VS2022 | I am trying to parallelize my sparse square matrix self multiplication. For instance, I want to compute:
R = A * A
where R and A are sparse matrices. These sparse matrices are represented using 2d unordered_map, where A[i][j] corresponds to the (i,j)-th element. Also i and j are the keys of the corresponding 2d un... |
You don't say how your code "doesn't work".
I'm guessing it doesn't compile: OpenMP needs a random-access iterator, and unordered map is not.
However, you're mapping int to a sparse row. Why not make that an array of sparse rows?
You have a race condition on your output array so the results will be incorrect. You need... |
73,412,127 | 73,412,337 | How do I preserve inter-string null characters in std::format string | In an attempt to refactor this code:
static const auto opf_str = [&]() {
std::string result;
for(auto& e : extension_list) {
result.append(StringUtils::ToUpperCase(e.substr(1)) + " file (*"s + e + ")\0*"s + e + "\0"s);
}
result += "All Files (*.*)\0*.*\0\0"s;
return result;
}();
I replaced ... | std::string as argument doesn't work, but at least std::string_view should be fine. There is no issue with having it even as the result of a constant expression if it is referencing only static objects:
std::format("{0} file (*{1})\0*{1}\0"sv, StringUtils::ToUpperCase(e.substr(1)), e)
Looking a the current draft spec... |
73,412,140 | 73,412,514 | Why can std::find_if potentially fail with std::bad_alloc exception? | As I stated in the title, I just can't understand why does this function throw std::bad_alloc. If we take a look at the cppreference all of the three possible implementations are just as someone would assume and it looks like there is no special need dynamic memory allocation.
| The 3 possible implementations shown in cppreference are for the 3 overloads that do not take an execution policy. It is specifically the overloads that do take an execution policy that are specifically listed as possibly throwing std::bad_alloc.
Execution policy involves the possibility of parallelizing or vectorizing... |
73,412,333 | 73,412,802 | Throw and Catch in c++ | (c++)So my throw code is like
throw "No paper"
And my catch code is
catch(const char *txt ){}
My question is why we are using a pointer to define the catch type and why char, can't we use something like
catch(string txt){}
I just learn exception handling and can't figure out why they used a pointer.
here is the code!
| When you throw a C string literal like "No paper" you are actually throwing a pointer of type const char* and not an array of characters. This is how C++ works.
In other words, a string literal automatically decays into a const char*. It doesn't magically turn into a std::string or something like that when the catch pa... |
73,412,515 | 73,434,692 | How to get global mouse position in Qt6? | I'm trying to get global position of the mouse however the functions mentioned in older topics are either deprecated or not working as intended. I have tried QCursor::pos() as seen below but it didn't work as intended.
#include <QtCore/QCoreApplication>
#include <QCursor>
#include <iostream>
int main(int argc, char *a... | It is very simple. QCursor is in the Gui module of Qt see here, so you have to change QCoreApplication to QGuiApplication and then it works (already tested it).
|
73,413,425 | 73,413,578 | How to write a void function for different Structs/Containers with a template? | For instance I have a function
void func(my_cont &C){
C.membA = 1;
C.membB = 2;
dosomething_with(C);
}
Also what to do in the function, if I have a Struct that does not have a member B?
| This is a way to statically check for the existence of a membB member inside the template function.
template<typename T>
void func(T& C)
{
C.membA = 1;
if constexpr (requires() { C.membB; })
{
C.membB = 2;
}
}
int main()
{
struct A
{
int membA;
};
struct B
{
... |
73,413,518 | 73,432,109 | Could golang implement this interview question of getting array summary without for/while if/else? | I'm looking into an interesting interview question, and try to implement it with go.
(1) Input an integer number, say i
(2) Calculate the summary of 1+2+...+i, output the summary
(3) Requirement: don't use multiply, don't use loop(for/while), and don't use if/else
Well, in c++ or java this is pretty easy. We can ... | Here's a language-neutral solution that uses no multiplication, no for and no if.
It's kind of like a recursive solution, where the if is substituted with a function map, having functions for the true and false branches:
fs := map[bool]func(int) int{}
fs[false] = func(int) int { return 0 }
fs[true] = func(i int) int { ... |
73,414,499 | 73,415,853 | Parallel programming with C++ and MPI -- same executable possible? | I would like to create a program that would work with both MPI and without at run time and I have reached a point where I think that is not possible.
For example, an MPI program might look like this:
#include <mpi.h>
int main(int argc, char* argv[])
{
MPI_Init(&argc, &argv);
...
MPI_Finalize ();
return 0;
}
B... | A compiled MPI program needs MPI libraries at runtime in addition to the mpirun call (not required by all MPI implementations for 1 process nor in all cases). Thus, to run MPI function only in some cases at runtime without having a dependency to MPI, the potion of the code using MPI needs to be dynamically loaded. This... |
73,415,591 | 73,416,484 | How to Write more than one data on same cell when export to excell? | I'm us'ng Qxlsx for export data to excell. Day, month and year data are not coming as a whole, but separately. I can print them one by one while printing them in excel. How can I combine these 3 data and print it?
here is my code for export
for (i = 0; i < maxRowCount; ++i) // get maximum data row
{
//strList.cl... | Sounds like you just want QString::arg:
xlsx.write(k, 5, QString("%1/%2/%3").arg(dataColums[4][i]).arg(dataColums[3][i]).arg(dataColums[2][i]));
As an aside, you can make your code a lot cleaner if you eliminate the for-switch pattern:
format.setNumberFormatIndex(2);
for (int j = 0; j < 8; j++) {
maxRowCount = min(... |
73,415,953 | 73,415,985 | How to instantiate and rename a template class | Description
I declared a template class
template <typename T,size_t RootNum>
class Tree;
And I want to specialize another template class BinaryTree, whose RootNum is 2, but every members is identicial with class Tree.
An inelegant method is defining a class BinaryTree inherits class Tree as below
template <typename T... | You are looking for an alias template:
template <typename T>
using BinaryTree = Tree<T,2>;
|
73,416,040 | 73,416,427 | cmake disabling MSVC incremental linking | Background
I have some project which after a while (many builds when developing) consumes so many computer resources during linking process. So much that my machine becomes unresponsive (even mouse do not move).
My project has many static libraries (4) targets and many executable (2 are production excusable and 4 for t... | For the static linker flags you do not need to add those options. In case of MSVC lib.exe is used as static linker and that one does not understand these options.
For most projects of mine I use inside the CMakeLists.txt the add_link_options command to let CMake properly add the link options to the linker commands.
add... |
73,416,712 | 73,416,777 | Why is lock_guard a template? | I just learned about std::lock_guard and I was wondering why it is a template.
Until now I have only seen std::lock_guard<std::mutex> with std::mutex inside the angle brackets.
| Using std::lock_guard<std::mutex> is indeed quite common.
But you can use std::lock_guard with other mutex types:
Various standard mutex types, e.g.: std::recursive_mutex.
Your own mutex type. You can use any type, as long as it is a BasicLockable, i.e. it supports the required methods: lock(), unlock().
|
73,417,828 | 73,418,313 | Explicit copy constructor of a parameter passed via std::async | In the following program foo function is executed asynchronously and its argument of type A is copied inside async by value:
#include <future>
struct A {
A() = default;
explicit A(const A &) = default;
};
void foo(const A &) {}
int main() {
auto f = std::async(std::launch::async, foo, A{});
}
Despite co... | In the post-C++20 draft (https://timsong-cpp.github.io/cppwp/n4868/futures.async) there is a "Mandates:" clause which effectively only requires std::is_move_constructible_v<A> to be satisfied. This tests whether a declaration of the form
A a(std::declval<A&&>());
would be well-formed, which it is even with explicit on... |
73,418,366 | 73,420,706 | searching for the maximum number between two indexes in an array of numbers | I want to calculate the maximum number between two indexes in an array in an efficient way. I will be given a very large number of queries in each query I will be given indexes l and r where I need to find the maximum number between these two indexes
when I tried to solve that problem my solution had a time complexity ... |
when I tried to solve that problem my solution had a time complexity of O((l-r)*q) where q is the number of queries
The only real way to reduce this is if the queries overlap. Then we need some way to store some kind of intermediate result (the max element of some given sub-range) so we can reuse it.
The general appr... |
73,418,382 | 73,418,505 | how to only indent brackets after case labels using clang-format | I wanna a style that only indent brackets after case labels, while keeping case label not indented.
this is what I want:
switch(a)
{
case 1:
{
do_some_thing();
}
break;
}
I find an option IndentCaseLabels, but it will the whole things include the case label, neither true or false isn't what I want
... | It's just immediate above one you found in the manual.
IndentCaseBlocks: true
Indent case label blocks one level from the case label.
false: true:
switch (fool) { vs. switch (fool) {
case 1: { case 1:
bar(); ... |
73,418,423 | 73,438,321 | MacPorts /opt/local/bin/python3 can't find _libiconv symbol unless run under shell | I just updated macOS to Monterey 12.5 and updated MacPorts as described here. I have MacPorts python38, python39 and python310 installed. Each exhibits the same new bad behavior.
I have a C++ program that writes a small Python script into a file and then runs a Python interpreter as a child process, specifying the full... | The only situation where macOS' loader would search /usr/lib/libiconv.2.dylib for a symbol that /opt/local/lib/libintl.8.dylib expects in /opt/local/lib/libiconv.2.dylib is when you have DYLD_LIBRARY_PATH set to include /usr/lib. This variable causes dyld (the macOS loader) to ignore the absolute path of /opt/local/lib... |
73,418,551 | 73,420,180 | C++ inherit class as static | After reading through How to write a Java-enum-like class with multiple data fields in C++? I decided to give it a try and added some functionality to it. In order to abstract this functionality I've put it in a separate class EnumClass<T>. But since these abstracted features have to be static in the implementation but... | If you want members of EnumClass to be static then just make them static. static as in class Planet : public static EnumClass<Planet> does not make sense. You cannot turn non-static members into static members like that.
#include <array>
#include <iostream>
#include <cstddef>
template<class T,size_t S>
class EnumClass... |
73,418,590 | 73,423,517 | Legality of using delete-expression on a pointer not obtained from usual new | I wonder if this code is legal:
delete new (operator new(1)) char;
This code does the same thing, but doesn't use delete expression on a pointer obtained from placement new:
void* p = operator new(1);
new (p) char;
delete static_cast<char*>(p);
The standard rules at [expr.delete#2]:
In a single-object delete express... | delete new (operator new(1)) char; does appear to be legal. Like you said, the standard does not make any exceptions for placement new.
Your second example is also legal:
void* p = operator new(1);
new (p) char;
delete static_cast<char*>(p);
Let's walk through what happens step by step. The call to operator new implic... |
73,419,022 | 73,419,673 | Android JNI GetMethodID for sharedPreferences.getString | I'm trying to get a string from sharedPreferences on Android from C++ code using JNI. I can successfully get the MethodID for getBoolean with this code:
jmethodID getBooleanMethodID = JEnv->GetMethodID(sharedPreferencesClass, "getBoolean", "(Ljava/lang/String;Z)Z");
The getBoolean function is defined in Java as getBoo... | The correct format turned out to be:
jmethodID getStringMethodID = JEnv->GetMethodID(sharedPreferencesClass, "getString", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;");
There were a couple issues with my original attemps. First, the second String arg inside the brackets needed a semi-colon. Then I needed... |
73,419,663 | 73,434,976 | QTabwidget click tab event C++ | I am new in QT 4 C++ .I have QT 4 form with QTabwidget like in th picture below.
enter image description here
I want to disply on console the string "aa" by selecting tab on clicking it.
Here is my newForm.h
#ifndef _NEWFORM_H
#define _NEWFORM_H
#include "qwidget.h"
#include "ui_newForm.h"
class newForm : publ... | First of all, why are you using Qt 4 in 2022?
Next thing use currentIndexChanged(int) istead of stateChanged().
Did you also noticed that stateChanged() doesnt pass an interger which is needed for onTabChanged(int).
You also connected widget.tabWidget which isn't initilized yet.
This code might work:
newForm.h
#ifndef ... |
73,419,669 | 73,549,652 | How to get the mangled symbol of a function in C++? | Context
I'm using dlmopen to load multiple instance of a shared library which I can't modify (proprietary). I do this because this library is not thread-compatible, so I need an independent version of it to be loaded for each thread.
void *handle = dlmopen(LM_ID_NEWLM, "/myLib.so", RTLD_LAZY);
In order to get the funct... |
How do i get <function_symbol> knowing that
Presumably you know which function you want to call. Let's say its name is somelib::Init(int, char**).
Find that function address:
nm -CD libsomelib.so | grep 'somelib::Init\(int, char\*\*\).
This should produce something like 12345fa T somelib::Init...
Find its mangled n... |
73,419,997 | 73,420,127 | Generate a random amount of numbers and sort them with bubble sort | I am new to programming and I am trying to generate an amount of numbers b and then sorting it with bubble sort without using the sort function of list (Because that would be too easy). Since arrays must have a constant value and I cannot put b as the value I'm trying to put the numbers into a list first and then conve... | Prefer to use std::vector<int>:
std::vector<int> data;
for (int index = 0; index < b; ++index)
{
int x = rand() % a;
std::cout << x << "\n";
data.push_back(x);
}
// The std::vector can be treated as an array.
To answer your question about converting std::list to an array:
std::list<int>::iterator iter ... |
73,420,175 | 73,420,364 | Fold expresion & CRTP | I'm writing this small application trying to test about fold expressions and i can't get it to compile, it complaints about ambiguous request on method Play, i don't understand why the signature of the function Play should be different on both calls..
#include <iostream>
#include <any>
using namespace std;
struct A
{... | Beside the constness mentioned in the comment, the fix is
template<typename... Keys>
struct MyMap : public BaseValue<Keys>...
{
using BaseValue<Keys>::Play ...;
};
The initial problem, has to do with name-lookup, which happens before overload resolution, see [this answer] https://stackoverflow.com/a/60775944/24128... |
73,420,352 | 73,420,646 | How to see intermediate files created during C++ compilation process | When building an application in C++, I want to see all my intermediary files generated during the process like .o file, .i file, .asm file etc. But when I jump into explorer in windows, it shows nothing even after I try to show "hidden files".
I tried to read one SO post but it is involving some CMake thing.
Can these ... | Just use the -save-temps compiler option. From the man page:
-save-temps
Store the usual "temporary" intermediate files permanently; name
them as auxiliary output files, as specified described under
-dumpbase and -dumpdir.
There are a bunch of other options to influence which files and what name t... |
73,420,763 | 73,421,142 | deducing variadic inheritance type from constructor | I have a struct that can have a variadic number of members by inheriting from them:
struct A{ int a; };
struct B{ float b; };
struct C{ const char* c; };
template<typename ... Ts>
struct collection : Ts... {
};
int main() {
collection<A, B, C> n;
n.a = 5;
n.b = 0.5f;
n.c = "123";
}
now I want to us... | You can do this using a user defined deduction guide and a couple "meta functions" to map the parameter type to the desired class type. First the meta functions get declared like
A type_map(int);
B type_map(float);
C type_map(const char*);
and then we can create a deduction guide in the form of
template<typename... T... |
73,420,945 | 74,254,696 | Air control for mouse movement to change direction mid-air after jumping | I'm working on a custom character in Unreal Engine 5. I want the player to have his velocity direction based on mouse movement when he is in the air.
For example, when you jump forward and move your mouse right, he should follow the new direction, but if you jump backwards and move your mouse right, it will change dire... | I created a custom character movement component and overrode CalcVelocity() method:
// AirControl = 0;
// AirControlBoostMultiplier = 0;
// AirControlBoostVelocityThreshold = 0;
void UCustomCharacterMovementComponent::CalcVelocity(const float DeltaTime, const float Friction, const bool bFluid, const float BrakingDecel... |
73,421,127 | 73,421,180 | Simple C++ code returns different outputs on different compilers | I wrote a program in C++ that receives 2 strings as input and checks if one is the inverse of the other.
#include<iostream>
#include<string>
int main() {
std::string word, word_inv;
std::cin >> word;
std::cin >> word_inv;
int n=word.size(), i=0;
while(word_inv[i] == word[n-i-1])
... | while(word_inv[i] == word[n-i-1])
This condition requires word_inv[i] to not be equal to word[n-i-1] for the loop to end. What if that doesn't happen while the indices are within bounds?
What happens then is that the program tries to read memory out of bounds with undefined behavior as a result, which means that anyth... |
73,421,277 | 73,421,799 | How does a shared_ptr handle copy to a pure virtual base class? | Class B expects to receive an instance of shared_ptr<IError>.
Class A implements IError and is passed by value to the constructor of B.
I would like to understand how this scenario is handled. How does the shared_ptr as a template class handle the conversion to IError?
In a simple case where B receives shared_ptr<A> I ... | Debugging time! Let's find out what happens by using the tools we have available as developers.
The memory of the shared_ptr objA looks like this (type &objA in the memory window; it will be replaced by its address):
It has a pointer to the object (000002172badd8e0) and a pointer to the control block.
The control bloc... |
73,421,698 | 73,479,188 | C++ client socket send from port change with send to change? | I have a UDP based server/client application where on initial communication, the client sends a message to the server (on specific IP/port), then the server replies with a new port to talk to. The client then sends another message to the new port (same server IP as before), and communications normally continue from the... | The answer turns out to be that the client IP/port is not guaranteed to stay the same. I added debug to the server and saw it happen again, so was able to verify that when the client changed it's send-to port, it caused the server to see a different client send-from port.
I'm not entirely sure if this is due to somethi... |
73,421,702 | 73,442,047 | Feature clock_monotonic is already defined to be "OFF" and should now be set to "ON" when importing features from Qt6::Core | I tried to run my project that I did 2 months ago and get this error. I suppose that's because of new version or something like that but I do not know what to do.
The error itself:
/opt/homebrew/lib/cmake/Qt6/QtFeature.cmake:1249: error: Feature clock_monotonic is already defined to be "OFF" and should now be set to "O... | It's a not-uncommon issue in CMake where values are cached, but then updating libraries does not update the values as expected.
If you delete CMakeCache.txt in your build folder and reconfigure (call cmake / qt-cmake with your initial options again) then it will go away.
|
73,421,752 | 73,430,153 | Expand tuple to parameters pack in member initializer lists | I need to initialize a base class with arguments stored in a std::tuple.
I have access to C++17 and managed to figure out that std::make_from_tuple may work but would require a copy constructor for the base class.
An example:
#include <tuple>
template<class Base>
class WithTupleConstructor : public Base // Sort of a M... | I found a solution based in this answer, turns out that it is achievable using std::make_index_sequence and std::get.
An auxiliary function that "unwraps" the tuple is required but it can be defined as a private constructor:
#include <tuple>
template<typename Tuple>
using make_tuple_index_sequence = std::make_index_se... |
73,422,091 | 73,425,424 | What is the proper way to zoom in and out using orthographic projection? | I have a view matrix:
float left = -(float)viewPortWidth / 240, right = (float)viewPortWidth / 240, down = -(float)viewPortHeight / 240, up = (float)viewPortHeight / 240;
viewMatrix = glm::ortho(left, right, down, up, -1.0f, 1.0f);
I am dividing by 240 to be able to show 16:9 units when it is full screen. Here... | Try dividing all the parameters.
float zoom = 16.0f / 14.0f; // 114% zoom in
float left = -(float)viewPortWidth / 240, right = (float)viewPortWidth / 240, down = -(float)viewPortHeight / 240, up = (float)viewPortHeight / 240;
viewMatrix = glm::ortho(left / zoom, right / zoom, down / zoom, up / zoom, -1.0f, 1.0f);
... |
73,422,114 | 73,429,394 | C++ Language Parsing and Logical Operators's Short-Circuit | When it comes to the short-circuit of the logical operators, according to the Standard in 7.6.14 e 7.6.15 (N4868).
7.6.14 Logical AND operator
[...] the second operand is not evaluated if the first operand is false.
7.6.15 Logical OR operator
[...] the second operand is not evaluated if the first operand evaluates t... | You are correct as far as compiler's "mental model" and whoever wrote "if cond1 is false, so the full-expression is false" is correct as far as CPU's "mental model" in this specific case.
On the compiler side, parsing cond1 && cond2 && cond3 results in (using clang -ast-dump)
`-BinaryOperator 0x557a79f02230 <col:1, col... |
73,422,693 | 73,422,762 | C++: How can one get return type of a class member function using std::invoke_result_t? | How can one get return type of a class member function using std::invoke_result_t in C++?
#include <type_traits>
#include <vector>
template <class T>
struct C
{
auto Get(void) const { return std::vector<T>{1,2,3}; }
};
int main(void)
{
// what should one put below to make x to have type std::vector<int> ?
std::... | std::invoke_result_t works on types, but C<int>::Get is not a type. It is a non-static member function.
The type of C<int>::Get is std::vector<int>(C<int>::)(): Member function of C<int> that returns std::vector<int> and accepts no parameters. That type is what you need to give to std::invoke_result_t. Or rather, a ... |
73,422,804 | 73,422,839 | Initializing array of Objects in C++ Composition | I wanted to design a composition using C++ as shown below:
#define NUMBER (4)
class wheel {
int radius;
public:
wheel();
wheel(int);
//copy constructors prototype
//getters and setters prototypes
};
wheel::wheel() : radius(1) {}
wheel::wheel(int r) : radius(r) {}
//wheel class copy constructor def... | You are attempting to assign to an array element. And one that's out of range at that.
Using the constructor's initializer list, this will compile, though you should consider using STL containers rather than a raw array.
car::car() : fourwheels{wheel(1), wheel(1), wheel(1), wheel(1)}
{
}
The code you had commented out... |
73,423,005 | 73,423,035 | Circular dependencies missing type specifier - int assumed. Note: C++ does not support default-int | I am still new with c++ and I was told that #pragma once was supposed to take care of circular dependencies
My GameManager.h and GameSetting.h both need to know each other and each have a pointer of the other
for my GameSettings.h i have:
#pragma once
#include "PlayerManager.h"
#include <fstream>
#include "GameManager.... | Use a forward declaration of GameSettings in GameMager.h. Pointers do not need complete class definitions until they are derefenced.
#pragma once
class GameSettings;
class GameManager {
private:
bool isActive = false;
GameSettings *gS;
public:
bool getIsActive() { return isActive; }
bool startGame() { re... |
73,423,060 | 73,427,103 | Is this out-of-bounds warning from gcc erroneous? | Earlier today, gcc gave me a warning that I belive to be erroneous and now I am very unsure if it is an actual compiler bug(usually highly unlikely) or a bug in my code(usually highly likely). I managed to reduce it down to the following code:
#include <algorithm>
#include <array>
#include <iostream>
int main()
{
... | It is indeed a compiler bug, as can be seen in this bugzilla report, which contains almost identical code to the one in my question.
Thanks to Marc Glisse for providing this link to a lot of similar bugs and thereby helping me track down the relevant one.
|
73,423,280 | 73,425,123 | How to install a cpp library using cmake on Windows x64? | I'm using CLion with MinGW-GCC on the Windows-x64 platform - This is the background of the problem.
I was trying to install gtest before. But a lot of confusion arose in the middle.
First time I ran those commands(in googletest-release-1.12.1\) according to the instructions of googletest-release-1.12.1\googletest\READM... | The difference between
cmake ..
and
cmake -G "MinGW Makefiles" ..
Is the choice of generator: The former uses the default generator, the latter uses the generator you specified. (cmake --help should put a * next to the default generator.)
Based on the error message I assume this is a visual studio generator and you m... |
73,423,328 | 73,423,422 | Creating the Backtracking Algorithm for n-queen Problem | I have tried to come up with a solution to the n-queen problem, through backtracking. I have created a board, and I think I have created functions which checks whether a piece can be placed at position column2 or not, in comparison to a piece at position column1. And I guess I somehow want to loop through the columns, ... | There is not always a solution, like e.g. not for 2 queens on 2x2 board, or for 3 queens on a 3x3 board.
This is a well-known problem (which can also be found in the internet). According to this, there is not a simple rule or structure, how you can find a solution. In fact, you could reduce the problem by symmetries, ... |
73,423,556 | 73,425,542 | elegant way to convert variadic inheritance members to tuple | consider a type that inherits from multiple classes. I want to iterate over the inherited classes, ideally making a get_tuple() member function that returns a reference tuple for precise manipulation:
struct A { int a; };
struct B { float b; };
struct C { const char* c; };
template<typename ... Ts>
struct collection :... | You could rely on the fact that every single one of the base classes allows for structured binding to work with one variable to extract the members.
/**
* Our own namespace is used to avoid applying AccessMember to arbitrary types
*/
namespace MyNs
{
struct A { int a; };
struct B { float b; };
struct C { const char... |
73,424,045 | 73,424,137 | Will a heap allocated object get deleted when I assign it to a vector and then delete the vector? | I'm new to computer science and I want to know if an object is being deleted if I heap allocate it and then for e. put it in a vector of pointer and then delete the vector. Will the heap object be gone? Here is an example of what I mean.
int main()
{
Type* someHeapObject = new Type();
vector<Type*> someVector... | There are two things that you have to take care of:
Mistake 1
In delete [] someVector you're using the delete [] form when you should be using the delete form because you used the new form and not the new[] form for allocating memory dynamically. That is, delete [] someVector is undefined behavior.
Mistake 2
The second... |
73,424,050 | 73,427,930 | How to use future / async in cppyy | I'm trying to use future from C++ STL via cppyy (a C++-python binding packet).
For example, I could run this following code in C++ (which is adapted from this answer)
#include <future>
#include <thread>
#include <chrono>
#include <iostream>
using namespace std;
using namespace chrono_literals;
int main () {
pro... | Clang9's JIT does not support thread local storage the way the modern g++ implements it, will check again when the (on-going) upgrade to Clang13 is finished, which may resolve this issue.
Otherwise, cppyy mixes fine with threaded code (e.g. the above example runs fine on MacOS, with Clang the system compiler). Just tha... |
73,424,175 | 73,577,429 | MacOS .app can't open file by double click | I have a c++ program, which should get the file name from argv, open this file, and work with it.
Program works perfectly well, because: when I call binary (Unix Executable) from the terminal, program gets th name from argv and works with it, but when I made from this binary MacOs program .app, then, by double clicking... | When you run a command line program it works as all command line programs, by reading argv/argc. But when you bundle it into a .app directory with a PLIST you are instructing it to use Launch Services and the Info.plist file.
By doing, so you change how it opens files. Using Launch Services, you can leave the applicati... |
73,424,252 | 73,424,283 | question about implementation of add_rvalue_reference | Implementation of add_rvalue_reference in cppreference is the following. What is the need for the int argument (i.e. 0) vs. no argument ?
namespace detail {
template <class T>
struct type_identity { using type = T; }; // or use std::type_identity (since C++20)
template <class T>
auto try_add_rvalue_reference(int) -... | If the implementation was like this:
namespace detail {
template <class T>
struct type_identity { using type = T; }; // or use std::type_identity (since C++20)
template <class T>
auto try_add_rvalue_reference() -> type_identity<T&&>;
template <class T>
auto try_add_rvalue_reference() -> type_identity<T>;
} // nam... |
73,424,936 | 73,425,014 | Given two arrays A & B with positive integers, find Maximum product of Array A after atmost N operation | We are given two Arrays of size n with positive integers. we are allowed to modify elements of array A such that A[i]=A[i]*B[j] or A[i]=A[i]+B[j], where 0<=i,j<n. we are allowed to use each element of array B only once. Find the maximum product of Array A after at most n operation.
The purpose of my question is to look... | Your for loop is wrong.
for(int j=0;j<n;j++){
a[i]=max(a[i]+b[i],a[i]*b[i]);
}
You're assigning using i as index instead of j. It should be
for(int j=0;j<n;j++){
a[j]=max(a[j]+b[j],a[j]*b[j]);
}
Edit: Since you've corrected your input, there's another logical fallacy. Consider the foll... |
73,425,423 | 73,425,562 | Why PCRE regex only capture 19 groups? |
My Question:
My regex pattern is: (a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)(n)(o)(p)(q)(r)(s)(t)(u)(v)(w)(x)(y)(z)
and My string is: abcdefghijklmnopqrstuvwxyz
the code's output is:
i_0:0 i_1:26 i_2:0 i_3:1 i_4:1 i_5:2 i_6:2 i_7:3 i_8:3 i_9:4 i_10:4 i_11:5 i_12:5 i_13:6 i_14:6 i_15:7 i_16:7 i_17:8 i_18:8 i_19:9 i_20:9 ... | It returns 19 capture groups, because you provided space to return 20 matches, and one is used for whole matching string
Captured substrings are returned to the caller via a vector of integers whose address is passed in ovector. The number of elements in the vector is passed in ovecsize, which must be a non-negativ... |
73,425,691 | 73,433,745 | Check the viability of a conversion function | I have the following code:
struct S {
operator int(); // F1
operator double(); // F2
};
int main() {
int res = S();
}
Since neither F1 nor F2 is cv-qualified, the type of the implicit object parameter is S&, and the corresponding argument to be matched against is S().
Now, per [over.match.viable]/4: ... | The main concern expressed in your question appears to be how a given rvalue argument can bind to an implicitly declared lvalue reference parameter. (I'm not here even attempting to make an adjudication on the extensive discusssion in the comments to your question about whether or not any actual overloads are involved ... |
73,425,887 | 73,426,169 | CMake, Public private folder structure | If I have a folder-structure like this:
.
├── Core
│ ├── Private
│ │ └── example.cpp
│ └── Public
│ └── example.h
└── Math
├── Private
│ └── Math.cpp
└── Public
└── Math.h
How would I accomplish it, in CMake, to make a import, in example the folder Math/Private, like this:
#include ... | You cannot accompilish this with the given project structure: There simply is no example.h file with a parent directory Core.
Restructure the project and use target_include_directories().
Project structure
.
├── Core
│ ├── Private
│ │ └── example.cpp
│ └── include
│ └── Core
│ └── example.h
├── ... |
73,426,525 | 73,436,622 | Scaling an input range by minimum in (upcoming) C++23 (using zip_transform and repeat) | In ADSP Podcast Episode 91 (2022-08-19, around 14:30 ... 16:30) Bryce Lelbach and Conor Hoekstra talk about an example application of the (hopefully) upcoming C++23 ranges views zip_transform and repeat: scaling a range of values by the (non-zero) minimum value of that range.
Since to my knowledge at the time of writin... |
Did I get it right?
No. zip_transform accepts variadic template arguments as input ranges, the first argument of zip_transform must be the transform functor, so you should
auto m = std::ranges::min(range);
return std::views::zip_transform(
std::divides{},
range,
std::views::repeat(m)
);
It's worth noting that ... |
73,426,849 | 73,528,223 | Fastest way to upload OHLC in C++ | I'm implementing a class to store time-series (OHLCV) which will contain methods applied to parsed file. I'm trying to figure it out if there is a faster way to upload the content of each file (.csv which are ≈ 40000 rows) into a std::unordered_map<std::string, OHLCV>. Knowing that the structure of the file is fixed (... |
Increasing buffer size to reduce number of writes. As referenced here, "With a user-provided buffer, reading from file reads largest multiples of 4096 that fit in the buffer"; following a test published in another answer, the optimal buffer size should be around 64KB. Also, note that for my compiler is ok to open the ... |
73,426,856 | 73,427,382 | C++20 : Parameter pack partial expansion | I need a way to partially expand a parameter pack. The size of the subset has to be determined by another variadic parameter. It will be more clear what I mean with sample code.
struct EntityA {
EntityA(int, char, unsigned) {}
EntityA(int, char, unsigned*) {}
EntityA(int, char*, unsigned*) {}
EntityA(i... | you can use std::index_sequence for that
template <typename E, typename ... SArgs, typename ... PArgs>
E construct(Service<SArgs...>& service, PArgs&& ... pargs) {
constexpr auto size = sizeof...(PArgs);
constexpr auto missing_size = 3 - size; // note: you need to somehow know the parameter count
using def... |
73,426,985 | 73,427,478 | Is it possible for implicit object creation to not create objects in certain situations? | According to [intro.object]/10:
Some operations are described as implicitly creating objects within a specified region of storage. For each operation that is specified as implicitly creating objects, that operation implicitly creates and starts the lifetime of zero or more objects of implicit-lifetime types ([basic.ty... |
it can choose not to create objects if that would make the program legal.
Um, no; it cannot. The literal text you quoted says "that operation implicitly creates and starts the lifetime of ... if doing so would result in the program having defined behavior." There is no conditional here, no choice about it. So if the ... |
73,427,089 | 73,427,104 | Merge Sorted array Error in c++: reference binding to null pointer of type 'int' (stl_vector.h) | https://leetcode.com/problems/merge-sorted-array/
In this leetcode question, this is the logic, I used
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int i = 0;
int j = 0;
int k = 0;
vector<int> ans;
while (i<m && j<n) {
if (nums1[i]... | This is a vector of size zero
vector<int> ans;
This code attempts to change an element of the size zero vector.
ans[k++] = nums1[i++];
That's the cause of your error.
If you want to add an element to the end of a vector use push_back
ans.push_back(nums1[i++]);
C++ vectors don't change size automatically, you have to... |
73,427,275 | 73,431,953 | QML - Cannot assign to non-existent property "onYes" or "onNo" in MessageDialog | I'm just making a simple message dialog using MessageDialog in QML. I got a problem about connecting onYes (also onNo) signal to a slot. Here's my code
import QtQuick
import QtQuick.Dialogs
import QtQuick.Controls
MessageDialog {
title: "Save File?"
text: "The file has been modified"
informativeText: "Do ... | Ok guys, I found the answer.
First, Add QT += widgets to the .pro file, then add the following code to the main.cpp:
#include <QApplication>
#include <QQmlApplicationEngine>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/... |
73,427,352 | 73,427,391 | Scaling models influences position in OpenGL | The scale of my models seems to changed their positions, but I don't know why. I am doing it in the S-R-T order. The blue plane has (0,0,0) as it's origin.
The model matrix is calculated like this:
// set model matrix
glm::mat4 model = glm::mat4( 1.0f );
// scale
model = glm::scale( model, _entity.Scale );
// rotate
... |
I am doing it in the S-R-T order.
No. You do it in the order T-R-S. The order S-R-T is p' = translation * rotation * scale * p. You have to read it from right to left.
// set model matrix
glm::mat4 model = glm::mat4( 1.0f );
//translate
model = glm::translate( model, _entity.Position );
// rotate
model = glm::rotat... |
73,427,878 | 73,432,548 | Python Bindings with C++ | I am interested in writing functions in C++ that can later be "imported" in Python. For example I wrote a simple function in C++ that adds two int numbers:
//function declaration
int addition(int a,int b);
//function definition
int addition(int a,int b)
{
return (a+b);
}
I also have a header file which contains:
... | ctypes only allows you to interact with a library using C types, not C++. boost.python, pybind11, etc allow you pass C++ objects.
However, there is a way to do what you want to do in ctypes using C-style arrays.
Declare a function like this:
extern "C" MATHLIBRARY_API void addToArray(int *array, int num, int size);
an... |
73,427,939 | 73,428,196 | How to set Boost RTree Node with template class | I have two files: header.h and code.cpp, I can not write any boost namespace on code.cpp, so all "boost::geometry::etc..." calls go on header.h. The idea is to implement two template classes: one for the RTree and other for the RTree Node, this way the user may include the header.h file and implement the RTree on code.... | We had to guess what BBox is. But all in all it looks like you "just" want a tree with nodes that are (box, name).
I'd suggest skipping the Node class (and all of the generics that wouldn't work anyways because you hardcoded the conversion to Node<T> anyways, which only works if the geometries were convertable (box and... |
73,428,067 | 73,430,778 | align right-to-left text with QPainter::drawText | I am trying to paint a right-to-left text with QPainter. It however still aligns the text to left despite the fact that it should be right-aligned. Or at least it is right-aligned when displayed in QTextEdit. That am I doing wrong? See the example:
QTextOption option;
option.setTextDirection(Qt::LayoutDirectionAuto);
p... | you should check your text with isRightToLeft() function.
QString isRightToLeft():
Returns true if the string is read right to left.
This will help you to understand your text language.
I checked the QTextEdit source and understand it uses this function.
void MainWindow::paintEvent(QPaintEvent *event)
{
QPainter... |
73,429,034 | 73,429,136 | Vector iterator inconsistent and Expression: cannot seek vector iterator after end | I'm trying to add a value to a vector after every 5 elements. This example gives me an assert error
Expression: cannot seek vector iterator after end
The error is self explanatory however the code executes in an online compiler and gives the desired result. I can just do 1 less iteration in which case the final insert ... | The issue is simply that it is forbidden to increment an iterator beyond the end iterator even if you never try to dereference the result.
When you write std::advance(it, 3); or it += vertexSize + 1; and the size of the original vector is not divisible by the step size you chose, the resulting value of it may be beyond... |
73,429,167 | 73,429,440 | C++ No ouput when Trying to run two functions at once using threads | Hello i am trying to run two functions at the same time.
Because i want to learn to make a timer or countdown of some kind.
And i have an idea on how to do so. But when i create two threads.
I get no output in my console application.
Here is my code.
#include <iostream>
#include <Windows.h>
#include <thread>
#include <... | You should use join instead of detach. Otherwise, the main thread won't wait for the other threads and the program will exit almost immediately. You can use std::this_thread::sleep_for instead of Sleep to make the code portable (no Windows.h required).
#include <iostream>
#include <thread>
using namespace std::chrono_l... |
73,429,589 | 73,433,830 | How to perform exponentiation using boost multiprecision and boost math? | I am running a biased Monte Carlo simulation, and I need to process the energies being reported. I essentially have to compute exp(-beta*energy), where energy is a negative number and beta can be around 100. If energy = 90, std::exp starts outputting inf.
This is a test run:
#include <boost/multiprecision/cpp_dec_float... | Just use exp! Live On Compiler Explorer
boost::multiprecision::cpp_dec_float_50 x = 900.0;
std::cout << "v = " << exp(x) << std::endl;
Prints
v = 7.32881e+390
The difference between exp(900.0) and exp(x) is that 900.0 is of type double and x is cpp_dec_float_50.
ADL finds the correct overload for exp in the associat... |
73,429,788 | 73,432,143 | How to link OpenSSL in windows using MSYS2? | I wrote a c++ program using OpenSSL, it works fine on linux but when I try to compile on windows I get an error that libcrypto-1_1-x64.dll, libssl-1_1-x64.dll are missing
I am compiling using
g++ main.cpp -lws2_32 -LC:\msys64\mingw64\bin -IC:\msys64\mingw64\include\openssl
Both dll files can be found in C:\msys64\mi... | I just came up with a simple openssl example and compiled/linked fine
$ g++ ssltest.cpp -lssl -lcrypto -o ssltest
$ ls -l
-rw-r--r-- 1 Fred None 1072 Aug 21 01:18 ssltest.cpp
-rwxr-xr-x 1 Fred None 77824 Aug 21 01:18 ssltest.exe
It just works out of the box.
I am using the CLANG64 environment and I have the mingw-w6... |
73,430,330 | 73,667,696 | Triangulation of polygon with holes using ear clipping algorithm | After parsing the contours from a truetype font file, I generated the points that compose the polygon that I want to triangularize.
These points are generated by merging the different holes into one polygon:
Generated Polygon of the letter A:
As you can see i "merged" the holes by picking two points between the inner... | The problem was that in is_point_in_triangle() the function was considering points on the outline inside the triangle (and then not consider the triangle as an ear).
This breaks because when merging the polygon and the hole, some points overlap.
I fixed this by removing the =: (Cross1 < 0.0f) && (Cross2 < 0.0f) && (Cro... |
73,430,379 | 73,430,417 | Understanding the convertible_to concept in c++20 | I'm still new to the C++20 concepts and I want to know why this does not work. I want to create a function template that concatenates numbers as strings. So I wanted to try concepts. I used std::convertible_to to check whether the entered datatype (which is int in this case) can be converted to std::string. But I'm fa... | You appear to want a concept for types that can be passed to std::to_string().
This code will achieve that.
template <typename T>
concept ConvertibleToStdString = requires(T a){ std::to_string(a); };
What am I doing wrong ?
You are misunderstanding the meaning of std::convertible_to<T,std::string>.
That concept vali... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.