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
68,251,554
68,260,468
TYPED_TEST for a class template <typename T, size_t size>
I am trying to write a unit tests for a templated class named Client. Couldn't succeed in compiling the unitTests code. Not sure how to pass both the class / typename T and the size_t size parameters in unit Testing. I have made a git repo git clone https://github.com/BhanuKiranChaluvadi/gtest-minimal-example.git in ca...
One possible solution would be to write a ClientTest class which takes the std::tuple (or std::pair) as a single template argument and splits it up into the two template parameters T and size again using std::tuple_element. Then it instantiates Client<T, size> as a class member. This can then be used to perform the wis...
68,251,950
68,263,974
I want to handle multiple windows in Edge-ie mode from Selenium
I'm running Edge-ie mode on Selenium The usage version is as follows Selenium: 3.141 (java) IEdriver: 3.150.1 So far, I started Edge-ie mode and was able to operate the first screen However, when I open another screen, I cannot get the window handle, Cannot operate It is commented that this is because IE driver is not ...
Edge IE mode should be driven by IE driver. The situation you mentioned is related to this issue on GitHub. The official hasn't fixed it yet so there's no way to handle multiple windows in Edge IE mode from Selenium. I suggest that you can provide feedback about this issue to related product team.
68,252,086
68,252,177
What does this line means(in cpp context) list[i].push_back(adj[i][j]);
What does this line means: list[i].push_back(adj[i][j]); ? vector<vector<int>>printGraph(int V, vector<int> adj[]) { vector<vector<int>>list(V); for(int i=0;i<V;i++) { list[i].push_back(i); for(int j=0;j<adj[i].size();j++) { list[i].push_back(adj[i][j]); }...
In your case, adj is a pointer to a vector(and in this case, I suspect it should be taken as a two-dimensional array), and list is just a vector of vectors, and therefore a two-dimensional array. list[i] is simply a reference to the i-th row of the array list, adj[i][j] is a reference to the value stored in cell [i][j]...
68,252,581
68,252,668
Multiple Vertex Buffers OpenGL c++
I want to draw 2 Vertex Buffers but it only draws the second one. I am using OpenGL 4.6 and the COMPAT profile. The code: float buffer[] = { 0.0f,0.0f, 1.0f,0.0f, 1.0f,1.0f }; float buffera[] = { 0.0f,0.0f, 1.0f,0.0f, 1.0f,-1.0f }; unsigned int...
When glVertexAttribPointer is called, the the buffer which is currently bound to the target ARRAY_BUFFER is associated to the attribute. It is not sufficient to bind the buffer object. You have to do the vertex specification before drawing the object: glBindBuffer(GL_ARRAY_BUFFER, id); glEnableVertexAttribArray(0); glV...
68,252,606
68,252,607
How to decompose a pointer-to-member in C++ (get class and member types)?
I have this scenario: #include <iostream> class SomeClass { public: int _int; }; #define DO_SOME_STUFF(ptr) std::cout << /* Print the typeid().hash_code() of the type which ptr is poiting to (int) */; int main() { int SomeClass::* ptr_to_int_member = &SomeClass::_int; DO_SOME_STUFF(ptr_to_int_member) } ...
You can do that with a "template trick": template<typename T> struct PointerToMemberDecomposer {}; template<typename T, typename P> struct PointerToMemberDecomposer<P T::*> { using ClassType = T; using MemberType = P; }; And change your code to: #include <iostream> template<typename T> struct PointerToMember...
68,252,930
68,253,438
Attaching a QLabel to a QLine or QLineF
Is possible to attach an QLabel to a QLine or QLineF? QLineF incidenceLine; painter.setPen(QPen(Qt::red, Qt::SolidLine)); incidenceLine.setP1(QPoint(width / 2, height / 2)); incidenceLine.setAngle(qreal(angleOfIncidence) + angleOffset); incidenceLine.setLength(indexLength); painter.drawLine(incidenceLine);
no you can not... you can add a widget to a widget but that is another story... but you can draw text in the paint method using the painter object: painter.setPen(Qt::yellow); // or another well contrasting color painter.drawText(x, y, my_text); where x and y are ints to map in the canvas, my_text is the string objec...
68,253,161
68,253,233
How to share a global variable between files using header file?
I have a header file and 3 cpp files. I want to share an array object between my files to store data in it and use it (global variable). My header file code : info.h #ifndef INFO_H #define INFO_H #include "QString" class ib { public: QString from,to,seat[32],driver; }extern o[10]; #endif // INFO_H and my cpp files...
Declaring an object as extern can be done many times. All it means is "this object's linkage data is somewhere else". Your code doesn't contain the "somewhere else" definition. file.h: extern int i; // i is defined somewhere else file.cpp: int i = 0; // this is the definition some-other-file.cpp: extern int i; // wil...
68,253,560
68,261,577
Error std::bad_array_new_length in a template
I was trying to define my own class template Array<T> to practice the usage of templates. The code I produced builds properly, but when executed it gives the following error terminate called after throwing an instance of 'std::bad_array_new_length' what(): std::bad_array_new_length I think I have found a solution t...
Compiling with GCC 9.1.0 in jdoodle.com, I consistently got a bad_alloc runtime exception with your original code. I added a new constructor with a different signature so I could see what value of size it was using to allocate the array Note: Even the existence of this new ctor prevented the bad_alloc error, whether it...
68,253,740
68,253,830
Smart pointer with local buffer optimization
This is example of smart pointer with type erased deleter and local buffer optimization enabled. It is from the book https://books.google.am/books/about/Hands_On_Design_Patterns_with_C++.html?id=iQGGDwAAQBAJ&printsec=frontcover&source=kp_read_button&redir_esc=y#v=onepage&q&f=false #include <iostream> template <typena...
It is not a bug - it is valid to have uninitialized memory. You only have Undefined Behavior (UB) when you read from uninitialized memory. This makes sense - if merely having uninitialized memory would already be a bug, then placement new such as in the smart_ptr ctor above would be pointless. But that is safe, because...
68,254,736
68,254,977
When was the ability to declare a variable in the if statement introduced in C++?
In C++, we can declare variables directly in the if statement and its value is used as the condition, e.g. if (SubClass *subObject = dynamic_cast<SubClass *>(baseObject)) { // ... } For some reason, I always assumed that this was a "relatively" new feature, introduced in C++11 at the earliest, but when I tried to ...
The first formal C++ Standard was ISO/IEC 14882:1998 (a.k.a. C++98). In this 'draft' version of that, the declaration of a variable inside an if statement is explicitly mentioned: 6.4 Selection statements       [stmt.select] … 3     A name introduced by a declaration in a condition (either introduced by the type-spec...
68,254,799
68,256,582
List or Array of Elements of different datatypes
I want to store 6 pointers to objects. But the Pointers can be in any order and point to different instances of (12) subclasses of one superclass, so they are possibly all of different types. Arrays and such don't work, because the superclass is virtual. Vectors and Tuples don't work, because the datatypes are of no s...
You CAN create a vector of superclass pointers. It will achieve what you want, as it will call the overwritten function. This is of course assuming you are talking about inheritance, like: #include <vector> using type = ????; class A { virtual type foo() = 0; } class B : A { type foo() override { ... } } clas...
68,254,941
68,255,957
C++ polymorphic shared_ptr
Сan you help me fixing this code, The function printIt from exampleA is not used. I used shared pointer and reference_wrapper but il does not look to work fine. Wrong result: 1;2;23;23;23; http://cpp.sh/9yqpq #include <iostream> #include <vector> #include <algorithm> #include <list> #include <vector> #include <iost...
As noted in the comments, you create example objects that are copies of const example& a. For object3, that a is just a reference to the base part. That's called "slicing". A simple fix is to copy the actual argument type, using a template: template <typename EX> void add (EX const& a){ input.push_back(std::make_shar...
68,255,070
68,255,127
The address of C ++ pointer
#include <iostream> using namespace std; int main(int argc, char** argv) { unsigned int a =5; unsigned int *pint = NULL; cout << "&a = " << &a << endl; cout << " &pint = " << &pint << endl; } Output: &a = 0x6ffe04 &pint = 0x6ffdf8 I'm wondering why the address of pint equals 0x6ffdf8. pint is an un...
Your pint is not an unsigned int. It is a pointer to an unsigned int. Pointer can have a different size and can especially have the size 8. It could hence fit into 0x6ffdfc before 0x6ffe04. But it also has bigger alignment needs, it wants an address dividable by 8, so 0x...c is out, it needs e.g. 0x...8. With 463035818...
68,255,487
68,255,757
Merge sort c++ code returns same order of numbers and does not sort
Code: // Merge sort #include <iostream> #include <algorithm> using namespace std; void Merge(int *A, int *B1, int one, int *B2, int two){ int *combi = new int[one+two]; int c = 0, d = 0, x=0; while(c < one && d < two){ cout<<"B1[C] "<<B1[c]<<" B2[d] "<<B2[d]<<endl; if(B1[c] < B2[d]){ ...
Your code has a problem with Merge. At the entrance to the function you expect that the array after merging will be written in argument A, but in reality it is written in the local variable combi, which you do not use anywhere, and accordingly it does not affect the result To solve this problem simply in the Merge func...
68,255,952
68,256,035
How do I create a pointer to key/value pair of a map in C++?
I'm trying to explore the different ways of creating pointers. In the following code, I'm trying to create a pointer pointing to a key/value pair of a map in two different ways: #include <iostream> #include<map> using namespace std; int main(){ //creating the map & the key/value pair map<string,string> mp; ...
mp.begin() does not return a pointer, it returns an iterator, which is an object that represents a reference to an entry, but still an object in of itself. You can convert an iterator into a pointer by using &*iterator, which means "The address of (&) the object referred to (*) by that iterator". Next up, map<string,st...
68,256,247
68,274,947
serpent encryption key schedule, how to padd the key to expand to 256bits
Im trying to implement the serpent encryption algorithm from scratch as a personal side project, now I am stuck with the key scheduling part of it. according to the only the documentation ,https://www.cl.cam.ac.uk/~rja14/Papers/serpent.pdf, I need to padd the key to 256 so I can start generating the subkeys. how do I a...
Let's have a look at the standard, assuming little endian representation as indicated at the start of the paper: The user key length is variable, but for the purposes of this submission we fix it at 128, 192 or 256 bits; short keys with less than 256 bits are mapped to full-length keys of 256 bits by appending one “1”...
68,256,300
68,256,445
Does my wrapper library .dll depend on the external .lib file I link?
I have built a C++/CLI wrapper for a static library in a .lib file. The .lib file is listed as an external dependency in my project, but when I use my compiled .dll, do I still need to somehow include the .lib file in projects I use it in, or will the .lib be embedded in my final .dll? Thanks
You're linking statically against your .lib, so everything needed by your wrapper will be "embedded". That's what statically linking is all about.
68,256,556
68,257,308
Initialization of values before constructor
Problem: I implemented this new opeator for my class. void* Objects::MemoryObject::operator new(size_t size, Memory::BaseAllocator* allocator) { Objects::MemoryObject* newObject = static_cast<Objects::MemoryObject*>(allocator->allocateItem(size)); newObject->_objectAllocator = allocator; newObject->_ob...
Only thing that works is adding one structure that is holding informations. These informations are used later by constructor. This struct is defined in code file (.cpp) so it is invisible for other objects in program. // Here we will save our values struct { Memory::BaseAllocator* allocator; Memory::SystemInt ...
68,256,579
68,256,607
Passing a value to an object of the class, how is that possible?
#include <iostream> using namespace std; class Complex { private: double real; double imag; public: Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {} bool operator == (Complex rhs) { return (real == rhs.real && imag == rhs.imag)? true : false; } }; int main() { ...
A non-explicit constructor that can be called with one argument is a converting constructor. Complex(double r = 0.0, double i = 0.0); Since this constructor has default arguments, we can call it with zero, one, or two arguments. Thus, it can act as a converting constructor. So, in the com1 == 3.0, which actually is t...
68,256,622
68,256,781
No definition in cpp composition when I define in function
#include <iostream> using namespace std; class Date{ private: int day; int month; int year; public: Date(int dy,int mt,int yr){ day=dy; month=mt; year=yr; } void showDate(){ cout<<day<<"/"<<month<<"/"<<year<<endl; } }; class Human{ private: string name; ...
In the definition of a constructor, all member variables must be initialized before the body of the constructor is executed. Since Date doesn't have a default constructor, there is no way to initialize it Human(string nm, Date bd) { // birthDay must be initialized before this point // ... birthDay = bd; // this ...
68,256,837
68,316,598
How to Correctly Remove All elements(including wxsizers and wxwindows) from inside a wxBoxSizer(wxVERTICAL)
Hi i am trying to remove all elements(including wxSizers and wxWindows) from inside a wxBoxSizer(wxVERTICAL) . The hierarchy structure I am using is shown in the screenshot below. wxBoxSizer(wxVERTICAL) : this contains everything and i want to remove everything inside this sizer. Let's call this sizer the mainSizer. w...
As far as I know there is no command to remove or destroy the children of a sizer. From the documentation of the deprecated function wxSizer::Remove(wxWindow* window) wxSizer::Remove(wxWindow* window); "Removes a child window from the sizer, but does not destroy it (because windows are owned by their parent window, no...
68,256,886
68,257,029
./libbar.so: undefined symbol: __gxx_personality_v0, how to solve it?
While making a simple test case I met with another problem. Please help me. Here are the files. <<< bar.cpp >>> #include <stdint.h> #include <stdio.h> extern "C" { uint64_t var_from_lib; } class BC; class BC { public: void bar(void); BC(); ~BC(); }; BC::BC() { } BC::~BC() { } void BC::bar(void) { ...
How can I remove the error? Link your application with C++ library. Link with g++ or GLOBAL dlopen the libstdc++.so library. Overall, gcc -shared -o libbar.so bar.o should be g++ -shared -o libbar.so bar.o - it's a C++ library. gcc -Wl,--no-undefined -shared -o libbar.so bar.o catches the problem.
68,257,064
68,257,650
Google mock with templates and inheritance
I am currently trying to get templates and inheritance to behave nicely with GMock. I have a feeling what I am trying to do are two opposing ideologies and I should just use an interface, but I wanted to avoid using an interface due to possible virtual call overheads (perhaps I am optimizing prematurely) Anyway, here's...
To avoid runtime polymorphism, you can use template, as follow: class ConcreteObj { public: // Called a lot and so don't want to hit possible virtual overhead void performant_function(); }; class MockObj { public: MOCK_METHOD(void, performant_function, (), ()); }; class ITest { public: virtual ~ITest(...
68,257,478
68,257,627
in function parameter why (i++) got some error while (i+1) is running
Case 1:when i put i++ at function parameter at that time i got blank output Case 2: when i put i+1 rather than i++ at that time i got correct output #include <iostream> using namespace std; int foccurance(int arr[], int n, int i, int key) { if (arr[i] == key) { return i; } if (i == n) { ...
The expressions i++ and i+1 evaluate to different things and after the operations, i will hold different values. void f(int v) { std::cout << v << std::endl; } int i = 0; f(i+1); // Prints 1 std::cout << i << std::endl; // Prints 0 f(i++); // Prints 0 std::cout << i << std::endl; // Prints 1. So i+1 will not mod...
68,257,652
68,257,823
What happens if you transfer control to a if(false) block by using goto?
I've thought of following code by trying to solve a difficult 'nested-condition' problem: goto error; if (false) { error: cout << "error block" << endl; } else { cout << "else block" << endl; } When I run this code, only error block is displayed, as expected (I guess?). But is this defined behavior across...
Yes, this is well defined. From stmt.goto#1 The goto statement unconditionally transfers control to the statement labeled by the identifier. The identifier shall be a label located in the current function. There are some restrictions, e.g. a case label cannot cross a non-trivial initialization goto error; int i = 42;...
68,257,663
68,257,942
Changing the variable defined in shared library in my program doesn't get reflected seen from the shared library
Trying to test a simple case where a global variable defined in a shared library is set by a program and used by the shared library, I saw a strange problem. Here are the program codes. bar.cpp #include <stdint.h> #include <stdio.h> extern "C" { uint64_t var_from_lib; } class BC; class BC { public: void bar(void...
Looks like you are not linking to the shared library. You are dlopen-ing it. Your expected behavior works like this only when you are directly linking with the shared library. With dlopen you are expected to do all the work yourself: using dlsym to obtain the address of a symbol that's defined by the shared library.
68,257,667
68,261,495
Device memory allocation fails on WSL2
I am trying to run a simple c++ program, with Cuda Thrust functions, on WSL2. It seems that program fails in runtime to allocate device memory. I use Thrust with Microsoft visual studio all the time, and I don’t get any errors. CMakeLists.txt: cmake_minimum_required(VERSION 3.8 FATAL_ERROR) project(proj LANGUAGES CXX C...
Before I post the question, I had already seen the instructions in here , and both downloaded and installed the CUDA driver for WSL, and joined the windows insider program and upgraded to windows 11 build. It did not work though. But I also had Ubuntu 18.04 installed. I think it was installing Ubuntu 20.4 instead that...
68,258,025
68,258,530
Inconsistent C26496 warning
I recently refactored my SDL2 C++ code using structs. It compiles and runs fine (using Visual Studio 2019), but is now throwing out an inconsistent warning: C26496 Variable 'Graphic::X' is uninitialized. Always initialize a member variable. This repeats for X = h, w, x, and y for the lines of code representing the rend...
None of your structure's members are initialized. They are assigned to after initialization would have been done. Initialize your structure when you declare it, something like Graphic createbutton { "Create Forest", "longbutton", 0, 1 * (Screen_Width / 5) + 5, Screen_Width / 10, Screen_Width / 5...
68,258,135
68,258,437
std::invoke_result doesn't work in a template function with auto return type
I'm trying to use std::invoke_result_t and it fails when called for nested lambda in function with auto return type. Here is a reproducer: template <typename T, typename... Args> auto print_ret_type(T &&t, Args &&... args) { using ret_type = std::invoke_result_t<T, Args...>; std::cout << typeid(ret_type).name() << ...
The rules for how return type deduction work are a bit quirky. To determine the return type, it actually instantiates the body of the function. Any errors in this instantiation are hard errors. Lambdas return types are implicitly ->auto basically; so those rules apply to them. If you want to know the return type of w...
68,258,170
68,258,426
Fastest way to convert a float to int in C++
What is the fastest and most efficient way to convert a float to an integer in c++ (rounding toward zero)? is it long ftoint(float x) { unsigned int e = (0x7F + 31) - ((* (unsigned int*) &x & 0x7F800000) >> 23); unsigned int m = 0x80000000 | (* (unsigned int*) &x << 8); return int((m >> e) & -(e < 32)); } ...
Lets compare the following two: long ftoint(float x) { unsigned int e = (0x7F + 31) - ((* (unsigned int*) &x & 0x7F800000) >> 23); unsigned int m = 0x80000000 | (* (unsigned int*) &x << 8); return int((m >> e) & -(e < 32)); } long ftointfast(float x){ return x; } Clang with -O3 produces: ftoint(float): ...
68,259,197
68,264,978
To read only specific data from file... if string value is passed else to read everything from file c++98
I have file named bird.lst. I am trying to read its contents and store the data map data structure. Where i am looking to read specific bird information, when string value is passed std::string find = "pigeon"; will get information of pigeon. (working with current code) if empty value passed to string std::string find...
" " is not an empty string, "" is. Nor are you checking for an empty string before searching anyway. In any case, when find() fails to find a match, you are skipping your inner while loop altogether, and thus not skipping that current bird's info. So the next outer loop iteration misinterprets those unread attributes a...
68,259,384
68,288,943
C++ how to move Text with ncurses.h?
C++ how to move Text from off screen to inside the terminal (animation 20/50 millisec.) and then stop the animation. with ncurses.h ? pls with examples with perhaps a loop that increases the X coordinate from (x = 0-number characters text-1) to (x = 2 or 1), for each Line of text containing the color. let me explain: t...
stackoverflow guys. i started stackoverflow bad. sorry for my wrong attitude (that's why I didn't get an answer) but luckily I managed to get the result I wanted! I can be of help for you! in the documentation it won't say, but through a while () loop I managed to do it! int main() { initscr(); int x = -1; while (x <...
68,259,469
68,259,881
CMake split target_sources in CMakeLists.txt into different targets
I have a test project called test_containers. Inside directory there are only cpp files and CMakeLists.txt which looks like this: cmake_minimum_required(VERSION 3.0.0) project(test_containers) add_executable(${PROJECT_NAME}) target_sources(${PROJECT_NAME} PRIVATE test_linear_hash_table.cpp test_list.cpp t...
For your question, as described, you will need to create 1 target per file -- each building the individual source, linking the correct dependencies, and being added as a test. You might be able to do something like (untested): set(source_files test_linear_hash_table.cpp test_list.cpp test_stack.cpp test...
68,259,699
68,271,100
How can you get frame-pointer perf call stacks/flamegraphs involving the C++ standard library?
I like the fp method for collecting call stacks with perf record since it's lightweight and less complex than dwarf. However, when I look at the call stacks/flamegraphs I get when a program uses the C++ standard library, they are not correct. Here is a test program: #include <algorithm> #include <iomanip> #include <ios...
With your code, 20.04 x86_64 ubuntu, perf record --call-graph fp with and without -e cycles:u I have similar flamegraph as viewed with https://speedscope.app (prepare data with perf script > out.txt and select out.txt in the webapp). Is it possible to get correct fp call stacks with libstdc++ without compiling it myse...
68,259,933
68,260,280
How to make well-encapsulated classes while using unordered_set/map in c++?
I was looking at some tutorials on how to make an unordered_set for a class/struct. I found this easy-to-understand code (as a Java developer) which does the trick: #include <iostream> #include <unordered_set> using namespace std; struct Node{ int val; bool operator==(const Node& n) const{ return (t...
There are a few questions here, so I'll try to answer them in order: can make the struct Node a class Yes, struct and class only differ in their default permissions (in struct things are public unless stated otherwise, in class they are private) So this is identical code to what you wrote: class Node{ public: int...
68,259,967
68,260,143
How to store references to other objects in C++?
This is a more general question that I'm trying to resolve for C++ best practices. Suppose I want to create objects which store references to each other, like a graph. All objects are owned by the same object, like a Graph object to all the Nodes, which is to say the ownership is fixed. Here's my idea: a class Graph ha...
When discussing "Best Practices", it's important to consider what your quality-attributes and needs are for the code. There is no "right" or "wrong" answer in the example of code such as a Graph; there are varying degrees that solve different problems in different ways -- and it depends strongly on the way its intended...
68,259,980
68,260,122
Is there a on change property for textEdit class in Qt?
I'm trying to create a notepad app in Qt, and I want to do something every time the "TextEdit" is changed. I've tried to search in the Qt Documentation but I had no luck. Maybe someone knows how to do it?
you dont need the property for that... I suggest you to instead connect the signal emited by the object... in this case the textChanged signal as in the doc specified: This signal is emitted whenever the document's content changes; for example, when text is inserted or deleted, or when formatting is applied. all you ...
68,260,070
68,306,289
Representing asn structs in c++
I have an asn schema file and am having trouble in representing two types of data id TID where TID::= OCTET STRING (SIZE(4)) How do I set the value of id? If it was type INTEGER, we directly set id = 10 for example. objects List where List::= SEQUENCE (SIZE(1..256)) OF Data , Data::= SEQUENCE { cl1 objData1, ...
If you look at the code generated by Lev Walkin's asn1c compiler, you'll find that your TID comes out as a containing a pointer to an array of uint8_t, and a length. Allocate an array 4 long, fill in the bytes as you require, and set the length to 4. Because you've defined it as an OCTET STRING (SIZE(4)), how you in...
68,260,579
68,261,021
Is std::coroutine_handle thread safe in any way?
Are there any parts of std::coroutine_handle that are defined as thread safe in the standard? I could for example see std::coroutine_handle::done() being implemented with an atomic variable, which would allow for completion checks without locking everything first. But if nothing related to thread safety is defined in t...
None of the functions of coroutine_handle are specified to not provoke data races. Therefore, the standard library's common rules apply: concurrently calling any functions with an object provokes a data race on that object unless all potentially conflicting functions access the object via a const pointer/reference (lik...
68,260,606
68,260,805
Bubble Sorting an Array of Objects in C++
I need to sort an array composed of the Date objects by using bubble sort. Objects include private attributes, so I tried to use friend functions. Currently, the program is running but the dates that are printed are unsorted, I guess there are some problems with the use of pointers in the swap and BubbleSortDates funct...
There is a typo in the function compareDates in this else statement else { if (date1->Month > date2->Month) return true; else if (date1->Month < date2->Month) return false; else { if (date1->Year > date2->Year) return true; else if (date1->Year < date2->Year) ...
68,260,641
68,477,004
How to add PoDoFo external library to my C++ project in Qt Creator?
I am using Qt Creator, Qt6, C++ for my program. I would like to use the PoDoFo library but I have no knowledge of how to add the library/headers so that I can use it in my project and build it. I have downloaded the PoDoFo code, just can't find any guidance/tutorials on how to add PoDoFo specifically in Qt Creator. Edi...
Did you take a look on this link: https://doc.qt.io/qt-5/third-party-libraries.html? I just followed it and my 3rdParty library (https://github.com/cutelyst/simple-mail) was linked and accessible from my application C++. Basically, your .pro file will look like this after setting everything properly: TARGET = MyQtApp ...
68,261,543
68,261,787
Constructor parameter access member field of object under construction
I have the following structure that has a member function pointer. My question is, is there a way for the lambda that I pass to it to refer to its own member variable? i.e. struct Foo { int aVar{1}; int (*funcPtr)(int); Foo(int (*func)(int)) : funcPtr(func) {}; }; auto bar1 = Foo([](int a) {std::cout << a...
The lambda must have the signature int(int) but your lambda has the signature void(int) so that's the first problem. The other is that the lambda must capture bar2. You could use std::function for that. #include <iostream> #include <functional> struct Foo { int aVar{1}; std::function<int(int)> funcPtr; F...
68,261,582
68,293,659
Initializing Vector4f with Vector3f
I am trying to perform view transform to a 3D point in world coordinates stored in Vector3f, my view matrix is stored in Matrix4f. Would it be possible to initialize Vector4f with an extended Vector3f. This's what I've done so far: Eigen::Vector4f Graphics::getLookVectorView() { Eigen::Matrix4f viewMatrix = dxToEigen(...
You could circumvent the conversion using Affine3f instead of Matrix4f. An Affine3f object internally stores a Matrix4f (that can be accessed by Affine3f.matrix()) and the multiplication with a Vector3f returns a Vector3f performing the same calculation done using a Vector4f created adding the trailing 1. #include <Eig...
68,261,748
68,264,029
My SDL_ttf rendered text ends up streched. How do I avoid that?
Here is a minimal example of how I render my SDL text: #include <SDL_ttf.h> void runttf() { constexpr auto SCREEN_WIDTH{300}; constexpr auto SCREEN_HEIGHT{300}; constexpr auto font_path = "/usr/share/fonts/truetype/fonts-beng-extra/MuktiNarrow.ttf"; //any font on your system constexpr SDL_Rect destination = {1...
You are setting your destination rectangle to be different than the text that was rendered to the surface so it will stretch. You should also free up the surface before your main loop. So the code I think you are looking for: #include <SDL_ttf.h> void runttf() { constexpr auto SCREEN_WIDTH{ 300 }; constexpr au...
68,261,766
68,267,787
File wx/wx.h does not exist
I've been trying for a while now to compile and use wxwidgets for a c++ project, but every time I think I get close, the same error occurs. File wx/wx.h does not exist. I've tried building wxwidgets with cygwin and VS2019, just downloading the binaries, and finally(what I've most recently tried), downloading the librar...
You can build or get and use wxWidgets in many different ways, all of which work, but you can't mix different ways together and expect them to work. If you want to use vcpkg, you should follow the instructions here and you can read this post for more details.
68,262,231
68,263,515
Getting an image on screen with SDL2
I've been trying to have a bitmap image displayed on screen but I can't figure out why it's not displaying it for the life of me. Here's the code: #include <iostream> #include <SDL.h> bool init(SDL_Window *window, SDL_Surface *surface) { bool success {true}; if (SDL_InitSubSystem(SDL_INIT_VIDEO) != 0) { ...
You are passing parameters to init() - but the function receives a copy of those things. Then you change the copies passed into the function so they point somewhere else - but that doesn't change where the original pointers point. Then when you return to main() you use the original pointers which are still pointing t...
68,262,371
68,263,654
Lidar Sensors not working properly - How to work with two lidar Sensors over I2C on arduino
I'm currently working on a project with some friends about lidar measuraments based on ARDUINO and GARMIN Lidar v3HP and we are getting some reading that are questionable from the sensors. They seem to work but the measurements are not correct. We have issues with the data and also with the address, we setup the sensor...
Based on your top comment, there may be an issue with configuring both lidars at the same time. From factory default, they will both respond to the default I2C address 0x62. So, when you try to reconfigure one at a time, they will both respond [and there may be a race condition] and will both get programmed to the new ...
68,262,512
68,262,909
Where to see what OMP schedule(auto) picks?
Is there a way to find out what scheduling scheme the OMP runtime chooses for schedule(auto)? I found that (and intuitvely it makes sense) for my problemschedule(static) is the fastest, so I am wondering if that's what the runtime chooses when is set schedule(auto) (they're equally fast).
Yes. You can set the environment variable OMP_DISPLAY_ENV to TRUE to get this information before running your program. It should print the OMP_SCHEDULE variable when the OpenMP runtime is initialized. For example, on my system, GOMP (GCC) choose DYNAMIC while IOMP (Clang/ICC) choose static by default. You can select th...
68,262,674
68,262,799
Is there a way to use concepts to disable member functions that would produce a reference to void?
I would expect it to be possible to write a class like this template <class T> struct A { T& operator*() requires (!std::is_void_v<T>) { return *ptr; } T* ptr; }; But if I write A<void> a; I get the compiler error prog.cc: In instantiation of 'struct A<void>': prog.cc:16:13: require...
No, it is unfortunately not possible. I wish what you wrote actually worked, and it would be the correct way to write it if there was one, but you just can't do it. Your options are: template <class T> struct A { // #1: a type trait that handles void for you std::add_lvalue_reference_t<T> operator*() requires (...
68,262,882
68,262,940
How can I remove the lines being output in my 2d array?
When I run the program, I get lines in between the elements of my 2d array. How do I get rid of them? I meant to have empty values cout << " "; for (int i = 0; i < 10; i++) cout << i << " "; cout << endl; for (int i = 0; i < 10; i++) { cout << i << " "; for (int j = 0; j < 10; j++) { cout << ...
Doing char grid[MAX_ROWS][MAX_COLS]; is not an initialization, it just creates the grid with garbage inside it. If you want to have empty spaces you have to do something like: for (size_t i = 0; i < MAX_ROWS; i++) { for(size_t j = 0; j < MAX_COLS; j++) { grid[i][j] = ' '; } }
68,263,043
68,263,514
Destruction of static members inside common classes between two shared objects?
I have the following hierarchy: classes with multiple static std::map that's initialized in cpp as following std::map<int, string> ClassA::MyStaticMap = ClassA::InitializeMyStaticMap() Shared object libfoo.so that includes these classes. Shared object libbar.so that includes these classes. An application that util...
Short answer: don't rely on global variables in code exported from a DSO. // from lib foo class B { public: B(std::map<int, string>& map) : a_map_ref(map) {} std::map<int, string>& a_map_ref; }; // from lib bar class C { public: C(std::map<int, string>& map) : a_map_ref(map) {} std::map<int, string>&...
68,263,211
68,263,444
What does std::vector<std::string> vec{3}; actually do?
I am currently trying to understand list initialization in C++11 and I have stumbled upon this line of code: std::vector<std::string> vec{3}; I am wondering what it is actually doing, I noticed 3 elements are created in the vector however, I am not sure why and what values these elements will be initialized with. Edit:...
vector<T> has a constructor which takes a single integer; it creates a vector containing 3 default-initialized Ts. This constructor is therefore a viable candidate constructor when you use syntax equivalent to vector<T>{3}. However, the use of {} syntax means that any vector<T> constructors which take an initalizer_lis...
68,263,915
68,265,453
How to ignore wrong cin input in C++?
This is code for a 4x4 tic-tac-toe game. I am new to programming. I don't know how to ignore wrong input from the user. I tried searching Google, I found cin.clear() and cin.ignore(). They did work a little bit, but not fully working. For example, if the user enters 11111111 4 o as input, the program exits instead of i...
OK. User input is hard. Interactive user input is line based. User inputs some values and then hits return. This flushes the stream and unblocks the readers to get the value from the stream. So you should design your input code to be line based. The first question seems to be is all the input on one line or do they inp...
68,264,189
68,264,348
Is there a way to get the name of the makefile where a make variable was defined?
For debugging purposes, when there are many make file inclusions, it's useful to print the full path of the makefile where a particular variable in the current makefile was first defined. Is there a way to do that?
Just run make -p. Make will print its internal database including all targets and variables that were seen along with the filename and linenumber where they were set.
68,264,451
68,264,498
Undefined reference to object when compiling with a header file
I'm getting an undefined reference error when compiling the code below. Here is main.cpp: #include <iostream> #include "Person.h" using namespace std; int main() { Person person1; cout << "Age is: " << person1.getAge() << endl; cout << "Name is: " << person1.getName() << endl; system("PAUSE"); ...
It's because you are not including Person.cpp as a compiling parameter. You need to add Person.cpp aswell as main.cpp file
68,264,685
68,264,927
Is there a way to pass all type template parameters in an old class template into a new class template?
I've created a simple template class called tuple_tag which is identical to std::tuple but only acts as a tag. // tuple_tag template <typename...> struct tuple_tag {}; // tuple_tag_element template <size_t I, typename T> struct tuple_tag_element; template <size_t I, typename Head, typename... Tail> struct tuple_tag_e...
3 steps. First, make a pack using indexes=std::make_index_sequence<tuple_tag_size<TupleTag>; then have a helper that expands the pack. I like this one: template<auto x> using constant_t=std::integral_constant<decltype(x),x>; template<auto x> constexpr constant_t<x> constant={}; template<std::size_t...Is> constexpr...
68,264,780
68,264,845
Pass any argument to a function accessed by extern "C"
I am using x64asm code in my C++ project. I am using this code to access my function that is defined in .asm file: extern "C" void strpl(char* , int*, bool ) what I want is it to have any type pf pointer at first argument instead of just char* I tried custom template which I googled like so: template<typename T> exter...
I believe a raw void pointer (void*) would be sufficient. You can use C-style casts to convert to and from void pointers to pointers of other primitive types in your calling C/C++ code. Some advice... The use of templates is overkill for what you're trying to accomplish and it takes a lot of understanding to get templa...
68,265,559
68,280,224
How can I transform a pointer to the type I input in C++?
I have a question here: I want to generate a type_t pointer (type_t *), pointing to a memory block, with specified value stored in it. In another word, its input is: string value, string type and its output is: (type*)pointer , pointing to some memory storing 'value'. I don't know how to do this. I tried to use templ...
This kind of functionality is not provided in c or c++.You can do that in python using exec(). One thing you can do to solve this problem is to declare some of the variables beforehand with the same name as the string that you want to pass.
68,265,992
68,289,946
Segmentation fault(core dump) when trying to read a float into a linkedlist in C++
I keep getting a segmentation fault(core dump) when I run addRecord() exactly after I type the float. There might be something terribly wrong with my use of pointers in the function but I can't seem to find what the problem is. This is from a project I am doing for school. Don't worry, the deadline has already passed. ...
As the comment says, you'll want to change the line: struct employee *newOne; to actually creating a new employee: struct employee *newOne = new employee(); otherwise the pointer won't actually point to a real employee struct and it'll crash.
68,266,265
68,266,594
error: conversion from ‘const char’ to non-scalar type ‘std::string’ {aka ‘std::__cxx11::basic_string<char>’} requested
I want to count letters in const string&, and save result in map. But compiler throws an error: error: conversion from ‘const char’ to non-scalar type ‘std::string’ {aka ‘std::__cxx11::basic_string’} requested My code: map<string, int>& MakeWordCounter (const string& word, map<string, int>& counter) { for (string...
The dereferenced iterator of word has the type char, we can't convert it to string. And the function declaration can be more clear to directly return the map. The key type here is char, we don't need to use a string type, its misleading and is a waste. std::map<char, size_t> MakeWordCounter(const std::string& word) { ...
68,266,434
68,269,835
Reading bytes written by Python with C++ and vice versa
Trying to read in the bytes of a file created with Python. In Python, I can read in the bytes length exactly. And retrieve the data and then successfully perform whatever I want to perform. However, when attempting to do the same in C++, it fails. Not sure of why. To write in Python: with open("secret.key", 'wb') as se...
The reinterpret cast for reading iv is not necessary, but iv is filled correctly. seek is not required either. The variable key is used as a file name, but no data is read into it. int main() { std::ifstream ifs("c:\\temp\\test.txt", std::ios::binary); if (!ifs.good()) throw new std::runtime_error("Scr...
68,266,549
68,266,644
Cannot convert template when using lambda as parameter
I want to pass a lambda to a function, but I have run into a problem of successfully passing it onto the function. The function chooses to append TrueVal or FalseVal and creates a vector of boolean, based on the given condition. I'm using 2019 Visual Studio's ISO C++14 Standard to compile the code. #include <iostream> ...
The issue is that OriginalElement is not a bool and cannot be implicitly converted to one. You can call it to get a bool by passing an int. Change this line in the template: TempCol.emplace_back(FalseVal(i)); then auto OriginalElement = [&BoolList](int i) {return BoolList[i]; }; vector<bool> b = ConstructNestedVectorB...
68,266,659
68,266,710
What is 'operator auto' in C++?
Clang and Visual Studio compilers (but not GCC) allow one to write the code as follows: struct A { operator auto() { return 0; } }; int main() { A a; a.operator auto(); } What is operator auto? Is it an extension of a particular compiler or a standard language feature and if yes in what language standard (e.g...
When auto is used in user-defined conversion function the type will be deduced via return type deduction, i.e. int for this case (0). This was introduced in C++14. The placeholder auto can be used in conversion-type-id, indicating a deduced return type: struct X { operator int(); // OK operator auto() -> short...
68,266,680
68,266,734
How to SFINAE using concepts on member non-template function of a template struct?
Background I'm writing an object pool. I would like to provide one constructor which just accepts the count of elements to default construct. There is a concept for that already, I would like to try to use C++20 feature for this. Code template <typename T, std::size_t capacity> class object_pool { /* storage for un...
You can put a requires expression after the signature object_pool(std::size_t count = capacity) requires std::default_initializable<T> { /*...*/ } Example
68,266,697
71,554,065
What is the best way to to wait until event happen in c++?
I am using fastdds publisher, following code to publish data. getMatchedStatus() returns publication_matched callback status if subscriber is matched, getMatchedStatus() = 1 if no matching subscriber, getMatchedStatus() = 0 if subscriber shutdown after reading data, getMatchedStatus() = -1 void publish(){ while (g...
I can think of three solutions: Sleeps, Condition Variables, and WaitSets. Using sleeps, however, seems to me like the less efficient one (but probably the easiest to implement): Using sleep As a general rule: it is not advisable to use sleeps to wait events. By using sleeps, you lose the control on your thread, and yo...
68,266,733
68,266,809
( | vs. || ) "OR" Operator Comparison in C++
I understand that in C/C++, the || is the normal OR comparison operator, and that | is the bitwise OR operator. My question is, why do we have 2 different operators for the same thing? Why don't we just use | everywhere? Example: int n = 1; if (n == 1 | n == 2) { cout << "Condition Matched\n"; } This also works, bec...
One of the more important differences is that the || operator short-circuits, but the | operator doesn't. Consider: void f(int* p) { if (!p || *p == 0) { // Do something } } If we used the | operator here and p was nullptr, we would end up dereferencing a null pointer. The || operator prevents t...
68,266,870
68,266,929
How to dynamically instantiate a class with parameterized constructor using std::vector?
I want to dynamically instantiate the object using vector, However, I don't know how to pass the parameter to the constructor. #include <iostream> #include <cstring> #include <vector> using namespace std; class Player { public: Player(int id, string name) : p_id(id) , p_name(name) ...
I assume, you may want to look toward this: class Player { public: Player() = default; Player(int id, string name): p_id(id), p_name(name) {} private: int p_id; string p_name; }; int main() { vector<Player> players; // construct a Player from an int and a string players.emplace_back(33, "F...
68,267,417
68,277,527
constexpr variable in source file global scope
What is the proper way to declare a constexpr constant in a source file? I'm split between two ways: constexpr int ORDER = 1; vs namespace { constexpr int ORDER = 1; } // unnamed namespace The reason I question the usefulness of wrapping into an unnamed namespace is because at global scope, constexpr implies static. ...
It's not required to enclose constexpr variables, declared in a source file, in an unnamed namespace. Since the end goal is to achieve internal linkage you have to remember this: The name of an entity that belongs to a namespace scope has internal linkage if it is the name of a variable, variable template, function, ...
68,267,592
68,267,737
Split uint16_t variable into 2 uint8_t variables
I am trying to split a 16 bit variable into two 8 bit bytes, but the code I have written doesn't seem to work correctly: #include <iostream> using namespace std; int main() { uint16_t value = 0x1234; uint8_t high = (uint8_t)((value & 0xFF00) >> 8); uint8_t low = (uint8_t)(value & 0x00FF); cout<<"higher...
When the variables high and low are declared as uint8_t, the result is incorrect. The "result" of the split isn't incorrect. The output may be other than what you expect because std::uint8_t is an alias of a character type (unsigned char) and character types are treated differently from other integral types by charac...
68,267,677
68,269,262
I want to create a 2D vector with each index being a vector of int
I want my data structure to look something like this when populated: [[1, 2, 3] [3, 3, 3] [4, 4, 4]] [[5, 4, 5] [3, 4, 5] [3, 3, 3]] I'm not sure where to go from here. I've tried doing: vector<vector<vector<int> > > x; But I'm having trouble populating it. I think it's basically a matrix of vectors? I'm just not sur...
It seems like you want this: std::vector<std::vector<std::vector<int>>> x(30, std::vector<std::vector<int>>(3, std::vector<int>(3))); The constructor I am using takes (std::size_t n, T t) as in n elements of type T. If you want to replace a vector in a given cell, you can use: x[2][4] = {2, 7, 9}; Or you can replace ...
68,267,902
68,267,960
How do i add the signal tabMoved?
I Want to create a map where every tab created is stored in there with his index as a key, the problem is that if I move the position of a tab his index change, so I need to update it only when the tab is moved, I saw in the documentation the signal tabMoved but I can't find how to implement it, usually, in the qt crea...
you have to "subscribe" your app to the signal: void QTabWidget::currentChanged(int index) This signal is emitted whenever the current page index changes. The parameter is the new current page index position, or -1 if there isn't a new one (for example, if there are no widgets in the QTabWidget) then you can have a...
68,268,434
68,269,144
RE: Arduino with neo 6m GPS and push button
I am an aeronautical student, new to the coding environment. I'm currently working on a GPS neo 6m module with Arduino mega 2560, where I wanted to save the current location upon pressing the push button. Which function is to be used to save the location by pressing the push button. Here is what I have done so far. Any...
It is simple just store the values in 2 variables. #include <SoftwareSerial.h> // The TinyGPS++ object TinyGPSPlus gps; static const int RXPin = 4, TXPin = 3; //gps module connections static const uint32_t GPSBaud = 9600; // The serial connection to the GPS device SoftwareSerial ss(RXPin, TX...
68,268,969
68,268,996
How to return from function lvalue or rvalue based on parameters?
Consider example: #include <string> #include <iostream> auto get_r_value() { return std::string("hello"); } int VAL = 15; int& get_l_value() { return VAL;} template<typename ...Types> auto&& func(Types... vars) { if constexpr (sizeof ... (vars) <= 2) { return get_l_value(); } else { return ge...
You might use decltype(auto): template<typename ...Types> decltype(auto) func(Types... vars) { if constexpr (sizeof ... (vars) <= 2) { return get_l_value(); } else { return get_r_value(); } } Demo
68,268,992
68,269,176
Segmentation Fault Linked List Merge Sort
I am trying to sort linked list using merge sort but every time i get a segmentation fault i have been trying very hard from 2 days and ran debugger many times please some one help . I followed approach of dividing the linked list into 2 parts and recursively calling merge sort . void merge_sort(Node**head){ if((*...
You should also consider the condition in which your head pointer itself is pointing to the null(In case the length is 0)(not just "head -> next " pointer). And then your first if would be like this: void merge_sort(Node**head){ if((*head)->next == NULL || (*head) == NULL ){ return ; } Node *a , *b ; FrontBackSplit...
68,269,360
68,269,445
why outside the funtion the pointer data is not getting updated
I am new to c++ I am trying to update the similar variable using one function I have a variable IComponent* m_component1; IComponent* m_component2; IComponent* m_component3; then I have set function IComponent is and interface void SetComponent1(IComponent* comp) { SetComponent(comp, m_component1); } void SetComponen...
It's because you're passing in oldComp as pointer by value. So setting this pointer to anything will only change the pointer locally in the function. Pass the pointer by reference if you want to affect the original pointer passed in.
68,269,361
68,269,511
CMake set custom configuration name for target
I have project called test_containers. It contains only cpp files with tests and CMakeLists.txt: cmake_minimum_required(VERSION 3.0.0) project(test_containers) set(source_files test_array.cpp test_linear_hash_table.cpp test_list.cpp test_set.cpp test_span.cpp test_stack.cpp test_string.cpp ...
Does this float your boat? foreach(source IN LISTS source_files) get_filename_component(name ${source} NAME_WE) add_executable(${name}) target_sources(${name} PRIVATE ${source}) target_link_libraries(${name} PRIVATE gtest_main wise_engine_cert) add_test( NAME ${name} COMMAND ${name} ) endforeach...
68,269,574
68,270,170
C++: recursively match argument type with class template type
I am hoping to achieve such type matching function: MyClass<int, bool> temp; temp.print(-1, false); // works temp.print(-1); // compile error, too less argument temp.print(-1, "string"); // compile error, wrong type temp.print(-1, false, 'c'); // compile error,...
#include <iostream> template<class... ClassType> class MyClass { public: template<typename... ArgType> void print(ArgType... args) = delete; void print(ClassType ... args) { std::cout << "works\n"; } }; int main() { MyClass<int, bool> temp; temp.print(-1, false); // ok ...
68,269,663
68,276,100
Why is there no variable template template parameter?
I'm planning to create a variable template that takes (variable) template-template parameter and one typename: template <template <typename> auto MetaPredicate, typename T> constexpr bool has_predicate_v_ = requires { { MetaPredicate<T> } -> std::convertible_to<bool>; } Where the expectations are: template <typename...
You already linked to the proposal, so you’ve largely answered the question yourself. You might not know about the paper tracker that can answer the “status” question; it says that more motivating examples are sought (which might very well have been delayed by the pandemic), so maybe you should contribute yours! As fo...
68,270,244
68,271,012
CustomButton displayed out of Boundary While Using wxScrollWindow
I am doing some scrolling using wxScrolledWindow class. The scrolling is working fine. I am also using wxNotebook to switch between tabs. I have 2 tabs for this example. The first tab contains a header and then a ScrolledWidgetsPane class which is derived from wxScrolledWindow. The 2nd tab contains a blank page. Now wh...
How can I resolve this issue and what is the cause of this? Note that this only happens when I use the onPaint method of CustomButton. In the paint handler, you need to use a wxPaintDC instead of wxClientDC: void CustomButton::onPaint(wxPaintEvent &event) { wxPaintDC dc(this); ... } Additional Question: Is ...
68,270,378
68,270,466
curl PATCH to update value works as a curl command but not in libcurl c++, any ideas what is wrong?
I am trying to replicate the following curl command in c++ code using the curl library but with no luck. The curl command is (the url is an actual url I am just hiding it): curl -iX PATCH '*URL*/attrs/topicData' \ -H 'Content-Type: application/json' \ -H 'Link: <http://context-provider:3000/data-models/ngsi-context.jso...
CURLOPT_POSTFIELDS expects a char* but you are supplying a std::string. This should be working better: curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_entity.data());
68,270,671
68,270,789
How to make smallest value is not equal to 0?
I want to get the highest and smallest value from the data. For the highest I managed to get it. but for the smallest, the value is always 0. I have tried many ways but didn't work #include <iostream> #include <fstream> #include <string> using namespace std; int main() { string input; ifstream nameFile("data.txt"); i...
There is no value of 0 in the data.txt, however I got 0 for my smallest value answer. This is because you initiailse smallest_X to zero, and then assign a read value only if it is smaller. Thus, if the content has no value smaller than 0, then smallest_X will remain as 0. One approach is to assign them unconditionall...
68,271,059
68,273,097
quick sort c++ code error segmentation fault 11?
Code: #include <iostream> #include <stdlib.h> #include <time.h> using namespace std; void partition(int *A, int start, int end){ //end is the position of the last number cout<<"start is "<<start<<" end is "<<end<<endl; if(end - start+1 > 1){ int i = start + 1, j = start + 1, pivot = A[start]; w...
So this is what's happening here. Imagine that in a certain partition the first element (the pivot) is also the largest. This means that in every iteration of the while loop the value of A[j]<=pivot will be true and i will be increased. Since both i and j are increased by 1 in every iteration there value is the same, s...
68,271,140
68,283,454
Boost.Log, using custom attributes in filename or target value of configuration file
I use Boost.Log in C++ to log, and use configuration files. I added some custom attributes and use them in the configuration file. Here is the registration of the attributes in C++: namespace logging = boost::log; namespace attrs = boost::log::attributes; namespace src = boost::log::sources; namespace sinks = boost::lo...
You can use the multi-file sink backend for logging into separate files. That backend supports generating the filename from the attributes attached to the log record. However, it is not supported for initialization from a config file by default. You will have to register a factory for this sink backend and implement co...
68,271,203
68,276,903
installation & compilation boost on Manjaro
I installed boost using pacman -S boost boost-libs. When I try to compile a program that uses boost::thread, and I got the following error: /usr/bin/ld: /tmp/cc3AkelG.o: warning: relocation against `_ZTVN5boost6detail16thread_data_baseE' in read-only section `.text._ZN5boost6detail16thread_data_baseC2Ev[_ZN5boost6detai...
I find the answer in an other question. I had to compile using -pthread -lboost_thread. thanks for your answer.
68,271,229
68,271,282
How to use std::bitset count() with constexpr in C++?
I want to use std::bitset<64>(n).count() in constexpr functions but bitset::count is not constexpr. I thought I could do something like the following: #include <bitset> inline constexpr size_t bit_count(uint64_t v) noexcept { if constexpr(true) { size_t n = 0; while (v) { v &= v - 1; // clear right-mos...
You can do this using std::is_constant_evaluated(). That would give you inline constexpr size_t bit_count(uint64_t v) noexcept { if (std::is_constant_evaluated()) { size_t n = 0; while (v) { v &= v - 1; // clear right-most 1-bit ++n; } return n; } return std::bitset<64>(v).count(); }...
68,271,478
68,272,013
Why is the compiler dedicating a memory location for storing a redundant variable in this case?
I wrote this simple C++ code, to see how atomic variables are implemented. #include <atomic> using namespace std; atomic<float> f(0); int main() { f += 1.0; } It is generating this assembly for main in -O3: main: mov eax, DWORD PTR f[rip] movss xmm1, DWORD PTR .LC1[rip] movd xmm...
Is there any specific reason to store that variable in stack rather than in registers? At the end of the day, atomics exist for inter-thread communication, and you can't share a register across threads. You might think that gcc could detect local variable atomics that are never shared with anything else and demote th...
68,272,403
68,272,570
Is sharing data with initializer list out-scoped valid in standard?
lst2 = lst Copying or assigning an initializer_list does not copy the elements in the list. After the copy, the original and the copy share the elements. According to C++ Primer Table 6.1, assign one initializer list will share the data, but what if the initializer list share with an other out-scoped, for example, th...
This code does not seem valid. Here is some relevant extract from cppreference The underlying array is a temporary array of type const T[N], in which each element is copy-initialized (except that narrowing conversions are invalid) from the corresponding element of the original initializer list. The lifetime of the und...
68,272,408
68,282,701
Use argument shortest in C++ code in FFMPEG
I need to set up the argument "-shortest" but in c++ code. I know that I can set up an argument with value for example: av_opt_set(codecContext, "crf", "28", 0); But here is the thing, there is a value, but in shortest no value. So how can I set up shortest in c++ code Thanks in advance
I got an answer here: https://www.reddit.com/r/ffmpeg/comments/oeuwlw/how_to_set_up_shortest_flag_programmatically_c/ So, -shortest is a part of ffmpeg binary. Not available when working with the libav* libs. You can set "fflags", "shortest" and "max_interleave_delta", "100M" on the AVFormatContext.
68,272,544
68,314,805
Cmake: target_compile_definitions with find_package
I have a package, libtorch, that depends on libraries that use the keyword slots for some function (e.g. in Aten). In the meantime, the project that I am using is based on Qt, which use slots as a special keyword (macro), which then interferes with torchlib. The solution to avoid such interference is to add the QT_NO_K...
Possible Solutions Option 1: Use QT_NO_KEYWORDS and replace slots and other keywords with their equivalent uppercase macros, e.g. Q_SLOTS. Option 2: Don't use QT_NO_KEYWORDS and wrap the parts of your C++ code with conflicting keywords like this: #undef slots #include <torch/torch.h> #define slots Q_SLOTS Explanations...
68,273,856
68,274,049
Search in a Doubly-Linked List founds members multiple times
I'm working through the exercises from PPPC++ and I have a List class that holds multiple gods with their attributes. Ex: {Thor, Norse, Chariot, Mjolnir} or {Hera, Greek, chariot, pomegranate} where Thor is Norse god and Hera is a Greek god. I'm trying to write the code to find the pointers that point to all the gods t...
Your code looks good (though not very OO). It also seems to be working the way I would expect: // When you start the list is: // Poseidon : Athena : Tyr : Hera ...... while (all_gods) { // So first time threw this loop you find: Poseidon Link *p = all_gods->find_mythology("Greek"); cout << "found " << p ...
68,274,309
68,275,635
why copy constructor and overloaded=operator of derived class not calling respective base class's copy constructor and overload=operator
.h #ifndef header #define header struct base { private: int p,q; public: base(); base(const base&); base operator=(const base&); ~base(); }; struct der: public base { private: int x,y; public: der(); der(con...
Let us Analyze the 3 statements in the main program one by one. We will discuss the second statement in the main program last, as that is the one that will require the maximum explanation Statement-1: der d1, d2 This works as expected and first, the base class is constructed and then the derived class is constructed fo...
68,274,402
68,274,459
What exactly is an iterator in C++?
I'm trying to grasp the concept of the iterator. I've run some tests via the following code: #include <iostream> #include<map> using namespace std; int main(){ map<string,string> mp;//create the map mp["key"]="value";//create a key/val pair map<string,string>::iterator it=mp.begin();//create an iterator n...
What exactly is an iterator in C++? Iterator is a concept. The concept describes a type with particular properties and operations with particular behaviours. A type that conforms to the "iterator" concept is said to be an iterator, and similarly objects of such type are also iterators. More specifically, iterator is ...
68,274,863
68,274,925
Async/future argument corruption c++
So I am working on async c++ code, and wish to find a pattern which will work well for me todo with partitioning a set of tasks, having each thread perform some fraction of the task. The general idea of the code below is to create some dummy tasks, as a vector. Call distributeTasksVec which creates a vector of vector o...
The vector thisTask is local to the loop for (int i = 0; i < threadPool; i++). You capture that vector by reference by the lambda expression that you use to for the thread. That vector is destroyed at the end of every iteration of the loop, leaving your thread with a reference to an invalid object. Using said object...
68,274,999
68,275,091
Is it allowed to self-move an object in C++?
Is it permitted for an object (in particular of an std class) to be self-moved or it is an undefined-behavior? Consider an example: #include <iostream> #include <string> int main() { std::string s("123"); s = std::move(s); std::cout << s; } In gcc/clang the program prints nothing, so s string is lost duri...
From cpp ref: Also, the standard library functions called with xvalue arguments may assume the argument is the only reference to the object; if it was constructed from an lvalue with std::move, no aliasing checks are made. However, self-move-assignment of standard library types is guaranteed to place the object in a v...
68,275,106
68,287,541
How to make cppcheck 2.5 show error on calls to a virtual function in constructor. Older version shows this error
In the list of cppcheck rules there is <error id="virtualCallInConstructor" severity="style" msg="Virtual function 'f' is called from constructor '' at line Dynamic binding is not used." verbose="Virtual function 'f' is called from constructor '' at line 1. Dynamic binding is not used."/> I've written a call to a v...
I found this comment https://sourceforge.net/p/cppcheck/discussion/general/thread/b18f7aaf/#d726 It will be fixed in the next release. For now I have disabled the check. But it can be enabled again if we write such warnings properly. The checker must ensure that the class is a base class! The post relates to 1.84 Loo...
68,276,207
68,277,052
Visual Studio 2019 is unable to start program
I'm trying to learn C++ so I started following microsoft's calculator tutorial here's my code so far #include "stdafx.h" #include <iostream> using namespace std; int main() { cout << "Calculator Console App" << endl << endl; cout << "Enter an Operation from the following operations, a+b, a-b, a*b, a/b" << end...
stdafx.h is a Precompiled header which is unnecesary unless you are facing a slow compilation time. Therefore, you can delete the following line: #include "stdafx.h" and continue your program. Good luck in your jorney with C++!
68,276,327
68,276,378
error: ‘foo’ is not captured Lambda function and boost integration
Im triyng to perform a numerical integral using Boost Library quadrature. I did it using trapezoidal like this double integrand(double xp, double yp, double x, double y, double a, double b) { double eps; if(x - xp == 0 && y - yp == 0) eps = 1e-6; else eps = 0.0; return std::log(std::hyp...
The problem is exactly what it says. Your lambda isn't capturing integrator. Change [x,y,a,b] to [x,y,a,b,integrator] to capture by value or [x,y,a,b,&integrator] to capture by reference. Alternatively you can capture everything by value with [=] or everything by reference with [&]. See lambda expressions for syntax.
68,276,963
68,277,081
I don't know how to use filesystem to look for .txt files c++
I would like to use std::filesystem in my project, which will allow me to show .txt files in the current directory (I use Ubuntu, I don't need a Windows function because I have already seen one on StackOverflow). Here is my GitHub repo: https://github.com/jaroslawroszyk/-how-many-pages-per-day I have a fix for this pro...
If you look into the reference (https://en.cppreference.com/w/cpp/filesystem/path) you will find the extension() method on paths (https://en.cppreference.com/w/cpp/filesystem/path/extension) which returns you the file's extension. Now you simply need to use the string() function on the path's extension and compare the ...
68,276,991
68,279,361
std::weak_ptr::lock and object destruction
I know that in a multi-threading environment it's not safe to check whether an object has been fully deleted by std::shared_ptr<T>::use_count() == 0, because the object's destructor may still be not completed. But what about using std::weak_ptr::lock() instead? if (weak_ptr.lock() == nullptr) { // The object's dest...
The following should all be equivalent: weak_ptr.use_count() == 0 weak_ptr.lock() == nullptr weak_ptr.expired() They share the interpretation that the last managing shared_ptr has begun its destruction. They do not imply that the managed object has yet begun its destruction, nor that it has completed its destruction.
68,277,041
68,277,274
std::out_of_range error and trying to get string between two delimeter
As I mentioned in the title, I want to get the string value between 2 delimiters. Inside the array, the first string may not include the start delimiter I'm looking for, but the second string may as well. As in the example. The ending delimiter can be in the last string of the array. I want to get the 1st string and th...
To keep it simple concatenate the strings before calling find: #include <iostream> #include <string> #include <numeric> std::string sub_between(const std::string& start,const std::string& stop,const std::string& input){ // try to find start auto start_index = input.find(start); // was it found? if (sta...