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
64,442,053
64,442,126
C++ How to prefix uint16_t in front of uint8_t *buffer
Here is how I create my message with FlatBuffers and how I send it over TCP with Boost ASIO. flatbuffers::FlatBufferBuilder builder; auto email = builder.CreateString("test@asd.dg"); auto password = builder.CreateString("test"); auto loginRequest = Vibranium::CreateLoginRequest(builder,email,password); builder.FinishSi...
You can allocate an intermediate buffer. flatbuffers::FlatBufferBuilder builder; auto email = builder.CreateString("test@asd.dg"); auto password = builder.CreateString("test"); auto loginRequest = Vibranium::CreateLoginRequest(builder,email,password); builder.FinishSizePrefixed(loginRequest); size_t size = builder.GetS...
64,442,321
64,443,541
Creating a mask based on a colour range
I'm trying to wind turbines in pictures. To make this easier I try to remove the background based on the color (sky is blue, ground is green) just something basic. But it seems that my mask is always completely black. What am i doing wrong? kind regards Mat HSV, mask, outputHSV; // Convert from BGR to HSV colorspac...
You don't need to set the threshold for the v channel. Just play with hue and saturation The HSV color space represents colors using three values Hue : This channel encodes color color information. Hue can be thought of an angle where 0 degree corresponds to the red color, 120 degrees corresponds to the green color, an...
64,442,442
64,445,044
C++ "for" loop condition in python
Is there a one-line way to translate this "for" loop from C++ to python? for(int i = 0; i < = 10 && i != 6; i++) I mean in C++ we have : for(initial_value; condition(s); step) and I am looking for the analogue version in Python where we can impose one or several conditions.
Probably the simplest Pythonic articulation is for i in range(11): if i == 6: continue ... stuff happens ...
64,442,518
64,442,784
C++ - Unable to get prefixed uint16_t header
Here is how I form up my message with FlatBuffers and how I send it over via Boost ASIO. enum ServerOpcode : uint16_t{ SMSG_AUTH_CONNECTION_RESPONSE = 0x001, SMSG_LOGIN_REQUEST = 0x002, SMSG_LOGIN_REQUEST_RESPONSE_TEST = 0xA99, }; ServerOpcod...
There is a mistake in your 'copy step', you are copying from source to target. (The compiler might actually notify you of that). If you change your memcpy to std::memcpy(&_packet.headerCode, &_packet.header_buffer[0], sizeof (_packet.headerCode));, it should start working.
64,442,541
64,471,478
Reading UTF-8 file, passing contents to other application using SendInput
I have a utf-8 formatted file that contains a character 'ů', when I read it in c++ using ifstream and cout it, the output is '┼»'. I can solve it by adding 'SetConsoleOutputCP( 65001 );', afterwards Im sending the char using 'SendInput();' to another window. But because the SetConsoleOutput() doesnt affect SendInput() ...
You need to convert the UTF-8 data to UTF-16 first, such as with MultiByteToWideChar() or equivalent, and then you can pass the individual UTF-16 codeunits to SendInput() using the KEYEVENTF_UNICODE flag. See my answer to Sending Two or more chars using SendInput for an example of sending UTF-16 strings with SendInput(...
64,442,578
64,460,588
How to link libnode.a to a shared library in linux
I'm porting a large C++ code from windows to linux. One part consists of a few shared libraries that contain node addons. My code compiles fine, but I get thousands of errors when linking to node. I recompiled node adding the -fPIC flag in the common.gypi file. In the Release section I added 'cflags': [ '-O3', '-fPIC' ...
The answer was (as @Botje suggested) to build node as a shared library. I had tried to compile a shared library modifying the common.gypi file, which has a variable defining the type of output, but that did not work. There is no information in the documentation about how to compile node as a shared library either. This...
64,442,708
64,442,808
Error: member - "Graph::V" is not a type name
#include <bits/stdc++.h> using namespace std; class Graph { int V; public: Graph(int V) { this->V = V; } vector<list<int>> adj_list(V); void add_edge(int u, int v) { adj_list[u].push_back(v); adj_list[v].push_back(u); } }; I am trying to make an adjacency lis...
You can't magically resize as you're attempting. the adj_list member should be in the initialization list and properly constructed: class Graph{ int V; std::vector<std::list<int>> adj_list; public: Graph(int v) : V(v) , adj_list(v) // <<===== here { } void add_edge(int...
64,442,785
64,443,075
C++ is there an existing no-op function (or syntax) that takes any number of arguments? (for iterating over a parameter pack)
Is there and existing function (or syntax) like: inline void noop(...) { /* EMPTY */ } so I can do things like: template <class... T> void foo(T... args) { noop( do_side_effect<T>(args)... ); } ------------- edit ----------- because something like this can not be compiled: template <class... T> void foo(T... args...
No, there's no such standard function. We'd need to ensure no expression coming out of the pack has a void type. And since the evaluation of function arguments is indeterminately sequenced with respect to each other, the use case becomes even more niche, because there's no way to enforce an order, whereas an ordered ap...
64,442,933
64,443,310
constructing a std::function object from a type with a variadic template constructor
I have a templated class which instantiates an internal object of the template type and its constructor forwards the arguments to the internal object. template<typename T> struct B { template<typename... Args> B(Args&&... args) : m(std::forward<Args>(args)...) {} B(const B& b) = default; B(B&& b) n...
The instantion of template<typename... Args> B(Args&&... args) with Args... == B& is a better match for copying a non-const lvalue B than either your copy or move constructor. Instantiating that is like B(B& args) : m(args) {} which uses A::A(B&) You could either add an overload B(B&) = default;, or add some SFINAE t...
64,443,239
64,456,476
a constant in dependent base class make out-of-line definition not matched?
template<template<typename, size_t>class V, typename, size_t N> struct X{ static constexpr size_t stride = N; }; template<typename Num, size_t N> struct Y; template<typename Num> struct Y<Num, 3> : protected X<Y, Num, 3>{ using X<Y, Num, 3>::stride; Y<Num, stride> foo(Num angle, Y<Num, stride> axis) const...
This is, ominously, CWG2, a lack of specification in the standard whose filing date has literally been forgotten. That said, your option #2 seems clearly the correct choice, since it names the same using-declaration as the declaration in the class.
64,443,556
64,443,909
Modern C++ approach for providing optional arguments
Let's take the following function declaration: void print(SomeType const* i); Here, the const* nature of the argument i suggest the intent, that the parameter is optional, since it may be nullptr. If this was not intended, the argument would instead just be a const&. Communicating optional-semantics were certainly not...
Accepting a raw pointer is perfectly fine and is still done in plenty of "modern" codebases (which I'll note is a fast-moving target). Just put a comment on the function saying that it's allowed to be null and whether the function holds a copy of the pointer after the call (i.e. what are the lifetime requirements for ...
64,444,104
64,444,375
Difference between Nlohmann Json "array" and "array_t"
How is nlohmann array_t different from Nlohmann json array? How is array_t actually used? The documentation for each is as follows. array Creates a JSON array value from a given initializer list. That is, given a list of values a, b, c, creates the JSON value [a, b, c]. If the initializer list is empty, the empty arr...
json::array is a static function that converts an initializer list into a json value with internal type value_t::array. array_t is defined as follows: using array_t = ArrayType<basic_json, AllocatorType<basic_json>>; where ArrayType is a template template parameter to basic_json: template<template<typename U, typename...
64,445,013
64,445,040
How to manipulate query value output?
Suppose in an SQLite table the data in a row is 1. I need to display on my GUI that 1 as an YES. How to achieve that? This is my code: QString name = ui->comboBox->currentText(); QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "conn_name"); db.setDatabaseName("/usr/share/SGLogs/"+name); db.open(); if (db.open()...
You would use a case expression to transcode the value of your column. Assuming that the concerned column is col in table mytable, you would do: select t.*, case when col = 1 then 'YES' else 'NO' end as new_col from mytable t
64,445,485
64,446,021
Does asio::ip::tcp::resolver::async_resolve need to be external canceled?
I use the function async_resolve() using tcp = boost::asio::ip::tcp; namespace asio = boost::asio; template <class Request, class Response> class HttpsClient : public std::enable_shared_from_this<HttpsClient<Request, Response>> { mutable asio::io_context::strand m_strand; tcp::resolver m_res...
I'd have more high-level timeout that will cancel any DNS request as well as other IO operations when they fail to complete in timely fashion. After all, it's only marginally interesting to know the difference, and a DNS resolution is usually a step in a sequential IO chain that represents something like "lookup, conne...
64,445,818
64,446,224
Trying to figure out how c++ manages memory with objects
I'm trying to understand how pointers allocate memory in c++. This is my node struct template <datatype T> struct Node { Node* next; Node* prev; T data; } If I did this: Node<someObj> *temp = new Node<someObj>; The node would be created on the heap, but what about the data object? Does that ge...
The node would be created on the heap, but what about the data object? Well, data a member of Node. It is embedded in the object. When using new, you are allocating memory. But... how much? Try this: std::cout << sizeof(Node<int>) << std::endl; It most likely print 24. Why? Well, on a 64 bit system, those pointer ar...
64,446,832
64,458,849
boost.asio how to avoid two clients to connect same server at same port
my server code is as follows: #include <bits/stdc++.h> #include <boost/asio.hpp> #include <boost/array.hpp> #include <boost/asio/socket_base.hpp> using namespace std; using boost::asio::ip::tcp; using namespace boost::asio; using namespace boost; int main(int argc, char* argv[]) { io_service iosev; ip::tcp::ac...
Your server is handling the first connection when the second one comes in. Though the second connection is accepted by the network layers in the operating system your program isn't available to handle it. That is why network servers must be made so they can handle multiple requests at the same time, for example by crea...
64,447,158
64,447,422
Why function pointer of overloaded function need static_cast?
For the below code, I get the error #include <iostream> #include <functional> using namespace std; class A {}; class B {}; namespace N { void func(A a, int z){} void func(B a, int z){} } void func_1(std::function<void(A, int)> x) { A a; x(a, 1); } int main() { func_1(N::func); return 0...
std::function<void(A, int)> is more complicated than void(*)(A, int). template< class F > function( F f ); Initializes the target with std::move(f). If f is a null pointer to function or null pointer to member, *this will be empty after the call. This constructor does not participate in overload resolution unless f i...
64,447,376
64,447,512
Why does a friend operator require const-ness on its operands while a member operator does not?
This may be related to the fact that taking references to temporary objects is allowed only in some situations, but I'm not sure how this rule applies. In this example, the compiler stops at line a + b + c because a + b returns an Int, to which a reference must be taken in order to evaluate (a+b) + c. According to what...
In the first case, the code is effectively equivalent to: operator+(operator+(a, b), c); Here, the expression operator+(a, b) is an rvalue, which cannot be bound to a non-const lvalue reference. In the second case, we have: a.operator+(b).operator+(c); There is no such problem, since only lvalues b and c are bound to...
64,447,446
64,448,440
How do I make a 2 point corner with a rectangle and keep the right thickness?
I'm trying to draw a dialog box with sfml and I'm using a VertexArray with quads. I want it to have a corner with 2 points like in this image: Could someone help me with the math on how to get the length of A? Or maybe someone has a suggestion to do it in a different way in sfml?
What you are seeking is called the miter angle. And the miter angle is just half of the corner angle. See this interactive diagram (at Geogebra) By trigonometry, the ratio A/Th = TAN(angle/2). A = Th * TAN(22.5)
64,447,590
64,448,073
Error when writing from file into pointer of string array (read access violation)? CPP
For a problem, I have to use dynamic allocation and functions (using pointer variables only) to read the names from the .txt file and sort the names in lexical order. However, I cannot even get the read function to work properly. This is what it wrote: void readNames(std::string* a[]) { std::ifstream fin; fin....
To elaborate on WhozCraig's comment, let us assume the following: names resides on the stack, so we give it address 0x7f001000. The array of strings you allocates resides on the heap, so we give it address 0x1000 You assigned that address to names, so address 0x7f001000 contains the value 0x1000. Inside readNames, a ...
64,447,628
64,447,646
"No match for operator>" when using priority queue in C++
#include<bits/stdc++.h> using namespace std; struct vert { int n,m; vert(int Node1=0,int Node2=0) { n=Node1,m=Node2; } bool operator<(vert const &obj) { return m<obj.m; } }; int main() { priority_queue<vert> q; q.push(vert(1,2)); } when I run this code, I get t...
As the error message says, use const. Try this bool operator<(vert const &obj) const
64,447,771
64,447,872
Why use the "new" operator?
The code below is an example that was used to demonstrate some logic in C++ int *p = new int; *p = 5; cout << *p << endl; delete p;
In this particular example, there is no reason for dynamic allocation (which is what new provides). It looks like a toy example to show how you would dynamically allocate, set, print, then delete an int. In reality, you wouldn't do this unless you had a more complex type to create, or you really needed the int to be sh...
64,447,931
64,448,107
C++: array1 = array2 vs using a loop to assign values of array2 to array1
I'm looking for someone to correct my understanding of pointers and arrays. Say I have two arrays: int* array1 = new int[10]; int* array2 = new int[10]{ 1,2,3,4,5,6,7,8,9,10 }; When I do array1 = array2 I get the following address values: array1: 0000027964C831D0 array2: 0000027964C831D0 &array1[0]: 0000027964C831D0 &...
Pointers are addresses. Think of them as pieces of paper with a house address written on them. int* array = new int[10]; is building a row of 10 houses (new int[10]), then writing down where those houses are and storing the address in array. Saying array is an array is a problem that will confuse you. It is mistakin...
64,448,328
64,448,936
Is `new` in `new int;` considered an operator?
The expression new int; such as in int * x = new int; is a new expression. The term "new operator" seems to be used interchangeably with "new expression", for example in this question : Difference between 'new operator' and 'operator new'? Is it correct to say that the keyword new as it is used in a new expression is a...
new in new int is not considered to be an operator. It is also not considered to be not an operator. The C++ standard is really vague, and even inconsistent, about what constitutes an 'operator'. When listing operators (as defined during lexing and preprocessing), it lists them along with "punctuators" (things like (),...
64,448,481
64,478,098
How convert QNetworkCookie to QString?
I am trying to convert QNetworkCookie to QString but I can't find a way how to do this. For example, I've tried to do something like this QString cookie = QVariant(cookies_[i]).toString(); and this QString cookie = (QString*)cookies_[i]; Nothing worked.
As @Aditya told, QNetworkCookie::value() works as QByteArray. So, problem solvetion for me is: auto cookie = reply->manager()->cookieJar()->cookiesForUrl(webReportsUrl);//).value(0); cookies = cookie[0].name() + "=" + cookie[0].value() + "; domain=" + cookie[0].domain() + "; path=" + cookie[0].path(); qDebug() << "Cook...
64,448,592
64,448,642
strcpy: array memory questions
I'm trying to learn C++ using the book "C++ for Lazy Programmers" and it gives the function myStrcpy for copying two strings (page 306), which I used in this little example: #include <iostream> void myStrcpy(char* destination, const char* source); int main() { char ca1[] = "this"; char ca2[] = " is a test of ...
You're copying from ca2 - where the text " is a test of this." is - into ca1 - which currently stores "this" and therefore has been sized for four characters plus a NUL terminator. There's not enough room to copy into. You should make ca bigger than whatever you want to copy into it, e.g. char ca1[128] = "this"; Mor...
64,448,779
64,449,719
Is modifying the internal bytes of a const object undefined behavior in case it contains another object constructed by placement new?
Consider the following example: #include <new> struct FunctionObject { int operator()() // non-const, modifies the state of this object { i += 1; j += 2; return i + j; } int i = 0; int j = 0; }; struct Wrapper { explicit Wrapper(const FunctionObject& input_object) ...
This is Undefined Behavior. From [dcl.type.cv], Any attempt to modify a const object during its lifetime results in undefined behavior. Adding the mutable specifier to buffer will allow it to be modified by a const member function.
64,449,078
64,450,379
C++ keyboard hook - what does the parameter nCode mean?
I am looking to write a keyboard hook for a c++ project. I found some code but dont want to use it without fully understanding it: HHOOK _hook; KBDLLHOOKSTRUCT kbdStruct; LRESULT __stdcall HookCallback(int ncode, WPARAM wParam, LPARAM lparam) { if(ncode>=HC_ACTION) { if((wParam == WM_KEYDOWN) || (wParam...
In a nutshell, nCode tells you whether the wParam and lParam contain valid data or not. If nCode is HC_ACTION (0), then they do, otherwise they do not. This is clearly stated in the documentation: nCode [in] Type: int A code the hook procedure uses to determine how to process the message. If nCode is less than zero...
64,449,180
64,449,275
clang: warning: argument unused during compilation: '-rdynamic'
I tried to use -rdynamic option in my CMakeLists.txt file, like this: cmake_minimum_required(VERSION 3.5) project(Tmuduo CXX) ... set(CMAKE_CXX_STANDARD 11) set(THREADS_PREFER_PTHREAD_FLAG ON) find_package(Threads REQUIRED) if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") add_compile_options(-Wthread-safety ) endif...
Because -rdynamic is a linker option, so if you use when compiling a source file into an object *.o it does nothing, there is no link phase here. When linking all the *.o and libraries into the finally executable, then it is actually used. From man gcc (but clang uses the same): -rdynamic Pass the fl...
64,449,616
64,449,663
unsigned long long(10) fails to compile on clang and gcc
The following code is rejected by both clang and gcc but accepted by msvc: #include <iostream> int main() { std::cout << unsigned long long(10); } The error is error: expected primary-expression before 'unsigned' godbolt This should compile, right?
No, what you have shown should NOT compile. See Explicit type conversions on cppreference.com for details. In a function-style cast, spaces are not allowed in the type name. For such types, you would need to use a C-style or C++-style cast instead, eg: std::cout << ((unsigned long long)10); or std::cout << static_cas...
64,449,856
64,460,264
Reimplement 3rd party non-virtual function
I'm wondering if there is a way how to reimplement a non-virtual function foo in a 3rd party class Base. The motivation is that I just need to append a callback into foo. However, the function is called from many places of the class Base, and since it is not virtual, it would require to either change the Base in place,...
To sum up, it depends on one's requirements on his/her project. In standard C++, it is impossible. Period. The question lacks more detailed requirements, so the techniques proposed by @Anonymous1847 and @ajm - patching/hooking - actually answer my question properly. However, I am rather looking for a standard, portabl...
64,449,871
64,449,990
How to check if an array is filled with zeros in C++
So, I have an array in C++ of length n and I want to know if it contains at least one positive number. I know for sure that the array contains only non-negative numbers. I know how to do that but I wonder if there's a more efficient or prettier method than for-loop over the array. I have something like this: bool is_em...
If you don't want to use a for loop, use a standard algorithm instead, for example: std::find_if() #include <algorithm> int arr[] = ...; int n = ...; auto end = arr + n; if (std::find_if(arr, end, [](int i){ return i > 0; }) != end) { ... } std::any_of() #include <algorithm> int arr[] = ...; int n = ...; if (s...
64,450,451
64,451,129
How can I get the internal error message to log?
I'm using perror: perror("Error message:"); When the above is used it displays the message passed to the string followed by the actual error that occurred. This is a standard function, however I want to log this to a file, how to I get the actual error that goes with this so I can log it?
You can use the code below: #include <stdio.h> #include <stdlib.h> #include <errno.h> int main() { FILE* filePtr; filePtr = fopen (logFilePath, "a"); //... //some code //... if(critical_part){ fprintf(filePtr, "errno :%s Error in critical part - line 123\n",strerror(errno)); ...
64,450,537
64,450,962
How to resolve this problems with move semantics
Here is my sample code: #include <iostream> template <class T> struct Message { public: T data; Message(const T& data) { this->data = data; }; Message(T&& data) { this->data = std::move(data); } }; template <typename T> class Store { public: Store() { segment_ = nullp...
Well, the error is caused at the compilation of the class Message<MoveOnlyExample>. When you write: T data; ... Message(T&& data) { this->data = std::move(data); } The compiler has to first default construct the data member and only then use the move assignment. If you want to use a move constructor, you must use ...
64,450,564
64,450,607
Is there an std::variant that holds all variants
I am looking for a class that is like std::variant that holds all types instead of one of the types. So I would like to be able to write: std::all_variant<int, double> av{1, 3.14159}; int i = std::get<int>(av); // i should be 1. double d = std::get<double>(av); // d should be 3.14159 This is basically a tuple but guar...
I am looking for a class that is like std::variant that holds all types instead of one of the types. What you are looking for is called std::tuple std::tuple<int,double> mytup( 1, 2.0 ); std::cout << std::get<int>( mytup ) << "\n"; // prints 1 std::cout << std::get<double>( mytup ) << "\n"; // prints 2 std::cout << s...
64,450,655
64,452,482
Window created with WINAPI is not drawing objects. What's the problem?
I have my window file (Window.h): LRESULT CALLBACK MessageHandler(HWND, UINT, WPARAM, LPARAM); class Window { private: HWND hWnd; HINSTANCE hInstance; bool running = true; const char* ID = "WINAPI_JVM64"; public: Window() { init(); } virtual void draw(Gdiplus::Graphics*) = 0; ...
Your drawing logic is in the wrong place. It needs to be inside the MessageHandler when processing a WM_PAINT message. PeekMessage() will generate a WM_PAINT message if the window needs to be drawn and no other messages are pending. You can't draw on the window from outside of a WM_PAINT handler. Also, you are assig...
64,450,951
64,450,989
Does access to int via pointer to unsigned long long cause UB?
int a; auto *pa = reinterpret_cast<unsigned long long*>(&a); *pa = 10; int and unsigned long long types have different size. Does this code produce undefined behaviour?
Does access to int via pointer to unsigned long long cause UB? Yes. The behaviour of the program is undefined. int and unsigned long long types have different size. The behaviour would be undefined even if the sizes were the same.
64,451,056
64,451,311
Unable to ignore the escape characters from a text file stream & store in a wchar_t [ ] in C++
I am trying to read data from a text file using C++ & store the strings at each line into wchar_t [] or LPCWSTR. (These 2 datatypes are the constraints of the application on which I am working. That's why I have to store the data in these datatypes) The format of data in the .txt file is, for example: abc\\def\\ghi 10 ...
Miles Budnek already stated your problems. If you look at the documentation of your function (http://www.cplusplus.com/reference/cstdlib/mbstowcs/), you will see that the third parameter does not expect the number of bytes to translate to wchar_t, but much rather the maximum number of characters the buffer you are poin...
64,451,157
66,412,866
VSCode - cannot enter input into console while debugging C++
I know this was asked many times before, but none of the solutions have worked for me. I am trying to debug a single C++ file on Visual Studio Code on Windows. Running and debugging works fine. However, when I try to debug a program that asks for user input (for example using cin or scanf()), the process starts and jus...
Reinstalling MinGW seems to have solved the issue for me. I used the installer from it's SourceForge page. I do not know what original the issue was, but now it is possible to type into the terminal when in debug mode. I suspect the issue was with my gdb installation.
64,451,190
64,451,651
Using Struct Members As Array, The Portable Way?
I have the following struct (lets take this case with 1 type as a simple case): struct Vector { double x_, y_, z_; }; According to C/C++ Pointer to a POD struct also points to the 1st struct member it seems that, in general, given there is no padding, you can write something like this: int main() { Vector v{ ...
Regardless of the memory layout of your struct, pointer arithmetic forbids this strategy. The relevant rule in this case is (link) : The built-in subscript expression E1[E2] is exactly identical to the expression *(E1 + E2) [except evaluation order (since C++17)], that is, the pointer operand (which may be a result of...
64,451,457
64,451,641
Segmentation error while calculating partial derivative
I am trying to calculate the partial derivatives of the function f(x,y)=x+y w.r.t x and y at the point (3, 2). I wrote the code but it is giving me an error called Segmentation fault (core dumped). I don't what that is. Can anyone please point out what is wrong in this? #include<iostream> #include<cmath> #include<vecto...
In your constructor your vector df is empty but you attempt to put values into the vector using this -> df[i-1] = v->at(i); This will result in undefined behavior because you are accessing outside the bounds of the empty vector. One way to fix is to replace that line with this: df.push_back(v->at(i)); which will incr...
64,451,647
64,451,704
Static constexpr member of a template class different for each instance?
I was under the impression that static members of a class share their value between all instances of that class. My understanding seems to be lacking though, perhaps because of the inclusion of templates or constexpr in this example: #include <iostream> #include <array> template <typename T, std::size_t maxSize> class...
Foo<int, 10> and Foo<int, 12> are different classes - they just share the same template. All instances of Foo<int, 10> will share the same containerLen, as will all instances of Foo<int, 12>; but the two classes will not share a common value.
64,451,802
64,451,903
C++17 can the 'new' operator still leak memory?
I'm working on a project, and need a char buffer to send a struct over a network. I was using: char* buf = new char[sizeof(obj)]; Later, someone told me that I would be leaking memory if I did it that way without deleting. I debugged my program with Visual Studio 2017 Professional, and my memory sat constant, no matte...
Calling new[] without delete[] will indeed leak memory. You might not see it unless you are leaking lots of buffers, depending on how your app's RTL allocates/caches memory under the hood. Traditionally, using a std::vector<char>, or even a std::string, is the preferred choice for dynamic buffers, let them handle thei...
64,451,806
64,457,641
(VC 2019) C++ return statement ignored in release configuration, works fine in debug
I have this simple piece of code: #include <iostream> #include <vector> bool sequence_increase(std::vector<int>& sequence, const int& index) { if (index >= sequence.size()) return true; if (sequence[sequence.size() - index - 1] < 2 * index) { sequence[sequence.size() - index - 1]++; return fals...
The issue is that you have never return a value under else { sequence[sequence.size() - index - 1] = 0; sequence_increase(sequence, index + 1); } Since Release mode performs a logical process under that, you have to return sequence_increase(sequence, index + 1); just as Johnny Mopp said(thanks to ...
64,451,861
64,454,030
Unable to compile R packages in Ubuntu Conda environment: x86_64-conda-linux-gnu-c++: not found
I'm running Miniconda3 on Ubuntu 20.04 LTS OS and have installed R-4.0.3 in a conda environment. When I try to install packages from CRAN repositoriesvia R prompt, I get a x86_64-conda-linux-gnu-c++: not found I have run source activate qwe (qwe is the name of the environment) as advised in Anaconda documentation on b...
If you have R in a Conda environment, I would strongly recommend avoiding installs through utils::install.packages. Instead, install through Conda. Many CRAN packages are available through the Conda Forge channel, usually with an "r-" prepended to the package name. So, try conda install -n qwe -c conda-forge r-bayesem ...
64,452,233
64,452,269
Why i cant add "\n" in c++ cout statement . and what is
On the last line in the code below, the compiler give me an error on the "\n": ERROR expected ';' before string constant #include <iostream> using namespace std; int main() { int num1; double num2; cout << "enter the inetger: \n"; cin>>num1; cout<<"enter the float: \n"; cin>>num2; cout<<"...
you have to use << to concatenate like cout<<"integer:""\t"<<num1<<" and float:""\t"<<num2<<"\n"; or better use cout<<"integer:""\t"<<num1<<" and float:""\t"<<num2<<endl;
64,452,244
64,452,526
C/C++: How should preprocessor directive work on macros argument list?
Both C and C++ standards specify the following: 16.3.1 Argument substitution (C++11) 6.10.3.1 Argument substitution (C11) After the arguments for the invocation of a function-like macro have been identified, argument substitution takes place. A parameter in the replacement list, unless preceded by a # or ## preprocess...
First, you cannot, at all, put preprocessing directives inside the arguments to a function-like macro, because of some text a little down from what you quoted: If there are sequences of preprocessing tokens within the list of arguments that would otherwise act as preprocessing directives, the behavior is undefined. [...
64,452,423
64,453,255
Updating Armadillo on Ubuntu 20.04
I currently have Armadillo 9.900.4 installed on my machine with Ubuntu 20.04. I have downloaded 10.1.0 and ran cmake . and sudo make install and when I recompile my code and run it it says it was compiled with 9.900.4. Am I do something wrong? Is there a way to fully remove armadillo and reinstall? Thank you
That is the drawback of using make install to install something. It circumvents your distro package manager and then you have to manually clean/upgrade what you have installed like that. It's also up to the creator of the library what the install make target actually does. Some libraries also create a "uninstall" targe...
64,452,893
64,471,491
pcl::EuclideanClusterExtraction vs pcl::Kmeans
In the PCL tutorial, we can learn how to segment a plane and extract the Euclidean cluster point clouds. So now, after I used the pcl::EuclideanClusterExtraction algorithm. I need the centroid or the mean position of each cluster. Using pcl::EuclideanClusterExtraction I need to calculate the centroid with the for loops...
These are two very different algorithms: k-means clustering iteratively finds spherical clusters of points (usually high-dimensional), where cluster affinity is based on a distance to the cluster center. From a math point of view: it chooses centroids that will minimize the squared distances of cluster points to the c...
64,452,987
64,453,186
How to convert QString to std::chrono
I have a task to make a function, which will convert time objects (QString type) to std::chrono::milliseconds. The format, which should be processed is QString("HH:MM:SS DD-MM-YYYY") to std::chrono::milliseconds I searched for answers before here Stack Overflow, and in other sources in google. In result, I have writte...
Why do I have to subtract chronoUserTime - chronoEpochTime instead of using chronoUserTime ? chronoUserTime is a point in time, a time_point. milliseconds is a duration. A point in time is not a duration and vice versa. In order to convert a point in time to a duration you need a reference point in time and you've h...
64,453,283
64,453,360
C++: How can I pass keys and values into a constructor to make a map without copying the values of the map during construction?
Here is a minimal example where an object of type WrapMap contains an unordered_map. The only thing that will change in the map is the values, not the length and not the keys. However, I have found that each value passed into each pair is copied twice. By using move, it seems to have reduced the number of copies by 1 (...
emplace You can use the emplace member function of unordered_map: Inserts a new element into the container constructed in-place with the given args if there is no element with the key in the container. Careful use of emplace allows the new element to be constructed while avoiding unnecessary copy or move operations. T...
64,453,313
64,454,364
Is there a C++ equivalent to Javascripts Symbol()?
I'm porting some code over to a C++ application and I need the functionality of a Javascript Symbol to (efficiently) generate a unique ID and store it in an std::map. Is there anything like it?
There is nothing existing in the standard, but assuming that you do not need the full functionality of a JavaScript Symbol, but are only interested in the unique ID part, I would recommend to use a counter. #include <cstdint> #include <map> #include <string> template <typename T = uint64_t> class UniqueIdGenerator { p...
64,453,674
64,453,733
Correct way of initialing an array within a struct in C++
Assume this code: #include <iostream> struct test { int a[3]; float b[2]; }; I can init the array in both these ways: int main(){ test t = {{1,2,3}, {1.0,2.0}}; return 0; } or int main(){ test t = {1, 2, 3, 1.0, 2.0}; return 0; } How is the second approach even compiling? is the compiler picking each value an...
The second snippet is perfectly valid as described in aggregate initialization: The braces around the nested initializer lists may be elided (omitted), in which case as many initializer clauses as necessary are used to initialize every member or element of the corresponding subaggregate, and the subsequent initializer...
64,454,084
64,454,160
Avoiding temporary creation just for the sake of passing by value
Say I have to call code into an API that I do not own. Said code accepts some parameters by value only. Example: class PleaseUseReferences { void DoSometing(VectorFloat passedByValue); } on the calling side I have to now do either: PleaseUseReferences pus; pus.DoSometing(VectorFloat(0.0f,0.0f,0.0f)); or PleaseUse...
either way I end up with two constructor calls. One on the caller side and then another copy constructor for the argument that was passed by value. Not necessarily. For example: If the method body is available as part of the same translation unit, the entire call might be elided. If link-time optimization is enabled...
64,454,119
64,454,531
Prime integer multiplication table c++
I'm relatively new to c++ and coding and general and I was wondering how I would be able to produce a prime integer multiplication table up to 20. This is what I tried so far. #include <iostream> using namespace std; void table() { int var; for(int x = 1; x <= 20; x++) { for(int y = 1; y <= 20;y++) { ...
An easy method is to use a look up array or vector of the first 20 primes. This will reduce the complexity of trying to find primes. You can focus on the multiplication table instead. const int primes[] = {2, 3, 5, 7, 9, 11, 13, 17, 19, 23 /*, ... */}; for (int row = 0; row < sizeof(primes); ++row) { for (int col...
64,454,145
64,455,770
Confused as to why increment function doesn't actually increment variable
I've recently taken up learning C++ and have started watching an interesting video series from a game developer known as the Cherno. After learning about how pointers work, I decided to attempt learning how references work and in the video, he gave an example snippet of code that I'm kind of confused about. In my head,...
in this code snipped you declared a function with an argument passed to it by value: void increment(int value) { value++; } What it really does, it increments this value ... inside the function, and that is it. It does not return the value nor updates any other variable. There are several ways you can address the ...
64,454,216
64,454,256
What to do about this loop?
char restart = 'y'; while (restart == 'y') { cin >> restart; cout << "great keep playing\n"; } cout << "thanks for playing\n"; When I run this code it also displays the code outside of the loop as well, I even tried using a break statement but it didn`t work. How do I fix this?
The main issue I see is that you get the value of restart on the 'cin' line, then display 'great keep playing' on the next line, without first checking to see what the value of 'restart' is. You need an if() statement around the 'great keep playing' line, so it will only be displayed if you entered 'y'.
64,454,572
64,454,690
Using STL functions with a struct?
I've recently read up on STL functions in C++. I understand the basic uses of the functions, but I am struggling getting them to use member variables of a struct. I have this struct: struct Apples { double weight; // oz string color; // red or green void print() const { cout << color << ", " << weight << end...
std::count_if takes unary predicate as the third argument. In this case unary predicate is a function taking one object and returning true if object matches find criterion or false if not. Since your criterion depends on toFind, it seems more laconic to use lambda capturing toFind: int cnt = count_if(crate.begin(), cra...
64,454,700
64,455,056
Decrease the length of headers with help of target_include_directories
I have a project ├── CMakeLists.txt │   ├── log │   │   ├── CMakeLists.txt │   │   ├── include │   │   │   ├── log.h │   │   └── src │   │   ├── log.cpp │   └── main.cpp In log.cpp I am usng #include "../include/log.h" and in main.cpp I amd using #include "include/log.h" I want to use #include "log.h" I read tha...
define the target and then use the name as the first argument for target_include_directories add_library(log_lib log/src/log.cpp) target_include_directories(log_lib PUBLIC log/include) worry about INTERFACE vs PUBLIC vs PRIVATE after you've got it all working and you want to understand it better. (This option transiti...
64,455,245
64,455,943
How to write a static C++ library and link it to an executable using g++ on Windows 10?
main.cpp #include <iostream> int main() { std::cout << "main()" << std::endl; foo(); return 0; } foo.cpp #include <iostream> extern "C" { void foo() { std::cout << "bar" << std::endl; } } Compile static library: $ g++ foo.cpp -static Error: undefined reference to `WinMain' But this compiles:...
What follows are the magical incantations you seek: main.cpp #include <iostream> extern void foo(); int main() { std::cout << "main()" << std::endl; foo(); } foo.cpp #include <iostream> void foo() { std::cout << "bar" << std::endl; } Console commands: $ g++ -o foo.obj -c foo.cpp $ ar rcs foo.lib foo.o...
64,455,360
64,455,699
Omit void as function result in C++
In C/C++ there are two ways to declare a function that returns nothing. First one is to declare a function without arguments: // no arguments void f() { } The second one is to declare a function that takes void: // still no arguments void f(void) { } However, this is not true for the function result: we can't omit vo...
So, is there absolutely no way to omit void at the beginning of the function like with the function arguments? No, there absolutely isn't. There is no function declaration syntax that doesn't have the return type in C++ nor in C99 or later. There used in C prior to C99, but the default return type would have been int...
64,455,846
64,588,564
Linux Can't play sound at the begining of system start in an auto-start process using SDL_Mixer
I've used SDL2_Mixer to play sound on Linux Ubuntu 16.04. Here is my class code. bool SoundPlayer::init() { if (SDL_Init(SDL_INIT_AUDIO) < 0) { LOG(ERROR)<<"init failed.\n"; } LOG(INFO)<<"Speaker SDL init succeeded."; volume = DEFAULT_VOLUME; if(Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MI...
No one responds, but I got the solution. I was confused before because I didn't know what system did when I logged on ubuntu with teamviewer. Now I know, I just enter the desktop system with a user. I use SDL_GetAudioDeviceName(0,0) to show audio devices. Before I log in, it returned dummy output. After I log in, it re...
64,455,853
64,456,183
How do I use the std::find to find a set element with a struct member value?
struct Node{ int id; float x; float y; float z; Node(int newId,float newX,float newY,float newZ){id=newId;x=newX;y=newY;z=newZ;} bool operator<(const Node& rhs)const {return id < rhs.id;} }; set<Node> graph; Node a(1,2,3,4); Node b(2,1,2,3); Node c(3,4,5,6); graph.insert(a); graph.insert(b); gr...
What you are trying to use is set<Node>::find() rather than std::find(). You could easily do what you want with a function similar to std::find() - std::find_if(): auto iter = std::find_if( graph.begin(), graph.end(), [](const Node& node){return node.id==3;}); The problem with this solution is that std::find() and std...
64,456,253
65,557,420
Why DeviceIoControl sometimes not working (error=2)?
DISK_PERFORMANCE DiskPerformance = {0}; DWORD dwDiskInfoSize = 0; for (int i = 0; i < 10; i++) { std::printf("Try %d th Open \\\\.\\c:\n", i); HANDLE hDevice = CreateFile(L"\\\\.\\c:", 0, FILE_SHARE_READ | FILE_SHARE_WRITE, ...
The disk performance counters in Windows Server 2016 are turned off by default. You can run CMD as admin and enter diskperf -Y to enable the disk counter of the task manager.
64,456,300
64,456,655
C++ Calculator, Read Inputs with and without spaces
I am writing a calculator program. When I run my code, if I enter 1 + 2 as the input, it will run as it should and print the output. However, if I enter 1+2 the program will not print out the output. I want to make it so that I can enter the inputs with or without the spaces. Some examples of inputs I want to be able t...
You are using the first cin on a string. When you input 1+2 into the console the entire '1+2' will be treated as a string and be inputted. When you input 1 + 2 the temp variable will only take '1' as it's input, string is space separated. A quick fix could be changing your std::string temp to char temp and instead of i...
64,456,432
64,456,580
QT -> timer loop, would this cause a stack overflow
Would the following create a stack overflow? // reference elsewhere this->update(); void devices::Sprinkler::update(){ if(this->_state == devices::Sprinkler::State::ON) { ... QTimer::singleShot(this->_updateFrequency, this, SLOT(update())); } } I know that if it were update() { update(); ...
No, it does not cause a stack overflow, because the call is not recursive. QTimer::singleShot() schedules a call for execution at a later time, allowing update() to exit and clean up its stack frame before it is called again, thus reusing stack space.
64,456,480
64,456,542
How to know the value of a reference
I recently started learning C++ and I can't understand the following code (it's a copy constructor, deep copy): Car::Car(const Car &c){ this->_make = new string(*(c._make)); this->_model = new string(*(c._model)); this->_year = new int(*(c._year)); } Here, we are passing by reference so why are we adding the "*" here:...
You need * in this->_make = new string(*(c._make)); because make was defined as a pointer: class Car { string* make; //... }; This design is pointless - it would be better to hold string by value: class Car { string make; //... }; In which case the code in question would look like: Car::Car(const Car ...
64,456,940
64,457,091
how to access class private data members in method parameter of class , i get an error invalid use of non static data members
i have two classes Node and AvlTree , i will make other methods of AvlTree later but i can't access root data member of AvlTree in it's own class , how can i access root in AvlTree class inOrder method. My code is following here class Node { public: int key; Node* left; Node* right; ...
The short answer, as the compiler is telling you, is that you can't do that as a default value of an argument. The simplest approach would be to overload the inOrder() function, for example (within the definition of AvlTree) void inOrder(Node *itr) { // whatever } void inOrder() { inOrder(root...
64,457,060
64,457,268
How to read a file having multiple lines, line by line in C++?
I am trying to read a file having multiple lines, where each line has a word and then a space followed by a short description of the word. Example of the text file: hello A type of greeting clock A device which tells us the time . The fullstop (.) at the end represents that there are no more lines to read. I tried an...
You don’t need multiple loops, a single loop will suffice. Read a line, and then use a std::istringstream to split it as needed. Repeat for each line. For example: #include <iostream> #include <fstream> #include <sstream> #include <string> using namespace std; int main() { string filename = "text.txt"; ifstr...
64,457,588
64,457,645
How to pass by pointer a multidimentional vectors using pointers in C++?
I want to print the values of the multi-dimensional vector a using pass by pointer. Can anyone please let me know what is wrong in my program? I am getting a lot of errors. #include <iostream> #include <vector> using namespace std; class foo{ private: vector <int> v; public: foo(vector<vector <int> >*...
You are confusing some things here: vector<vector<int> >** is a pointer to a pointer of vector<vector<int> >. In foo f(&a); the expression &a is vector<vector<int> >* (pointer to vector of vectors of int) A reference would be vector<vector<int> > &. You would have foo like this: // Reference here VVV foo(vector<v...
64,457,889
64,458,830
Convert from one type to another based on input
I'm trying to create a proxy between two networks. I want to do something like: void onMsg(std::string topic, Msg msg) { if (topic == "topic1") { InMsg1 inmsg1 = parseMsg1<InMsg1>(msg); OutMsg1 outmsg1 = convert(inmsg1); publish<OutMsg1>(topic, outmsg1); } // repeat for each message type we need to c...
This is what std::variant is for: representing values of a known set of types. Your incoming message is an std::variant<mqtt::type1, mqtt::type2, ...>. Your outgoing message is an std::variant<ROS::type1, ROS::type2, ...>. Converting from one to the other should be done by std::visit. using Incoming = std::variant<t...
64,458,130
64,528,133
How to sort my list of most frequent 3-mers in ascending order?
I am writing a code to find out most frequent 3-mers in a DNA sequence. I wrote a code that counts the occurrence of a 3-mer and if it greater than 1 then code records both string and number of occurrences. This is giving me a list that is redundant in nature. I want to sort the list such that I only see each 3-mer onc...
Here's a reasonably fast way to do it in C #include <stdlib.h> #include <string.h> #include <stdio.h> typedef struct { char n_base[4]; int count; } NMer_3; typedef struct { int count; NMer_3 trimer[4 * 4 * 4]; } dict; int cmp(const void* a, const void* b) { return strncmp((char*)a, (char*)b, 3); ...
64,458,399
64,458,539
Can we assign a integer to a object?
I just wanted to know can we assign a integer value to a object directly. Here I just want to assign a rational value(22/7) to object x; #include<iostream> class rational { private: int num = 22, den = 7; public: void assign(rational x) { x = num / den; } }; int main() { ...
You can write a converting constructor and an assignment operator: class rational { public: rational (int val) { // initialize as you want } rational& operator= (int val) { // Assign as you want return *this } } But it's not at all clear what you're trying to do here. There are other proble...
64,458,960
64,464,971
Q_DECLARE_INTERFACE for plugin creation throws errors all over
Environment: Framework: Qt 5.12.9 Compiler: MSVC 15.9.28307.1234 (x64) Debugger: CDB 10.017763.132 (x64) Standard: C++11 Editor: Qt Creator 4.12.2 OS: Win10 Enterprise 1809 I want to develop an application that can be expanded through plug-ins. Therefore I created a standard library project where I want to define the...
I have found the issue. The problem is that the compiler couldn't find the macro, so all I had to add was: #include <QtPlugin> Since Q_DECLARE_INTERFACE is defined in QtPlugin. Your example didn't import QtPlugin but was probably imported implicit by another import, probably QMainWindow. It would have been simpler if ...
64,459,123
64,459,196
Canonicalizing the case of a word entered by the user
I am building a console bot. There is a way to specify the gender of the user there. Now if the user gives the command !setgender then the gender of the user will be asked by the bot. My question is the user can enter male, Male, mAle, maLe, malE ,mALE or any form of "male" the user wants (same goes for female and othe...
Transform the input to all lowercase, then the only valid input is "male" (shamelessly copied and adopted from here): #include <algorithm> #include <cctype> #include <string> #include <iostream> std::string data; std::cin >> data; std::transform(data.begin(), data.end(), data.begin(), [](unsigned char c){ return ...
64,459,521
64,460,064
What exactly is assigned by the `=` assigment to the new std::string?
I want to write a method that should trim a std::string's ongoing and trailing white spaces. For example, if the method gets " HELLO WORLD ", it should return "HELLO WORLD". Note, that between the return string is a white space, that is important. This is the signature of my method: std::string MyHandler::Trim(const ...
It's undefined behaviour to pass an iterator from toTrim to methods of toTrimCopy, so you are lucky that the type mismatch caught it. std::string::begin has two overloads: std::string::iterator std::string::begin(); std::string::const_iterator std::string::begin() const; The constness of the string participates in o...
64,459,598
64,471,407
What's the canonical way to use the fmtlib with wofstream
We're switching to the fmt library and aim to rewrite many wide character output stream based formattings. I found fmt::output_file which returns a class ostream : private detail::buffer<char> instance but it looks like there's no support for wchar_t. What's the canonical way to use the format library in wide character...
fmt/ostream.h provides an fmt::print overload that can write to wofstream: #include <fmt/ostream.h> #include <fstream> int main() { std::wofstream ofs("foo"); fmt::print(ofs, L"The answer is {}.\n", 42); } godbolt That said, I would recommend avoiding wchar_t if you care about portability and performance.
64,459,610
64,459,764
Why is T[] trivially copyable but not trivially destructible?
First of all, what is the correct term for T[] (not T[12] and not T*)? Second, if T is both trivially copyable and trivially destructible, why is T[] trivially copyable but not trivially destructible? I know it is for bounded arrays (T[12]). godbolt
First of all, what is the correct term for T[] It is an array of unknown bound (shortened to AOUB below). Why is T[] not trivially destructible? Standard (latest draft): [meta.unary.prop] Trait: is_­trivially_­destructible Condition: is_­destructible_­v is true and ... Trait: is_­destructible Condition: Either ...
64,459,722
64,459,950
Template deduction with derived templated class and smart pointers
Let's say I have a templated base class, and a templated class that derives from it: template <typename T> class Base {}; template <typename T> class Derived : public Base<T> {}; Further, I've got a function that wants to accept a shared pointer to any Base<T> or subclass, and be able to easily use the T parameter as...
You can use a template template parameter in your function, then a static_assert to enforce your requirement. #include <memory> #include <vector> template <typename T> class Base {}; template <typename T> class Derived : public Base<T> {}; template <typename T, template <typename> typename U> T DoSomething(std::shar...
64,461,244
64,461,636
Why is a name's point of declaration before its initializer?
Sayeth the C++ standard: The point of declaration for a name is immediately after its complete declarator and before its initializer (if any)... [basic.scope.pdecl] That is, a variable is in scope, and can be referred to, in the context of its own initialization expresion. As far as I can tell, you can do the followi...
its address isn't generally going to be important to its initialization. template <class T> struct Node { Node *prev, *next; std::optional<T> data; }; template <class T> struct List { Node<int> sentinel {&sentinel, &sentinel}; // methods ... }; This is a totally legitimate and useful initialisation of a...
64,461,299
64,474,434
in python, I use derived class of Base which is a Base class wrappered by SWIG, but failed with error info: argument 2 of type 'Base *'
// a.h class A { public: void register(Base*); } // a.cpp void A::register(Base* pBase) { pBase->run(); } // Base.h class Base { public: virtual void run()=0; } Then, I use SWIG 3.0 to wrapper this Class A's function register with module.i // module.i %module(directors=1) myModule %{ #include "a.h" #include "B...
Well, After reference to Wiki(http://www.swig.org/Doc1.3/Typemaps.html) I fixed it. I give a example as below: // a.cpp #include "a.h" void A::re(Base* pBase) { // pBase->run(); baseList.push_back(pBase); } void A::notifyrun() { vector<Base*>::iterator iter = baseList.begin(); for (; iter != baseList....
64,461,444
64,461,647
Is that the thread object can be moved in C++ 11 reasonable?
In C++11, the thread object can be moved. As we all know, every thread we created owns a functor. Obviously, to move a thread which its functor has not been executed is reasonable. But what about moving a thread of which functor is being called or has been executed for some time? To step further, if I implements a thre...
A std::thread does not formally own the functor it was constructed with. Rather, the functor is held by the invocation of std::invoke which is kicked off (in the target thread) by the constructor. So moving a std::thread doesn't need to, and isn't going to, move the functor. As long as the thread is executing, the func...
64,461,686
64,462,252
How to print two setfill() in same position
I'm trying to practice left and right justification with setfill() and setw() but I'm facing a problem: I cannot print out the ~ character with the - character. #include <iostream> #include <iomanip> #include <string> using namespace std; typedef struct kereta{ string brand, model; int year; float price; }...
You should think about output in parts. setw and other output manipulators sets parameters for the next stream's data. cout << left << setfill('*') << setw(10) << car[i].brand; cout << left << setfill('~') << setw(10) << car[i].model; cout << right << setfill('-') << setw(15) << car[i].year; cout << right << setfill('....
64,461,832
64,462,165
Templated template parameter U<T> does not recognize const qualifier
I was looking into the following piece of code (no real application, just out of curiosity): #include <memory> template <typename T> struct MyClass{}; template <template <class> class U, class T> void foo(std::shared_ptr<U<T>> t){ } template <class U> void bar(std::shared_ptr<U> t){ } int main() { std::...
It's a failure of template deduction. There's no combination of U and T to match std::shared_ptr<U<T>> from std::shared_ptr<const MyClass<int>>. const MyClass isn't a template. You can overload foo template <template <class> class U, class T> void foo(std::shared_ptr<const U<T>> t){ } template <template <class> class ...
64,462,437
64,462,590
Why clang missing default argument on parameter pack error?
When I use clang (10.0.1) to compile that: #include <iostream> template <typename ...Args> void f( int a = 4, Args&&... aArgs ) { std::cout << a << std::endl; } int main( int argc, char *argv[] ) { f( 1, 2 ); return 0; } I get: main.cpp:4:30: error: missing default argument on parameter 'aArgs' But stan...
Yes, it's a bug: https://bugs.llvm.org/show_bug.cgi?id=23029. It's fixed in clang 11: https://reviews.llvm.org/rGb5f2c4e45b8d54063051e6955cef0bbb7b6ab0f8
64,462,503
64,463,510
Unable to pass function pointer as function param
I would like to pass function pointer as a function parameter. Here is my code: void AuthServerOpcodes::ValidateAndSetServerOpcode(ServerOpcode serverOpcode, void(*handlerFunc(std::vector<std::byte> data))) {} Here is the function I would like to pass as second parameter in ValidateAndSetServerOpcode: void AuthServerO...
Pointers to member must be qualified with the class type, so you need to get the pointer you'll need to use ValidateAndSetServerOpcode(SMSG_LOGIN_REQUEST, &AuthServerOpcodes::Test); But it looks like you've tried that in the previous edit, so I guess you've called the function pointer to member incorrectly. You didn't...
64,462,637
64,463,045
JNI - How to get the Double.toString() method to convert a jdouble to a jstring
So I want to be able to convert a jdouble to a jstring using the inbuilt Double.toString() from c++. This is how I think I would do it. jdouble result; //Get the class for Double so we can get the method id of toString(). jclass doubleObjectClass = env->GetObjectClass("Ljava/lang/Double;"); //Get the Double.toString(...
You use GetObjectClass when you have access to concrete jobject. If you only have a class name, that is the FindClass function with the class' binary name. You are looking up a static method ID, so that is a different set of functions (GetStaticMethodID and CallStaticMethodID). Finally, the method signature must be cor...
64,462,814
64,610,732
NVidia NVML nvmlDeviceGetMemoryInfo() loads and unloads nvapi64.dll immediately
I use some NVIDIA Management Library features to produce metrics in my application. Every 1 second I call nvmlDeviceGetMemoryInfo() in a thread, and after a few minutes, in the output of Visual Studio, I can read hundreds of : 'MyApp.exe' (Win32): Loaded 'C:\Windows\System32\nvapi64.dll'. 'MyApp.exe' (Win32): Unloaded...
you can simply call LoadLibraryW(L"nvapi64.dll"); after this dll already will be not unloaded (RbMm) This did the trick
64,462,815
64,464,606
Reading a file that contains chinese characters (C++)
I got issues reading a file that contains chinese characters. I know that the encoding of the file is Big5. Here is my example file (test.txt), I can't include it here because of the chinese characters: https://gist.github.com/haruka98/974ca2c034ebd8fe7eeac4124739fc41 This is my minimal code example (main.cpp), the one...
First check you have the locale for "Chinese-traditional" installed. On Linux this is zh_TW.UTF-8. You can check using locale -a. If it's not listed, install it: sudo locale-gen zh_TW.UTF-8 sudo update-locale (There's a list of locales here with their names on Linux and Windows.) Then use imbue with the input and outp...
64,462,890
64,462,999
I'm trying to fill arr in c++ and show it to user. My code is working but, I get error when the program ask me to push any button
I'm trying to fill arr with numbers from -5 to 16 and show it in terminal, but when the task is done and "system("pause");" ask me to push any button to continue(in my language Для продолжения нажмите любую клавишу . . . ) I get error. It's my code: #include <iostream> #include <cstdlib> using namespace std; int main...
The definition int arr[21]; defines arr as an array of 21 integers. Both of your loops will use 22 elements of that array. The size used in array declarations is the number of elements in the array, not the top index. If you want an array of 22 elements, you should specify it as such: int arr[22]; But then you need t...
64,463,026
64,463,398
Using variables by reference
We have Myclass &funcref(); and Myclass func(); and assign the return value to a variable (not a variable reference). If I understand correctly we use the copy constructor in both cases. The only difference is that funcref() returns a reference, and we copy over what is refers to into our object, while in func(), we co...
If I understand correctly we use the copy constructor in both cases. Not quite. In C++11, move constructor will be used in case of Myclass func() (and compiler is allowed to optimise the copy / move away). Since C++17, there is neither move nor copy in case of Myclass func(). Is there any case in which those two wil...
64,463,343
64,464,036
Strange behaviour of integer overflow
I created the following code for finding the answer to the coin problem. This involves finding minimum number of coins of given k denominations (where each such coins are in infinite supply) to form a target sum n. In particular I have investigated the case where k=5, denominations = {2,3,4,5,6} and target sum n=100. C...
Here: values[x] = min(values[x],values[x-coins[j-1]]+1); For example, for x=3 and coins[0]=2, you add values[1] + 1. However, values[1] = INT_MAX. Then, you get an undefined behavior when performing this calculation. You can solve the issue with INF = INT_MAX - 1;
64,463,644
64,463,948
How do I find the average of the whole class?
#include <iostream> #include <fstream> #include <string> #include <iomanip> using namespace std; struct Students { char name[30]; char first_name[30]; int n1; int n2; int n3; }student list[10]; int n; void reading_student_list() { int i; ifstream f("in.txt"); f>>n; for(i=0;i<n;i...
Here's how you would add up all the n1 values (whatever that means). int total = 0; // start the total at zero for (int i = 0; i < n; i++) // for each student total += list[i].n1; // add list[i].n1 to total Hopefully you can adapt that to suit your particular requirements.
64,463,809
64,477,947
Why does sip complain about unexpected type 'str' when using a char *?
I am trying to use sip to create python bindings from c++ to python 3.8. I found a simple example here and updated it to get it working with sip version 5.4 which I installed with pip. Details can be found here I changed the names from word to basicword because I rewrote and tested the word example with strings. To do ...
In short Python2 uses str-type by default and python3 byte-type so I had to change default encoding for python3. I found the relevant detail here Encoding This string annotation specifies that the corresponding argument (which should be either char, const char, char * or const char *) refers to an encoded character o...
64,464,511
64,464,680
how can I achieve overloading in c++ as Number + Object?
I am trying to perform following operation, ABC a1; ABC a2=2+a1; I have tried using overloading using friend function ABC operator+(double h, ABC a){ return a+h; //consider this + to be overloaded } But it does not work. I don't know of any other way to do this, Please help!
class A { public: A(double x) : v{x} {} A add(const A& b) const { return v + b.v; } private: double v; }; A operator+(const A& a, const A& b) { return a.add(b); } int main() { A a{3}; auto x = 5 + a; auto y = a + 7; return 0; } https://godbolt.org/z/1TxWYE Note ...
64,464,819
64,465,121
VisualC – DLL Class Implemented in Header not Exported
Create a “Dynamic Linked Library with exports” project (Test.vcxproj). Replace the predefined class with the class below. Delete the implementation of predefined classes and #include "Test.h". Build. Drag the DLL in Dependency Walker -> Nothing is exported. The class is exported if you use the header, or implement the...
Referencing the header in the project file is a red herring. You can, indeed, exclude it from the base working example and everything still works. The actual files being processed are the .cpp files. DLL imports and exports are generated by the compiler (and later used by the linker) when encountering __declspec(dllimp...
64,465,779
64,468,375
Using C++17 to build ios apps?
The latest XCode clang has support for c++17 but I'm not sure if older iOS devices (e.g., iPhone5, iPhone6) would have the libc++ library to support that. Is there a way to find out if I can use C++17 to build ios apps that supports all supported iOS versions? Reference: iPhone5, with iOS12 is still supported https://s...
The answer is yes, to some extent. If you're back-deploying to older OSes, there are things from C++17 you'll be able to use, and others you won't be able to use. Just try using it and you'll get a compiler error if it's not available on your deployment target. This requires telling the compiler your deployment target,...
64,465,968
64,466,595
Openmp multithreaded code giving different answer when using multiple threads
I have the following monte carlo code with openmp multithreading int main() { std::uniform_int_distribution<int> dir(0, 1); std::uniform_int_distribution<int> xyz(0, 2); std::uniform_real_distribution<double> angle(0,360); mt19937 gen{0}; auto M = 20; long double sum = 0; auto num_trials = 10000; // om...
The issue is that you call the generators (dir and xyz) without a lock around them. You're also using the PRNG (gen) without locking. Neither of those calls is atomic, since implementing them as such by default would make single threaded code slower than it needs to be. Marking the lines to generate d and p with #pragm...
64,466,083
64,466,620
How to use libpqxx with qt creator
I use Ubuntu 18.04, Qt creator 4.5.2. I added in pro file: CONFIG += c++1z QMAKE_CXXFLAGS += -lpq -lpqxx Still got following error: /usr/local/include/pqxx/strconv.hxx:76: error: undefined reference to `pqxx::internal::demangle_type_name[abi:cxx11](char const*)'
-lpq -lpqxx are linker flags. The variable QMAKE_CXXFLAGS specifies compiler flags. Use the proper variable QMAKE_LIBS for specifying linker flags: LIBS += -lpq -lpqxx
64,466,214
64,466,673
What C++ design pattern is available for swapping behavior of a function template between production code and testing code?
I am refactoring a component to make it more unit testable. A first step is to enable unit testing for some core component code. Unfortunately, this core component code calls some in-component utility functions that directly interact with other components' concrete classes, which are hard to instantiate without the pro...
You can make your class template, something like: // myclass.hpp template <typename Utility> class MyClassT { public: bool canProcess(TheirClassA* a) const; bool canProcess(TheirClassB* b) const; }; class UtilityProd; // Class where you have your static methods using MyClass = MyClassT<UtilityProd>; // my...