question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
71,157,117
71,157,361
Qt How can I use DocumentsLocation
I am trying to develop an application with Qt. My problem is: I need to write and delete something in a text file. I am writing the text file as full path, the path on my computer. If the application runs on another computer, it will not find this path. I found out that I can use QStandardPaths::DocumentsLocation for i...
You can get Documents location by below code: #include <QGuiApplication> #include <QDebug> #include <QStandardPaths> int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); qDebug() << QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); return app.exec(); } This code prints cu...
71,157,159
71,157,385
Use arbitrary classes as parameter for parametrized tests in googletest
I have some repetive tests where the input of the tests needs to be created uniquely in a non-repetive way. Imagine 2 tests like this: struct ComplexInput{}; ComplexInput CreateA(); ComplexInput CreateB(); bool FunctionUnderTest(ComplexInput& input); TEST(TestCase, TestWithA) { auto input = CreateA(); auto r...
You can store function pointers and pass them to parameterized tests, as long as they have the same type (i.e., same parameters and return type) See it online struct ComplexInput{}; ComplexInput CreateA(); ComplexInput CreateB(); bool FunctionUnderTest(ComplexInput& input); class ParamTest : public ::testing::TestWi...
71,157,409
71,217,683
Error while trying to make Camera Calibration using Charuco Board (OpenCV, C++)
I'm trying to find distortion coeffitients using Charuco Board from the Aruco OpenCV library. I'm using Qt and OpenCV libraries compiled for Qt. First I've needed to do is to create the Charuco Board. I've done it using this: using namespace std; using namespace cv; using namespace cv::aruco; ... ...
The problem was in OpenCV library. Maybe it was badly compiled, or the problem is in the library itself. I have used OpenCV version 4.5.3 before. Then I compiled 4.5.4 version, and the program started to work well.
71,157,560
71,158,910
std::string class wrapped with cstring API (property proxy pattern)
I want to convert static data structures using cstrings in our legacy codebase to dynamic ones by using std::strings instead. The problem is that, right now, it is unfeasible to adapt all the functions in our codebase that use them. I proposed using a wrapper class (property proxy pattern) that exposes a cstring API us...
The reason why 9.2 and 8.2 do not work is because std::string has a size_ data member. strcpy function does not modify it. You can use friend functions (or regular functions) to workaround this issue. class CStringProperty { public: CStringProperty(){} CStringProperty(std::string const& value) : _value{value}{} C...
71,157,598
71,157,803
Multiple failed attempts to open a text file in C++
I have been spending the past hour trying to figure out how to display a text document programmatically in c++. The following is the simple main.cpp code, in which I create a directory "Profiles", and another directory "TestProfile" inside. In Profiles/TestProfile I create a "TestFile" and write "Test data" into it. #i...
I understand that you want to open the created file with an appropriate application. Let's assume the file is /dir/file. To open a file from the command line / terminal, you would run: open /dir/file Or, if you want a specific applications: open -a TextEdit /dir/file Also see The macOS open Command. If you just run: ...
71,157,686
71,157,971
Copy Constructors of classes instantiating derived classes
I have unsuccessfully been trying to create a copy constructor of a class that instantiates a derived class. Let's say I have the following pure virtual class: class AbstractBar{ public: virtual void printMe() = 0; }; Class Bar inherits from AbstractBar as follows: class Bar: public AbstractBar { std::string ...
First off, std::unique_ptr<T> is indeed unique. Therefore you cannot expect two things to point to the same instance-of-whatever by copying them. That said, I think what you're trying to do is clone whatever the "thing" is that is held by that member unique_ptr to allow a deep copy of a Foo. If that is the case, you ne...
71,159,998
71,184,493
Guarantees on the Object lifetime of inline static Meyers singleton, with explicit placement in a section?
I have inherited some code that compiles fine under g++ 9 and 10, but gives a runtime error for both compilers when optimization is turned on (that is, compiling -O0 works, but compiling -Og gives a runtime error from the MMU.) The problem is that there is a Meyers singleton defined in an inline static method of a clas...
GCC uses COMDAT section groups when available to implement vague linkage. Despite being explicitly named as MY_C_SECTION, the compiler still emits a COMDAT group with _ZZN7my_prod1C8instanceEvE1c as the key symbol: .section MY_C_SECTION,"awG",@progbits,_ZZN7my_prod1C8instanceEvE1c,comdat I expect that your othe...
71,160,713
71,161,492
Delete last element from dynamic array in C++
I was making a std::vector like clone for a fun little project in C++, and I've come across the following problem: I'm trying to implement the method pop_back but for some reason, I can't get it to work. The class I'm using is called Array and is defined in ../d_arrays/d_array.h and ../d_arrays/d_array.cpp I have a mai...
Your problem is here: delete[] tmp; Now: _array = tmp means: Point _array to the memory address that tmp is pointing to. Now, _array is pointing to &tmp (& means 'address of'), and then you delete tmp, which causes issues. Also resizing the entire array would be ok if the array is small. But it would not be ok if t...
71,160,909
71,161,071
Can you use a string(or c string) as a typename
I have a map loading function that takes input using ifstream from a file and creates objects from them. Here is what the file might look like: tree=50,100,"assets/tree.png" box=10,10,"assets/box.png" Which should create the objects tree and box and pass the values to their constructor. I already have the value part f...
No. As far as I know, there is no provision in C++ for finding types from an in-language string of any kind. As for your other problems: A value template parameter must be constexpr: since C++11, you can use variables of some constexpr types as template parameters Apparently you can use a constexpr string_view templ...
71,161,221
71,161,271
std vector.data return void
I required your help for a very strange behaviour that I can't understand. I wrote a simple usage of vector.data : void* ptr = NULL; // really initialized somewhere else bool* boolPtr = NULL; boolPtr = ((std::vector<bool>*)ptr)->data(); and when I compile (with -std=c++17) I got the error void value not ig...
vector<bool> is not a proper vector. As weird as that sounds, that's the way it is. It can't give you a pointer to its internal bool array, because it doesn't have one, since it stores the values packed into single bits.
71,161,989
71,162,481
Finding a hierarchy of polygons
I need an algorithm to determine a hierarchy of polygons. For example, I have only closed loops of vertices, where polygons have CCW vertices order and holes have CW vertices order. I want to create a structure to contain such hierarchy of polygons and holes. using Loop = std::vector<Point>; class PolygonHierarchy { ...
As per what @YvesDaoust said in the comments, for each polygon/hole, you can find all the polygons/holes which contain it. This will give you a directed graph. In this graph, for each node, you may have more than one incoming edges. For instance, something like this: 1 (a) |\ | \ | 2 (b) 3 / Here, both 1 and 2 know a...
71,162,266
71,170,101
Getting a std::string or C string from a QString representing an arbitrary filename on Windows
I'm using QFileDialog::getOpenFileName() to have the user select a file, but I need the result to be a C string, since I have to pass it to something written in C which uses fopen(). I cannot change this. The problem I'm finding is that, on Windows/MinGW, using toStdString() on the resulting QString doesn't work well w...
File paths in the non-unicode API of Windows are either parsed in the current ANSI (Microsoft codec) codepage, or in the OEM codepage (see also https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/fopen-wfope). ANSI is the default. So your question translates to: How can I convert a UTF-8 or UTF-16 string ...
71,162,411
71,162,455
Vector subscript out of range AND The application was unable to start correctly [c++]
I'm writing quite simple program in c++ using Visual Studio but i keep getting 2 errors and i could use some help. One sometimes pops up when i run Local Windows Debugger after the app crashed and it says: The application was unable to start correctly (0xc0000142) message sometimes when running And the second one i gue...
This sstatement cin >> wejscie; inputs only one word as soon as a white space character is encountered. So this for loop does not make a sense. stringstream wejscieStream(wejscie); int element; for (int i = 0; i < ilecyna; i++) { wejscieStream >> element; cyna.push_back(element); } Instead of using the opera...
71,162,463
71,199,698
How to use clang AST matcher usingDirectiveDecl to find using namespace directive with specific name?
I'm trying to prototype a clang-tidy matcher with clang-query to find using namespace directive with a certain name like using namespace ns1::ns2;. With clang-query I tried these variants but none is matching anything: clang-query> match usingDirectiveDecl(hasName("ns1")).bind("changeNamespaceName") 0 matches. clang-q...
Unfortunately, it appears to be impossible to do this with a clang-query AST matcher alone. usingDirectiveDecl matches using namespace declarations, but further restriction based on the nominated namespace is incomplete. While UsingDirectiveDecl does have a name, it is simply the placeholder string ::<using-directive>...
71,162,642
71,172,028
CMake C++ library includes toolchain name
I am building a Python extension in C++ using pybind11 and scikit-build. I base on the example provided at https://github.com/pybind/scikit_build_example/blob/master/setup.py. My CMakelists boils down to this: pybind11_add_module(_mylib MODULE ${SOURCE_FILES}) install(TARGETS _mylib DESTINATION .) setup.py: setup( ...
Conclusion: as Alex said this part of the name is necessary. See https://www.python.org/dev/peps/pep-3149/. Python will automatically figure out it can use _mylib.cpython-38-x86_64-linux-gnu.so if you import _mylib.
71,162,842
71,163,194
Override C++ method from multiply inherited templated base class
The enclosed code is a trimmed-down example of something I'm encountering. First, here's an even more simplified version that manages to compile: #include <string> template<typename T> class Base { public: Base() {} virtual ~Base() {} virtual size_t Size (void) const = 0; }; template<typename T> class De...
What you have is essentially this: struct A { virtual int foo() { return 0;} }; struct B { virtual double foo() { return 0;} }; struct C : A, B { int foo() override { return 42; } double foo() override { return 3.14; } }; Oops! You can't do that. Each overrider of foo() in C overrides all foo() (...
71,162,855
71,164,666
Thrust How could i acces my flatten array with a thrust::make_zip_iterator
Could some one could explain me why i can't access to my data. I got a flatten vector thrust::host_vector<double> input(10*3); inside i have points data X,Y,Z i make try to use a zip_iterator to access to my data so i make : typedef thrust::tuple<double, double, double, int> tpl4int; typedef thrust::host_vector<doubl...
Because this is how a zip iterator works: It takes multiple buffers (Struct of Arrays: SoA) and lets you access them as if you had one buffer of tuples (Array of Structs: AoS). The first element accessed by your zip iterator is the tuple input[0], input[10] and input[20] (ignoring the integer). The second element is in...
71,162,974
71,163,441
C++ ConcurrencyInAction: 7.2.2 Stopping those pesky leaks: managing memory in lock-free data structures
I am trying to understand how more than one thread hold head pointer in pop(), If two threads hold head pointer at "node *old_head = head.load();" then the first thread will complete the loop by updating the head and at the end let's say we delete the old_head and Thread1 completes it's work, now Thread2 is still holdi...
In the above process Thread2 never dereference the deleted node because it will come to else if condition if head and old_head are not same. This is not true. Consider this line: head.compare_exchange_weak(old_head, old_head->next) This will access the value of old_head->next before the compare_exchange_weak even run...
71,163,557
71,166,590
Linking glfw and assimp for a "standalone" project
I have a project following this tutorial. It works fine on my pc, but not on others since the libraries are not installed there. I have assimp, glfw, glm and stb installed through msys, so they are not directly included in the project. How would i need to link the libraries so that the application runs on other mashine...
Static linking is now working! The commands for linking now look like this: -l:libglfw3.a -opengl32 -lgdi32 -l:libassimp.a -lminizip -lz I just had some libraries missing that glfw and assimp depended on.
71,163,651
71,164,557
Collection of template child classes
I'm still new to template classes. But I have a parent class and then a template child class. namespace Foo::Bar { class BaseClass { // No declarations }; template<typename ChildClassType> class ChildClass : public BaseClass { public: /// Public declarations private:...
std::unique_ptrs cannot be copied. If you could copy them they would not be unique. Hence you get the error when you try to call push_back. If you do have a std::unique_ptr<ChildClass<foofoo>> to be placed in the vector you can move it: #include <string> #include <memory> #include <vector> class BaseClass {}; templa...
71,163,739
71,163,785
Does base class destructor need to be virtual if only some derived classes are polymorphic?
I have a similar situation to this question where I have 2 classes that share a public interface function, and so I've pulled that function (manage_data_in_memory() in the example) out into a base class which the 2 classes inherit from. However, the 2 classes are otherwise not related, and one of them is polymorphic,...
The destructor of a base class must be virtual if and only if an instance of a derived class will be destroyed through a pointer to the base object. If the destructor isn't virtual in such case, then the behaviour of the program would be undefined. Example: struct Base { // ... }; struct Derived : Base {}; std::u...
71,164,023
71,164,448
How to pass a std::function callback to a function requiring a typedef of a pointer to a function
I've got a C library that takes a function pointer to register commands. I want to use this in my C++ application. I've tried to use std::function in combination with std::bind to create a C compatible function pointer that will call my member function inside a class. When trying to pass the std::function, I get an com...
struct { console_cmd_func_t func; } console_cmd_t; void console_cmd_register(const console_cmd_t *cmd) { // Register the command } Your C program is ill-formed. I'm going to assume that console_cmd_t isn't actually an instance of an unnamed struct as is depicted in the quoted code, but is rather a typedef ...
71,165,137
71,165,593
How do I use getline to read from a file and then tokenize it using strtok?
I want my program to read lines from a file using getline(), and then tokenize the words using strtok(), and put them into a two-dimensional array. I understand there are probably way better ways to do this, but I am limited by what I've learned so far and the assignment requirements. I've tried using these threads/sit...
First of all, the line if (argc = 2) is probably not doing what you intend. You should probably write this instead: if (argc == 2) The function std::istream::getline requires as a first parameter a char *, which is the address of a memory buffer to write to. However, you are passing it the 2D array words, which does ...
71,165,146
72,311,693
Conditionally import a module on C++20
Is there a way to conditionally import a module on C++20 without a preprocessor directive? pseudo-code: if WINDOWS: import my_module; else: import other_module; If there's no way, what would be the cleanest way of do it with the preprocessor?
If your goal is to have multiple implementations of the same functionality (for example, platform dependent) then cleaner way of doing this is to have multiple implementation units for the common module interface. For example, we want to have "my_module" module that provides platform dependent functionality void show_n...
71,165,150
71,166,491
How to open a std::ofstream using a custom allocator?
I'm writing a debugging tool in C++. The tool is not allowed to use the malloc heap, because doing so might alter the behavior of the program being debugged. Instead, the debugging tool has its own heap, separate from the malloc heap (let's call it the "debugger's heap"). My debugging tool is making heavy use of the ...
Yes, you can't use streams in your scenario. On most platforms, you can use the POSIX open function and then call read, write and close as appropriate. On Windows they renamed it _open, but it's basically the same. These functions are unbuffered, so incur no heap allocations. On the other hand, if you perform a lot o...
71,166,102
71,178,118
Add OpenGL to Linux Vscode
I followed this tutorial successfully. But it doesn't explain how to configure on vscode. Glad is in this folder /usr/include and I did use sudo in the terminal to compile and generate a.out. How do I do that in vscode? I have this error output when I try to build task: terminal Starting build... /usr/bin/g++ -fdiagnos...
If anyone has the same problem I solved it adding these args in tasks.json "${workspaceFolder}/*.c", "-lGL", "-lglfw", "-ldl" And the folder glad in /usr/include for some reason had a gray x on the folder icon and it couldn't be accessed without sudo command. I deleted and made a glad empty folder and copied glad.h in...
71,166,339
71,166,543
Return class object with member variable
Why the function test() works even I'm not returning a Base class ? What happens with the compilation ? Can someone explain me ? #include <iostream> class Base { public: Base(){} Base(int val): _val(val){}; ~Base(){}; Base test(int n){ return (n); } int &operator *() { return (_val); }; private: ...
You declared a constructor that takes in an int, and you declared that test(int n) should always return a Base class. The compiler knows that in order to create a Base object you need either nothing (default constructor) or an int, so it creates an object using the constructor that takes an int an returns that. If you ...
71,166,391
71,167,460
(C++ vectors) How to assign values in a range of elements inside a vector?
I have a vector of ints, like {0, 0, 0, 0, 0}. I need to increase v[i] by 1 for a range of elements, like v[1] to v[3] so that I have {0, 1, 1, 1, 0}. How to do that?
Just use a simple iterative loop, eg: std::vector<int> v = {0, 0, 0, 0, 0}; for(size_t i = 1; i <= 3; ++i) { v[i]++; } Online Demo Which you can also replicate using standard library algorithms like std::for_each() and std::transform(), eg: std::vector<int> v = {0, 0, 0, 0, 0}; std::for_each(v.begin()+1, v.begin()...
71,167,077
71,211,660
Overloading with template nested type
Consider #include <iostream> template <typename T> void foo (T*) { std::cout << "foo (T*) called.\n"; } template <typename T> void foo (typename T::Node*) { std::cout << "foo (typename T::Node*) called.\n"; } struct A { struct Node { }; }; int main() { A* a = new A; foo(a); A::Node* node = new A::N...
This is because when you call foo the type for T needs to be deduced by the compiler. Since both A and A::Node are valid for the first foo. And the second Foo is not more specific. It'll call the first version of foo (substituting T with A and A::Node). To force the compiler to replace T with A and then see T::Node* yo...
71,167,185
71,168,763
opengl drawing a 3d cube with with EBO
I am trying to draw a cube with OPENGL by using EBO, VAO, and VBO. the first function init the VAO of the cube initVAO() { GLfloat cube_vertices[] = { // front -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, // back -1.0, -1.0, -1.0, ...
See Index buffers. The index buffer binding is stated within the Vertex Array Object. When a buffer is bound to the target ELEMENT_ARRAY_BUFFER, then this buffer is associated to the vertex array object which is currently bound. When calling glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); the binding of the element buffer to...
71,167,585
71,167,680
How can I return a calloc pointer from C into C++?
I am working on a personal project that requires me to call C functions from C++ code. These C functions return a calloc() pointer. 1t5.h #include <stdio.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> char * prob1(char * number); 1t5.c #include <1t5.h> char * prob1(char * number) { int ni = atoi...
Thanks to @Remy Lebeau for the answer. My code contained many chances for memory to leak, resulting in a mess of a return value. string Link::problemRouting(string problem, vector<string> contents) { string answers = ""; char * ca; int pi = stoi(problem); for (int i = 0; i < contents.size(); i++) { ca = cv.string...
71,167,650
71,167,762
Why we can reuse a moved socket_ in acceptor_.async_accept?
Reference: https://www.boost.org/doc/libs/1_35_0/doc/html/boost_asio/reference/basic_socket_acceptor/async_accept/overload1.html boost::asio::ip::tcp::acceptor acceptor(io_service); ... boost::asio::ip::tcp::socket socket(io_service); // you have to initialize socket with io_service first before //you can use it as a...
It all depends on the implementation of the types. We can loosely describe the intent of a move as "the compiler is allowed to cannibalize". But really, for user-defined types we're going to have to tell it how to do that, exactly. In language "doctrine" a moved-from object may only be assumed safe to destruct, but in ...
71,168,032
71,168,072
Retrieving structure from vector of structs following a find_if
I have written this small program to search for a struct inside a vector of structs. After this line in the code below, how should I extract the element of the vector that matched. i.e. the structure and its contents. if (std::find_if(jobInfoVector.begin(), jobInfoVector.end(), pred) != jobInfoVector.end()) #i...
You can save the result of the std::find_if() as an iterator, then dereference to extract its components. Like: #include <iostream> #include <vector> #include <algorithm> #include "boost/bind.hpp" using namespace std; struct jobInfo { std::string jobToken; time_t startTime; time_t endTime; }; t...
71,168,173
71,168,203
How to call a function from another function using STL list in C++?
I'm new to data structures in C++, I want to write a code using STL list to display the following: Input for data radius: Radius 1: 20 Press [Y] for next input: Y Radius 2: 12 Press [Y] for next input: N List of Existing Records: ID:1, Radius: 20, Volume: 33,514.67 ID:2, Radius: 12, Volume: 7,239.17 Total record: 2 I...
double dataVolume(double radius) { double v = (4 * 3.14 * radius * radius * radius) / 3.0; return v; } void dataRadius(sphere* values) { int i = 0; char choice; do { cout << "Radius " <<i+1 <<": "; cin >> values->radius; values->volume = dataVolume(values->radius); c...
71,168,259
71,168,553
Number of ways to delete a binary tree if only leaves can be deleted
I am solving an algorithm question: You are given a binary tree root. In one operation you can delete one leaf node in the tree. Return the number of different ways there are to delete the whole tree. So, if the tree is: 1 / \ 2 3 / 4 The expected answer is 3: [2, 4, 3, 1],[4, 2, 3, 1] and [4, 3...
For a give node X, we want to know u(X) - the number of unique delete sequences. Assume this node has two children A, B with sizes |A|, |B| and known u(A) and u(B). How many delete sequences can you construct for X? You could take any two sequences from u(A) and u(B) and root and combine them together. The result will ...
71,168,275
71,168,501
openGL 3D Rectangle not overlapping properly in C++
You are given 3 rectangular strips whose vertex coordinates are as given below. Rectangle A (RED COLOR) (-0.5,0.6,-0.8), (-0.2,0.9,-0.8), (0.8,-0.1, 0.8), (0.5, -0.4, 0.8) Rectangle B (GREEN COLOR) (0.0, 0.8, 0.8), (0.3, 0.5, 0.8), (-0.7, -0.5, -0.8), (-1.0, -0.2, -0.8) Rectangle C (BLUE COLOR) (0.6, 0, -0.8), (0.6, -...
The reason why this was not working is because You initialized display mode as GLUT_SINGLE (Not including the GLUT_DEPTH). You did not enabled glEnable(GL_DEPTH_TEST). Those two are needed to enable the depth test, so, you have to put glEnable(GL_DEPTH_TEST); right after glClear, and change glutInitDisplayMode(GLUT_S...
71,168,355
71,168,536
Is writing to uninitialized memory allocated by allocator UB? And what about reading it afterwards?
struct Foo{ int i; int j; }; int main(){ std::allocator<Foo> bar; Foo* foo = bar.allocate(1); foo->i = 0; return foo->i; // ignore the memory leak, it's irrelevant to the question } I'm curious about whether there are undefined behaviors in the snippet above? Will the conclusion vary accordi...
It is an error to use raw memory in which an object has not been constructed. We must construct objects in order to use memory returned by allocate. Using unconstructed memory in other ways is undefined. Source: C++ Primer, Fifth Edition Since you have not used construct the behavior of your program is undefined prior ...
71,168,479
71,171,530
Quicksort not sorting one element in the list of strings
Could anyone tell me what is wrong with my code: int Partition(vector<string>& userIDs, int i, int k) { int pivot = (i + (k - i) / 2); string temp; while(i<k) { cout << "pivot:" << pivot << endl; while (userIDs.at(i).compare(userIDs.at(pivot))<0) { cout << "1. i:"<<i<<" User...
#include <bits/stdc++.h> using namespace std; int Partition(vector<string>& userIDs, int i, int k) { int pivot = i; string pivotValue = userIDs[pivot]; string temp; int leftIndex = i; int rightIndex = k; while(i<k) { while (userIDs[i].compare(pivotValue)<=0) { i++; ...
71,168,723
71,168,865
How to find package and link library without cmake in simple cpp file?
file name: main.cpp #include<iostream> #include"boolector.h" using namespace std; int main() { Btor* btor=boolector_new(); cout<<"hello world"; boolector_delete(btor); } What if I don't want to make CMake project, just a C++ file and still wants to link library as in CMake? I want equivalent to following (in CmakeLis...
You can use -l, -L and -I options of g++ like: g++ -L /usr/local/lib/ -lboolector -I /usr/local/include/boolector main.cpp -o main -l option is for setting the name of the library to be linked -L option is for setting the path where the library to be linked has to be searched -I option is for setting the path where h...
71,168,884
71,169,188
How to push values and delete a record from a list in C++?
I'm new to data structures in C++, and I'm stuck at some points that I couldn't fix, I want to write a code using STL list to display the following: Input for data radius: Radius 1: 20 Press [Y] for next input: Y Radius 2: 12 Press [Y] for next input: N List of Existing Records: ID:1, Radius: 20, Volume: 33,514.67...
You were making some mistakes. In removing element, you cant just use integer index.U have to use iterator of the list type. then you were push_backing sphere element in record list after all choices which only inserts last choice of user. I have fixed that too. 3rd mistake was, you were push_backing pointer to sphere ...
71,168,948
71,169,045
inline static variable in different translation units has different values(c++17)
I want to implement a source file that contains a global variable, and I want to do this through inline static. I can change a variable (e.g., i) within the context of a translation unit, but when I call the variable outside of that translation unit, the result will remain unchanged for the caller. It's like there is a...
static variables (as in your example) have internal linkage. There are 2 ways to achieve what you want, both of which are shown below. Also note that the static keyword has other meanings as well. Method 1: C++17 With C++17, we can use the inline keyword as shown below: header.h #ifndef UNTITLED1_TEST_H #define UNTITLE...
71,169,533
71,169,600
Emplacing an std::pair of strings to an unordered map reusing the string's heap
I have an unordered map of string-pairs that i reference via a message id (key). Now I want to construct the string pair in place using the temporary string objects that the function receives, hence reusing the memory already allocated for the string on the heap. But I'm having difficulty wrapping my head around this c...
Your construction is not using the move constructor to construct the new strings, thereby it is not reusing allocations. The names of variables are always lvalues. Therefore std::forward_as_tuple will forward topic and data as lvalue reference, causing use of the copy constructor for the strings. To pass rvalues, you n...
71,169,549
71,170,070
Getting wrong hex value from read function
Function gets valid data by 1 step, but when go to 2 step gets wrong hex data, what i`m doing wrong? stringstream getHexFromBuffer(char* buffer,short startFrom = 0, short to = 4) { int len = strlen(buffer); stringstream hexValue; for (size_t i = startFrom; i < to; i++) { hexValue << hex << (int)buff...
d0 is a negative 8 bit value in signed char. This is exact the same negative value ffffffd0 in int. For getting "d0" in output, cast the signed char to another unsigned type of the same size (1 byte) then cast the result to int: hexValue << hex << (int)(unsigned char)buffer[i]; hexValue << hex << (int)(uint8_t)buffer[i...
71,170,283
73,388,419
Creating two or more CEF browser windows
I have been suffering for two weeks, please help me: And I use the built-in CEF example - "cefsimple" - it works fine: https://bitbucket.org/chromiumembedded/cef/src/master/tests/cefsimple/?at=master The "cefsimple" example creates a browser window and opens the specified URL in it. But as soon as I add another browser...
I've encounter this problem recently, and this may help you. In your native window proc, process WM_SETFOCUS with: if (!::GetFocus()) { // set cef focus; } Without call ::GetFocus(), two cef windows will blink constantly.
71,170,900
71,176,516
Display the whole file
I have an assessment about asking the user to enter his/her name and their desired score and display it. I have made progress but when I try to display all the text in the save file (I called scores.txt) it didn't print all out but instead just print the first line of the text file. Here the code: #include <iostream> #...
Try it like this: #include <iostream> #include <fstream> #include <string> #include <stdlib.h> using namespace std; int score; int highscore; string name; void menu() { cout << "1.Enter a score" << endl; cout << "2.Display scores" << endl; cout << "3.Exit" << endl; } void enterScore() { cout << "Ente...
71,171,613
71,221,231
C++ isdigit() Query for converting a char array to an int array
I am trying to convert an input character array, to an int array in c++. Inputs would be in a format like: 'M 911843 6', where the first value of the char array is a uppercase letter, which I convert to an ASCII value and -55. Edit: I should also mention I just want to use the iostream library The last value of the cha...
Just a follow on from Serge's answer which gave me a good understanding of how strings are read - I solved my problem using cin.getline() function.
71,171,739
71,185,780
Initialize nontrivial class members when created by PyObject_NEW
I have a Python object referring to a C++ object. Header: #define PY_SSIZE_T_CLEAN #include <Python.h> #include <structmember.h> typedef struct { PyObject_HEAD FrameBuffer frame_buffer; } PyFrameBuffer; extern PyTypeObject PyFrameBuffer_type; extern PyObject* PyFrameBuffer_NEW(size_t width, size_t height); ...
I've successfully used code similar to typedef struct { PyObject_HEAD FrameBuffer *frame_buffer; } PyFrameBuffer; and then if (fb != nullptr) { fb->frame_buffer = new FrameBuffer( ... ); } But you have to account for deleting the object explicitly. You'll need to add a tp_dealloc() function to your PyFra...
71,172,106
71,172,450
ifstream struct read (What's wrong with my code??)
I save struct array as binary. (fIn.write) and I read it using below code. std::ifstream fIn(LOG_PATH, std::ios::in|std::ios::binary); ... IAttackSave_t IAttackSave; while(fIn.read((char*)&IAttackSave, sizeof(IAttackSave_t))) { for(uint32 ulIdx = 0; ulIdx < ulCurLogCnt; ++ulIdx) { LIB_mem...
The outer loop reads elements one by one. The inner loop overwrites all elements of the array with the same element. After both loops finish, all elements have been overwritten with the element that was read last. Instead, you need something like this: for(uint32 ulIdx = 0; ulIdx < ulCurLogCnt; ++ulIdx) { if (!fIn....
71,172,147
71,172,643
How to create a folder with a dot in the name using std::filesystem?
There was a need to create a Windows directory with the name ".data". But when trying to create this path via std::filesystem:create_directory / create_directories, a folder is created in the directory above with an unclear name: E:\n¬6Љ P.S in the documentation for std::filesystem i found: dot: the file name consist...
You are passing the address of line to sprintf, not a string! Try sprintf(patht, "E:\\game\\%s", line.c_str());
71,172,554
71,177,196
How to Pass Vector of int into CUDA global function
I'm writing my first CUDA program and encounter a lot of issues, as my main programming language is not C++. In my console app I have a vector of int that holds a constant list of numbers. My code should create new vectors and check matches with the original constant vector. I don't know how to pass / copy pointers of ...
I don't know how to pass / copy pointers of a vector into the GPU device First, remind yourself of how to pass memory that's not in an std::vector to a CUDA kernel. (Re)read the vectorAdd example program, part of NVIDIA's CUDA samples. cudaError_t status; std::vector<int> selectedList; // ... etc. ... int *selected...
71,172,775
71,181,936
`glm::linearRand(-1.0f, 1.0f)`, gives more negative numbers than positive. Why is that? `rand` seems ok
I am using glm::linearRand(-1.0f, 1.0f) to generate random floating point numbers between -1 and 1. Afterwards, I output the percentage of numbers that are positive (0.0f or above). std::srand(time(0)); // Give glm a new seed uint32_t samples = 1000000000; uint32_t positive = 0; uint32_t negative = 0; for (uint32_t i...
This is a bug in GLM. While the usual admonition about using % with rand is that the range doesn’t evenly divide RAND_MAX, this code opts for the more straightforward approach of reducing rand() modulo UINT8_MAX, so that 255 is never produced. Every random value is ultimately derived from combining several such bytes...
71,172,879
71,172,977
Misunderstanding with move constructor
I have such class, where I create a move constructor class Test { private: int m_a; public: Test(int val) { m_a = val; } Test (const Test &) {} // move constructor Test (Test && d) { std::cout << &m_a << std::endl; // Line X std::cout << &d.m_a << std::endl; } v...
Each time fun(Test a) is invoked, an instance of Test is created on the stack. Each time fun() returns, the stack frame is freed. So when invoked twice in a row, the chance is great that you get an instance of Test created at exact same location on the stack. If you wanted to take Test by reference, it should be void f...
71,174,313
71,174,348
How to have a templated function require its argument be passed by rvalue reference?
Because of the confusing syntax of forwarding references and rvalue references, it's not clear to me how I would write a function that takes some type, T, by rvalue reference. That is, while template <typename T> void foo(T x); takes x by value and template <typename T> void foo(T& x); by reference, and template <typ...
template<class T> void f(T &&) requires(!std::is_lvalue_reference_v<T>);
71,174,500
71,174,826
A more elegant way of writing repetitive code (template)?
I have a block of code in which there are multiple times the same kind of operations: void fn() { if (params[0].count("VARIABLE_1")) { STRUCT.VARIABLE_1= boost::lexical_cast<VARIABLE_1_TYPE>(params[0].at("VARIABLE_1")); } if (params[0].count("VARIABLE_2")) { STRUCT.VARIABLE_2 = boost::lexical_cast<V...
Because you want something as both an identifier in code, and as a string literal, you either repeat yourself template<typename T, typename Map> void extract_param(T & t, const Map & map, std::string name) { if (auto it = params.find(name); it != params.end()) { t = boost::lexical_cast<T>(*it); } } voi...
71,175,636
71,189,318
What shell does std::system use?
TL;DR; I guess the shell that std::system use, is sh. But, I'm not sure. I tried to print the shell, using this code: std::system("echo $SHELL"), and the output was /bin/bash. It was weird for me. So, I wanted to see, what happens if I do that in sh? And, the same output: /bin/bash. Also, if I use a command like SHELL=...
The GNU sources (https://github.com/lattera/glibc/blob/master/sysdeps/posix/system.c) say /bin/sh So, whatever /bin/sh is hardlinked to is the shell invoked by std::system() on Linux. (This is correct, as /bin/sh is expected to be linked to a sane shell capable of doing things with the system.)
71,175,935
71,178,060
How to call function by given pointer using raw data (bytes) on runtime (instead of casting to compile-time defined function) in C/C++
Imagine we have an untyped raw function pointer void * my_func = ...; // get from DLL for example How to call my_func with specif data (and get return value), if the size of all parameters together and the size of return type could be known only on the runtime. For example I need to implement the following interface: ...
This is exactly what I searched for linux.die.net/man/3/ffi_call: The ffi_call function provides a simple mechanism for invoking a function without requiring knowledge of the function's interface at compile time. fn is called with the values retrieved from the pointers in the avalue array. The return value from fn is ...
71,175,941
71,176,239
TI ARM CLANG wont resolve symbol even though objdump shows its there
I am trying to compile my code on CCS(Code composer studio) using TI ARM CLANG compiler. I am trying to implement Ethernet fucntionality which uses TI's enet SDK I call a fucntion in my main which is in the enet SDK but the comiler is throwing error unresolved symbol Enet_initOsalCfg(EnetOsal_Cfg_s, first referenced i...
Big oops our friend in the comments found my problem. I forgot extern "C" sorry for being stupid I was scratching my head on this since 4 hours, my aplologies :P
71,176,032
71,176,069
return type deduction of lambda function not working
Why does the following code not compile? Why do I have to tell the compiler that the passed function pointer returns a double? (It works if one explicitly calls call<double>()!) template<typename T> void call(T (*const _pF)(void)) { } int main(int, char**) { call( [](void) -> double ...
Because the implicit conversion (from lambda to function pointer) won't be considered in template argument deduction, the template parameter T can't be deduced and the invocation fails. Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolut...
71,176,278
71,176,607
Create a copy on demand
Is there an idiomatic way to invoke the creation of a copy in an expression? For example say I have a function declared as: template <class T> void foo(T&& arg) { } Now I need to call foo with a copy of my object: MyType object; foo(object); As written above, I will have a call on void foo(MyType& arg), but I don't w...
You can build a decay-copy function yourself: template <class T> constexpr std::decay_t<T> decay_copy(T&& v) { return std::forward<T>(v); } then foo(decay_copy(object)); It's worth noting that you can also use auto(x) to get language-supported decay-copy in C++23: foo(auto(object)); Demo See P0849 for more detail...
71,176,442
71,205,709
How to remove the distance between the QTabBar scroller buttons?
Please tell me why there is a distance between the QTabBar scroller buttons with a small width of the scroller buttons and how can this be fixed? In this case, I have the following in the style sheet: QTabBar::scroller { width: 6px; } At the same time, the whole paradox is that in a pure example there is no dista...
It's because of an outdated version of Qt.
71,176,554
71,226,982
PyTorch C++ Frontend: Registering New Modules and using them during Forward
I am creating a model that is empty like so: struct TestNet : torch::nn::Module { TestNet() { } torch::Tensor Forward(torch::Tensor x) { return x; } }; I then register new modules to the model: auto net = std::make_shared<TestNet>(); torch::nn::ModuleHolder<ConvLayer> conv(1, 1, 3, 1, 1);...
I found a way to do this using torch::nn::Sequential, hope this helps anyone else: struct TestNet2 : torch::nn::Module { TestNet2() { layers = register_module("layers", torch::nn::Sequential()); } template <typename T> void sequentialLayer(T Layer) { layers->push_back(Layer); } ...
71,176,946
71,177,140
C++ fmtlib: "Undefined reference" error after building and #include <> this library
I downloaded the library from https://github.com/fmtlib/fmt and then executed the following commands from official documentation https://fmt.dev/latest/usage.html: mkdir build cd build cmake .. sudo make install The commands were executed without errors. The final output of the sudo make install command: Install the p...
Adding the argument -lfmt to the compilation command solves the issue. -l<name> arguments generally stand for including the library <name> into the compilation (see GCC documentation) The command thus looks as follows: $ g++ main.cpp -lfmt -o main
71,177,591
71,177,780
Problem with IF condition and && OPERATOR
i have encountered a major problem in my code that, when i hits 1 and j is 5, although, the boolean function returns False, the IF statement still manage to operate. #include <iostream> using namespace std; #include <string> using namespace std; bool checkSym(string s, int left, int right) { if (left >= right) ...
The code looks unreadable. Nevertheless at least this function bool checkSym(string s, int left, int right) { if (left >= right) return true; else { if (int(s[left]) != int(s[right])) return false; else { checkSym(s, left + 1, right - 1); } } } can invoke undefined behavior because it...
71,177,615
71,182,017
String timestamp give unrealistic date
I have a ridiculous problem but I can't figure out... I juste want to convert a timestamp string to a human readable date but the only date I have is completely wrong. #include <iostream> #include <string> #include <stdio.h> #include <ctime> int main() { char buf[80]; std::time_t epoch = std::atol("164512807...
Fwiw, in C++20: #include <chrono> #include <cstdlib> #include <format> #include <iostream> int main() { using namespace std; using namespace std::chrono; sys_time epoch{milliseconds{atoll("1645128077111")}}; cout << format("{:%Z: %A %e %B %Y %T}", epoch) << '\n'; } Output: UTC: Thursday 17 February 2...
71,177,711
71,178,356
How to read from a file that has numbers in the beginning of each line of the string and extract numbers as an idx then store in a vector. Using C++
Hello I'm working on a school project and I'm trying to read from a file with these contents: the idx of question, the corresponding concept 1 Arrays Hold Multiple Values 1 Pointer Variables 2 Arrays as Function Arguments 3 Comparing Pointers 4 Pointer Variables 5 Pointer Variables 6 Initializing Pointers 7 Pointers ...
This is not the cleanest solution, but it should get you started. The following separates the numerals at the beginning of each line from other content: // for each line string string idxStr; string lineWithoutIdx; for (const char& c : line) { if (isdigit(c)) { idxStr.push_back(c); } else { lineWithoutIdx.push...
71,177,855
71,179,360
Leetcode: Time limit exceeded, Longest palindromic substring
I am wondering how to optimize my solution to the LeetCode question: 5. Longest palindromic substring: Given a string s, return the longest palindromic substring in s. I get Time Limit exceeded on really long strings (up to 1000 characters), but on the other hand, using the same long string on my terminal gives me th...
The algorithm loses a lot of time by working from the outside inwards. Realise that a palindrome has a "center" (on, or between neighboring indexes), and your algorithm will often look for palindromes using the same center but with decreasing sizes. You could reduce work by working from the inside out, i.e. select all ...
71,178,173
71,178,380
CMake: Create DLL including dependencies instead of separate dll's
Im writing a SDK for Windows and Mac OS in C++, and im using CMake. On windows, I'd like the compiled DLL to contain all necessary dependencies, instead of having separate DLLs for all third party libraries im using. Here are the relevant sections of the MakeFile: find_package(OpenSSL REQUIRED) find_package(CURL CONFIG...
I'm using Vcpkg for simplicity but you should compile your dependencies as static libraries instead of shared. If you're using vcpkg you can install the dependencies as static like such vcpkg.exe install openssl:x86-windows-static Make sure you run CMake with VCPKG_TARGET_TRIPLET set to x86-windows-static or whatever p...
71,178,599
71,178,823
C++Builder correct way to Load string from ressources
I am new in either c++, and c++builder(11 v-28), i have put in ressources a text file(via projet->Ressources and Images), but i can't find any method to retrieve my text from ressources, LoadStr(..) function reclaim a numeric identifier that i can't found or how to get it.
Using C++ Builder you can use functions in the RTL to help you. When you put the large text file into the resources you would have given it a type and Id. Normally for an embedded file the type would by RT_RCDATA. (I haven't checked this code at all so it probably won't compile, but should give you a pointer) TStrea...
71,178,682
71,178,790
understand how char works in c++
I am a C++ newbie. Although many similar questions have been asked and answered, I still find these concepts confusing. I know char c='a' // declare a single char c and assign value 'a' to it char * str = "Test"; // declare a char pointer and pointing content str, // thus the content ...
char * str = "Test"; is not allowed in C++. A string literal can only be pointed to by a pointer to const. You would need const char * str = "Test";. If your compiler accepts char * str = "Test"; it is likely outdated. This conversion has not been allowed since C++11 (which came out over 10 years ago). how does char...
71,178,849
71,178,949
fmt linking for dummies
I'd like to make a python-like dynamic integer class in C++ as an experiment. It requires me to change many integers to string types. As in here: https://www.zverovich.net/2013/09/07/integer-to-string-conversion-in-cplusplus.html it states that fmt format_int will be best for that kind of job. So I installed fmt with c...
Use $ g++ -std=c++17 dynamic\ mem.cc -lfmt fmt is provided as a static library (.a). With those, the order is important as the linker takes out of a library only the objects which are needed to provide symbols to other objects or libraries which precede them in the command line. If you start with a library, there is o...
71,179,122
71,180,892
Running pip install twice to see changes ("developer mode") -- second install fails but first works
I am wondering how to use pip to develop a Python package which is going through many revisions rapidly. My work flow is to write C++ code, compile and install with pip install and test my code. Then, I would like to change some underlying C++ code, recompile and reinstall with pip, test the new feature, change somethi...
I found that deleting the build directory inside the cmake_example directory resolved the problem and pip install ./cmake_example worked again as it did the first time. You can combine the two commands: rm -rf ./cmake_example/build && pip install ./cmake_example Looking a little closer, (for me) it was sufficient to ...
71,180,130
71,180,230
Why don't I have to specify that the result of a fortran function is being passed by value to my C++ program?
I am learning about fortran C++ interoperability. In this case I was trying to write a 'wrapper' function (f_mult_wrapper) to interface between my 'pure' fortran function (f_mult) and C++. The function is defined in my C code as double f_mult_by_wrapper(double i, double j); and called like double u=f_mult_by_wrapper(w...
Function results are simply not function arguments/parameters. They are passed differently and the exact mechanism depends on the ABI (calling conventions) and their type. In some ABIs, results are passed on the stack. In other ABIs, they are passed using registers. That concerns simple types that can actually fit int...
71,180,394
71,182,035
Armadillo: Inefficient chaining of .t()
consider the following two ways of doing the same thing. arma::Mat<double> B(5000,5000,arma::fill::randu); arma::Mat<double> C(5000,500, arma::fill::randu); Okay two dense matrices in memory. Now I want to multiply them to a new matrix, but with B transposed. Method 1: arma::Mat<double> A = B.t() * C; Method 2: arma:...
Hi all I'm going to answer my own question here might be useful to others. The answer for me is that it was because I was using a generic OpenBLAS, not an Intel processor-specific version of BLAS, and running in debug mode. With optimization at compile time and using an Intel processor-specific version of BLAS: Bt = B...
71,180,794
71,180,882
C++ std:format not available in VS2022 /std:c++latest
I'm trying to use C++ std::format in Visual Studio 2022. I've selected C++ Language Standard: "Preview - Features from the Latest C++ Working Draft (/std:c++latest)" after initially trying "ISO C++20 Standard (/std:c++20)" The post below seems to indicate that selecting the Preview standard should work, but I don't hav...
Should std::format work in VS2022 with the #include statement? Yes, but it currently only works in /std:c++latest (Preview) mode which you can set in Project\Properties\Configuration\Properties\C++ Language Standard. Demo
71,181,223
71,181,242
Allocating Sufficient Memory for a Known Number of Structs
First time implementing a graph where the total number of nodes is known when the constructor is called and performance is the highest priority. Never allocated memory before, so the process is a little hazy. The number of nodes required is (n*(n+1))/2 where n is the length of the string passed to the constructor. #inc...
use std::vector<ColorNode> nodes; life will be very simple after that. You can be helpful to std::vector if you know the size you want auto nodes = std::vector<ColorNode>(size); This will allocate a contiguous array on the heap for you, manage its growth, allocation, deallocation etc. You will basically get the same ...
71,181,442
71,186,277
v8 - how to debug Map.prototype.set and OrderedHashTable?
I'm learning more about v8 internals as a hobby project. For this example, I'm trying to debug and understand how Javascript Map.prototype.set actually works under-the-hood. I'm using v8 tag 9.9.99. I first create a new Map object in: V8 version 9.9.99 d8> x = new Map() [object Map] d8> x.set(10,-10) [object Map] d8> %...
(V8 developer here.) Many things in V8 have more than one implementation, for various reasons: in this case, there's the C++ way of adding an entry to an OrderedHashMap (which you've found), and there's also a generated-code way of doing it. If you grep for MapPrototypeSet, you'll find TF_BUILTIN(MapPrototypeSet, ... i...
71,181,566
71,181,912
-Wconversion diagnostic from gcc-trunk when -fsanitize=undefined is passed
This is about the correct diagnostics when short ints get promoted during "usual arithmetic conversions". During operation / a diagnostic could be reasonably emitted, but during /= none should be emitted. Behaviour for gcc-trunk and clang-trunk seems OK (neither emits diagnostic for first or second case below)... until...
For a built-in compound assignment operator $= the expression A $= B behaves identical to an expression A = A $ B, except that A is evaluated only once. All promotions and other usual arithmetic conversions and converting back to the original type still happen. Therefore it shouldn't be expected that the warnings diffe...
71,181,896
71,181,946
how can i declare a C++ array of 10 pointers to objects of a class?
Assume a circle class has been implemented. how can I declare an array of 10 pointers to objects of the circle class?
how can I declare an array of 10 pointers to objects of the circle class? Like this: circle* myArray[10]; It is then your responsibility to assign those pointers to point at valid circle objects. But how you do that exactly is outside the scope of your question, as you did not explain how you intend to use the circl...
71,182,029
71,182,044
How to pop a string from one stack and push onto another?
Code snippet: string token; token = mystack.pop(); This gives "operator=" error. It is my understanding this is due to the fact that strings do not have the = operator, and that strcpy() is the proper method. However, when I use: strcpy(token, mystack.pop()); I receive "error: ‘strcpy’ is not a member of ‘std’; did ...
This gives "operator=" error. Assuming you are using std::stack then its pop() method has a void return type, ie it does not return anything, so you can't assign it to your string. You need to instead read from its top() method before calling pop(), eg: string token; token = mystack.top(); mystack.pop(); It is my...
71,182,056
71,182,096
c++ SFINAE - fallback overload with ellipsis does not work
I'm writing function working with STL containers that have iterator. And I'm trying to handle container that doesn't. my template function: template <typename T> void easyfind(...) { throw std::invalid_argument("No iterator"); } template <typename T> typename T::iterator easyfind(T& cont, int tofind) { t...
T is not used as a function argument so it can't deduce what T should be. In this case you could replace the varargs function with a variadic template: template <class... Args> void easyfind(Args&&...) // Now Args... can be deduced { throw std::invalid_argument("No iterator"); } However, your current check exclud...
71,182,070
71,182,211
Getting last value printed twice when reading file in c++
I'm new to c++. Currently I'm learning how to read and write to a file. I've created a file "nb.txt" with content like this: 1 2 3 4 5 6 7 2 3 4 5 6 7 9 I'm using a simple program to read this file, looping until reached EOF. #include <iostream> #include <fstream> using namespace std; int main() { ifstream in("nb...
The problem is that after you read the last value(which is 9 in this case) in is not yet set to end of file. So the program enters the while loop one more time, then reads in(which now sets it to end of file) and no changes are made to the variable current and it is printed with its current value(which is 9). To solve ...
71,182,090
71,182,120
How can I store the digits of two numbers in an array like in the code below, without using a string?
I need a program to read two numbers and store these number's digits in an array with a ';' in between them. I tried it using a char array but it didn't seem to work for me, and I also tried, as you can see below, by storing the numbers in a string first and putting a ';' in between then storing them in the array. How ...
You may want to use a function that's called getline(std::cin,) ( as long as you don't press a specific keyword like: Enter or sth) it will take your string all at once ( you can write 3;4 or sth and it will store it word-by-word). getline(cin,numTotal);
71,182,761
71,183,097
How to erase the inner map's key and then erase outer map element in C++
I have a map like this: std::map<int, std::map<float, char>> m; In this I need to delete the inner map's key, which is a float value. And after erasing that, if the inner map is empty then erase that element from the outer map also. One example. std::map<int, std::map<float, char>> m; std::map<float, char> m1; m1[2.5]...
As you stated in comments, you only know the key in the inner map (why do you not know the key in the outer map?), in which case you have no choice but to iterate the entire outer map until you find an element whose inner map contains that key. Then you will know which outer element you can erase. For example: std::map...
71,182,775
71,186,268
How to register QObject class in CMake with qt_add_qml_module?
I have a QObject derived class Expense that I use in QML like this. // main.qml Expense { id: expenseManager onExpenseCreated: { // Do something } } The expense class has no UI components, it has some basic Signal and Slots for API communications. // expense.h #ifndef EXPENSE_H #define EXPENSE_H #include ...
You just need to add QML_ELEMENT to your QObject-derived Expense class's header and make sure you have moc enabled in your CMakeLists.txt. In application case it doesn't matter if the expense.h/cpp sources are included via qt_add_executable or qt_add_qml_module. I think it's clearer to add them to qt_add_qml_module SOU...
71,183,145
71,186,841
Create std::chrono::time_point from string
A program like this int main() { using namespace date; std::cout << std::chrono::system_clock::now() << '\n'; } prints something like 2017-09-15 13:11:34.356648. Assume I have a string literal "2017-09-15 13:11:34.356648" in my code. What is the right way to create std::chrono::time_point from it in C++20?
Just to be clear, there is no namespace date in C++20. So the code in the question should look like: #include <chrono> #include <iostream> int main() { std::cout << std::chrono::system_clock::now() << '\n'; } The inverse of this is std::chrono::parse which operates on streams. You can also use std::chrono::from...
71,183,352
71,195,287
Merging Tables in Apache Arrow
I have two arrow:Tables where table 1 is: colA colB 1 2 3 4 and table 2 is, colC colD i j k l where both table 1 and 2 have the same number of rows. I would like to join them side-by-side as colA colB colC coldD 1 2 i ...
arrow::ConcatenateTables only does row-wise concatenation. There is no builtin helper method for column-wise concatenation but it is easy enough to create one yourself (apologies if this is not quite right, I'm not in front of a compiler at the moment): std::shared_ptr<arrow::Table> CombineTables(const Table& left, co...
71,183,490
71,183,532
How to get the address of an array pointer?
I have the following c code: int arr[8] = {1, 2, 3, 4, 5, 6, 7, 8}; int **pp = &arr; The compiler complains and I don't know why. Isn't arr a pointer points to an int array? I should be able to assign the address of it to a int**. Are there any other way to do it?
Isn't arr a pointer points to an int array? No, arr isn't a pointer at all. arr is an array. If you take the address of arr, what you get is a pointer to an array, not a pointer to a pointer. This would work: int arr[8] = {1, 2, 3, 4, 5, 6, 7, 8}; int (*pp)[8] = &arr; // cleaner by using a type alias: using Arr8 = i...
71,183,642
71,183,765
MobaXterm does not display the whole image received from WSL
I am using WSL1 in Windows 10 with Ubuntu 18.04 LTS. Configured everything fine to use OpenCV with C++, but when I wanted to display an image, I always received the below error. terminate called after throwing an instance of 'cv::Exception' what(): OpenCV(4.5.5-dev) /opt/opencv/modules/highgui/src/window_gtk.cpp:63...
Maybe you can try with another option such as gWSL or XShell? If these are working, then it would be probably an issue related with MobaXterm and you can contact with the developer of this application. If the problem continues, then it should be further investigated.
71,183,782
71,186,465
Rewrite template names when debugging with lldb
When debugging a c++ program using templates, the output can quickly become unreadable. For this reason it would be convenient, during a debugging session, to rewrite shorten specific type names. For example void std::__1::vector<std::__1::tuple<unsigned long, state_change_t, ...
Clang have an attribute called preferred_name that can be used to create template aliases for compile-time diagnostics. It requires a bit of forward declaring, like this: template<typename T> struct Heap; using IntHeap = Heap<int>; template<typename T> struct [[clang::preferred_name(IntHeap)] Heap; // Possibly add im...
71,184,408
71,184,577
How can I avoid `#pragma once in main file` in GCC when using precompiled headers?
Here is a minimal example: // pch.h #pragma once #include <iostream> And I run: g++ -x c++-header -o pch.h.gch -c pch.hpp When I run the command, I get pch.h:1:9: warning: #pragma once in main file 1 | #pragma once | From my understanding, this behavior is intended by GCC after reading their bugz...
From my understanding, this behavior is intended by GCC As far as I can tell, it's a bug. How can I disable this warning? Unfortunately, it appears that you cannot since the warning cannot be controlled by an option. In my opinion, this is a bug as well. You can circumvent the issue by using a header guard instead ...
71,184,455
71,184,710
How to define a template function that only accepts a base class with parameter T of type its subclass?
It is not specific to casting. My scenario is how to define a template function that only accepts a base class for parameter T of type subclass. template<typename T> // T must be a subclass T* DoSomething(<I don't know> parent) // parent must be a base class { // here the specified subclass of type T is produced. ...
One way could be by using std::is_base_of or std::is_base_of_v in combination with a static_assert: template<typename Derived, typename Base> Derived* CastChecked(Base* parent) { static_assert(std::is_base_of_v<Base,Derived>); return dynamic_cast<Derived*>(parent); }
71,184,990
71,185,187
Where is std::this_thread for jthread?
Can't figure out where is std::this_thread for jthread? I have a function that theoretically makes a jthread sleep until a cancellation is requested: template<typename Rep, typename Period> void sleep_for(const std::chrono::duration<Rep, Period>& d, const std::stop_token& token) { std::condition_variable cv; s...
The jthread constructor accepts a function that takes a std::stop_token as its first argument, which will be passed in by the jthread from its internal stop_source. Here is an example: std::jthread t([](std::stop_token stop_token) { while(!stop_token.stop_requested()) { //Process data... std::this...
71,185,030
71,185,259
C++ concept that checks a value for requirements
Is there a way to use c++20s concepts to check that a value meets some requirements? Lets say I am writing some sort of container that uses paging and i want to make the page size a template parameter. template<typename Type, std::size_t PageSize> class container; I could use a static assert with a constexpr function ...
C++20 introduced std::has_single_bit to check if x is an integral power of two, so you can use requires expression to constrain PageSize. #include <bit> template<typename Type, std::size_t PageSize> requires (std::has_single_bit(PageSize)) class container { }; Demo
71,185,376
71,185,655
std::visit with passing pointer fails to compile under clang 13
The following code compiles properly under x64 msvc x19.30 and gcc 11 but fails to compile under clang 13.0.1: "error: cannot pass object of non-trivial type 'std::shared_ptr<std::pair<int, std::variant<Struct1, Struct2, UnsupportedStruct>>>' through variadic function;" Does anyone know what the problem is? The follow...
thanks to @康桓瑋 for the answer. this code does not work for clang, because of void print(...) {std::cout << "no implementation";} answer: void print(...) is a C function, where variadic actually means the 's parameter. It accepts only trivial types, which std::shared_ptr is not. So the behavior is undefined or only co...
71,186,447
71,186,727
How to inspect pop up windows/tool tips/hover effects which are designed to hide/close on mouse move with tools like WinSpy++ or Spy++?
Essentially I'm trying to learn more about the Win32 api, how certain classes/elements are created, destroyed, what items make them up etc.. Dissecting windows if you will for a project of mine. I'm very curious at the moment what popups/tool tips/hover effects ubiquities to all windows applications are made up of. My ...
The MiniSpy tool on Codeproject comes in handy in situations like this because it uses the corner of the spy window as the location, not the mouse.
71,186,547
71,414,421
How to read the length of audio files using Juce "C++." Without playing the file
I'm trying to display the length of audio files in a Playlist component for an application. I've not used Juce or C++ before, and I can't understand how to do that from Juce documentation. I want to make a function that takes an audio file's URL and returns the length in seconds of that audio without playing that file ...
juce::AudioFormatReaderSource has a method called getTotalLength() which returns the total amount of samples. Divide that by the sample rate of the file and you have the total length in seconds. Something like this: if (auto* reader = audioFormatReaderSource->getAudioFormatReader()) double lengthInSeconds = static_...
71,186,795
71,195,766
How to override emacs-projectile default configuration for project?
I try to use emacs with projectile to configure and than build C++ CMake project. By default projectile use next configuration: (defconst projectile--cmake-manual-command-alist '((:configure-command . "cmake -S . -B build") (:compile-command . "cmake --build build") (:test-command . "cmake --build build --tar...
Have you tried put this .dir-locals.el in the root dir of your project? ;;; Directory Local Variables ;;; For more information see (info "(emacs) Directory Variables") ((c++-mode . ((projectile--cmake-manual-command-alist . ((:configure-command . "cmake -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -S . ...
71,186,902
71,186,995
Using has_include with variables in a loop to check libraries
I'm trying to check if a library is available using __has_include from this post. Since I want to check each one I'm using a loop /* Array of Strings */ const char* libraries[5] = { "iostream", "unistd.h", "stdlib.h", "Windows.h", "winaaasock2.h"}; /* Getting the length of the array */ int librariesSize = sizeof(lib...
It compiles It shouldn't. The C++ language doesn't allow expression statements such as loops in the namespace scope. The example program is ill-formed. Besides that, pre-processor has no knowledge of your loops. There are two possible ways that your program may be processed: // if the header \"libraries[i]"\ exists f...
71,186,966
71,187,631
Max Heap built with pimpl in c++ not working properly
I have a class built using the pimpl idiom that represents a binary max Heap and it is not working properly: the program compiles and prints the content of the array but the array is not sorted correctly. In the examples I used in the main I should see the array sorted as: 100->19->36->17->3->25->1->2->7. I checked mul...
I should see the array sorted as: 10->19->36->17->3->25->1->2->7 That can't be, because in main() function you don't even put 25 in :-) But anyway, here: for (size_t i = (pimpl->heapsize/2)/-1; i>-1; i--) { If you read compilation warnings (because you compile with warnings enabled, right? :-) ) you would see: warn...
71,187,113
71,187,166
Constrain non-type/value template parameter using requires in an ad-hoc fashion
My goal for this code is to constrain a function parameter's passed value to a select few possibilities, being checked at compile time in C++20. My original broken first attempt looked something like this: template<GLenum shader_type> requires requires { shader_type == GL_VERTEX_SHADER || shader_type == GL_FRAG...
If you wanted to constrain a template parameter, a single requires is enough: template <GLenum shader_type> requires(shader_type == GL_VERTEX_SHADER || shader_type == GL_FRAGMENT_SHADER) void foo() {} A function parameter can be constrained like this, at the cost of requiring it to be a compile-time constant: struct S...