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,609,066
68,610,945
Save a file formatting the text Qt
I'm currently making a notepad and I've found a problem. I want to save a file formatting the text so with different fonts, point sizes and colors in a .rtf file, but it just saves without formatting it so without any color or different fonts. Here is the code I put to save a file: void MainWindow::on_saveas_clicked() ...
I guess that Qt does not support RTF format, which is a proprietary format by MS, see https://en.wikipedia.org/wiki/Rich_Text_Format. So it does no make sense to save it with RTF extension. Nevermind. Qt however does support formatting via HTML tags (at least some subset of HTML, see https://doc.qt.io/qt-5/richtext-htm...
68,609,139
68,610,606
Can `constexpr` function be forward declared in C++?
Can I declare a constexpr function in C++ before giving its definition? Consider an example: constexpr int foo(int); constexpr int bar() { return foo(42); } constexpr int foo(int) { return 1; } static_assert(bar() == 1); It is actually supported by all compilers, demo: https://gcc.godbolt.org/z/o4PThejso But if one c...
This is core issue 2166. Section: 7.7 [expr.const] Status: drafting Submitter: Howard Hinnant Date: 2015-08-05 According to 7.7 [expr.const] bullet 2.3, an expression is a constant expression unless (among other reasons) it would evaluate an invocation of an undefined constexpr function or an undefined c...
68,610,033
68,613,481
Why can a `constexpr` function produce different results at compile- and run-time?
A colleague of mine showed me this shocking C++20 program: #include <iostream> constexpr int p(auto) { return 0; } constexpr int q() { return p(0); } constexpr int p(auto) requires true { return 1; } static_assert(p(0) == 1); static_assert(q() == 0); int main() { std::cout << q() << p(0) << '\n'; } GCC cannot b...
While this program is contrived, it is valid and does what you think (prints “01”), so all compilers are wrong. GCC is failing to mangle the requires true into the name of the second p, MSVC/Debug is failing to select that more-constrained overload, and the other two cases are failing to use the lookup result from q (...
68,610,792
68,612,166
Why does static_cast in the std::move() wipe value of argument?
My question contains two parts: Does function static_cast<Т>(arg) alter the innards of arg? Obviously not, according to such code: float i1 = 11.5; int x = static_cast<int>(i1); std::cout << i1<<std::endl; //11.5 std::cout << x<<std::endl; //11 Why does such code: std::string s1 = "123"; std::string s2 = std::m...
While reading your question, I had a sense of feeling that you already understood what's happening and yet wanted it to be confirmed. I guess, it is because of using move constructor of string after s2 =. It must wipe the initial string by equating to nullptr or 0 all data in string object. While std::move() by itself...
68,610,932
68,610,997
Not identifying a method called from header to main C++?
I defined a class in a header file and declared the functions in it and made the function body in a seperate cpp file. Then it was not identified in main. I have reviewed a lot of questions and some used the word static in the declaration but when I tried it the function was re declared so it did nothing and I made sur...
The error results from not creating an object of the Class User in your main file. You could either declare a global User variable: User g_User{}; Or a local variable in your main method depends on your use case. Another solution would be to make Register and Login static in the Class User. If you choose the object me...
68,611,030
68,611,345
C++ negative byte value
I have c++ code that read 16 byte from a file as char value And I have a table of unsigned char from 0 to 255 I want to use byte values from file as a index in my unsigned char table to change the original file byte values but I get negative value from file and as you know you can't use negative value as a index in arr...
Don't use operator new unless absolutely necessary. Rather than char *Transform_Buffer = new char[BufferSize]; you can define the buffer as a local array: const unsigned int BufferSize = 16; unsigned char Transform_Buffer[BufferSize]; For this to work, you should declare BufferSize as const. Notice also t...
68,611,650
68,642,378
How do I convert a parameter of type "std::function" to a slightly different std::function?
I have a function, one of the parameters of which is of type std::function<std::string(ConvertableToInt)>, where "ConvertableToInt" is a type that can be converted to int and can be constructed from int. From this function, I need to call another (library) function one of the parameters of which is of type std::functio...
Just to flesh out what Igor is saying in comments, if what you mean is that the class is constructible from an int then you can use a lambda as an adaptor as below: #include <iostream> #include <functional> #include <string> class constructible_from_int { int v_; public: constructible_from_int(int v) : v_(v) {...
68,612,008
68,612,174
C++ map <std::string,static method pointer>?
So, to start, I'm hesitant to ask this because there is (basically) the same question regarding this on SO, but the answers didn't fix my problem. Question I've checked: C++ map<char, static method pointer>? (Marked as duplicate of How to create class objects dynamically? but I'm not dynamically creating objects) I'm w...
getParser_A returns a lambda, like a pointer to a function. So a pointer to getPArser_A is a pointer to a function that returns a function. You can store that in a map. I am assuming below the functions returns an int. #include <map> #include <vector> #include <functional> #include <string> struct SemanticValues {}; s...
68,612,210
68,612,500
C++ writing to myArray[0] and setting myInt = myFloat, why is this working?
I'm playing with a function to get used to some C++ syntax. Now I think, I might have misunderstood: I'm writing to a static (?) array I had defined as myArray[0] for experimenting. So it seems NOT to be static, but sizeof(myArray) always returns 0 (?) but I can find mem address for each item (while I have no idea, how...
I'm writing to a static (?) array I had defined as myArray[0] for experimenting. By 'static' you probably mean 'fixed-sized'. static means something totally different, see https://www.geeksforgeeks.org/static-keyword-cpp/. So it seems NOT to be static It is not static, hence, it's not surprising that it's not stati...
68,612,284
68,612,402
I want to add multiple values at the end of the array? I am not getting right answer with below code?
Why I am getting wrong output? Suppose, If I am initializing 10 as array initial size and then 15 more elements to append at the end of an array. Then array total size will be 25. But in below code when I input multiple values to append at the end of array then after some input values either program stop or give wrong ...
cin>>n; int arr[n]; The size of an array variable must be compile time constant. User input is not compile time constant. This program is ill-formed. Don't do this. elem = lastindex + elem; cout<<"elem now: "<<elem<<endl; for(int i=lastindex; i<elem; i++) { cout<<"enter index "<<lastindex<<" value numb...
68,612,525
68,612,575
Can I mix new and malloc on different redirection?
Is this behaviour undefined where I am mixing both new and malloc? int main() { int ***arr = new int**[1]; arr[0] = static_cast<int**>(malloc(sizeof(int**))); arr[0][0] = new int; arr[0][0][0] = 1; //now, release memory using appropriate operator }
Yes, you can do that. You must call delete[], delete and free accordingly later on. Be careful to not free something you got from malloc with delete etc.
68,612,925
68,612,958
Change the field of a derived class object but the change was recovered after returning
I override the create function. void IBlock::create() { Cell a; a.setCoords(0, 3); a.setblank(false); Cell b; b.setCoords(1, 3); b.setblank(false); Cell c; c.setCoords(2, 3); c.setblank(false); Cell d; d.setCoords(3, 3); d.setblank(false); vector<Cell> row2; row2....
for (auto co : ro) makes a copy of each iterated object rendering calls like co.setX() useless. It is like passing parameters by value. If you need your loop (function) to mutate the iterable's elements (arguments), bind them to a reference loop variable (parameter). Use for (auto& co : ro), see this answer for more d...
68,613,069
68,613,250
std::conditional_t for class type vs non-class type
How to fix this: template<class T> struct ResultType { using type = std::conditional_t<std::is_class_v<T>, typename T::result_type, void>; }; It cannot be it is supposed to return void, if T is not class type, but instead: error: ‘int’ is not a class, struct, or union type 24 | using type = std::conditional_ts...
std::conditional_t is to select between two types, but when T = int then T::result_type is not a type. You can use sfinae: #include <type_traits> template <typename T, typename = void> struct result_type_or_void { using type = void; }; template <typename T> struct result_type_or_void<T,std::void_t<typename T::resu...
68,613,462
68,614,100
What happens inside std::cin in C++?
I'm reading about std::cin and I see that my program stops at a line with it and kind of "waits" for me to enter input and press Enter. What is happening under the hood? How does std:cin suspend the entire program?
Roughly speaking, a call to read from std::cin will result in a system call to read from 'Standard Input'. On Linux, that's File Descriptor 0. When your process makes a system call, you are in the kernel, which can leave your process snoozing until it has some data to hand you (which it writes into your buffer and res...
68,613,501
68,613,589
Why class with destructor is not trivially move constructible?
Why is this class: class test_type { public: ~test_type() { std::cout << "~()\n"; } }; // fails static_assert(std::is_trivially_move_constructible_v<test_type>, ""); not trivially move constructible?
Why class with destructor is not trivially move constructible? Because the standard says so: [class.prop] A trivially copyable class is a class: that has at least one eligible copy constructor, move constructor, copy assignment operator, or move assignment operator ([special], [class.copy.ctor], [class.copy.assign]...
68,613,605
68,613,685
Use std::array in function using 'overloaded' lambdas
I wish to do the following in C++20: template <class... Ts> struct overloaded : Ts... { using Ts::operator( )...; }; // Updated to work with C++17 #if (_cplusplus != 202002L) // check for C++17 or C++20 // Deduction guide, google `CTAD for aggregates` for more info template <typename... Ts> overloaded(Ts...) ->...
You can use the lambdas template parameter list introduced in C++20. The lambdas argument is not a std::array<T,C> but it is T, and T is some std::array<S,C>: #include <iostream> #include <array> template <class... Ts> struct overloaded : Ts... { using Ts::operator( )...; }; template <typename T> void emit(T con...
68,613,742
68,613,875
replace() not changing characters in a string to the intended characters they are supposed to be replaced with
I am creating a program in C++ that encrypts text using the Caesar Cipher it allows the user to pick the offset that is used to encrypt at the moment i have on written it for offset 1 but when i use replace()function as part of the STL, rather than replacing them with the specified characters they should be replaced to...
The Golden Rule Of Computer Programming states: "Your computer always does exactly what you tell it to do, instead of what you want it to do". Now let's explore what you told your computer to do. replace(Message.begin(), Message.end(), 'a', 'b'); You told your computer to replace every occurrence of the letter 'a' wit...
68,613,789
68,613,873
This code throws an error at line 6. Is it because cout stream doesn't allow it or it's some conflict in ostream?
#include<iostream> using namespace std; int main() { int a=4,b; cout<<b=a*a; return 0; } it shows "error: no match for 'operator=' (operand types are 'std::basic_ostream<char>' and 'char')" If it has to do something with cout, can someone tell me how does cin and cout works exactly?
See here for operator precedence: https://en.cppreference.com/w/cpp/language/operator_precedence. << has rank 7. = has rank 16. And * has rank 5. Hence the line is parsed as (std::cout << b ) = (a * a); You cannot assign an int to std::cout. Write this instead: int a = 4; int b = a*a; std::cout << b;
68,613,828
68,614,072
How to create a vector of objects which inherit from the same base classes and have unique functions?
I want to create vector of objects which inherit from the same base class but have their own functions, which are not in the base class (creating virtual function is not possible, because the classes which inherit take in different variables as parameters of a function). Base class: Model First class which inherits fro...
I'm afraid what you want to achieve is not possible in a simple way. That is because the C++ mechanisms you are trying to use were not designed to be used in such a way. Inheritance - you would use it if: you want to reuse the interface, which seems not to be the case here, because you want different function names; o...
68,614,285
68,616,432
comparison operator for std::array
The comparison operator== for std::array, as provided by the standard library, works only for arrays of equal size. E.g., the following code does not compile #include <array> int main() { std::array<int, 2> a{1, 3}; std::array<int, 3> b{1, 2, 3}; bool x = (a == b); } It seems logical to define a comparison b...
Is there a fundamental reason why the standard library does not define operator== as in the code above? Most fundamental reason that standard library doesn't define it is: Such operator== wasn't proposed. This is the proposal to add the wrapper into the standard. It does not contain rationale for not providing compar...
68,614,475
68,795,285
Converting contents of a character array into ASCII key values
I am writing a Caesar Cipher program i take the users input as a string and then convert that string into a character array i am stuck on converting all of the characters in that array into there ASCII key values because the amount of characters in the array can change every time the program runs depending on what mess...
I managed to solve this problem by taking the length of the string and storing it into a variable declared as an integer to store the string length i used Message.Length()to get the length of the string I then created a for loop to iterate over the length of string i then declared int ASCII_Converter = int(Message[i]) ...
68,614,544
68,614,761
Need for clarification with pointer behaviour
Suppose I have an array int a[] = {2, 3, 4}; Why can a pointer to the first element &a[0] point to array elements, or values in general, but the pointer &a cannot? cout << (&a[0])[1]; // 3 cout << (&a)[0]; // some weird adress (presumably of the array itself cout << (&a)[1]; // a higher adress probably the adress afte...
Arrays and pointers are two different types in C++ that have enough similarities between them to create confusion if they are not understood properly. The fact that pointers are one of the most difficult concepts for beginners to grasp doesn't help either. So I fell a quick crash course is needed. Crash course Arrays, ...
68,614,621
68,614,856
Is it possible to cast the contents of a C++17 stl collection?
I have a one-to-many relationship between two classes, where the owned classes can be of more than one type. The data model requires that a relationship in the superclass can be 'subsetted' in a subclass. Each end of the relationship looks like this: weak_ptr<Element> owner; unordered_set<shared_ptr<Element>> ownedElem...
Something along these lines: std::unordered_set<std::shared_ptr<SubElement>> subElements; std::transform( ownedElements.begin(), ownedElements.end(), std::inserter(subElements, subElements.end()), [](std::shared_ptr<Element> elem) { return std::static_pointer_cast<SubElement>(elem); }); This assu...
68,614,706
68,614,818
move operation with pimpl idiom
In the following code I am attempting to use a move assignment within the PIMPL idiom, but the code does not compile. struct.hpp: #pragma once #include <memory> struct A { std::unique_ptr<struct B> m_x; A(int x); ~A(); }; struct.cpp: #include "struct.hpp" struct B { int x; }; A::A(int x) : m_x{new B} { m_x...
While std::unique_ptr does have a move assignment operator and it certainly seems natural to want to make use of that fact to make A move-assignable, the user-declared constructor runs into problems. cppreference on the move assignment operator: Implicitly-declared move assignment operator If no user-defined move assi...
68,615,054
68,615,080
Calling a template function from a template function in a class
I am trying to use a template function from a template function in a class. I have the following code in class Sort.h: class Sort { public: Sort(); virtual ~Sort(); template <typename T> static std::vector<T> merge (std::vector<T> array, int p, int q, int r); template <typename T> static std::ve...
You have accidentally declared a separate function called merge that is not part of the Sort class. Instead of template <typename T> std::vector<T> merge ( ... you need: template <typename T> std::vector<T> Sort::merge ( ...
68,615,149
68,615,479
Code for decrypting simple sentences made with CodeBlocks crashes without outputting a single character
I am making a program that inputs the alphabetical order for encrypting a sentence to decrypt it (just replacing characters). I am required to input the number of words it has, but the method I'm using doesn't need that so I just input it and do nothing with it (it doesn't matter because an AI will be verifying only th...
Your program has the following bugs: First bug: As already pointed out in the comments section, you should change the line for (j=0;j<encrypted.size();j++) to for (j=0;j<key.size();j++) Second bug: Due to integer promotion, the expression alphabet[j]+32; will evaluate to a value of type int, not char. This means that c...
68,615,212
68,624,196
Six different usages of std::enable_if<> in conditionally compiled templates
I'm trying to understand two different versions of a template function that uses std::enable_if<>. Version 1: template<class T, typename std::enable_if<std::is_convertible<T, std::string_view>::value, T>::type* = nullptr> void foo(const T& msg); Version 2: template<class T, typename = typename std::enable_if<std::is_c...
How should one constrain a template? If you are not limited to compatibility with older C++ standards, and you don't need to refer to the template type, and the constraints only involve a single template parameter, prefer the least boilerplate option: // #1 void foo(const std::convertible_to<std::string_view> auto& msg...
68,615,240
68,695,195
Filling zero-value elements of an OpenCV Mat
I have Mat objects like this one below: In matrices like this, some columns are intercalated by a predefined (fixed) number of columns in which values are all zero. I'm looking for a filter to fill up those zero-columns with some column-wise linear interpolation. For example, the previous Mat will end up like: Note t...
If your zeros are columns in a specific pattern, you can sample the non-zeros values and then resize (as described in the comments): cv2.resize(mat[:, 0::3], mat.shape)
68,615,426
68,617,827
Compile a header to executable in CMake
Suppose I have a dual purpose header that can be used as either a header or a source file controlled by a preprocessor switch AS_CPP. It is possible to use the command g++ -x c++ -DAS_CPP foo.h -o foo to compile it into a executable. Is it possible to achieve this in CMake in a cross-platform way (without explicitly wr...
Just copy the file to a proper suffix. add_custom_command( COMMENT "Copying foo.h to foo.cpp" OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/foo.cpp DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/foo.h COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_CURRENT_SOURCE_DIR}/foo.h ${CMAKE_CURRENT_BINARY_DIR}/f...
68,615,486
68,615,512
How to access user-chosen struct variable C++
I am using a function to print out data from a linked list, the list Nodes have 2 variables which could be accessed, data or index. I want to add a parameter to the print() function that allows the user to call the variables name within the Node that they want to be outputted, I've heard of passing by reference and I'm...
p.s: variable name is not necessarily a pointer But it is a pointer. A member pointer, specifically: void print(int Node::*member) { Node *n = _head; while (n->next != nullptr) { std::cout << n->*member << std::endl; n = n->next; } } It would get invoked as either print(&Node::data); or print...
68,616,247
68,913,662
Never notify HDN_TRACK message of CListCtrl's CHeaderCtrl
I want to catch HDN_TRACK message from listCtrl's header, but it's never notified. I tested HDN_BEGINTRACK and HDN_ENDTRACK, and these are working well. I also changed the Control Id of message map to IDC_TEST_LIST and 0, there was no difference - it is still not working. I searched many forums, but I couldn't find any...
This is an odd behavior with header control, it's described in HDN_TRACK and HDS_FULLDRAG also posted by @Constantine You have to remove HDS_FULLDRAG style from header control in OnInitDialog: m_list.GetHeaderCtrl()->ModifyStyle(HDS_FULLDRAG, 0); Then you should receive HDN_TRACK message void CDlgTest::OnTrack(NMHDR* ...
68,616,801
68,616,912
Using Boost with C++?
I'm on Mac OS. I'm using Visual Studio Code. I'm coding in C++. I recently installed the most recent version of Boost (1.76.0). My file name: test.cpp I've included this header in my file: #include <boost/smart_ptr/scoped_ptr.hpp> I'm compiling with this command: g++ -std=c++11 test.cpp My code won't compile. I keep...
It's simple, whenever you use g++, you need to define your include folders with -I switch, in this case you can say: g++ -Iboost -std=c++11 test.cpp here boost is the name of the folder that your .h/.hpp files are inside it. Update Here is also a link that completely explain about how to use boost library: Link
68,616,808
68,617,193
Sort a map on the basis of first value of pair
suppose i do have to describe my map as map<int,pair<long,int>> mp; now I insert elements as int y; long x; pair<long,int> p; for(int i=0;i<5;i++) { cin>>x>>y; p.first=x; p.second=y; mp.insert({i,p}); // *** what is wrong here syntax wise???*** } Further, i want to sort it on the basis of first val...
You can use a little trick here. Map in c++ automatically sorts everything by key, so you can do following => map <long, (set,vector) < int > > mp; //Create this kind of map //it will sort elements by first value and depending on your needs, select vector or set //if you need to sort elements by second value use set //...
68,617,067
68,640,108
Need help in code to read a particular string value from a file in C++ and print that value
I am newbie in C++ programming, I need to write a code to read a particular value from a file. for example if enter input as servername then it has to show ABCDE-1. I am trying with string function I am not able to get the results. Will anyone help in writing the logic. File data [ServerName] ABCDE-1; [DBLcation] \\ABC...
#include "stdafx.h" #include<iostream> #include<fstream> #include<string> using namespace std; void read_file(); int main() { read_file(); return 0; } void read_file() { ifstream myfile; myfile.open("config.txt"); string str; if (myfile.is_open()) { cout << "Enter the name :" << ...
68,617,436
68,684,969
converting hls livestream to rtmp
i'm new to ffmpeg Is it possible to convert hls livestream into rtmp with video resize and rotate without re-encoding eg: hls into rtmp is this even possible ? sorry moderators for my bad grammer forgive me
Not possible Resize (scaling) and rotation of the video requires using filters. Filters require re-encoding.
68,617,466
68,628,642
Grid mesh looks fine under mvp operation, but not in orthogonal projection
I have these 2 shaders: #version 450 #extension GL_ARB_separate_shader_objects : enable layout(location = 0) in vec3 in_position; layout(binding = 0) uniform MVPOnlyUbo { mat4 model; mat4 view; mat4 proj; } ubo; void main() { gl_PointSize = 5.f; gl_Position = vec4(in_position.xy, 0.5, 1.0); } #...
If anyone ever runs into this, I made a mistake when creating the winding order for my triangles. Some triangles were in the correct winding order, others were not. The perspective projection "made things work" because it rotated by 180 degrees the image, thus fixing the incorrect winding order.
68,618,055
68,618,695
Implementing virtual functions' overriding mechanism with templates
I recently had a thought of implementing virtual functions without virtual tables or storing a pointer with CRTP (though using static_cast<CRTP&>(*this) instead. The initial set up is rather cumbersome compared to conventional virtual functions. So the code is: namespace detail { template<typename T, typename = voi...
To solve your infinite recursion, you might still compare that "&dummy::setup != &base<dummy>::setup": namespace detail { template <typename B, typename T, typename = void> struct virtual_set_up { void operator()(T&) {} }; template <typename B, typename T> struct virtual_set_up<B, T, ...
68,618,376
68,618,568
C++ weird long long division (not common type conversion error)
I was trying to do some newbie competitive programming problems (because currently i am a newbie :D). I got this strange error with constant and long long division... And watched carefully about tipe conversion problems (can't see any). I don't understand why such division, gives 1e18 instead of desired result... #incl...
Macros are just simple text replacements. UPPER / second will be replaced with (ll)1e18 + 1 / second which is always equal to (ll)1e18 unless second is 1 You must use parentheses around that #define UPPER ((ll)1e18 + 1)
68,618,466
68,618,536
C++ Primer 5th Edition: Pointer to member function
Hello I have this text from C++ Primer 5th edition: function<bool (const string&)> fcn = &string::empty; find_if(svec.begin(), svec.end(), fcn); Here we tell function that empty is a function that can be called with a string and returns a bool. Ordinarily, the object on which a member function executes is passed to t...
It refers to the implicit this parameter to member functions. They get a pointer to the current object passed under the hood. std::function has some magic to turn that implicit parameter into an explicit one: #include <iostream> #include <functional> struct foo { void bar() { std::cout << "Hello World\n";} }; int...
68,618,740
68,618,826
New line after a recursive function
I wrote a function which will print all nodes in single line at certain level in the tree, Now I want to break line after printing all the nodes, Which I could have done easily in the main function, but I can't think of a way to do it in the function itself. I want to do this in the printLevelK function which is just b...
Something like this? void printLevelK(treeNode<int>* root, int k, bool newline=true){ if(root==NULL) return; if(k==0){ cout<<root->data<<" "; if (newline) { cout << "\n"; } return; } for(int i=0;i<root->childNodes.size(); i++){ printLevelK(root->childNodes[i], k-1...
68,619,231
68,619,290
Does "A::B::C v;" means that A and B are namespaces and C is a class?
When you see an instruction like A::B::C v; in a c++ code, does it mean that A and B are namespaces defined in some header file, and C is a class in the namespace B?
It could be following three possibilities: namespace A { namespace B { using C = int; // some types } } or namespace A { struct B { using C = int; // some types }; }; or struct A { struct B { using C = int; // some types }; }; You need to look into the source...
68,619,534
68,619,615
Is it possible to get the nesting level (dimension) of a multi-dimensional vector during compile time?
Assume a multidimensional / nested std::vector. Like for example: using V4D = std::vector<std::vector<std::vector<std::vector<int>>>>; Can I retrieve the dimension of "V4D" at compile time? E.g. constexpr size_t Dimension = something very smart here; which would give me 4?
You can do something like std::rank, but for vector. Simplified version: template <typename T> struct vector_rank : std::integral_constant<std::size_t, 0> {}; template <class T> struct vector_rank<std::vector<T>> : std::integral_constant<std::size_t, 1 + vector_rank<T>::value> {}; using V4D = std::vector<std::v...
68,619,670
68,619,858
Pointers pointing to same memory location but different program
I've written two programs, one (p1.cpp) that prints the value and address of a variable every 1 second.. // p1.cpp int main() { int x = 13; int *p = &x; while (true) { cout << " value of x: " << *p << " addr: " << p << endl; sleep(1); } } and the other (p2.cpp), in which I manuall...
In modern operating systems like linux, windows or MacOs each process has its own virtual memory address space. Therefore the memory address from the process of your program p1 has nothing to do with the memory of the process of your program p2. If you really want to access memory between processes directly you need to...
68,620,172
68,620,380
Creating/destroying an object in a static memory section
Is the static memory section alignas(alignof(T)) char bytes[sizeof(T)] suitable to hold an instance of T during its lifetime by calling std::construct_at(bytes, ...) / std::destroy_at(bytes)? My instincts say, yeah, the alignment and size requirements are guaranteed, so after construction (since there are also triviall...
Is the static memory section alignas(alignof(T)) char bytes[sizeof(T)] suitable to hold an instance of T during its lifetime by calling std::construct_at(bytes, ...) / std::destroy_at(bytes)? Yes. reinterpret_cast<T*>(bytes) is a valid pointer to a completely valid instance of type T. Am I missing something? You wo...
68,620,329
68,620,553
Functions in derived class not being able to access members in base class
#include <memory> template<typename T> struct vector_base{ std::allocator<T> alloc; T *elem; int sz; int space; vector_base(const std::allocator<T> &a, int n):alloc{a},elem{alloc.allocate(n)},sz{n},space{n}{} ~vector_base(){alloc.deallocate(elem,space);} }; template<typename T> class vector:priv...
You can not initialize the members of the base class directly, it would contradict any sense of class encapsulation. That's why you wrote constructors in the base class, you can invoke those like: template<typename T> class vector:private vector_base<T> { public: std::allocator<T> myalloc; vector() : vector_bas...
68,620,548
68,624,379
z3::operator- causes program to terminate
I have this c++ code that uses z3 operators. std::vector<z3::expr> bv_vector_immediate = {}; int immediate_int = immediates[0]->get_immediate_value_int(); bv_vector_immediate.push_back(z3_ctx.bv_val(immediate_int, 64)); Z3_LHS = get_register_value(register1).back(); //bv_val(0, 64) Z3_RHS = bv_vecto...
Please always post reproducible code segments. Just posting "parts" of your code makes it very difficult for others to diagnose the problem. Having said that, your problem is that the value 0-10 does not fit in an int64 value as a bit-vector. Here's a minimal reproducer: #include <z3++.h> using namespace z3; using nam...
68,620,720
68,620,742
Please explain the code below (This is a question about for-loop arguments in C++):
char title[] = "Computer"; for(int i=0; title[i]; i++){ cout<<title+i<<endl; } Please tell what is "title[i]" doing in the arguments. What role does it play in the loop? I'm confused because there should be a conditional in there instead.
C/C++ strings are implicitly terminated with a null \0 character, which is equal to 0, which equates to false. Once the loop has iterated to one past the last character where the null character is, the loop will terminate.
68,620,723
68,620,931
Calling each vector in vector<vector<pair<int, int>>>
I have a set of values saved into: vector<vector<pair<int, int>>> subsets If I wanted to output the values from each vector within the vector. How would I go about doing that? vector<pair<int, int>> would be in the format <(1, 2) (2, 3) (5,0)> vector<pair<int, int>> = <(1, 2) (2, 3) (5,0)> subsets would contain sever...
Here's one example: #include <iostream> #include <vector> #include <utility> int main() { std::vector<std::vector<std::pair<int, int>>> subsets{ {{1, 2}, {2, 3}, {5,0}}, {{1, 2}, {4, 8}}, {{0, 1}, {5, 5}, {1, 1}} }; for(auto& inner : subsets) { // loop over the outer vector ...
68,620,730
68,623,576
zlib gzclose: How to detect a successful file closure?
I have used zlib to compress a file. All works well. After the operation is complete, I call gzclose(file) to flush and close the gzip file. According to the documentation, the gzclose returns an int which provides the success or failure of the gzclose operation. Since there can be many failure reasons, checking for ea...
The zlib functions are documented in zlib.h. You can also find zlib.h formatted a bit in the zlib Manual. In there you find: ZEXTERN int ZEXPORT gzclose OF((gzFile file)); Flushes all pending output if necessary, closes the compressed file and deallocates the (de)compression state. Note that once file is closed, you c...
68,620,780
68,808,761
Dynamic memory allocation in STD
Working a lot with microcontrollers and C++ it is important for me to know that I do not perform dynamic memory allocations. However I would like to get the most out of the STD lib. What would be the best strategy to determine if a function/class from STD uses dynamic memory allocation? So far I come up with these opti...
You have some very good suggestions in the comments, but no actual answers, so I will attempt an answer. In essence you are implying some difference between C and C++ that does not really exist. How do you know that stdlib functions don't allocate memory? Some STL functions are allowed to allocate memory and they are s...
68,620,868
68,621,004
error: FILE was not declared in this scope
I'm new to WIN32 programming. I followed up a tutorial series and tried to include it to my code. I got the error FILE was not declared in this scope. Seeing this in the video it seems that it is a type. But it isn't recognised here. void write_file(char *path) { FILE *file; file = fopen(path,"wb"); int...
Hi fopen is a function from C I/O standard library (stdio.h). If you would use that function, in your C++ program, you must include that library #include <cstdio>. But in the title you wrote C++, so in this case you can use iostream or fstream like #include <iostream> #include <fstream> Read more here: fopen, stdio.h,...
68,620,871
68,621,655
CMake does not set variables for g2o
On macOS 11.0, I downloaded and built g2o (https://github.com/RainerKuemmerle/g2o) and installed it using cmake --install . I then tried to include it in my own project via CMake like this (CMakeLists.txt): cmake_minimum_required (VERSION 3.14) project (MY-PROJECT) set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQ...
why CMake did find g2o but not set the variables accordingly. FindG2O.cmake does not set these variables, so they are not set. The variables checked for G2O_FOUND to be set are G2O_STUFF_LIBRARY AND G2O_CORE_LIBRARY AND G2O_INCLUDE_DIR AND G2O_SOLVERS_FOUND. There is no rule that find_package has to set _LIBRARIES or...
68,621,493
68,621,799
Why capture lambda does not working in c++?
I am playing with lambda expressions in C++, and I have tried a few things to see the outcome. I actually watched the video in CppCon Back to Basics: Lambdas from Scratch - Arthur O'Dwyer - CppCon 2019 @21:47 and started to play with lambdas. As an example, I've tried this: #include <iostream> using namespace std; int ...
auto kitten = [=] () {return g+1;} This lambda doesn't capture anything at all. It's nearly the same as just int kitten() { return g+1; } Only local variables can be captured, and there are no local variables visible in the scope of the kitten definition. Note that [=] or [&] don't mean "capture everything", they mea...
68,621,930
68,622,051
C++ : undefined reference issue in a simple case of separate compilation
Given the below class definition in the header file - "class1.h" #ifndef CLASS1_H #define CLASS1_H class class1 { public: class1 &fcn(); }; #endif and the member function fcn is defined in the source file - "class1.cpp" #include "class1.h" #include<iostream> inline class1 &class1::fcn() { std::cout << ...
The inline keyword is the problem. You are supposed to use that with functions that are defined in headers. In your case, remove it and it should work fine.
68,622,369
68,624,464
Why is the concept in template template argument not verified?
C++20 allows the program to specify concept for template template argument. For example, #include <concepts> template <typename T> concept Char = std::same_as<T, char>; template <typename> struct S {}; template <template <Char U> typename T, typename U> T<U> foo() { return {}; } int main() { foo<S, int>(); } the fir...
A template (actual) argument matches a template (formal) parameter if the latter is at least as specialised as the former. template <Char> typename T is more specialised than template <typename> struct S. Roughly speaking, template <Char> accepts a subset of what template <typename> accepts (the exact definition of wha...
68,622,608
68,622,906
Saving a const reference of a list that I get from another class is not working
My code is a bit more complicated, but I think the structure can be boiled down to this, imagine the following two classes: class Foo { std::list<std::shared_ptr<SomeType>> listOfType; const std::list<std::shared_ptr<SomeType>>& getList() const { return listOfType; } } class A { std::shared_pt...
Foo getFoo() { return *foo; } In this member function, you are returning a temporary which is a prvalue in the calling expression. Because you call .getList() on it, it will get materialized and become a xvalue (expiring value) and as soon as the expression finishes, it will be destroyed and as you are capturing t...
68,622,748
68,631,074
php exec() not showing expected output
I am trying to run cpp executable on php, but its not working. Please help. var_dump(shell_exec("D:\\c_cpp_programs\\string.exe")); $output = system('D:\\c_cpp_programs\\string.exe', $retval); var_dump($output); passthru ('D:\\c_cpp_programs\\string.exe'); if(file_exists('D:/c_cpp_programs/string.exe')) echo "...
Finally I got the output when I started wamp with admin privileges, C:\wamp64\www\chatclub\application\views\test.php:2:string 'Hello ' (length=6) Hello C:\wamp64\www\chatclub\application\views\test.php:4:string 'Hello' (length=5) Hello File exist C:\wamp64\www\chatclub\application\views\test.php:9: array (size=1) 0 ...
68,622,804
68,622,873
Bitwise opertor ^ on right side of equality operator == doesn't work as intended
Code snippet: void fn(){ if(14-2==0^2){ cout<<"14-2 is "<<14-2<<"\n"; cout<<"0^2 is "<<(0^2)<<"\n"; //cout<<0^2 shows error: invalid operands of types 'int' and 'const char [2]' to binary 'operator<<' cout<<"How is if evaluated to be true?"; } else{ cout<<"else"; } } Ou...
From operator_precedence, 14 - 2 == 0 ^ 2 is parsed as ((14 - 2) == 0) ^ 2 so (12 == 0) ^ 2 so false ^ 2 so 2 (so true)
68,622,836
68,623,461
C++: How to remove "Cereal" XML node?
I want to (de)serialize C++ object into XML files. To do so, I use Cereal library which is lighter than Boost. So using the Cereal documentation, I created a very simple MWE. Thus, using Cereal serialize function inside the object definition, it is possible to export the object into an XML archive. The MWE: #include <s...
Looking at the source code of cereal, it doesn't look like you can remove the root tag. I guess it exists because cereal can only deal with a single root node, and since you could serialize multiple values directly into the archive, for example: ClassRectangle Shape; cereal::XMLOutputArchive archive( std::cout ); archi...
68,622,892
68,623,055
how adding string and numbers in cpp works using + operator?
I've used cpp for quite a while, I was known that we cannot add string and numbers(as + operator is not overloaded for that). But , I saw a code like this. #include <iostream> using namespace std; int main() { string a = ""; a += 97; cout << a; } this outputs 'a' and I also tried this. string a =""; a=a+97...
The first snippet works because std::string overrides operator+= to append a character to a string. 97 is the ASCII code for 'a', so the result is "a". The second snippet does not work because there is no + operator defined that accepts a std::string and an int, and no conversion constructor to make a std::string out o...
68,623,473
68,624,294
C++: specializing member requires template<> syntax
I am trying the following... #include <iostream> using namespace std; template<class T> class Singleton { private: class InstPtr { public: InstPtr() : m_ptr(0) {} ~InstPtr() { delete m_ptr; } T* get() { return m_ptr; } void set(T* p) { if (p != 0) ...
Singleton<ABC>::InstPtr Singleton<ABC>::ptr; should be used for defining the static member of a explicitly specialized class template, e.g. template<class T> class Singleton { ... }; // explicit specialization template<> class Singleton<ABC> { private: class InstPtr { ... }; static InstPt...
68,623,787
68,627,429
How to access compatible std::variant variants?
#include <variant> struct A { void foo(){} }; struct B { void foo(){} }; int main() { std::variant< A, B > v{ A{} }; v.foo(); // doesn't work } How do I use the std::variant value not knowing it's type but knowing it's properties? I believe this is called Generic Polymorphism equivalent to Duck T...
Totally valid use case. I imagine there's many ways to do it, but here's one: std::visit([](auto&& val) { val.foo(); }, v); Demo The reason your initial code doesn't work is because A::foo is unrelated to B::foo, so to use them interchangeably you need a context where the type "containing" a foo member is deduced. In ...
68,623,999
68,624,063
I don't understand ",b[a] " in the cin >> a , b[a] = 1 ;
using namespace std; int i, t, n, x, a; main() { int t; cin >> t; while (t--) { cin >> n >> x; int b[n + x] = {0}; while (n--) cin >> a, b[a] = 1; // ***here is my question for (i = 1; x > 0 || b[i] != 0; i++) if (b[i] == 0) x--; ...
This is an example of bad written code (make it weird and harder to read). In C and C++ there is , operator where both arguments are evaluated and last one is returned as a value of whole expresion. So this line: cin >> a, b[a] = 1; return value for operator, is discarded so cin >> a and b[a] = 1 are just evaluated. T...
68,624,489
68,624,530
Why the regex to mark beginning of line doesn't work?
Why the commented regex doesn't behave the same as uncommented regex? I thought '^' also marks beginning of line. isn't it? #include <iostream> #include <regex> int main() { std::string str ("this subject has a submarine as a subsequence"); std::regex re ("\\b(sub)([^ ]*)"); // std::regex re ("^(sub)([^...
It's working just fine. It can't match anything because your line doesn't start with the letter "sub," it starts with the letters "The" To explain these regexes: \\b(sub)([^ ]*) Start of new word, begins with sub, followed by some number of non-space characters. Two capture groups, one for "sub" and one for the oth...
68,624,733
68,626,412
C++ getting console app in windows to print as fast as in linux
This code: #include <iostream> #include <chrono> #include <functional> #include <time.h> int main() { time_t b4 = time(NULL); for (int i = 0; i < 50000; i++) std::cout << i << " "; std::cout << std::endl; time_t a4 = time(NULL); std::cout << "Time taken is " << difftime(a4, b4); getchar...
Your standard library implementation may be part of your problem. I ran the following code with plain vanilla Visual C++: #define WRITE_CONSOLE_API #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <chrono> #include <functional> #include <time.h> #include <windows.h> int main() { LARGE_INTEGER freq;...
68,625,136
68,625,313
Threading queue in c++
Currently working on a project, im struggeling with threading and queue at the moment, the issue is that all threads take the same item in the queue. Reproduceable example: #include <iostream> #include <queue> #include <thread> using namespace std; void Test(queue<string> queue){ while (!queue.empty()) { ...
You are giving each thread its own copy of the queue. I imagine that what you want is all the threads to work on the same queue and for that you will need to use some synchronization mechanism when multiple threads work on the shared queue as std queue is not thread safe. edit: minor note: in your code you are spawning...
68,625,188
68,636,284
C++ calls Python in Anaconda3 error: ModuleNotFoundError: No module named 'zlib'
I need to use the C++ code to call the Python code(which used TensorFlow), Python was installed by Anaconda3. But I found my code couldn't load the python code because the tensorflow module was not loaded successfully. The clear question is below. My C++ code: #include <iostream> #include <python.h> int main() { P...
to avoid confusion and as the reported error message is different to what usually in conflict between imported library and linked library is reported. I'm adding this answer to this particular question,(ModuleNotFoundError: No module named 'zlib') In this case dll library that is used to build executable and libraries ...
68,625,502
68,625,565
Syntax confusion regarding C++ while loops
I recently started to learn C++ and I have a question regarding the syntax of an exercise given in our lecture about the accuracy when we declare different types of variables, in this case float and double. #include <iostream> using namespace std ; int main() { // Accuracy test with float float eps_f = 1.0 ; ...
In C++, indentation does not affect the flow of a program, but it DOES affect the readability. This can be better written as: #include <iostream> using namespace std ; int main() { // Accuracy test with float float eps_f = 1.0 ; while (float(1.0 + eps_f) != 1.0) { eps_f /= 2.0 ; } cout ...
68,625,874
68,663,617
Change Windows language settings programmatically in C++
I tried to set language from Mandarin to English using: SystemParametersInfoA API returns true, but the language of data collect from device manager is unchanged. DWORD hKLEnglUS = 0x00000409; if (SystemParametersInfoA(SPI_SETDEFAULTINPUTLANG, 0, &hKLEnglUS, SPIF_SENDCHANGE)) printf("Success!!\n")...
Solved by using SetThreadUILanguage API
68,626,001
68,627,379
error: no match for ‘operator<’ (operand types are ‘const A’ and ‘const A’)
#include <set> #include <iostream> using namespace std; template<class T> class A { public: A(T a = 0,T b =0): m_a(a),m_b(b) {} bool operator<(const A& lhs) { /* compare code */ } private: T m_a; T m_b; }; int main() { ...
Your operator< needs to be const, because set operates on const objects internally. Also, your operator< is not implemented correctly anyway. It is ignoring the members of the A object on the left-hand side of the comparison, it is only looking at the member of the A object on the right-hand side. Try this instead: #i...
68,626,002
68,634,185
C++ firebase application windows application, CMake needed or VS project only possible?
As stated here: https://firebase.google.com/docs/cpp/setup?platform=android#ndk-build One need CMake. Is this really needed or is it enough to add libs and headers to my VS2019 project?
The C++ SDK was made with CMake in mind and is listed as a requirement, this is for compiling and ensuring the SDK is cross-platform. You may be able to get away without it if you manually add the libraries and correct headers, but there is no guarantee all the services would work as intended. If this is not an option ...
68,626,140
68,626,196
How to switch with pointer to member functions?
Well, all I want to do is a "switch" with a function pointer, but with methods pointers. The switch is that if I call the method Run(), it will either redirect to A::RunOn() or A::RunOff() according to Run ptr is pointing to these member functions. I know it can be done. I did it in plain c but I have searched and goog...
Your member function pointer typedef is wrong (Despite the other issues in the shown code). You need typedef void(A::*RunPtr)(int); Or you can provide the alias for the member function pointer of class A with the help of using keyword as follows: using RunPtr = void(A::*)(int); RunPtr RunMethod; Now in the SetOn you...
68,627,557
68,627,794
Precision of a power of double in bison and avr-g++
I am writing a calculator for an avr microcontroller using bison and I have a problem with the resolution of a power of 2 doubles. In my bison file I define the type as %define api.value.type {double} %token NUMBER and then give the following rule expr: NUMBER | expr '^' expr {$$ = pow($1, $3);} And the ...
This has nothing to do with bison. The culprit is the math library on the AVR microcontroller. When you write (in C): double a = 2.0; double b = 8.0; double c = pow(a, b); Gcc is smart enough to figure out that c will be 256.0. it's not necessary to do that computation at run time. Gcc just rewrites that to double c =...
68,627,666
68,627,700
C++ Error in creating the file (name based on other file name)
I have a problem with creating a file, whose name is a little bit modified from some other file's name. But if the new name is not based on another name - the program works - but I need to use that first method. I used backslash (\b) to remove ".srt" from the original file name to modify the copy - in this program, I c...
Adding \b\b\b\b to your string adds 4 backspace characters. It does not remove 4 chars from the string. This would work: std::string path_file_new = path_file_1.substr(0, path_file_1.size()-4) + "-corr.srt";
68,627,831
68,628,098
How to convert a C-type variadic to C++ style variadic type?
I have a function which currently looks like this: void log(uint8_t level, const char* fmt, ...) { va_list va; va_start(va, fmt); char msg[128]; int msg_size = vsnprintf(msg, 128, fmt, va); va_end(va); callback->dosomething(level, msg); // some api } I want to convert it to, void log(uint8_t l...
This would be one way of doing it: template<class... Args> void log(uint8_t level, const char* fmt, Args&&... args) { char msg[128]; int msg_size = std::snprintf(msg, 128, fmt, std::forward<Args>(args)...); callback->dosomething(level, msg); // some api } Note that I'm using snprintf instead of the va_lis...
68,628,885
70,356,232
Embree: stream mode - how does gather and scatter work and what are pid and tid?
I'm trying to upgrade my application from single ray intersection to stream intersection. What I don't quite understand is how it's possible that the gather and scatter functions shown in the tutorials are even working The example defines a custom extended ray struct Ray2 struct Ray2 { Ray ray; // ray extensions ...
Having not written this example myself it's hard to guess what the original intention of it was, but I think the clue lies in exactly your observation that for rid and pid calculations, the division/modulo by '1' are meaningless. So, if rid eventially always ends up as being '0' (because every value mod 1 will be 0 :-/...
68,629,063
68,629,109
Declaring a member template function with the same template type as class
I have a class that I want to initialize this class using a factory function of the template type. It also needs to depend on a long-lasting dependency that I want to store as member variables and refer to in the factory functions. E.g. template <class T> class Foo { public: Foo() : member_(Create<T>()) {} templa...
There is no need to have a template on Create() at all, since it is already on Foo. Just have Create() use Foo's own T template parameter as-is, just as you are with member_, eg: template <class T> class Foo { public: Foo() : member_(Create()) {} // <T> not needed here! T Create(); // no 'template' here! privat...
68,629,271
68,670,463
OpenCv read / write video color difference
I am trying to simply open a video with openCV, process frames and write the processed frames into a new video file. My problem is that even if I don't process frames at all (just opening a video, reading frames with VideoCapture and writing them with VideoWriter to a new file), the output file appears more "green" tha...
There is a bug in OpenCV VideoCapture when reading video frames using FFmpeg backend. The bug results a "color shift" when H.264 video stream is marked as BT.709 color standard. The subject is too important to leave it unanswered... The important part of the post, is reproducing the problem, and proving the problem is...
68,629,329
68,642,007
Is it safe to capture `this` in a coroutine lambda (C++)
I've been working with c++20 coroutines and I stumbled upon this issue with the lifetime of the lambda captures not extending for the entire life of the coroutine. I was wondering what's safe to capture, since I've been having to copy all my captures into new objects like this: [a1=object]() -> task<void> { // need...
Programmers should ignore that sentence in the standard: it merely allows implementations to allocate less memory than might naïvely be expected for lambda objects with reference captures (especially when the call operator is inlined).
68,629,836
68,630,291
How to get file name using libcurl?
I use libcurl to download file, url may be like this below url = "https://***.com/**/***/abc" url = "http://***:8000/**/test.txt?***2484d197c16b2e" url = "http://***:8000/**/test.txt" It is troublesome to get its file name, so is there a way to get file name using libcurl when downloading it? My download code is below...
Use CURLOPT_HEADERFUNCTION to get a callback for each of the HTTP headers. You are looking for the header called Content-Disposition.
68,630,103
68,642,647
error: no matching function for call to ‘sf::RenderWindow::draw(Map (&)())’ | c++
I'm using SFML on Linux, and I'm trying to draw a class name Map it has public: sf::Drawable, But when I try and do window.draw(map) I get src/Main.cpp: In function ‘int main()’: src/Main.cpp:30:18: error: no matching function for call to ‘sf::RenderWindow::draw(Map (&)())’ 30 | window.draw(map); Also tried makin...
Defined Map as Map map(); Fix was defining it as Map map;
68,630,499
68,634,305
Implementing Kalman filter in C++
I'd like to implement an extended Kalman filter in C++ using the eigen library because I'm interested in robotics, this seems like a good exercise to get better at C++ and it seems like a fun project. I was hoping I can post my code to get some feedback on writing classes and what my next steps should be from here. So ...
One thing to consider, which will affect the answers to ypur questions, is how 'generic' a filter you want to make. There is no restriction in a Kalman filter that the sampling rate of the measurements be constant, nor that you get all the measurements every time. The only restriction is that the measurements appear in...
68,630,982
68,631,040
Getting error while initializing string with string character array?
I'm trying to initialize this string s1 but Idk why I'm getting this error, This may be due to s[0] is character but why everything turns fine when I initialize and declare same string s1 but in diffrent lines, one after another. #include <bits/stdc++.h> int main() { std::string s = "text"; std::string s1 = s[0]; ...
There's no constructor for char. There's a copy assignignment, which works for the second snippet. However, you can write either like std::string s1 ( 1, s[0] );
68,631,802
68,634,394
Issue when connecting a socket application over a port forwarded over adb
I was developing an application which has a server on the PC and client as an android device connected over adb (USB). I have setup port forwarding by: adb forward tcp:5100 tcp:5100 Whenever I'm trying to run my python server over this it says : server.bind(("127.0.0.1", 5100)) OSError: [WinError 10048] Only one usage ...
To have the python server code and the android client side to talk each other you should use adb reverse instead of forward. This is the adb command that you should use adb reverse tcp:5100 tcp:5100
68,631,824
68,631,906
Difficulty in loading boolean array using AVX2 instruction
Currently I have two boolean array X and Y which I want to do a bitwise or operation of both of them and store it back into X. I wish to do it using SIMD instruction but I find that the load instruction I used is not doing the expected. #include <iostream> #include <immintrin.h> int main(){ bool mask[256]={0}; ...
The size of bool mask[256] is 256 bytes not 256 bits. The minimum size of an array element is 1 byte. This means mask[130] is not loaded by _mm256_loadu_si256. You would need to pack your booleans into 256 bits before loading into the register: #include <iostream> #include <immintrin.h> int main() { uint8_t mask[3...
68,632,219
68,632,255
Why is true && false equal to 1 in C++?
I was playing around with booleans and ended up with this line of code: std::cout << true && false; which, for some reason, produces 1. How is this possible, if && requires both sides to be true, in order to produce 1?
Because operator<< has higher precedence than operator&&, std::cout << true && false; is just same as (std::cout << true) && false; (i.e. print out true firstly, then the returned std::cout is converted to bool, which is used as operand with false for the operator&&, the result is discarded at last). Note that std::cou...
68,632,533
68,632,854
Linked List : Push : please explain why this code is not working
int main(){ node** head = nullptr; push(&head,1); push(&head,2); push(&head,3); printlist(&head); return 0; } void push(node*** head_ptr,int data){ node* new_node = new node; new_node->data = data; if(*head_ptr != nullptr){ node* temp = **head_ptr; while(temp ...
You assign the address of a local variable, and then use that value after the function has returned, which means your program's behaviour is undefined. *head_ptr = &new_node; Having fixed that, you dereference a null pointer, which means your program's behaviour is still undefined. node* temp = *head_ptr; while(temp...
68,632,885
68,633,753
lambda expression using scope variables - is safe?
When f is called, a is already "destructed". Is it safe to use it this way? How does it work? std::function<void()> f; { int a = some_calc(); f = [=] { std::cout << a << std::endl; } } f();
Here is conceptually what is going on: #include <functional> #include <iostream> int some_calc() { // ... return 42; } int main() { std::function<void()> f; { int a = some_calc(); class Lambda { private: int a; public: Lambda(int const& _a) : a{_a} {} void operator()()...
68,632,984
68,633,287
Unexpected reference behaviour
I was studing the Composit Pattern and experienced an unexpected behaviour of the following code: namespace Composit { class Component { public: virtual ~Component() { } virtual void operation() = 0; protected: private: }; class Leaf : public Component { public: ...
It's because Composit::Composit c(b) calls the copy constructor, which is generated by default. This is why the pointer version works, since a Composit* argument won't work with the copy constructor. There's no good way to prevent this behaviour, since if Composit::Composit c(b) is valid, most containers/generic algori...
68,633,060
68,635,185
Is there a clean way to disable a C++ feature macro?
We have a module that pulls in 3rd-party, specifically sqlite_modern_cpp although I don't think that is particularly important. What is important is that code uses C++ feature macros and (specifically) tests for __cpp_lib_uncaught_exceptions to know whether std::uncaught_exceptions is defined. So far so good, except th...
Feature test macros are just normal macros, which you can #undef. Include <exception> first to define the macro, then undef, then include the library. sqlite_modern_cpp is a header only library, so this should cause no problems. #include <exception> #undef __cpp_lib_uncaught_exceptions #include "sqlite_modern_cpp.h"
68,633,295
68,633,831
Are both the keyword "typename" and "template" not necessary in this case?
template<class T> T::type<int> f(){ } According to [temp.names#3.4] A < is interpreted as the delimiter of a template-argument-list if it follows a name that is not a conversion-function-id and [...] that is a terminal name in a using-declarator ([namespace.udecl]), in a declarator-id ([dcl.meaning]), or in a...
Yes, this is the rule, and it’s correct; compilers simply haven’t implemented the (newer) template part yet. In discussing that addition, an example was brought up that illustrates the absurdity of requiring the keyword in this context: template<typename T> struct A {   template<typename U> struct B {     B();   };  ...
68,634,114
68,635,093
How to create multiple threads to populate array optimising processing time
Hey everyone im having trouble creating threads to populate an array, The objective is to populate an array in the fastest time possible using pthreads to show parallelisation. im trying to parallelise this piece of code to increase the speed of the processing time. for (int i = 0; i < size; i++) { v3[i] = v1[i] + v...
Given the following struct: struct thread_context { pthread_t thread; int *v1, *v2, *v3; unsigned long size; }; You can do the following: thread_context threads[THREAD]; for (int i = 0; i < THREAD; i++) { int part_size = size / THREAD; int part_offset = part_size * i; threads[i] = { 0, &v1[part...
68,634,142
68,634,279
Why does overload resolution not fall back to constructor with reference to base class when copy-constructor is deleted?
As a followup question to this question: class Base { public: virtual ~Base() {} virtual void func() = 0; }; class A : public Base { public: void func() override { std::cout << this << std::endl; } }; class B : public Base { private: Base& base; public: B(B&) = delete; ...
Because = delete is a still a definition of the constructor (it is defined as deleted). Deleted functions are still possible candidates in overload resolution, and, in this case, the copy constructor is still the most viable candidate, and it is selected. Since a deleted function is referred to, the program is ill-form...
68,634,228
68,634,475
Why can't compile std::views::take(std::uint64_t{})?
#include <cstdint> #include <ranges> int main() { auto const il = {1, 2, 3, 4, 5, 6}; auto const n1 = std::int32_t{3}; auto const n2 = std::uint32_t{3}; auto const n3 = std::int64_t{3}; auto const n4 = std::uint64_t{3}; il | std::views::take(n1); // ok il | std::views::take(n2); // ok ...
range | std::views::take(n) is expression equivalent to std::ranges::take_view(range, n), which takes a ranges::range_difference_t<V>. Following the aliases through, gcc 11.1 doesn't want to consider unsigned long as usable where a long is wanted
68,634,827
68,635,198
Android NDK RegisterNatives more full example
I'm try to make Android Native C++ project in Android Studio 2020.3.1. Here and here provided common tips for using RegisterNatives in JNI_OnLoad. But in this examples i can't understand what is nativeFoo and nativeBar ? These are methods or functions of c++ code? And what is doing MyClass in example ? I want more full...
Going backwards from the RegisterNatives call in the first link, it hooks up native C++ methods to the following Java class: package com.example.app.package; class MyClass { public native void nativeFoo(); public native bool nativeBar(String, int); } and it expects that you defined the following C++ functions...
68,634,914
68,636,086
Why glm transform functions are applied "backwards"?
Edit: it is "backwards" to me - I may be missing some intuition Given a glm transform function such as glm::translate, the two parameters are first a matrix m and then a vector v for translation. Intuitively, I would expect this function to apply the translation "after" my matrix transform, i.e. multiplying an object b...
This intuition comes from the fact that one usually builds a transformation in mathmetical order But there is no such thing as a mathematical order. Consider the following: v is an n-dimensional vector and M a n x n square matrix. Now the question is: which is the correct multiplication order? And that depends on you...
68,635,838
68,636,123
Boost 1.71.0: How to get process output?
I had code like this that worked fine on Ubuntu 18.04 and with Boost 1.65.0: // See https://www.boost.org/doc/libs/1_65_0/doc/html/boost_process/tutorial.html std::pair<int, std::string> runCommandAndGetOutput(const std::string & cmd, const std::vector<std::string> & args) { namespace bp = boost::process; boost::as...
You need to wait until the child is finished. exit_code - "Get the exit_code. The return value is without any meaning if the child wasn't waited for or if it was terminated." #include "boost/process.hpp" #include <iostream> std::pair<int, std::string> runCommandAndGetOutput( const std::string& cmd, const std::vec...
68,636,510
68,737,038
How to read values (possibly NULL) from database into std::vector via Poco::Data?
I want to read many rows (values may be NULL) from a SQL-Server database into an std::vector. Reading a single value both NULL and non-NULL works. But I have problems reading multiple values. Following the POCO Data User Guide, I came up with the following code: Boilerplate code before: Poco::Data::ODBC::Connector::reg...
Many approaches were tried out. In the end I replaced the std::vector by Poco::Data::RecordSet. Now I can iterate over its Poco::Data::Rows, which in turn gives me the column values typed as Poco::Dynamic::Var. Here Poco::Dynamic::Var::isEmpty() lets me check if the database entry is NULL. See the simplified code for c...
68,636,739
68,636,801
How to import function from c++ dll
Here is c++ dll code: #include<stdlib.h> #include "pch.h" extern "C" _declspec(dllexport) int Add(int a, int b) { return a + b; } C# code, that i run in Visual Studio: [DllImport(@"C:\Dll1.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)] public static extern int Add(int port, int speed)...
Make sure that you are using 32 bit dll for 32 bit powershell process and 64 bit dll for 64 bit powershell process. The error looks like as if you trying to load 32 bit dll into 64 bit process. Please note that .net applications compiled as "Any CPU" will run in 32 bit mode by default even on 64-bit operating system. U...
68,636,752
68,636,814
Is there a way to down cast a struct to its derived one in C++?
Here is my situation: struct A { int numberAllChildStructsUse; } struct B : A { std::string strUniqueToB; } struct C : A { std::string strUniqueToC; } (in some source file) B b = thisFunctionReturnsBOrCStructsAsTypeA(int idThatGuaranteesItIsTypeBNotC); Error: no suitable user-defined conversion from A t...
You can use dynamic_cast for this, but only if the class hierarchy is polymorphic. To achieve the latter, write struct A { int numberAllChildStructsUse; virtual ~A() = default; }; reference: https://en.cppreference.com/w/cpp/language/dynamic_cast