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,551,872
68,551,918
Passing entire struct array to function
I'm learning C++ and graphics programming, and following a tutorial, but I can't seem to be able to find any solutions to this problem. This is the code: struct CUSTOMVERTEX { FLOAT X, Y, Z; DWORD COLOR; }; void writetovram(struct CUSTOMVERTEX *verticies) { ... memcpy(pVoid, verticies, sizeof(verticies)); ...
Inside of writetovram(), sizeof(verticies) doesn't return what you think it does. You can't get the size of an array from just a pointer. There are TONS of questions on StackOverflow on this issue. Your simplest option is to just pass the array size as another parameter, eg: struct CUSTOMVERTEX { FLOAT X, Y, Z; DWORD C...
68,552,304
68,560,999
Can't connect to Oat++ with other WebSocket libraries
Does Oat++ support the RFC 6455 WebSocket protocol? I tried to connect to an Oat++ WebSocket server from browsers by js, and from QWebSocket (qt), but they didn't connect.
To connect and test oat++ and other WS servers you may try using this online client: https://www.websocket.org/echo.html - for WSS http://www.websocket.org/echo.html - for WS Also, make sure to connect to a correct endpoint
68,552,551
68,552,791
Why does FOLDERID_ProgramFiles return "C:\Program Files (x86)"?
#include <Shlobj.h> #include <iostream> #include <string> std::string fun(REFKNOWNFOLDERID val) { ITEMIDLIST* pIDList; if (S_OK == SHGetKnownFolderIDList (val, 0, NULL, & pIDList)) { char cpath[MAX_PATH] = {0}; if (TRUE == SHGetPathFromIDList(pIDList, cpath)) return cpath; ...
This happens because you are compiling your application as a 32bit executable, even though you are running it on a 64bit system. So FOLDERID_ProgramFiles is mapping to the 32bit Program Files (x86) folder. This is especially evident by the fact that FOLDERID_ProgramFilesX64 is failing, per the KNOWNFOLDERID documentat...
68,552,698
68,553,042
Connecting QSignalMapper QT 5.15.2
I am trying to map two QPushButtons to the openLanguageDialog(QPushButton *button) function. I get the following errors: no matching member function for call to 'connect' candidate function not viable: no known conversion from 'void (QAbstractButton::*)(bool)' to 'const char *' for 2nd argument candidate function not ...
You have the following problems: There is a problem in the connection since the compiler cannot understand it since there are signal and slots overloads. Qt does not do any conversion (cast) even if the sender is a QPushButton object that inherits from QWidget. You should not make the connection many times The sol...
68,552,740
68,553,176
Problem with orthographic projection in OpenGL
So I'm pretty new to OpenGL I was trying to create orthographic projection and the problem is when I do glm::mat4 ortho; ortho = glm::ortho(-(float)WINDOW_WIDTH / 2.0f, (float)WINDOW_WIDTH / 2.0f, -(float)WINDOW_HEIGHT / 2.0f, (float)WINDOW_HEIGHT / 2.0f, -1.f, 1.f); It works just fine but the 0, 0 point is in the mi...
So what I have done wrong is in shader I have multiplied position by orth projection and not orth projection by position so do not do this: gl_Position = position * u_MVP; do that: gl_Position = u_MVP * position;
68,552,930
68,552,957
Is it possible to extract a struct containing fields that are unique/shared pointers from a set
so essentially I have a set of instances of struct A. I want to extract an instance, modify the fields. One of the fields is a unique ptr. I'm not that great at reading c++ errors, it looks like the field is deleted on extraction. I.e. the destructor of the unique pointer is called. Example: Here when I try to access t...
The node is not deleted on extraction, but shortly after, before you use it. Specifically, you don't save the node-handle .extract() returns, but directly get a reference to part of the node it manages. At the end of the full statement, that reference becomes dangling, as nobody keeps the node-handle owning it alive. T...
68,552,973
68,553,066
Parallel std::foreach loop calling a non-static class member function
I would like to use C++17 parallel std::foreach to iterate over an operation involving a non-static class member function. Basically, each object of the class has its own version of the data and a method acting on that data, and I would like to run the method in parallel over a sequence of values (which are inputs to t...
You need to pass an object to std::foreach that contains some reference to this XYZ. Otherwise, how will it know on which object to call that method? A lambda will do std::foreach(std::execution::par, std::begin(xvec_), std::end(xvec_), [&](double x) { add_to_m(x); }); Alternatively, std::bind_front works if you don't...
68,553,335
68,553,418
What is the difference between int{10} and 10?
As the title, I have two expressions: int&& a = const_cast<int&&>(int{10}); int&& a = const_cast<int&&>(10); The first compiling passed, but second not. Why is this happening? In my view, it's because 10 is a literal and int{10} is a unamed variable. Is it?
The only reason why your first conversion passed is a bug in g++. Neither code is legal, and both clang and icc reject it. They even give a good message: error: the operand of a const_cast to an rvalue reference type cannot be a non-class prvalue This does make sense, since both 10 and int{10} are prvalues, and you c...
68,553,603
68,553,628
Changing variables in namespaces
I want to declare an array inside a namespace, then from another file, define it, and from a third file, access it after it is defined. Can anyone help me? btw, i'm open to using either int[] or std::array. //name.h #pragma once namespace Info { int arr[2]; array<int, 2> arra; } //file1.cpp #include "name.h" ...
The code could look like this // header file namespace Info { extern int arr[2]; } // file1.cpp namespace Info { int arr[2] = { 2, 3 }; } Prepending the extern keyword makes it a declaration that is not a definition (it is not permitted to have multiple definitions). If you are OK with having the initialize...
68,555,347
68,555,574
two-dimension vector custom predicate greater function
I have a two-dimension vector like below. vector<vector<int>> vec = {{2,5}, {3, 4}, {0,1}, {1,2}} I want to sort this array based on the second element of each vec[i]. So the end result should be {{2,5},{3,4},{1,2}, {0,1}} I want to use something like sort(vec.begin(), vec.end(), secondGreater); bool secondGreater(v...
secondGreater is a member function. But you are trying to call it as if it were a free function with no associated object. Since it accesses no member variables, it doesn't need to be a member function, move it outside the class: bool secondGreater(vector<int> boxA, vector<int> boxB){ return boxA[1] > boxB[1]; } cl...
68,555,447
68,571,841
g++11 : getting rid of missing initializer for member 'A::<anonymous>'
I am about to release a code and I want no warnings in it. Currently running with -Wall -Wextra to hunt down everything I can. Now I have this example code (extremely contrived from the production code): // Type your code here, or load an example. #include <iostream> #include <vector> using namespace std; struct A { ...
For the question : "Are all my field initialized ?" Since all the fields have a default initialization The answer is: yes Source: https://en.cppreference.com/w/cpp/language/aggregate_initialization Section: Designated initializers Example: struct A { int x; int y; int z; }; A a{.y = 2, .x = 1}; // error; designator o...
68,555,547
68,555,731
what is the value of the expression involving bitwise operation in C++
On my machine, the following expression:- int main() { int q = 0b01110001; cout << q << endl; cout << (~q << 6); } prints the following :- 113 -7296 I have tried working it out assuming 16-bit integer, but my answer doesn't match the value obtained after the bitwise operations. Is it simply a case of unde...
You can check binary representation of an integer using bitset. Program : #include <iostream> #include <bitset> using namespace std; int main() { int q = 0b01110001; cout << q << "\n"; cout << bitset<(sizeof(int) * 8)>(q) << "\n"; cout << ~q << "\n"; cout << bitset<(sizeof(int) * 8)>(~q) << "\n"; ...
68,555,702
68,555,771
Passing a templated function as method argument without lambdas?
I did like to being able to use extFunction or std::max or std::min as argument for the square method without declaring a lambda : template<typename T> T extFunction(T a, T b) { return a; } class Stuff { public: template <typename F> int square(int num, int num2, F&& func) { return func(num, n...
You should not be taking the address of a standard library function. See in detail here: Can I take the address of a function defined in standard library? Therefore, there is no simple way other than, pack std::max into a function object(i.e. lambda, functor) or in a function.
68,555,772
68,556,049
Should we define variable with constexpr in a function
I don't know if it is meaningful to define a variable with constexpr in a function. void func() { static const int i = 1; } void func2() { constexpr const int i = 1; } static const in a function would be initialized on the first function call, how about constexpr in a function? I know that constexpr specifies that the...
There is an important difference. A static local variable is initialized on the first call, so that in subsequent calls its declaration is no longer used. In particular, the constructor of the static local variable is called only once. A static const is a static variable which is also a constant: thus, its value, once ...
68,556,057
68,559,502
Can std::chrono::from_stream convert string to time_point with microseconds accuracy?
TLDR: std::chrono::sys_time<std::chrono::microseconds> tTimePoint; std::istringstream stream("2020-09-16 22:00:00.123456"); std::chrono::from_stream(stream, "%Y-%m-%d %H:%M:%S", tTimePoint); I expected the code above to parse the .123456 as microseconds. However, when running this tTimePoint only contains the date an...
As far as I can see, VS2019 has a flaw when using from_stream and a time_point where subseconds are supposed to be used. There is a place in the VS2019 library where it is supposed to deal with it - but it never enters that case. Fortunately, it works if you use a duration instead of a time_point, so you can work aroun...
68,556,093
68,580,463
Can concept checking be delayed till class instantiation in C++?
A common practice to speed up compilation is to only declare classes instead of giving their full definitions, e.g. struct A; template<typename T> struct B; using C = B<A>; By if one likes to use C++20 concepts in template classes then the code as follows #include <concepts> struct A; template<std::destructible T> str...
This is how you forward declare. struct A; template<class T> struct B; using C = B<A>; keep this. In B.h: #include <concepts> template<class T> struct B; // or template<class T> struct B { static_assert( std::destructible<T> ); }; template<std::destructible T> struct B<T> { }; specialize. Leave the base B<T> und...
68,556,227
68,556,321
Allocation of a struct vector containing an array
Imagine a structure struct A { int i; int arr[1000]; }; std::vector<A> vec; I cannot find an answer to know if the array "arr" in my structure "A" will take up space on the stack or not at all. I these although the vector will allocate an array of "A" which will be on the heap and will not impact my stack but...
std::vector is one of AllocatorAwareContainers and default allocator use dynamic allocation (often called heap allocation, which is true for systems with heap-like memory model). When using those two std::vector<std::unique_ptr<A>> vec1; std::vector<A> vec2; both have own advantages and disadvantages. The vec1 offers ...
68,556,427
68,556,577
Why constexpr method can return correctly class members whose value change during execution?
I just discovered that a constexpr method can return correctly the value of a class member that changes during execution. My question is, how is this possible if constexpr methods are supposed to be evaluated completely at compile time? The example below correctly outputs Value: 0 and then Value: 5. Even more, if I cha...
In your example you're not even calling the constexpr function, you're calling get, which is not constexpr. However, constexpr functions can be evaluated at compile time, but also during run time if compile time evaluation is not possible. If you called value instead of get, it would still work and the function would b...
68,556,468
68,556,557
Use std::lock to protect return statement?
As I understood, std::lock locks section under its scope. But what if access to variable is performed in return statement? Example: // Looks safe... bool foo { std::lock_guard<decltype(myMutex)> tLock(myMutex); if (bar == 123) { return true; } else { return false; } } // Is ...
Destructor is called after the return, so you are fine in both cases.
68,556,995
68,557,127
fstream << a(0) << ...<<a(n) vs fstream << a(0); ... fstream <<a(n);
Given a number of variables containing data a(1) - a(n), what is the best way to write this data to a file using std::fstream and what are the differences? if I have an open std::fstream to a file do I use std::fstream << a(0) <<"\t" << << a(1) <<"\t" << ... << a(n) <<"\n"; or st...
std::fstream << a(0) <<"\t" << << a(1) <<"\t" << ... << a(n) <<"\n"; The return value of basic_ostream::operator<< is basic_ostream &. The above could be rewritten as: std::fstream.operator<<( a(0) ).operator<<( "\t" ).operator<<( a(1) )... i.e., a sequence of std::ostream.opera...
68,557,154
68,563,955
How to solve GMP C++ Installation, can not find ../libgmp.la problem on MAC OS X
I have downloaded GMP 6.2.1 from the link supplied from the website to my macos Big Sur, unzipped it. I runned the configure script and make check make install then realized I should have added --enable-cxx to ./configure --enable-cxx. I did that and rerun make check. Error I've got is libtool: warning: '-no-install'...
I followed the instructions from https://gmplib.org/manual/Installing-GMP correctly the first time but the second time I didn't run make before make check. Following the manual exactly solved my problem.
68,557,386
68,632,157
libbson help to read data into object C++
i have my unreal project that must read out some BSON document data into a map. right now i'm able to load that file and print it out with the following code : void AMyActor::BeginPlay() { Super::BeginPlay(); std::ifstream input( filePath , std::ios::binary ); std::vector<unsigned char> buffer(std::istream...
Breaking out nlohmann::json: using nlohmann::json; std::map<std::string, DatabaseBase> dictionaries; json input = json::from_bson(buffer); for (auto& obj : input["_dictionary"]) { auto name = obj["_classID"]; auto key = obj["_dictionary"][0]["v"][0]; auto idx = stoi(obj["_diction...
68,557,644
68,557,885
Stringizing / stringify name mangling
I load a path name with cmake add_definitions(-DMY_PATH =${CMAKE_INSTALL_FULL_DATADIR}/path) and want to use as a string in my C++ program to load some data. For this the stringification operator # is really handy - I use the macro provided in this answer which is the same as here. Now when I have "linux" or "unix" in...
why is this happening Macros unix and linux are legacy defined to 1 on UNIX platforms. Part of the program /path/x86-unix/linux/pat consists of tokens unix and linux, so as part of macro expansion in xstr these macros are substituted for 1. how I can prevent it? #undef linux and unix macros. Or disable gnu extensio...
68,557,714
68,571,838
Why does `std::set::extract` not support heterogeneous lookup as `std::set::find`?
#include <set> #include <string> #include <string_view> using namespace std::literals; int main() { auto coll = std::set<std::string, std::less<>>{"abc"s, "xyz"s}; coll.find("abc"sv); // ok coll.extract("abc"sv); // error } See online demo Why does std::set::extract not support heterogeneous lookup as...
The overloading of std::set::extract() in C++17 standard is as follows: node_type extract(const_iterator position); // (1) node_type extract(const key_type& x); // (2) Assume that the following overload exist here (it does not exist in C++17 standard): template<typename K> node_type extract(const K& x); ...
68,557,754
68,558,084
C++ - invalid conversion
The code shows an invalid conversion from int to *int how do I fix the problem ... the full detail of error is given below : Code: #include <iostream> using namespace std; bool isSafe(int** arr[], int x, int y, int n) { if (x > n && y > n && arr[x][y] == 1) { return true; } return false; } boo...
Passing c-arrays to functions is an oddity inherited from C. When you write void foo(T a[]); Then this is actually shorthand notation for void foo(T* a); Because arrays cannot be passed by value. They decay to a pointer to their first element when passed to functions. Hence, bool ratInmaze(int** arr[], int x, int y, ...
68,558,011
68,558,280
Why isn't this C funtion calculating sqrt working for decimals?
#include <iostream> float calculating_root(float N, float root_N, float increment) { int safety=1; while(safety==1) { if (N == (root_N*root_N)) { safety=0; return root_N; } else if(N<((root_N+increment)*(root_N+increment))) { saf...
Using == for comparing floating point numbers that you calculated is not advised. Especially in this case N might actually be a number that is not representable by any float a such that a*a == N. so instead of N == (root_N*root_N) try to use something like fabs(N-(root_N*root_N)) < epsilon Where epsilon is your accep...
68,559,346
68,559,469
C++ break variadic template parameter loop
is there a way break variadic template parameter loop early. For example, in the following code, I want to quit the process function after process b1 without calling ProcessInvoke function for the types of B2 and B3. In the following code, class B1, B2, B3 inherits B with their unique IDs. the templated process functio...
&& is short-circuiting. For example join pack with && and return if it matched or not. template<class T> int ProcessInvoke(const A &a) { std::cout << "Check Type " << T::ID << std::endl; if (a.GetID() == T::ID) { std::cout << "Process " << a.GetID() << " OK" << std::endl; return 0; } re...
68,559,414
68,559,678
Using Qt mainwindow object separately or as class member of applications' class
A theoretical question: in Qt examples, an object of QMainWindow class is always (at least in the examples I've seen so far) used to create a separate variable in main: int main(int argc, char **argv) { QApplication app(argc, argv); QMainWindow w; w.show(); return app.exec(); } I'm quite new to applica...
Probably, you made typo here: int main(int argc, char **argv) { MyApp app(argc, argv); QMainWindow mainWindow = new QMainWindow; app.mainWindow->show(); return app.exec(); } Your mainWindow is a local variable here, but then you are accessing to the app.mainWindow member. Furthermore, the mainWindow ha...
68,559,416
68,559,797
The judge said wrong answer in cAPS lOCK
everyone. In the question cAPS lOCK on Codeforces, the judge said the wrong answer for test case number 3, i.e, 'cAPSlOCK'. Now, from reading the question and the following conditions being given: "Let's consider that a word has been typed with the Caps lock key accidentally switched on, if: a) either it only contains ...
You should really use a debugger to see what the code does. Using a debugger you will see that for input cAPSlOCK your code... Initializes bool flag = true; checks if the first character is uppercase (it is not) if(isupper(first)) checks if count equals number of characters -1 (count is still 0) if (count == len - 1)...
68,559,481
68,559,585
Copy constructor deleted error. Compiler is not calling the move assignment operator
Here's an MRE. struct SDL_Renderer {}; struct Renderer { Renderer(SDL_Renderer* renderer) : pRenderer{ renderer } {} Renderer& operator=(Renderer&& other) { pRenderer = other.pRenderer; other.pRenderer = nullptr; return *this; } SDL_Renderer* pRenderer; }; int main() { ...
Renderer moved = std::move(renderer) This syntax looks like an assignment but since moved is being created it's actually equivalent to Renderer moved(std::move(renderer));. In order to use the assignment operator you should use it after moved is instantiated. Renderer moved(nullptr); moved = std::move(renderer);
68,559,709
68,559,872
Boolean value not being returned correctly?
Completely new "developer" here. I was tasked with writing a program which would give you the height of a ball falling from a tower, at each subsequent one second intervals. Unfortunately, the code doesn't actually stop and instead runs forever. After some debugging I found the source of the problem: the fact that the ...
double getBallHeight(int seconds, double towerHeight, bool& ballGround) { ... }
68,560,097
68,560,312
If only one thread modifies an std::vector, does that same thread need to use a lock when it reads from the vector?
As I understand a data race can only occur with a std::vector when one or more threads are modifying a vector. If all threads are simply reading that is thread-safe. Now assume I have 2 threads. One which can only read from the vector, but the other reads and modifies the size of the vector. I have a lock to remain thr...
You are correct. If your single writer thread is in read mode, then a lock does not need to happen because the other thread is only a reader. Readers can't conflict with each other. The read only thread will still need to acquire the lock on every read, and the writing thread will need to lock when it writes, but it...
68,560,229
68,560,440
C++ Why do we use << instead of braces at std::cout?
Ive started c++ and im wondering, why I dont use at cout braces to give it an argument. Why do we use << ? Isnt cout also a function, so shouldnt we use braces?
The definition of std::cout by cppreference is: The global objects std::cout and std::wcout control output to a stream buffer of implementation-defined type (derived from std::streambuf), associated with the standard C output stream stdout. In your case, the operator << is used as an operator overload. This means tha...
68,560,663
68,560,969
Attempt at mimicking the python print function using variadic templates not working
I came across variadic templates while reading a book and thought it would be pretty cool to implement a python style print function. Here is the code. #include <iostream> #include <string> #define None " " template<typename T, typename... Tail> void print(T head, Tail... tail, const char* end = "\n") { std::cout...
It is possible, but not in the way you have tried. You could do something like the following (one possible solution in c++17): Provide an enum (Ending) which will be used to specify the way of printing (i.e newline, with space, etc). Split function print and one of them will be used to print one argument at a time, wh...
68,561,093
68,561,175
Why the defaultly initialized value of an integer is 4200187 in C++?
from 2.2.1 variable definitions of "C++ primer" , "variables defined outside any function body are initialized to zero". However, like the following code, I define an integer i and print it out. why the result is 4200187? (I use Clion) Update: thank you for your anwsers! now I know that i is defined inside the main fun...
I think the document you're referring to is talking about this kind of variables: #include <iostream> int i; int main() { std::cout << i << std::endl; } Variables declared this way are guaranteed to be initialized at 0 whereas non-static primitive variables created inside of a function are uninitialized. Accordi...
68,561,248
68,561,308
c++ expression value (operator precedence)
The following expression :- int main() { int x=2, y=9; cout << ( 1 ? ++x, ++y : --x, --y); } gives the following output:- 9 As per my understanding, it should return ++y which should be 10. What went wrong?
According to operator precedence, 1 ? ++x, ++y : --x, --y is parsed as (1 ? ++x, ++y : --x), --y
68,561,387
68,561,608
Does a std::map with default allocator initialised to be empty allocate memory?
If I have a std::map with default allocator that initialises to no element, will memory be allocated when it is defined to provide some capacity? Is there a way I can prevent the memory allocation until the first time an insertion is performed? I would like this behaviour because I need to frequently create a map, but ...
A more detailed answer to a similar question can be found here: https://stackoverflow.com/a/57299732/5754656 What an empty / default constructed map is isn't mandated by the standard. Most have their internal pointers point to some "end node". In libc++ and libstdc++, this end node is not heap allocated, and the defau...
68,562,036
68,562,268
Why does the mutex lock twice in LevelDB?
I'm learning the levelDB C++ project, here is the situation, Status s = Write(WriteOptions(), nullptr) triggers a compaction work, and then enter the while loop to wait the signal, the compaction thread goes to BackgroundCall method, and it also needs to lock the mutex_, I'm not sure the TEST_CompactMemTable still hold...
This is simple background_work_finished_signal_ is conditional variable which is associated with a mutex_. This is done during construction: see DBImpl::DBImpl DBImpl::DBImpl(const Options& raw_options, const std::string& dbname) : env_(raw_options.env), internal_comparator_(raw_options.comparator), int...
68,562,717
68,562,871
c++ find implicit type conversion in the expression
For the below expression:- int main() { unsigned ui = 1; float fval = 2.5; cout << sizeof(ui) << endl << sizeof(fval) << endl; cout << typeid(ui+fval).name(); } we get the following output:- 4 4 f It seems that ui+fval is a float. However, given that both float and unsigned int are 4 bytes, and that n...
The rules for arithmetic operators are actually slightly different than the rules for general function overload resolution. From cppreference on arithmetic operators: Conversions If the operand passed to an arithmetic operator is integral or unscoped enumeration type, then before any other action (but after lvalue-to-...
68,562,873
68,563,068
How to use operators defined in namespaces?
I have an operator defined in a namespace as follows: namespace Foo { class Bar { public: Bar(double val): baz(val) {} // Rest of my object here private: double baz; }; namespace Qux { Bar operator "" _quux(long double opd) { return Bar(opd / 10); } } } int main()...
You can't qualify the namespace for user define literals like std::cout << 100.0Foo::Qux::_quux << std::endl But what you can do is use a using statement to import just the literal operator into main using using Foo::Qux::operator""_quux; and you would use it like std::cout << 100.0_quux << std::endl; You could also...
68,564,133
68,564,201
Why is calling the main function supposedly undefined behavior (UB)
I fear this is again a question about interpreting the ISO/IEC 14882 (the C++ standard) but: Is calling main from the program e.g. my calling main() recursively from main not at least implementation defined behavior? (Update: I imply later ill-formed not implementation defined, also not UB, see below and answer) 6.9.3....
I think your analysis is correct: calls to main are ill-formed. You have to pass the -pedantic flag to make GCC and Clang conform. In that case, Clang says warning: ISO C++ does not allow 'main' to be used by a program [-Wmain] and GCC says warning: ISO C++ forbids taking address of function '::main' [-Wpedantic] But...
68,564,193
68,564,317
error C2679: binary '<<': no operator found which takes a right-hand operand of type 'std::vector<char,std::allocator<char>>'
I am quite new to C++ and I have gotten the error: error C2679: binary '\<\<': no operator found which takes a right-hand operand of type 'std::vector\<char,std::allocator\<char>>' (or there is no acceptable conversion) Here's the code: #include <iostream> #include <random> #include <vector> using namespace std; int...
At this line cout << values; you are trying to call the std::basic_ostream::operator<< for vector of chars (i.e.std::vector<char> values). This is not defined, therefore the compiler does not know about it. Hence, the error. You need to iterate through the elements of the vector of chars (i.e. values). For example, us...
68,564,325
68,565,406
G++ Unused Label Warning for Preprocessor Macro
I'm working through compiler warnings in a project, attempting to clean up the code, and one warning/error that has confused me is an unused-label warning for the following code. STATE(initialize) It says that the "initialize" label is defined but not used. STATE is a #define macro that is as follows: #define STATE(x)...
from what I can tell, the initialize label is passed to __TRACE__ where it's used as an argument for a printf() call. No, it is not, actually. The x parameter of STATE() is not the same as the x parameter of __TRACE__(). In the statement STATE(initialize), the x parameter is initialize, so x: becomes simply initiali...
68,564,374
68,564,468
Question about differences in standard I/O optimization for cin and cout
As a competitive programmer, I've always used ios::sync_with_stdio(0); to speed up cin and cout. But I've also seen other people use optimizations like cin.sync_with_stdio(0); or cout.sync_with_stdio(0);. For example, the latter two were used in this website: https://usaco.guide/general/fast-io?lang=cpp. I know that io...
sync_with_stdio is a static method, cin.sync_with_stdio(0) does "exactly" the same as ios::sync_with_stdio(0);. Not really exactly as it odr-uses std::cin but it is no-op.
68,564,683
68,564,730
How to extract number before a symbol in C++
I have tried Googling but just can't find my answer. I have a string "0-9". I want to extract the number before and after the dash and store it in a variable e.g string A = "0-9"; output: min = 0 max = 9 I managed to get the number after dash but not before. string str = "0-9"; string max = str.substr(str.find("-") + ...
https://www.cplusplus.com/reference/string/string/substr/ string substr (size_t pos = 0, size_t len = npos) const; string str = "0-9"; string min = str.substr(0, str.find("-")); cout << min;
68,566,211
68,605,095
MFC Win32 | LButtonUp not being received after clicking toolbar button (CMFCToolBarButton::OnClick)
What I'm trying to achieve Well, the title might not have explained the problem very well, so here goes: I am trying to create a Win32 app using MFC that lets you edit and inspect other windows. I want the user to be able to select other windows. I got inspired by the "Find Window Process" tool on the toolbar on sysint...
I found that in CMFCToolBar::OnLButtonUp, after calling OnClick in the button, it recaptures the cursor, invalidating our SetCapture. BUT if I return TRUE instead of FALSE in OnClick, the mouse is not recaptured. So changing this: BOOL CLocateWindowButton::OnClick(CWnd* pWnd, BOOL bDelay = TRUE) { //(CMainFrame*)m_...
68,566,303
68,566,353
Unsigned char value cycle C++
I (think I) understand how the maths with different variable types works. For example, if I go over the max limit of an unsigned int variable, it will loop back to 0. I don't understand the behavior of this code with unsigned char: #include<iostream> int main() { unsigned char var{ 0 }; for(int i = 0; i < 501;...
Why doesn't it print the expected integer value? The issue is not with the looping of char. The issue is with the insertion operation for std::ostream objects and 8-bit integer types. The non-member operator<< functions for these types treat all 8-bit integers (char, signed char, and unsigned char) as their ASCII chara...
68,566,420
68,566,890
QSlider handle ignores border radius when height is reduced
I am trying to create a gui application to control the volume level of my machine using Qt5 and C++. This is what I kind of want to achieve. So, I created the basic layouts and added the QSlider, and then used the following stylesheet to style it: QSlider::groove:horizontal { height: 16px; background: yellow; ...
your border-radius should be proportional to the length and width to become a circle. Try this style : QSlider::groove:horizontal { border-radius: 1px; height: 3px; margin: 0px; background-color: rgb(52, 59, 72); } QSlider::groove:horizontal:hover { background-color: rgb(55, 62, 76); } QSlider::hand...
68,566,694
68,566,734
OpenGL/SDL - Can't make line load
I've been trying to make a code so that a line appears across the window. I've been using c and opengl/sdl. But for some reason the code is not making a line in the window. I can't figure out what I'm doing wrong: #include <SDL.h> #include <stdio.h> #include <GL/glew.h> #include <SDL_opengl.h> int main(int argc, ...
glOrtho doesn't just set a matrix. The function creates an orthographic projection matrix and multiplies the current matrix with the new matrix. If you call glOrtho in the application loop, you must first load the identity matrix with glLoadIdentity: glLoadIdentity(); glOrtho(0.0, 800, 400, 0.0, -1, 1);
68,566,946
68,567,014
C++ Why is the uint16_t being implicitly cast to int here?
I have this line in my code: Locus locus({track.chrom, track.begin, LOCUS_TYPE_INNER, it->left, it->right, it->gc / 5, true}) ; The it is an iterator which points to one of these: struct SimpleKmer { uint64_t kmer ; uint64_t left ; uint64_t right ; uint16_t gc ; }; All the fields are unsigned. When co...
Does the division operator automatically cast arguments to int? Promote, not cast, but yes. See Implicit conversions: Integral promotion on cppreference.com: In particular, arithmetic operators do not accept types smaller than int as arguments, and integral promotions are automatically applied after lvalue-to-rvalue...
68,567,090
68,571,289
How can I use CMake and FindLibXml2 to link against a static version of LibXml2 that requires no DLL
I am modernizing our CMake build system and switching to static compilation of all dependencies so I can deploy the application as single binary. One of the dependencies is LibXml2 which is statically compiled (Environment MSVC 2019 x64 Native): cscript configure.js iconv=no compiler=msvc cruntime=/MT debug=yes static=...
User @alex-reinking gave the important tip: Set the cached variable before calling the find module - and not afterwards. Because I don't want to hardcode the path (and can't because I have a debug and release build of LibXml2), I use find_library to find the static library (Note: I added the libxml directory via CMAKE_...
68,567,209
68,567,444
Unable to call a object changing method
I have a class which is something like this: Example.h: class Example{ private: int m_x, m_y; public: void print_params() const; void modify_params(); }; Example.cpp: void Example::print_params() const{ cout << "x: "<< m_x << ", y: " << m_y << endl; } void Example::modify_params(){ m_x += 1; ...
Just some theoretical background here. You should remember that std::set is implemented as a binary tree, so where the element is inserted in the tree depends on its value and on the value of the elements that are already on the tree, this is defined during the insertion of each element. This binary tree is built so th...
68,567,390
68,567,701
What is the fastest way to get the frequency of numbers in an array in C++?
My method creates an std::map<int, int> and populates it with the number and its frequency by iterating over the array once, but I'm wondering if there's a quicker way without using a map.
std::unordered_map<int,int> can count frequencies as well but its operator[] has complexity (cppreference): Average case: constant, worst case: linear in size. Compared to Logarithmic in the size of the container. with a std::map. When the maximum number is small you can use an array, and directly count: for (cons...
68,567,765
68,567,871
Who and when deletes object when unique_ptr was set to nullptr
I worked with a class with unique_ptr pointing at object and method set it in runetime asynchroniously to nullptr and then another method might call make_unique and set mentioned pointer to this new object. void Class0::f0() { mPtr = std::make_unique<Class1>(); } void Class0::f1(SomeType param) { mPtr->doWork(...
Who and when deletes this previous that was not explicitly deleted? Not explicitly deleting the object managed by the smart pointer is the reason to use a smart pointer in the first place. It takes more than deleting the object in the unique_ptrs destructor to properly manage the lifetime of the object (see What is T...
68,567,897
68,568,160
Why does ofstream avoids the first 4 character while storing the value of the string?
Im using ofstream to get an input type string from user and put it in a file called question.txt. It doesnt show the first 4 characters in the file..I also tried without putting cout<<question and just getline(cin, question), If i do that, it doesnt let user put input at all string question; cout<<"Enter Your Question...
In this code: string question; cout<<"Enter Your Question: "<<endl; cin>>question; // <-- WRONG getline(cin, question); cout<<question<<endl; ofstream g("question.txt",ios::app); g<<question<<endl; cin >> question is reading in only the 1st word of the user's input into question, and then getline(cin, question) is re...
68,568,043
68,568,259
ESP32 HTTPS POST JSON to AWS
I'm trying to post some data to AWS over HTTPS post but seems not to reach there. Setting host to server address and path to /prod No authentication is required yet on the method. When I connect it just gets frozen and no response, despite saying it's connected. Also tried not to use path and set the full path to the h...
You forgot the \r\n at the end of the Content-Type line. It should be: "Content-Type: application/json\r\n" + You're also not providing WiFiClientSecure with a fingerprint or certificate so that it can verify the server you're connecting to. This is also going to stop your code from working. You should provide the roo...
68,568,538
68,568,923
How to override the OpenMp runtime scheduling policy using OMP_SCHEDULE environment variable?
I have an openMP parallel for loop of the form #pragma omp for schedule(dynamic) for(std::size_t i = 0 ; i < myArray.size() ; i++) { //some code here } In other words by default this loop uses dynamic scheduling. However if the user specifies the OMP_SCHEDULE environment variable I want to be able to override the dy...
To get what you want, you'll probably need to do a bit of manual intervention. During initialization, I'd add some code on this general order: #include <omp.h> std::string scheduling = getenv("OMP_SCHEDULE"); // If the user didn't specify anything, set the default we want. if (scheduling.empty()) omp_set_schedule...
68,568,682
68,568,895
Pistache: how to set TCP server options, for example SO_REUSEADDR
I'm starting to do some tests with Pistache, and I'd like to know how to set TCP options. Like in the example below, I'd like to set SO_REUSEADDR to the server socket. #include <pistache/endpoint.h> using namespace Pistache; struct HelloHandler : public Http::Handler { HTTP_PROTOTYPE(HelloHandler) void onRequest(...
listenAndServe() has an optional options parameter, and the Options class has a ReuseAddr flag defined (and a ReusePort flag), eg: int main() { auto opts = Http::Endpoint::options(); opts.flags(Tcp::Options::ReuseAddr); // set other options as needed... Http::listenAndServe<HelloHandler>(Pistache::Addre...
68,568,940
68,568,991
Generating a warning when a member function is invoked on a temporary object
Given a matrix template class mat<M,N,T> the following member function allows me to efficiently transpose a row vector or a column vector, since they have the same/corresponding memory footprint: template<int M, int N=M, typename T = double> struct mat { // ... template<int Md = M, int Nd = N, typename = std::e...
Member function can be qualified for lvalue or rvalue objects. Using that, you can create an overload set like template<int M, int N=M, typename T = double> struct mat { // ... template<int Md = M, int Nd = N, typename = std::enable_if_t<Md == 1 || Nd == 1>> const mat<N, M, T>& transposedView() & const { ...
68,569,049
68,569,224
why do values returned by std::end() change as the container changes, but not with std::begin()?
I have a std::list that I am inserting items into, and I have a std::unordered_map where I want to store iterators to the elements inserted into the std::list (I am implementing a LRU cache). The following code does not give me the output I expect: #include <list> #include <unordered_map> #include <iostream> int main...
To get the last element's iterator, it can be achieved by: std::prev(std::end(l)). Your code stored the end iterator and dereference it, it's UB. And the doc of std::list::end: Returns an iterator to the element following the last element of the container, This element acts as a placeholder; attempting to access it re...
68,569,249
68,580,518
Why do EnumDomains/NextDomain loop forever?
The following simple code can be directly run in Visual Studio C++ console project. It will loop forever because the NextDomain will always return the same IUnknown * According to Microsoft, it should return NULL if the enumeration reaches end. See https://learn.microsoft.com/en-us/dotnet/framework/unmanaged-api/hostin...
Return code from most enumerators is S_OK to continue and S_FALSE when it did not succeed. S_FALSE is not a fail code. while (S_OK == clrCorRuntimeHost->NextDomain(hDomainEnum, &domain)) && domain != NULL) { std::cout << "why loop forever here?" << std::endl; domain->Release(); ...
68,569,873
68,584,943
No reverse iterators for `std::filesystem::path`?
Is there a technical reason why std::filesystem::path doesn't offer reverse iterators (i.e., rbegin and rend)? If I have a std::filesystem::path for /a/b/c/b/d/b/e and I want to find the first component that matches b, I can use std::find(p.begin(), p.end(), fs::path("b")). But if I want to find the last component that...
According to this page of cppreference.com: "std::reverse_iterator does not work with iterators whose dereference returns a reference to a member of *this (so-called "stashing iterators"). An example of a stashing iterator is std::filesystem::path::iterator." Also from a page of boost.org, which says: Path iterators...
68,570,118
68,570,161
How do you test if an input is a number
I am having trouble determining if an input is a letter or a number. If I enter anything it always says that it is not a number, what am I doing wrong. Here is my code: #include <iostream> #include <unistd.h> #include <ctype.h> using namespace std; int main() { int input = 0; cout << "Enter a number ...
Since isdigit() expects an ASCII value as its argument, it will return true only if you type in a number between 48 (aka the ASCII code for "0") and 57 (aka the ASCII code for "9"), which isn't what you want. In order to get the behavior you want, you'll need to read the user's input into a string, and then analyze the...
68,570,220
68,571,873
How to know which processor is being used by a process?
In a multithreaded environment, I want to exactly know which processor is being used by my process. I looked into the source code of top and htop. The problem with the top/htop is that it gets the total time (from /proc/stat and /proc/[pid]/stat) and divides it by the number of CPUs irrespective of the load that is dis...
As said in the comments of your question, there's no point in asking the system where your process is executed as the scheduler can change it before you even get the reply. In a Posix environment you can use pthread_setaffinity_np() to force your code to only execute on certain threads/cores although I'm not sure that ...
68,571,138
68,616,151
Asan dynamic runtime is missing on Ubuntu 18+
If I compile a simple program (sample.cpp): #include <cstdio> int main() { printf("Hello, World"); return 0; } with a shared sanitizer library, i.e. clang++-12 -fsanitize=address -shared-libsan sample.cpp -o sample I am getting the following error when running ./sample: ./sample: error while loading shared libra...
This is a deficiency of the clang front-end -- when given -shared-libsan flag, it should automatically add -Wl,-rpath=/usr/lib/llvm-NN/lib/clang/MM.M.M/lib/linux to the link line, but it doesn't. You could do that yourself by using e.g. CXX=clang++-12 $CXX -fsanitize=address -shared-libsan sample.cpp -o sample \ -Wl...
68,571,671
68,571,881
get second element of a vector pair from specific first element
how can i get the second element of a vector pair from specific first element? I have codes below: vector< pair <string, string> > vect; vect.push_back(make_pair("hello","s:hihi")); vect.push_back(make_pair("hi","s:hello")); string check; string first; string last; while(true) { cout << "Create new pair.\nFirst ele...
If you insist on using a std::vector<std::pair<std::string, std::string>> instead of std::map or std::unordered_map then I would suggest something like this: auto it = std::find_if(std::begin(vect), std::end(vect), [&check](const auto & pair){ return pair.first.compare(check) == 0;}); // this returns the iterat...
68,571,869
68,572,115
Is it possible to generate a compile-time error if some member function hasn't been called
I'm coding a class with Singleton pattern. class GroupListDAO { public: static GroupListDAO* getInstance() { static GroupListDAO groupListDAO; return &groupListDAO; } init(server::mysqldb::MysqlHelperTempalte* pHelper) { mysqlHT = pHelper; } bool getUserHeartNum(uint32_t ow...
As suggested in a comment, you can use an argument with a default: getInstance(server::mysqldb::MysqlHelperTempalte* pHelper = nullptr) On the one hand it isnt nice to let the caller pass the parameter but using it only on the first call. On the other hand your design suggests that there is one place where you know it...
68,572,385
68,574,718
Moved to VS2019, virtual destructor option no longer there
Since moving to Visual Studio 2019, when adding a item class there is no longer an option for virtual destructor. Is there an option to re-enable it? I don't really know how I should compensate for this. Ty in advance before: Now:
Solved, still dont know why the feature is gone. But just add the deconstructor yourself. Here's an example class Game { public: Game(); //constructor virtual ~Game(); //destructor };
68,572,815
68,573,253
Choosing an IDE that is capable of running source command
I would like to use an IDE for debugging but prior to running the program (either debug or execute), I run a source command. So without any IDE, I run these commands in the terminal: make source foo.sh ./run my_args OR gdb --args ./run my_args I tried to use Kdevelop, but I didn't find any way to tell Kdevelop to run ...
I guess you run source to change some envs? If this action can be done before make, you can just run source xxx.sh && kdevelop Kdevelop has the ability to change envs before run/debug, just setting it in project configure.
68,572,827
68,573,010
Pointer to member function of instance instead of class
I have the following class when I get a pointer to a member function according to some condition and then call the function. class Test { public: bool isChar(char ch) { return (ch >= 'a' && ch <= 'z'); } bool isNumeric(char ch) { return (ch >= '0' && ch <= '0'); } enum class TestType { Undefine...
If the syntax bothers you so much, you can always use std::mem_fn to generate a cheap one-time wrapper around a member function. auto caller = std::mem_fn(f); caller(this, ch);
68,572,945
68,574,025
C++ convert a single binary char to int number
I tried to search for answer and couldn't find a similar question. I have an array of chars, where i need to store in the array numbers. The numbers can only be one char (not a string or more the one index in the array) for example, 3 will turn to 11 and then to a char (mostly gibberish) Now I want to reverse the proce...
The problem is that you mix up two different types, i.e., int and char. You cannot simply convert a binary representation of an int to a single char because they have a different number of bytes used to represent them. With a char, you can represent only 256 different numbers. Below I post a code example that converts ...
68,573,423
68,574,660
Replace right shift by multiplication
I know that it is possible to use the left shift to implement multiplication by the power of two (x << 4 = x * 16). Also, it is trivial to replace the right shift by division by a power of two (x >> 5 = x / 32). I am wondering is it possible to replace the right shift with multiplication? It seems to be not possible in...
"Multiply-high" aka high-mul, hmul, mulh, etc, can be used to emulate a shift-right with a constant count. Usually that's not a good trade. It's also hardly related to C++. Normal multiplication (putting floating point stuff aside) cannot be used to implement a shift-right. my question is limited to modulo 2^32 and 2^...
68,573,589
68,573,732
iterating through all the directories and subdirectories in c++
I wanted to use the std::filesystem::recursive_directory_iterator class to create a class method iterating through all subdirectories and processing found xml files. The only way I have found on the internet to do this was using a for loop like this: for (fs::directory_entry p : fs::recursive_directory_iterator("my_fil...
If you look a std::filesystem::recursive_directory_iterator Non-member functions you can see that there is: // range-based for loop support begin(std::filesystem::recursive_directory_iterator) end(std::filesystem::recursive_directory_iterator) And then std::filesystem::begin(recursive_directory_iterator), std::filesys...
68,573,739
68,574,534
How to check that a C++ class is incomplete (only declared)?
I would like to write a C++ function that will check that its template parameter class is incomplete, so only class declaration is available but not full definition with all class members. My function incomplete() looks as follows together with some demo program: #include <type_traits> #include <iostream> template <ty...
Which compiler is correct is currently undecided. It's CWG Issue 1845. The current wording of 13.8.4.1 [temp.point] does not define the point of instantiation of a variable template specialization. Presumably replacing the references to “static data member of a class template” with “variable template” in paragraphs 1 ...
68,573,938
68,574,532
Operator overloading (object addition)
#include "stdafx.h" #include "iostream" using namespace std; class complex { int real; int img; public: complex(int x = 0, int y = 0) { cout << "Inside Prama" << endl; real = x; img = y; } complex operator+(complex x) { complex temp; temp.real=real + ...
Just summarizing comments... Here complex operator+(complex x) { complex temp; temp.real=real + x.real; temp.img=img + x.img; return temp; } complex temp; calls the constructor and thats the output you see. Typically you'd pass x as const reference to avoid the copy, but as you need a copy anyhow you c...
68,574,006
68,574,090
Generic programming with ranges/views not templates?
I'd like to have function that accepts any container of a fixed type. For a example a function that will accept both std::array<float,1> and std::array<float,2>. I thought this would be possible with ranges but I'm realizing my understanding is quite superficial. I this possible without templates? Edit: Can we define ...
For contiguous ranges, you might use std::span (C++20): void foo(std::span<float>) { // ... }
68,574,037
68,576,157
How do I know if this function works in time O(N) and memory O(N)?
The task is: Given is an array containing N numbers, A[0],A[1],...A[N-1]. Compute the array B of length N, such that B[i]=A[0]*A[1]*...A[i-1]*A[i+1]...*A[N-1]. You shouldn't use division and both time and memory complexity should be O(N). #include <iostream> #include <math.h> #include <conio.h> #include <time.h> lon...
I would suggest generating much larger inputs to test time complexity, for example N1=100000, N2=200000 ... . For small inputs and small timeframes compilers, caches and other processes may impact the time you measure, and shouldnt be part of your analysis. Your algorithm looks to be O(N) to me, as find_solution() is c...
68,574,443
68,577,890
how to get integer value of a z3 expression in c++
I have this piece of code here that adds two z3 bit-vector values in c++ expr Z3_LHS=z3_ctx.bv_val(0, 64); expr Z3_RHS=z3_ctx.bv_val(8, 64); output=Z3_LHS+Z3_RHS; when I print the output I get bvadd #x0000000000000000 #x0000000000000008 Please how can I get the integer value of this output expression which should be ...
This is a bit of an odd thing to do, since you wouldn't use z3 to add constant numbers. But, here's how you'd code what you want using the C++ api: #include <z3++.h> using namespace z3; using namespace std; int main () { context c; expr lhs = c.bv_val(0, 64); expr rhs = c.bv_val(8, 64); expr out = lhs+rhs; ...
68,574,612
68,642,117
swift build - default arguments (c++ package)
I'm having multiple Swift Packages which produce cross-platform libraries (iOS, macOS). I'm trying to build those packages (as a part of CI), and got the following observation: When running swift build: swift build [1/1] Build complete! Then, when specifying iOS Simulator specifcially: xcodebuild -showsdks ...
This worked: swift build -Xswiftc "-sdk" -Xswiftc "$(xcrun --sdk iphonesimulator --show-sdk-path)" -Xswiftc "-target" -Xswiftc "x86_64-apple-ios14.0-simulator"
68,575,394
68,575,508
C++: Passing lambda pointer as a function pointer
I want to get values of an implicit function in C++. For simplicity let's say that I am interested in the function is x(a) which is defined by x*x - a == 0. I have a root finder that uses Brent's method which is declared as BrentsFindRoot( double (*f)(double), double a, double b, double tol ) Since the first argument ...
Your BrentsFindRoot takes a stateless function pointer. Your lambda has state. These are not compatible. Both conceptually and syntactically. BrentsFindRoot( double (*f)(void const*, double), void const*, double a, double b, double tol ) this is how the signature would change if you added state and wanted it to remai...
68,575,478
68,580,224
sched_yield flagged as top hotspot
In analyzing a program with Vtune, I see that the libc function sched_yield is flagged as a significant hotspot. Now I see that this function is roughly responsible for context switching; I say roughly because it's the first time I encounter this function, so my understanding is that it runs inside the OS scheduler to ...
What does having sched_yield as a major hotspot, mean for my program? On Linux, sched_yield does not necessarily switch to another thread to execute. The kernel does not deschedule the calling thread if there aren't threads that are ready to run on the same CPU. The last part is important, since the kernel will not r...
68,576,099
68,576,551
Is `reinterpret_cast` actually good for anything?
I recently learned that it is Undefined Behavior to reinterpret a POD as a different POD by reinterpret_casting its address. So I'm just wondering what a potential use-case of reinterpret_cast might be, if it can't be used for what its name suggests?
There are two situations in which I’ve used reinterpret_cast: To cast to and from char* for the purpose of serialisation or when talking to a legacy API. In this case the cast from char* to an object pointer is still strictly speaking UB (even though done very frequently). And you don’t actually need reinterpret_cast ...
68,576,464
68,589,080
Clang sanitizers missing a read from uninitialized memory
I have the following code, that I am confident reads from garbage memory, but clang sanitizers do not complain. Is there something I can do to make them trigger or I should just accept this as limitation/bug? #include <algorithm> #include <iostream> #include <vector> struct B{ int x; }; struct D : public B{ s...
From the documentation Uninitialized values occur when stack- or heap-allocated memory is read before it is written. MSan detects cases where such values affect program execution. MSan is bit-exact: it can track uninitialized bits in a bitfield. It will tolerate copying of uninitialized memory, and also simple logic a...
68,577,160
68,577,584
Port QRegExp::exactMatch() in Qt6
I'm porting a Qt5 application to Qt6. I want to move away from Qt5CoreCompat module of Qt6 as soon as possible. My problem is with QRegExp class which should be replaced with QRegularExpression class. Most patches are relatively trivial but how can I port QRegExp::exactMatch() in Qt6. Here is some code from the applica...
The documentation suggests using the anchoredPattern helper function to do the anchoring from the regular expression itself: QRegularExpression version(QRegularExression::anchoredPattern(QLatin1String("(.+)_v(\\d+)")));
68,577,608
68,593,084
How can I pass a 3D Python list to a c++ program
I have a .py file, that holds a 3d lists of signed floats. test.py def myfunc(): tabToReturn = [[[-1.03,5.68],[4.16,-78.12]],[[74.1,8.95],[59.82,1.48]],[[74.1,8.95],[59.82,87.4]]] print(tabToReturn) return tabToReturn I want to call that .py, make it return this 3d list, and convert it to a 3D vector for m...
Even though what has answered @Botje is (probably) right, I got a solution without using json. After having struggle a bit, I have discovered the source of the C-API : Thanks to that I found a solution to solve this no matter the dimension of your vector. Here is the details : #include <Python.h> //first to import #inc...
68,578,004
68,578,156
Is it faster to pass the pointer to a vector than the vector itself?
In my programm I have a function that takes multiple vectors as arguments. I used to pass them as normal vectors so like the definition of the function starts like this: void do(std::vector<int> a, std::vector<int> b, std::vector<int> c){ and the call looks like this: do(d, e, f); but I want my code to be as fast as ...
Consider the C++ Core Guideline F.16: For “in” parameters, pass cheaply-copied types by value and others by reference to const. What is cheap and what is expensive to pass by copy depends on some factors. A good rule of thumb is to pass anything as big as a pointer or smaller by value and anything bigger by reference. ...
68,579,824
68,580,365
c++ passthrough mutliple objects to a function
This problem has been confusing me for quite some time now. Bascily I need to be able to individually access multiple objects by their name in another function. Ive seen examples where object pointers are pushed into a list but I cant access them by their name that way it seems. Lets say in one function I create many o...
From a design perspective, put things that belong together logically into a single context. Furthermore, avoid dynamic allocation if not necessary. struct EnemyScene { GameObject chief; GameObject grunt; GameObject elite; }; inline EnemyScene createScene() { // You also may want to consider making this function...
68,580,692
68,581,386
How does one send custom MPI_Datatype over to a different process?
Suppose that I create custom MPI_Datatypes for subarrays of different sizes on each of the MPI processes allocated to a program. Now I wish to send these subarrays to the master process and assemble them into a bigger array block by block. The master process is unaware of the individual datatypes (defined by the local ...
First of all: You can not send a datatype like that. The value MPI_Datatype is not a value of type MPI_Datatype. (It's a cute idea though.) You could send the parameters with which it is constructed, and the reconstruct it on the sending type. However, you are probably misunderstanding the nature of MPI. In your code, ...
68,581,014
68,581,086
Checking for template parent class in C++ using SFINAE
I've been learning the concept of SFINAE in C++ recentlly and I am currentlly trying to use it in a project. The thing is, what I'm trying to do is different than anything I could find, and I can't figure out how to do it. Let's say I have a template class called MyParent: template <typename Elem> class MyParent; And ...
You might do template <typename T> std::true_type is_my_parent_impl(const MyParent<T>*); std::false_type is_my_parent_impl(const void*); template <typename T> using is_my_parent = decltype(is_my_parent_impl(std::declval<T*>())); Demo
68,581,136
68,581,332
Unexpected outputs are coming by only changing the data type
unsigned long long int s=0; s=191689628 +646033877 +109099622 +798412961 +767677318+ 190145527 +199698411; cout<<s<<endl; return 0; Output to above code is 18446744072317341664. unsigned long int s=0; s=191689628 +646033877 +109099622 +798412961 +767677318+ 190145527 +199698411; cout<<s<<endl; return 0; OUTPUT to ...
All of your integer literals are using the int type, so the result of 191689628 + 646033877 + 109099622 + 798412961 + 767677318 + 190145527 + 199698411 exceeds the highest int value and thus overflows. Signed integer overflow is undefined behavior. You are then assigning the overflowed values (which are negative) to u...
68,581,345
68,581,402
C++ Concept, how to check a constexpr static int is equal to 1, or similar...? Clang disagrees with GCC and MSVC
I can't find the correct syntax on cpprefference for a concept that matches the value of a static constexpr member. This code compiles, and functions correctly on GCC and MSVC, but does not work in Clang. I was wondering if anybody knew if this was my mistake, or an issue with either GCC and MSVC or Clang? Here's a god...
Clang is correct here (thanks, Casey). [expr.prim.req.nested]/2 says: A local parameter shall only appear as an unevaluated operand within the constraint-expression. And [expr.ref]/1 says: A postfix expression followed by a dot . or an arrow ->, optionally followed by the keyword template, and then followed by an id...
68,581,421
68,581,603
Can I use template member functions as an alternative to the CRTP in order to implement static polymorphism?
I want to implement the template method pattern using static polymorphism in C++. Right now I have two classes A and B which are very similar. They have an identical public API and the exact same list of private data members. Most of the public member functions are also implemented identically but for some of them the ...
If the question is strictly "can I" - the answer is than "yes, you can, quite trivially": template<typename T> int Three() const { return static_cast<const T*>(this)->Private(); } However, I would not advise this, since one of the benefits of CRTP is that it is (almost) impossible to misuse the cast - static_...
68,581,598
69,175,897
Migration from wxHTML to wxWebView in wxWidgets
I am trying to replace wxHTML with wxWebView in wxWidgets. I have a problem when trying to get the URL of a clicked hyperlink. Previously the code was like this: void mywxHtmlWindow::OnLinkClicked( const wxHtmlLinkInfo& link ) { ... link.GetHref(); ... } and now I have: void OnLinkClicked( wxWebViewEvent& ...
The default scheme for Internet Explorer is about when you are setting a page source manually. So instead of using setPage function, I registered a custom scheme (e.g myScheme) like mBrowser->RegisterHandler( wxSharedPtr<wxWebViewHandler>( new WxHtmlFSHandler( "myScheme" ) ) ); load an arbitrary URL like myBrowser->...
68,581,742
68,581,814
cpp operator overloading inside std::function
I create a complex struct in complex.h and overload a series of operators (including ^) to work on the four operations complex+double, double+double, complex+complex, double+complex: complex operator^(complex& lhs, complex& rhs){ double new_mag = std::pow(mag(lhs), rhs.re); double new_arg = angle(lhs.re, lhs.im...
Your operator requires non-constant references: complex operator^(complex& lhs, complex& rhs); In the expression return a ^ complex(1/2) the second operator is an r-value. Try to define the operation using const references: complex operator^(complex const& lhs, complex const& rhs);
68,582,100
68,582,161
free(): invalid pointer when using scanf
Hello guys so this is my code. I could not use cin nor getline() so I had to use scanf. It reads all the values in as expected but after entering the last value it says: free(): invalid pointer ./comp: line 8: 877 Aborted (core dumped) ./$BIN Anyways, here is the code. Help would be appreciated. #include <cmath> #i...
scanf is designed to work with character buffers, not strings. You probably want to use std::string (it's more intuitive and manages memory for you), so scanf is a poor fit. There's a version of getline that works with string. std::vector<std::string> v(n); for (int i = 0; i < n; i++) { cout << "i: " << i << endl; ...
68,582,795
68,582,853
Move constructor needed, but not used, in array initialization with elements of class with deleted copy constructor
I apologize for the wordy title, but I'm having trouble concisely expressing this question. I have a class with a deleted copy constructor and copy assignment operator. When I attempt to initialize an array with instances of the class I get a compiler error unless I provide a move constructor. However, the provided mov...
With A arr[]{A{"some"}, A{"string"}}; You are creating two temporary A objects and then copying/moving them into the array. Now, the compiler can optimize this copy/move away, but that class still needs to be copyable/moveable in order for this to happen. When you comment out your move constructor, the class is no l...
68,583,068
68,583,378
How to extract the remaining elements from std::sample
In the sample code here it shows cases how to use std::sample as shown below std::string in = "hgfedcba", out; std::sample(in.begin(), in.end(), std::back_inserter(out), 5, std::mt19937{std::random_device{}()}); std::cout << "five random letters out of " << in << " : " << out << '\n'; Possible output: ...
If you're not concerned about the order of the characters in the output strings, then you can use std::shuffle to randomise the input string and then copy the first 5 characters of the result to one output string and the last 3 to the other: #include <iostream> #include <random> #include <string> #include <algorithm> ...
68,583,134
68,739,095
vcpkg and cmake and vsc on Ubuntu can not find package
I installed vcpkg on Ubuntu 20.04 and install boost and opencv. I have this cmakelist file: set(CMAKE_TOOLCHAIN_FILE /home/m/local/vcpkg/scripts/buildsystems/vcpkg.cmake CACHE STRING "") set(VCPKG_TARGET_TRIPLET "x64-linux" CACHE STRING "") cmake_minimum_required(VERSION 3.0.0) project(test1 VERSION 0.1.0) find_pa...
Case matters in CMake as mentioned in the comments: find_package(OpenCV CONFIG REQUIRED) and find_package(Boost REQUIRED) vcpkg does not install config files for Boost, so you cannot use CONFIG here. You probably also want to call it with the COMPONENTS option to list the modules you actually want. Usage from vcpkg: ...
68,583,210
68,583,337
qt4 the clicked signal in the connect button doesn't trigger the settext in the label
The app runs okay but the clicked() signal doesn't trigger the setText() of the label. Any hint why it doesn't? #include <QApplication> #include <QLabel> #include <QPushButton> #include <QHBoxLayout> #include <QWidget> #include <QObject> int main(int argc, char *argv[]) { QApplication app(argc, argv); QWidget...
The arguments within the connection must indicate the signature between the signal and the slot, that is, they must indicate the types of objects that send the signals and receive the slots. In this case it does not make sense to place "<h1>hello</h1>". A possible solution is to create a class that inherits from QLabel...
68,583,472
68,583,588
cudaStream_t default value
I'm writing a cuda library where some functions would have a parameter accepting a cudaStream_t from outside(user side) if the user give one, otherwise will use an internal stream. So this function would like to have a cudaStream_t as the last param with default val, but I didn't find an appropriate value for cudaStrea...
Without any additional information, I would recommend use of pass-by-value with cudaStreamLegacy as the default option. See here. If you know that you intend your application to be compiled with the per thread default stream option, then a better choice would be cudaStreamPerThread. These choices make no assumptions t...