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
67,874,040
67,874,970
Is there a way to get eigenvalues for a particular point in an image?
I am working with OpenCV and inside there is the function goodFeaturesToTrack to apply ShiTomasi method to find corners. We know that Shi-Tomasi is based on finding eigenvalues so there is even a function in OpenCV to calculate the minimal eigenvalue of gradient matrices for corner detection called cornerMinEigenVal in...
Short answer: There is no such function in OpenCV that calculate MinEigenVals for sparse points. However, you can implement one from HarrisResponses() with just small modifications. The HarrisResponses() function is used to calculate Harris score for sparse points (it's static in OpenCV, so you can't call it directly)....
67,874,100
67,874,146
Return the name of object in method
I'm pretty new to coding, and I'm following this French tutorial that is basically making a RPG game used through console. So I got a Character class in a .cpp file and .h, another .h .cpp couple of files for the weapons, and my main. I got a function on my CPP file that's like this : void Character::attack(Character &...
Assuming the Character class has field like name you can access the field in your method by using this->name (it will acces name of the object which called the method, in this case it is David) and the target.name will be "Goliath".
67,874,143
67,874,259
C++ experimenting with insertion sort fail?
This code is a direct translation of the pseudo code on Wikipedia. And yet it does not swap any elements. Could someone point me to what is going on? #include<iostream> #include<string> #include<fstream> #include<cctype> #include<vector> using namespace std; void sortowanie(vector<int> v) { for(int i=1; i<=(int)v....
You're passing the std::vector by value, so a copy will be made, and changes are only going to be done on that copy: void sortowanie(vector<int> v) Add a & to use pass-by-reference instead, so that any change to the std::vector inside the function will be applied to the original std::vector as well: void sortowanie(ve...
67,875,072
67,875,206
What are .o.d files used for?
I use netbeans and notice that in addition to creating the .o files, it also creates .o.d files. What are these files (.o.d) for?
As described by Netbeans: Dependency files. Build systems try to make it so that if you recompile, you save effort by not recompiling translation units whose generated object file will be identical. So it only attempts to recompile files that have changed, or files that maybe haven't changed but a file they depend on h...
67,875,171
67,875,302
difference between different c++ library method?
As I know, we can write our c++ library in .h file,.C file and .c &.h file? can someone describe difference between these 3 library method?
First, a C++ library should no be in a .c file. That indicates C language. C++ source modules should generally have .cpp extension.Then, common to both C and C++ language, a header file should have .h extension to denote that it is a header. Header files are used to define the APIs in your library; i.e., the names of f...
67,875,496
69,062,772
How to create a button c++
I am trying to create a button but I always got an error "cannot convert 'const wchar_t*' to 'LPCSTR {aka const char*}' for argument '2' to 'HWND__* CreateWindowExA(DWORD, LPCSTR, LPCSTR, DWORD, int, int, int, int, HWND, HMENU, HINSTANCE, LPVOID)'" I tried: HWND hwndButton = CreateWindow( L"BUTTON", L"OK",...
#include <Windows.h> int main(INT argc, WCHAR* argv[]) { MSG msg; HWND hWnd = CreateWindowExW(0L, L"button", L"Hello, World!!!", WS_VISIBLE | WS_POPUP, 10, 10, 100, 25, NULL, NULL, NULL, NULL); ShowWindow(hWnd, SW_SHOW); UpdateWindow(hWnd); while (GetMessageW(&msg, NULL, 0, 0)) { Translate...
67,875,995
67,876,328
Unable to Understand Custom Allocator
I was reading about typedefs vs using on Microsoft docs website: Aliases and typedefs (C++) #include <stdlib.h> #include <new> template <typename T> struct MyAlloc { typedef T value_type; // Failed to understand why it is needed MyAlloc() { } template <typename U> MyAlloc(const MyAlloc<U>&) { } // Failed ...
Basically, the answer to all questions is that standard requires them if you want to have a type that meets Allocator requirements. typedef T value_type; value_type is a required member type for every allocator. Standard requires it from allocators, because this is the only way to extract T back from this type or obje...
67,876,547
67,879,288
error: non-const lvalue reference w.r.t. boost::multi_array and foreach
so I have created a boost::multi_array<Tile *, 2> map; and I want to for(auto&i:map) { i->reveal(); } but clang/llvm says error: non-const lvalue reference to type 'sub_array<...>' cannot bind to a temporary of type 'sub_array<...>' pointing at the 'i' of "auto&i" as the culprit. I see other discussions of err...
The elements of a N-dimensional array are (N-1)-dimensional array views. This is what the sub_array<...> temporary means. So, you will want to: #include <boost/multi_array.hpp> struct Tile { void reveal(){} }; int main() { boost::multi_array<Tile*, 2> map; for (auto row: map) { for (auto& col: ro...
67,876,613
67,876,895
Pointer to object created in parameter
I have a class called Rectangle which holds two pointers to objects of the class Point2D. class Rectangle: public GeoObjekt { private: Point2D* lu; Point2D* ro; public: Rectangle(Point2D lu, Point2D ro); } Rectangle::Rectangle(Point2D lu, Point2D ro) { this->lu = &lu; this->ro = &ro; } To create a...
Change the members lu and ro to be Point2D instead of Point2D*. The Point2Ds you supplied in the constructor are destroyed on the next line, so your pointers end up pointing at nothing (dangling pointers).
67,876,712
67,877,184
What is the best way of using arrow parquet in more modern cmake?
Below is the solution that worked for me, but not sure if it is the best way to do this. I used brew to install it. vcpkg does not work at the moment, unfortunately. What I don't like about this solution is that I need to set Parquet_DIR and find_package(Parquet) separately. set(Parquet_DIR /usr/local/lib/cmake/arrow) ...
You can pass PATHS to search to find_package. You may also want to prevent searching in other places by passing NO_DEFAULT_PATH. See find_package documentation find_package(Arrow CONFIG REQUIRED) find_package(Parquet CONFIG REQUIRED PATHS /usr/local/lib/cmake/arrow NO_DEFAULT_PATH ) target_link_libraries(databa...
67,876,904
67,877,310
Understanding Cycles Per Element for For Loops
I understand (vaguely) what Cycles Per Instruction (CPI) and Instructions Per Cycle (IPC) mean. CPI is the number of clock cycles required to execute the program divided by the number of instructions executed running the program. IPC on the other hand is the number of instructions executed while running a program divid...
(Your code examples are taken from the textbook, Computer Systems: A Programmer's Perspective.) Cycles per element is a higher-level metric here. Rather than measuring the CPI or IPC, the actual unit that matters for the example loops are the elements of the vector. Therefore, in running the loop across hundreds or t...
67,877,055
67,877,496
IDirectMusicPerformance8 - MIDI only, or WAV?
I'm trying to work with an old version of DirectX (8.1) and I'm finding the documentation more than a little confusing. It feels like the IDirectMusicPerformance8 interface is for MIDI playback, as it has various MIDI-related methods on it, but various parts of the documentation suggest that it can be used to play bac...
OK, I figured it out. Apparently I had been using IDirectMusicPerformance instead of IDirectMusicPerformance8, which I guess is some kind of old compatibility thing that is missing various new DirectX 8.1 methods. Once I switched to that (along with the associated '8' versions of the loader and segment interfaces), u...
67,877,493
67,877,949
How to debug and print a template alias type c++
I have some nested typedefs which I am trying to debug. The first I want to do is to print them out so I can see how they are instantiated. E.g. using tt = std::conditional<conditionForType1, type_1, type_2>; where type_1 and type_2 are two other evaluated aliases. How can I print the content of tt, type_1, and type_...
A quick and dirty way: template <typename T> void print_type() { #ifndef _MSC_VER std::cout << __PRETTY_FUNCTION__ << '\n'; #else std::cout << __FUNCSIG__ << '\n'; #endif } What exactly is printed depends on the compiler. For print_type<int>();, my Clang prints void print_type() [T = int]. See this...
67,877,560
67,877,660
memory layout of C++ object
As far as my understanding all the member functions will be created in separate memory when class definition and is common for all objects. And only the member variables are created individually for each object. But how member function is executed when called using object? Where is the address for these member function...
Non-virtual member functions are extremely like regular non-member functions, with the only difference between them being a pointer to the class instance passed as a very first argument upon invocation. This is done automatically by compiler, so (in pseudo-code) your call b.fun() can be compiled into B::Fun(&b); Where...
67,878,096
67,898,774
In QMake, how do I add a subdir only if the target supports C++20?
I want to run my unit tests in all available C++ versions, so I have a directory structure like tests/ component/ tst_component.cpp cxx11/ cxx14/ cxx17/ cxx20/ And I compile tst_component.cpp in each of the cxxNN subdirs in C++NN using CONFIG += c++NN. This works well if the...
qmake has a compilation test feature, which you can use to compile a simple source file with a defined set of building flags. See https://doc.qt.io/qt-5/qmake-test-function-reference.html#qtcompiletest-test for the reference, and here is a skeleton for such a project: mainproject/ ├── config.tests │   └── test ...
67,878,196
67,878,534
Mysql.h 0 results after query
I made this: int querystate; std::string pol; std::string login; std::cout << "login: "; std::cin >> login; pol = "select * from table where login = '" + login + "';"; querystate = mysql_query(conn, pol.c_str()); if (querystate != 0) { std::cout << mysql_error(conn); } res = mysql_store_result(conn); while ((row =...
First, your code is open to an SQL injection attack. You need to escape the login string using mysql_real_escape_string_quote(), eg: std::string escapeStr(MYSQL *mysql, const std::string &str, char quoteChar) { std::string out((str.size()*2)+1, '\0'); unsigned long len = mysql_real_escape_string_quote(mysql, o...
67,878,203
67,878,721
enable_if with is_move_constructible allows non-movable types, but requires does not
I have a non-movable structure and a templated class in which I want to have a function that exists only when the type is movable (using enable_if and type_traits). However, it seems that despite std::is_move_constructible_v returns false, the function still exists and can be executed. However, when I changed the code ...
If you only want to disable that foo function for non move constructible types, you could make the template parameter a dependent type: template<typename T> struct Foo{ template<class U = T, class = std::enable_if_t< std::is_same_v<T,U>&& s...
67,878,819
67,880,204
C2440: 'initializing': cannot convert from 'A<double>' to 'A<double>'
This code throws a compilation error in Visual Studio 2017: #include <iostream> #include <string> using std::cin; using std::cout; template<class T> class A { public: A(T a); ~A() {} #if 0 A(const A<T>&); #else A(A<T>&); #endif T t; }; template<class T> A<T>::A(T a) : t(a) {} template <class T> #...
In this situation, the MSVC error message is particularly lacking; if you run GCC over this you get the following error: main.cpp: In function ‘int main()’: main.cpp:42:20: error: cannot bind non-const lvalue reference of type ‘A<double>&’ to an rvalue of type ‘A<double>’ 42 | A<double> a3 = A<double>(a2); //gi...
67,879,282
67,879,354
Is it possible to add a private member-variable without increasing the containing object's size?
I've got a tiny little utility class called ObjectCounter that has no virtual methods and no member-variables; all it contains is a constructor and a destructor, which increment and decrement a global variable, respectively: int _objectCount = 0; // global class ObjectCounter { public: ObjectCounter() {printf("Def...
If you can use C++20, you can use the attribute [[no_unique_address]] to accomplish this. Using #include <cstdio> #include <cstdint> int _objectCount = 0; // global class ObjectCounter { public: ObjectCounter() {printf("DefaultCtor: count=%i\n", ++_objectCount);} ~ObjectCounter() {printf("Dtor: count=%i\n",...
67,879,397
67,879,676
How to pass inputs (not arguments) thorugh command line in C/C++?
Say I have the following simple C++ program, #include <bits/stdc++.h> using namespace std; int main() { //no argv or argc allowed cin >> t; while(t--) { int n; cin >> n; // do whatever } } and the following command in terminal: g++ -std=c++17 -O2 -lm b.cpp && ./a.out When I run th...
Process substitution is not the right way to do this. Use a heredoc: g++ -std=c++17 -O2 -lm b.cpp && ./a.out << EOF 7 1 2 2 4 2 6 7 5 3 6 4 6 7 2 EOF
67,879,795
67,879,987
Shortest path with file as input
I'm creating a graph taking a file as input and I want to calculate the shortest path, to do so I used SPF algorithm. I have a few file I can use to see if it works, and here comes the problem because it works until I try it with the biggest one (which has over 1 million vertex and 2 million edges), considering that th...
The problem is most likely here: int d[V + 1]; Firstly, variable length arrays are non-standard. Secondly, if V is large you will overflow the stack. Solution: replace this with std::vector. bool inQueue[V + 1] should be treated similarly. Also, replace char buffer[BUFFER_SIZE]; with std::string. You'll be glad you...
67,879,897
67,880,416
Android ndk file not found on github actions
I am trying to implement CI on app which contains native code in C++ using github actions When i am running workflow it's says that there is no headers near the .cpp, but it is here and i have setted include directories in build.gradle and Android.mk file, the build is fine on local PC(windows) [armeabi-v7a] Compile++...
If you're using backslashes in your include directives as the error seems to suggest, try to change them into forward slashes: #include "vendor/RakNet/SAMP/samp_netencr.h" Also check the path for case correctness. Windows has a case-insensitive filesystem, while the CI might be running some form of Linux.
67,880,179
67,880,190
winsock2 accepting clients without calling accept function
I'm trying winsock example from Microsoft docs, client code https://learn.microsoft.com/en-us/windows/win32/winsock/complete-client-code server code https://learn.microsoft.com/en-us/windows/win32/winsock/complete-server-code Problem I'm facing is connect function in client code returns valid socket fd without acceptin...
If listen() returns success, the OS will accept requests for new connections for you in the background and put the new connections into an internal queue, which accept() will then pull from. So, even if the server code never calls accept(), new connections will still be accepted in the background as long as the queue ...
67,880,751
67,880,813
use a pointer to the current object - C++
just wondering how to use (pass or return) a pointer to the current object in c++? in my case I have a map of nodes, and I want to assign a node a child, and in doing so have the current node be added as a parent to the child below is what I have right now void node::assign_child(node* child) { children.push_back(ch...
Well, this itself is a pointer, named as "the this pointer". About why is it a pointer, This SO post might be helpful. Or just look at what the C++17 Standard says. §12.2.2.1 The this pointer stands: the keyword this is a prvalue expression whose value is the address of the object for which the function is called. The...
67,881,172
67,881,222
C++: ODR violation for member functions defined outside of class body but enclosed within header guard (as shown in YouCompleteMe plugin)
I have a simple header file as shown below. #ifndef PERSON_H #define PERSON_H #include <iostream> #include <string> using namespace std; struct Person { string name; string address; auto get_name() const -> string; }; string Person::get_name() const { // Function 'get_name' defined ...
It can be included in multiple compilation units. If you mark the definition inline it should be happy.
67,881,434
67,892,009
Keep calling a callback until a particular value is recieved through the callback
I have a callback function that provides some data. callback([](int check) { }); I want to keep calling this callback function until the returned value of check is 0. How can I do it? The callback function takes some time to send the data. If I use a loop normally, it is calling the callback multiple times while I am ...
If callback performs the callback synchronously (and assuming it accepts any callable), you can just use a capture: bool go; do callback([&go](int check) {go=check;}); while(go); Alternatively, if callback performs the callback in another thread, you can use a std::promise to “undo” the concurrency: while([] { std...
67,882,330
67,882,700
Socket timeout: select vs setsockopt
I am using timeout for sending and receiving data on a socket. I found that timeout can be achieved either by setting socket to non-blocking mode and using select or by using setsockopt with SO_SNDTIMEO/SO_RCVTIMEO option. What are the differences between these two methods and is there any reason to prefer one impleme...
What are the differences between these two methods and is there any reason to prefer one implementation over the other both for Linux (Redhat) and Windows? For Linux, the differences seem to be rather small: Specify the receiving or sending timeouts until reporting an error. The argument is a struct timeval. If an i...
67,882,496
67,886,105
how to make a v2 credential provider initialize its credentials without `ICredentialProviderUser` object?
i built a V2 credential provider sample and registe it to windows10, the provider can be load and displayed in unlock screen after i click "Sign-in options", but the provider can not be displayed in power-on/switch-user logon screen. i put some log in the code like this HRESULT CSampleProvider::_EnumerateCredentials() ...
The exact answer - noway. New Windows Logon scenario assumes that there are some users that can login into computer and have an option to choose which provider use for login. Each User's tile will have a set of icons from Credential Providers registered on computer. Your provider must accept a list of users that can be...
67,882,509
67,882,568
Program for deck of cards compiles but crashes when running (c++)
i tried to write a program that prints out all the cards in a deck but it crashes i tried removing the for loop in the main function and manually asigning the value to one card for the deck and then printing it and then it worked, but with the whole code compiler doesnt see any errors and runs just fine only to crash, ...
Indices are zero-based. So, your array int num[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K, A}; which has 13 items will be indexed from 0 -> 12. As such, the loop for(int j=0; j<=13; j++) will accessed num[13] which isn't in the range. The same goes for for(int i=0; i<=4; i++) and for (int f=0; f<=52; f++) To solve thi...
67,882,848
67,884,094
What justifies the lvalue category of unevaluated non-static data members in C++?
Both gcc and clang accept the following code, and I'm trying to figure out why. // c++ -std=c++20 -Wall -c test.cc #include <concepts> struct X { int i; }; // This is clearly required by the language spec: static_assert(std::same_as<decltype(X::i), int>); // This seems more arbitrary: static_assert(std::same_as<d...
How can an expression like `X::i--which can't be evaluated at all, let alone determine the identity an object--be considered a glvalue? Ignoring the misuse of «result», it is [expr.prim.id.qual]/2: A nested-name-specifier that denotes a class, optionally followed by the keyword template ([temp.names]), and then foll...
67,883,076
67,885,137
CPP:How to get the REAL element in a vector?
I'm new of C++ and I'm making a huffman tree written in c++, and I'm in trouble in generating tree structure. Here is my code: void Huffman::generateTree() { std::vector<Node> nodes; for (auto itr : freq) { nodes.push_back(*(new Node(itr.first, itr.second))); } while (nod...
As the comments suggest, you need to stop thinking that C++ is similar to Java, it really isn't. Objects in C++ have explicit lifetimes, and the language doesn't stop you from holding onto a reference or pointer to an object after it has ceased to exist. If you want something to outlive the call it was created in, it n...
67,883,421
67,884,374
Object pointer in .msg file
I am currently implementing a scheduler for which I need more information on each frame than the message and its standard headers carry. I created an Object containing all the information and now I want to add a pointer to a .msg file pointing to the informatino object. The .msg File is used to tag the information to t...
Add the following line into your message definition: class noncobject intptr_t; It tells the message compiler that intptr_t is an external type.
67,883,701
67,883,917
Structured binding violations
The code as follows #include <tuple> int main() { auto [a] = std::make_tuple(1); return [a]() -> int { return a; }(); } produces an error in clang 12: <source>:6:13: error: 'a' in capture list does not name a variable return [a]() -> int { return a; }(); <source>:6:34: error: reference to local binding ...
So they both still violate the rule that that structured bindings are never names of variables, making them never capturable? No, it is actually clang that is violating the standard, at least for the compiler flags provided. In C++20, the restriction of not directly supporting captures of structured binding aliases h...
67,883,770
67,883,885
C++ : I cannot give the input - What is wrong?
I am writing a code in C++ and one part of it is to read user's input and save it in an array. I have written the following : #include <iostream> using namespace std; int main() { int i; double C[3]; cout<<"Enter the coefficients:\n"; for(i = 0; i < 3; i++) { cin >> C[i]; } return 0; } The user is...
Wandbox does not support interactive console. Any input has to be written upfront, before running the program, in a special window "Stdin" If you want interactive console, you need to use a different online compiler, e.g. Online GDB
67,883,798
67,883,951
Moving a Tensorflow tensor from C to python
Im currently working with a tensor on using the tensorflow c api. However i have created it and done the operations i wish to do to it. Now i want to move it into python to do further operations on it. Im using the tensorflow c-api because it offers a functionality not availible in the python api. So my goal was to cre...
Tensorflow's PyFunc op has code to convert the tensor to a PyObject which could be found here An example to use this could be: #include "tensorflow/python/lib/core/py_func.h" Status TensorHandler::ExportTensorAsNumpy(const Tensor *inputTensor) { PyObject* numpyObject = Py_None; tensorflow::ConvertTensorToNdarr...
67,884,156
67,884,205
How to disable writes on temporary returned by getter?
I have a getter which returns a temporary object, copy of the internal object. Something like the following: class Foo { public: QString name() {return m_name;} void setName(const QString &name); private: QString m_name; } The intended usage of the setter/getter is to get the data through name() and set th...
Maybe try const QString name() const {return m_name;} This will prevent direct use of: foo.name().clear(); Please also note, as underlined in the comments, that as the returned QString is a copy, foo.name().clear(); won't modify foo.m_name. But yes, a quick read of the code can be confusing. EDIT extra reads: when-u...
67,884,199
67,888,337
Problem with general tree implementation in C++
I have to implement a general tree en C++ for one of my class, and I come across a problem I don't understand. I have two classes, EmployeeNode and EmpoyeeTree. EmployeeNode contains the data elements needed for the work : a string name, an EmployeeNode parent and a List<EmployeeNode> children which is a linked list I ...
There are some structural problems in EmployeeNode. List<EmployeeNode> *child; shouldn't it be List<EmployeeNode *> child; which is to represent that every EmployeeNode have a member called child to remember a list of pointer to its child? In the constructor :name(employeeName), parent(employeeParent), child(employee...
67,884,591
67,900,735
Can't load library from ctypes
I would like to use a C++ API from python. The files that I have are XX.dll, XX.lib and XX.h The only info that I have are : Notes: To use the XX functions inside your C++ project you must integrate the XX Object file library "XX.lib" and XX header file "XX.h". The XX DLL must be add in your computer environment but n...
I found a quick fix. Apparently, the idea is to use "mt.exe" to incorporate a manifest in the dll. The manifest "XX.dll.manifest" <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <dependency> <dependentAssembly> <assemblyIdenti...
67,884,726
67,884,881
How to declare a function returning a class instance, that is used in the same class?
I've tried couple of weeks and searched for days for an answer, but haven't found it. My code is rather large and intertwined, but my problem is with 3 functions/classes, therefore I will only show my declarations and relevant information. I have the following non-compliable code: class Word{ private: *members* public:...
You want this: #include <string> using namespace std; // declare that the class exists class Word; // Declare the function Word search_in_file(const string& searchee); class Word { private: public: //friend declaration so i could access members and use it in class - doesn't help friend Word search_in_file...
67,884,789
67,914,254
Qt: make resize event do not move the objects on the scene
I have the following code, which creates a scene and a green rectangle on it (see image below). The problem is, I want the rectangle to stay on its place, when I resize the window, but it moves with it. I don't know where to start: do I need to mess with scene, view, resize event or even rectangle itself? I tried to pl...
You can easily fix this using view.setAlignment(Qt::AlignLeft | Qt::AlignTop);, this function will set the alignment of the scene to the top left corner of the QGraphicsView. This is what your code should look like. #include <QtWidgets> int main(int argc, char *argv[]) { QApplication app(argc, argv); QGraphics...
67,884,798
67,896,787
CMake with ROS Package:Header files not detected
I am trying to organise my code into a more OOP style with each class taking on its own header and cpp file. This is my tree in the package folder in the workspace - CMakeLists.txt - include - - Master_Thread.h - - Entry.h - - ROS_Topic_Thread.h - src - - pcl_ros_init.cpp - - archive - - - pcl_ros_not_updated.cpp - - -...
In essence you don't need to include either header into the other. This fixes the circular includes. In ROS_Topic_Thread.h, friend class Master_Thread; already forward declares Mater_Thread, so you don't need the Master_Thread.h header. In Master_Thread.h, you can also forward declare class ROS_Topic_Thread; before the...
67,884,953
67,900,256
extern "C" extern variable in C++ program sought as a class variable.. how to declare it?
I have a code below. It is part of a dynamic shared library which is loaded by qemu program (a C program) using dlopen. extern "C" { extern uint64_t host_virt_offset; } int Driver::CallSetBareMetalMode( uint64_t * args_ptr) { dbg_enter(); (... some codes ..) baremetal_axpu_es = (struct es_t *)...
This is how I solved it. I added the variable host_virt_offset in class Driver which is different from the variable host_virt_offset which is set by qemu. And I copied the extern host_virt_offset to the class Driver's variable host_virt_offset like below. extern "C" int some_function_during_the_init(...) { ... some co...
67,885,413
67,885,477
C++ How do I prevent Memory Protection Violation?
I have a problem with memory violation problem that occurs if reach else if(argc == 2) I'm trying to have a nice written script with no errors like that, anything else works like a charm... Here's a code fragment: //... // POWER ON if(strcmp(argv[2], "on") == 0) { // GPIO On pin_...
I followed @Yksisarvinen advice and reorder the code and now it works flawless: //... if(argc == 3) { // POWER ON if(strcmp(argv[2], "on") == 0) { // GPIO On pin_on(); // Open the serial port READ-WRITE i...
67,885,689
67,886,519
Set a QStandartItem as Expandable without having a child item
i am trying to send a folder structure between two differnt programs which can be on different computers. On my server I have a QFileSystemModel and on my client I have a QTreeView which has a QStandardItemModel as a model. And i have a prebuild signal/slot system which can send QString and QStringList between the pro...
I think your best bet would be to override QStandardItemModel::hasChildren... class item_model: public QStandardItemModel { using super = QStandardItemModel; public: virtual bool hasChildren (const QModelIndex &parent = QModelIndex()) const override { if (const auto *item = itemFromIndex(parent)) { ...
67,886,002
67,886,117
Having trouble passing lines from txt file to array
I feel like I'm completely missing out on something but my compiler shows absolutely nothing when i test out if my array is getting filled with values from the txt file. void orderID(){ ifstream result; int flag; int loop = 0; string temp; string line; string myArray[flag]; result.open("resultat.txt");...
You need to initialize myArray with the correct size, which means after you compute the flag not while it is undefined void orderID(){ ifstream result; int flag = 0; int loop = 0; string temp; string line; result.open("resultat.txt"); while(getline(result, line)){ flag++; //number of lines in file ...
67,886,431
67,886,516
How to access each numerical element in cv::Point_<int> type?
I have a cv::Rect object. From it, I am getting the bottom right point of the rectangle. I want to separate the point object into two separate int variables. How do I do this? This is what I have so far: cv::Rect rectangle; bottomRight = rectangle.br() // this gives me a Point <int>, such as [545, 364] I want to separ...
The x and y ordinates of the cv::Point_<T> structure are stored as public member variables (of type T) called x and y (rather than as a 2-element array). So, your code should be: // bottomRight is [545, 364] bottomRight_x = bottomRight.x; bottomRight_y = bottomRight.y; (That is, if you really need to isolate them from...
67,886,706
67,887,992
Using preprocessor constant with cmake
I have a preprocessing constant in my code : const unsigned int nbins= _NBINS; And I would like to be able to change it when compiling. For example, I would like to be able to write: cmake build_path [string to change _NBINS] How can I do it using cmake? Edit: I usually use makefiles so I was a bit confused For those...
How can I do it using cmake? You can pass the value of your constant into a cmake variable then inside a cmake script get the value of that constant and pass it to compiler. Call cmake with: cmake build_path -D NBINS=something And inside CMakeLists.txt: add_executable(your_target ...) target_compile_definitions(your...
67,886,916
67,901,483
Alias to a double array from another byte array
I am trying to create an alias to a double array from an array of bytes. But it happens to be behaving differently than I have expected. The array of bytes stores - sensor code (int) followed by location data (double[3]). This is what I have tried std::byte mSensorData[sizeof(int32_t) + 3 * sizeof(double)]; int32_t& m...
i cant comment on your post so i will add another answer :D. That version works because now you are doing the conversion correctly. The mSensorData + sizeof(int32_t)) now will get you sizeof(int32_t) bytes to the right in mSensorData (notice that this happens because mSensorData is of type byte .. it's actually taking ...
67,887,165
67,887,405
C++ vector constructor implementation
How do I make it possible to call the following construct for my vector class? vector <int> v{1,2,3}; how to properly declare such a method? My source code: template<typename T> class my_vector { T* values; std::size_t values_num; std::size_t max_size; public: explicit my_vector(std::size_t si...
The easy way is a constructor taking a std::initializer_list<T>. Another way is writing a template constructor, a bit like this: template<class...Ts> requires (std::is_same_v<T, Ts> && ...) explicit my_vector(Ts...ts); but getting that just right is a pain, so just go with initializer_list.
67,887,208
67,887,561
Queue using struct (Taxi dispatch problem)
I want to write program that reads command from user, when d is entered a taxi is entered ,it prompts to enter driver_id and stores taxi in in queue (queue can have maximum n taxi), when command c is entered by customer it assigns the earliest taxi in the queue to the customer. I'm trying to solve it using struct membe...
The problem is that when you check the condition if(!q.insert(driverid)), you've already insert that driver into the system. Then the else statement insert it another time with q.insert(driverid); So the solution is to simply remove the else statement. #include<iostream> using namespace std; const int n=4; struct Queu...
67,887,451
67,917,794
How do I set the whole rows background color in a C++ console app
How do I go about doing as mentioned in the subject line? Below is a screenshot of my console app as well as some code. switch (indicator) { case GreenFlag: indicator = GreenFlag; system("CLS"); SetConsoleTextAttribute(GetStdHandle (STD_OUTPUT_HANDLE), BACKGROUND_GREEN); cout << "IF...
So this is what I came up with in the end! I think it's pretty solid, but it still needs quite a bit of work. @IInspectable I'm still looking into the best approach to clear the screen so that it's future proof. string message = ""; // Indicator mood; // mood = (Indicator)Random.Range(0, System.Enum.GetValues(typeof(In...
67,887,863
67,887,982
Data hiding worth for simple data containers
In my company, we generate code from XML. The code generator generates header files that contain Messages, and each message contains only data. NOTE we don't do any validation while setting or returning data; also, we don't have to take care of the state, i.e., data x and data in a message are independent; if x is chan...
If you have the following pattern: class A { public: void SetFoo(const Foo& newFoo) { f = newFoo; } const Foo& GetFoo() const { return f; } protected: private: Foo f; }; That is, you have a getter/setter pair and all they do is have a single return statement and a single assignment ...
67,888,722
70,534,435
How to know C++ derived class's base class?
Assume I have a base class A, and two abstract class B and C, and their derived class D and E. How can I distinguish D and E's last layer class? (D's last layer class is B, E is C) Here is the code: #include <iostream> using namespace std; class ClassA { public: virtual int testFunc() { return 1; } }; class ClassB : p...
It is already in the comments, you can use dynamic_cast as a replacement of somemethod in your code as follows: #include <iostream> using namespace std; class ClassA { public: virtual int testFunc() { return 1; } }; class ClassB : public ClassA { public: virtual int testFunc() override =0; }; class ClassC : public Cla...
67,888,896
67,891,634
I am having trouble implementing SFML into Visual Studio
This is the output of the attempt I have tried multiple different tutorials through today and I seem to get this same output: 1>main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: __thiscall sf::CircleShape::CircleShape(float,unsigned int)" (__imp_??0CircleShape@sf@@QAE@MI@Z) referenced ...
Didn't realize I was compiling for x86 so I switched it to x64 thank you for that comment :)
67,890,187
67,890,816
C++ outputted data overlaps?
I'm writing a program that reads a text file and outputs the data. For example, here's what one "entry" of the data looks like: Alexander, Maurice DB 1 0 0 0 0 I've written some code to read this first entry and output it. struct playerType{ string name; string position; int touchdowns; int catches; int yard...
You'll have to replace all the carriage-return + new-line character combinations(which are used as new-lines on Windows but aren't understood by (some distros of) Linux) with simple new-lines. Here's some code for doing that: #include <string> #include <regex> name = std::regex_replace(name, std::regex("\r\n"), "\n");...
67,891,058
67,896,915
adding the libpng library to cpp in visual studio 2019
I have never added libraries before and I couldn't find a tutorial which I understood and could follow. I downloaded libpng from here in "download latest version". could anyone explain to me what goes where with specific names and how to find everything? much appreciated.
I suggest you could follow the following steps: 1,Add the path to the header file to the Additional Include Directories(property - >c/c++ -> General -> Additional Include Directories) 2,Add the path to the .lib file to the Additional Library Directories (property -> linker -> General -> Additional Library Directories) ...
67,891,107
67,892,472
How to make a class template specialization for reference and non-reference types?
I have a class called Pen: class Pen { int m_color; public: Pen(const int &color) :m_color(color) {} }; and I want to have a class called Drawable that stores a Pen. If the user passes in an lvalue reference of a Pen to the constructor of Drawable then I want to store that Pen as a reference inside D...
So I found a way that suits my needs and that is basically the combination of @Kevin's answer and @Sam Varshavchik's comment on the question. So I'm using std::shared_ptr with Class template argument deduction guides. Here's my solution: template<typename> // Base Condition class Drawable {}; /* Lvalue */ template<> ...
67,891,271
67,891,601
how to have a QVector of QMap
I wanna have a QVector of QMap. I used this syntax: QVector<QMap<QString, QString>> x; x[0].insert("name", "jim"); x[0].insert("lname", "helpert"); x[1].insert("name", "dwight"); x[1].insert("lname", "schrute"); but this is not working: I'd appreciate it if someone guide me to the correct format.
The "Index Out of Range" error comes up because you are trying to access an element of the vector which doesn't exist. Instead of accessing a particular index/element of the array it would be better to create a QMap outside of the QVector first and then x.push_back(map) so the map will be happily placed at the back of ...
67,891,303
67,912,453
Using std::fstream causes program to end with SIGILL in PASE for i (7.3)
I am working in an IBM i 7.3 environment from IBM's CECC service. I'm attempting to test a large application in the PASE environment, but I've had trouble with scripts that use the <fstream> library. Opening a file in write mode causes scripts to terminate with SIGILL. To test this problem, I wrote the following script...
When using GCC to compile for PASE you must use -pthread instead of -lpthread (or also set -D_THREAD_SAFE). Without this you can run in to problems as AIX header files shipped by PASE have compile-time threading behavior. In addition, the libstdc++ has a different ABI depending on whether you compile with -pthread or w...
67,891,338
67,892,765
c++ terminate called after throwing an instance 'std::out_of_range' what(): basic_string::substr: __pos > this->size()
Problem: Given a word quiz with m blanks, clues and a maximum of n words per clues (3<=m,n<=100) The first line of the input contains m,n. The next m line contains the word quiz and the clues you need to fill. The blank which you need to fill is marked as 1 and the one you don't need to fill is marked as 0. The output...
for (int i=1; i<=m;i++){ string str= map[i]; ... } This loop is wrong. map[i] will go out of bounds of the vector when i == m, thus any use of the returned string& will be undefined behavior (including the initialization of str). But you are not getting a runtime error on that because vector::operator[] doe...
67,891,441
67,892,042
new with multiple arguments in cppreference example
From cppreference's new page. new T; // calls operator new(sizeof(T)) // (C++17) or operator new(sizeof(T), std::align_val_t(alignof(T)))) new T[5]; // calls operator new[](sizeof(T)*5 + overhead) // (C++17) or operator new(sizeof(T)*5+overhead, >std::align_val_t(alignof(T)))) new(2,f) T; ...
What does new(2, f) T; do? That second argument in placement-new can be used to pass a parameter to your custom T::operator new implementation. Here is a toy example that triggers it (in the output, you can see that the parameter f=42.0is passed to T::operator new): #include <iostream> struct T { T() { std::co...
67,891,815
67,891,949
Defining a string literal
What's the difference between this two literal string definitions?: const char *message1 = "message1"; const char message2[] = "message2"; If both of them are null-terminated it's so strange - when i pass the first one to some text printing function I get an "memory could not be written" error but when pass the second...
const char message2[] = "message2"; "message2" will be placed in read-only memory. Then its characters are copied to the allocated memory of the message2[] array. const char *message1 = "message1"; "message1" will be placed in read-only memory. message1 will simply be a pointer to that memory. In both examples, value...
67,892,358
67,892,413
Ordering of thread member relative to atomic bool member
In this code simplified for SO m_thread is the first member of Foo and m_ready is the second member. Does this mean that m_thread can see an uninitialized value for m_ready or will the thread start after the other members are set (after m_ready is set to false)? #include <atomic> #include <thread> #include <unistd.h> ...
Class data members are initialized in the order they appear in the class definition. m_ready is declared after m_thread so it is constructed after m_thread. Your m_thread constructor starts a thread of execution, the given function will start immediately. There is a race between the thread reading m_ready and the const...
67,892,405
68,434,243
how do I properly link GLAD to my project
I am making a small game engine in Visual Studio. As far as I am aware I have everything linked correctly, but I am still generating this in the .log file Creating library C:\dev\Gluten\Gluten\bin\x64\Release\Gluten.lib and object C:\dev\Gluten\Gluten\bin\x64\Release\Gluten.exp WindowsWindow.obj : error LNK2001: unreso...
I suggest you should add the glad.c to your solution. Go to Visual Studio > Solution Explorer > Source Files > Add > Existing Item.
67,892,572
69,034,408
How to detect power saving mode of graphic card in windows application?
I have an application using an OpenGL window that works ok, but someone detects that if the graphics performance is configurated as power saving, the screen doesn't show any render, it only show a black screen that could be interpreted as a UI bug. I was wondering if there is a way to know if my application is running...
The problem was that I was trying to use texture2D that the Intel GPU doesn't support. I just change it to texture, as recommended in comments
67,892,664
67,899,400
How to use classes inside headers in c++
So i'm very new to c++ and i'm trying to test out the simple features it has. I currently have a problem that there is a 'class' type redefinition and I can't figure out why. I have used #pregama once in the header file, but still. I have even tried #ifndef and #define, but they did not work either. I'm using Visual st...
First of all, I agree with Silvio Mayolo, You're defining the class once in the header and once in the C++ file. You don't use the keyword class in your cpp file. And then you need to distinguish between class Vector2 and Vector2(double x, double y); As far as I'm concerned you should try to use Vector2::. Here is my c...
67,892,764
67,893,611
Compare char with char[i] not working in hangman game
I was trying to do a hangman game, my idea was that you give the number of letters and the word, then the program fills a char with _ as letters the word has. Then it asks you a letter and it compares if the letter matches any letter in the word given. Then it replaces the respective _ with the letter, but it doesn't r...
int n = 0; char blank[n - 1]; There are three things wrong with this: The n is initialized to 0, but then the array will have 0 - 1 length. The value of n isn't really known until it is input by the user, but you went ahead and declared blank with n-1 entries. Even if n were initialized to something reasonable, the...
67,893,383
67,893,632
C++ : why have a return in a if statement?
I've trying to work out why someone would write the following section of code in a Arduino loop. To me, it doesnt make sense, why have a return in a if statement? Does it just return to the start of the loop and not carry on with the rest of the loop. Here's the snippet of interest: if (!modem.available()) { Se...
Being able to return from functions early is one major reason to use functions. Arduino perculiarities aside, a very common case is for example to break out of nested loops. Suppose you have for (int i = 0; i < imax; ++i) { for (int j = 0; j < jmax; ++j) { do_something(i,j); if (some_condition(i,...
67,893,577
67,953,771
build failed with first substrate chain
wanna create my first substrate chain step by step done based their guide [1]: https://substrate.dev/docs/en/tutorials/create-your-first-substrate-chain/ run this command : cargo build --release but get this error: Compiling sc-chain-spec v3.0.0 The following warnings were emitted during compilation: warning: ...
in arch based linux you need these prereqs : export OPENSSL_LIB_DIR="/usr/lib/openssl-1.0" export OPENSSL_INCLUDE_DIR="/usr/include/openssl-1.0" for other oses look at ./docs/rust-setup.md
67,893,981
67,894,038
Invalid pointer after a call to delete
I have this simple code in a file called virtual.cpp: #include <iostream> class Parent { public: virtual ~Parent(){ std::cout << "Parent Destructor" << std::endl; } virtual void VirtualFunction() { std::cout << "VirtualFunctionInParent" << std::endl; } }; class Child: public Parent { ...
I delete the pointer parent1, so this erases the memory to which the pointer point. Is my reasoning correct? No. You are getting a core dump from your delete. Only addresses returned from new may be passed to delete. delete does not erase memory, as memory has no concept of an "erased" state. which is the correct ...
67,894,192
67,894,909
get specific object by attribute called id or name from list object c++
I want to get/identify the object who has the Id "C003", for example, to print all data of that object. I receive the id typed with cin and store in a string variable. I've been reading many webpages and YouTube tutorials that use function find() or find_if(), but those examples use only numbers, so the third parameter...
I've been reading many webpages and YouTube tutorials that use function find() or find_if(), but those examples use only numbers, so the third parameter is just a number, like 2. The 3rd parameter of std::find(), and the parameter of the std::find_if() predicate, can take any type that is compatible with the type ref...
67,894,226
67,895,854
range based for-loop on r-value
The following does not behave as i would like it too, as the destructor of Foo is called before the range-based for loop enters the body making the iterators invalid (msvc 2019). Is there a way to "capture" the Foo object within without changing the syntax in the following code? I have seen the c++20 initializer part o...
It really depends on what your operator<< returns. Remember that behind the scene, your range-based for loop basically produce a code like this: auto && __range = Foo() << "bar" ; auto __begin = __range.begin() ; auto __end = __range.end() ; for ( ; __begin != __end; ++__begin) { auto& row = *__begin; ... lo...
67,894,319
68,178,073
Cannot add Widgets to QMainWindow using Qt Designer and Clion
I am starting to learn Qt for a project and I would like to use CLion to do it. Having said that I followed the official tutorial to configure Qt on CLion: https://www.jetbrains.com/help/clion/qt-tutorial.html I set both Qt Designer and Creator as External Tools, so I can edit the .ui files. Then I created a Qt Widgets...
I had the same problem in CLion. When we inspected the ".ui" file, we realized that this was the case because there was no "central widget". We found a workaround, but yet we can not get results for a definitive solution. Solution: Right-click on the ".ui" file and mark it as "Mark as Plain Text". Then open the file. I...
67,894,424
67,895,115
(Windows HID API) HidD_GetPreparsedData() failing in WM_INPUT message handler due to incorrect handle?
I am trying to write custom handling for an Apple Magic Trackpad 2 (ultimately any Windows Precision Touchpad) into a Windows Desktop application. I am using this project as a guide, as it accomplishes similar goals. I am at the point where I have registered the HID touchpad, and am able to receive WM_INPUT messages, w...
I fixed it! I am not sure as to why I couldn't use HidD_GetPreparsedData(), but getting the data with GetRawInputDeviceInfo(), using the RIDI_PREPARSEDDATA param, worked just fine.
67,894,517
67,897,422
boost::enable_if enabler() related to the tutorial on creating an iterator with boost::iterator_facade
So... looking at this code fragment: #include <boost/iterator/iterator_facade.hpp> #include <boost/type_traits/is_convertible.hpp> #include <boost/utility/enable_if.hpp> template <class Value> class LMI : public boost::iterator_facade<LMI<Value>, Value, boost::forward_traversal_tag> {...
So... sheepishly, if I add struct enabler {}; to the private section of the class template, all is good. Doesn't exactly explain how this works --- but I'm happy with the secret sauce for now. Obviously, I was adapting the tutorial example to my own work, sigh.
67,894,675
67,894,816
input string with spaces on FOR LOOP c++
I already know how to input a string with space in c++, but it doesn't work in a for loop, already tried some variants of this: for (int i; i = 0; i < 10; i++){ cout << "Name: "; cin >> getline(cin, obj[i].name); } Can someone show me what I'm doing wrong? edit as requested: this is a dummie struct to show struc...
Whatever your problem is, it is likely not with the getline() function. Try reformatting your question. Possible solution: Check if you are using cin earlier in your code, as this is what will cause the bug. You should not mix input streams. If you do use cin, add a cin.ignore() after and this will fix your issue. If y...
67,894,815
67,899,346
boost unit test cartesian product of mpl list
Suppose I have two mpl lists, say typedef boost::mpl::list<int, double> inner_types; typedef boost::mpl::list<std::vector, std::set> outer_types; I was hoping to be able, in a boost unit test, to iterate over the cartesian product of these lists and construct an object from each combination..something like the followi...
You could use Boost MP11 similar to this to merge merge the two lists to a single Cartesian product as follows #include <boost/mp11.hpp> template <template <typename...> typename... F> using mp_list_q = boost::mp11::mp_list<boost::mp11::mp_quote<F>...>; using outer_types = mp_list_q<std::vector, std::set>; using inne...
67,895,002
67,895,223
how to get a return type of a member function pointer
Is there a way to determine a return type of a member function pointer? Code sample: ///// my library void my_func(auto mptr) { // have to use `auto` // some logic based on a return type of mptr: int, string, A, etc. } ///// client code struct A { int foo(); std::string bar(int); }; class B{ public: A func(in...
You can use partial template specialization to determine the return type of mptr: template <typename T> struct ReturnType; template <typename Object, typename Return, typename... Args> struct ReturnType<Return (Object::*)(Args...)> { using Type = Return; }; void my_func(auto mptr) { typename ReturnType<decltype...
67,895,394
67,895,449
How can I parametrize the execution policy of a standard library algorithm?
I have this call to the sort C++ algorithm: std::sort(std::execution::par_unseq, vec.begin(), vec.end()); Now I would like to parametrize the execution policy: std::sort(executionPolicy, vec.begin(), vec.end()); However, std::execution::seq, std::execution::par, std::execution::par_unseq, std::execution::unseq are ob...
The approach I've used for this has been to use std::variant and std::visit for this purpose. using parallel_policy_holder = std::variant < std::execution::sequenced_policy, std::execution::parallel_policy, ...
67,895,685
67,905,752
Name integers in a loop
I need to give these integers names like ex_number_1, ex_number_2, ex_number_3, etc... These are each going to be saved as a different branch of a tree. So I have done: char m_variable2 [40]; For (……){ sprintf(m_variable2, "ex_number_%d",iSyst); int m_variable2 = … } This is within another couple of loops, e.g. to v...
It sounds like you want an associative container such as std::map or std::unordered_map. std::map<std::string, int> numbers; numbers["ex_number_1"] = 42; // or with a dynamic key: std::map<std::string, int> numbers; for (...) { int iSyst = ...; numbers[std::format("ex_number_{}", iSyst)] = 69; }
67,896,528
67,896,775
CProgressCtrl::CprogressCtrl(const CProgressCtrl &)"(declared implicitly) cannot be referenced -- it is a deleted function
I am working on an MFC dialog application. I created a progress control (IDC_PROGRESSUPLOADING) in the dialog interface and add a variable m_progress for this control. The m_progress is passed to a function (start_update), which will set and display the progress control. Dlg.h ... public: afx_msg void OnStnClickedS...
Just focusing on the error, basically a compiler error of this type: SomeObject::SomeObject(const SomeObject &)"(declared implicitly) cannot be referenced -- it is a deleted function indicates that SomeObject cannot be copied due to the default compiler's copy constructor: SomeObject::S...
67,897,033
67,897,155
Sorted container of pointers to custom types based on a non-unique priority value, as a class member
I need a container that meets this scenario: Needs to be a member of a class Needs to contain pointers to a custom type The elements are sorted using a non-unique priority value (an integer. for example: priority 0 items go before priority 1 items, before priority 2 items. Order between items of the same priority is n...
A std::multiset with a custom compare function will suffice: #include <iostream> #include <string> #include <set> using namespace std; struct Item { std::string data; int priority; }; struct item_compare { bool operator()(Item* lhs, Item* rhs) { return lhs->priority < rhs->priority; } }; i...
67,897,064
67,897,102
Is closing fstream ( I/O ) necessary?
I was learning about fstream, ofstream, and ifstream. This work as expected Here's the code: myFile.open("brod.txt"); myFile << "Item 1"; myFile.close(); myFile.open("brod1.txt"); myFile << "Item 1"; myFile.close(); but if I remove the myFile.close() and change the output string. The second ...
A std::fstream will close itself when it goes out of scope. In your case however, the second call to std::fstream::open() fails, which sets the failbit on the stream (and could thrown an exception, but obviously doesn't in this case). With the failbit set, additional attempts to write to that stream will fail. See Re...
67,897,162
68,614,362
Error using C++ COM/IFileDialog in VS Code while the same code works in Visual Studio. Message: 'IID_IFileOpenDialog' was not declared in this scope
I have C++ code where I'm trying to open a file select dialog with the Component Object Model's IFileDialog. The code works in Visual Studio but when I type the exact same code in VS Code, there are 2 errors: IID_IFileOpenDialog' was not declared in this scope and invalid use of incomplete type 'IFileDialog' {aka 'str...
By default, it looks like MinGW sets the value of the NTDDI_VERSION macro to 0x05020000 (NTDDI_WS03), which disables the IFileDialog definitions in shobjidl.h. The value of the macro must be at least 0x06000000 (NTDDI_VISTA) to enable the definitions. Possible values of these macros and their meanings are listed here...
67,898,278
67,898,643
Partial Template Specialization in C++ 98?
Does C++ 98 support partial template specification? The following code compiles fine under C++ 11, but doesn't compile in Visual C++ 6.0. So I am wondering if the syntax needs to be slightly different or if it's just not supported: #include <iostream> #include <string> template <typename A, typename B> class Foo { pub...
Microsoft Visual C++ 6.0 does not support partial template specialisation. It is a known bug. For more known standard compliance issues of VC++6.0, see here. Archive links, since these KB articles seem to be removed from Microsoft databases
67,898,391
67,898,463
How do i print an array out to the console?
I'm currently working to make a 2D grid which the user can select the start destination, end destination and obstacles in between. I would like to print the array (as shown above) to the console to help users visualise the the array they are traversing. I'm using Visual Studio and working in c++. Further to this, is th...
To change specific parts of an array you can access it's values like this: arr[4][5] = 5; // Returns the sixth element in the fifth row and changes it to 5 To print you would right something like this assuming you are working with std::vector (if not substitute arr.size() with a literal or your own variable). for(int ...
67,898,558
67,901,077
What happens in C++ if a function return value is passed to a function reference argument?
Let's consider two functions: //Test functions Object MakeObj(){/* processsing */}; Object ChangeObj(const Object& obj){/* processsing */}; //Then execute Object test_obj = ChangeObj(MakeObj()); Is the execution safe? Where is stored the 'Object' return value of the MakeObj()? Can I use a reference to that storage? ...
Execution is safe because const reference extends object lifetime(or here) The object itself is stored somewhere on the stack, but it will not be erased as long as the const reference exists(compare asm line 20(non-reference) and 25-27(const reference)) No. It isn't necessary. In the general case, the code from poi...
67,898,722
67,928,817
boost::xtime has no member named 'is_pos_infinity'
I've been tasked with porting a piece of legacy software and the client has decided they want to update Boost from 1.34 to 1.75 in the process. Unfortunately, I'm having this issue show up when compiling: /usr/include/boost/thread/pthread/recursive_mutex.hpp: In instantiation of ‘bool boost::recursive_timed_mutex::time...
In my particular case, I was able to find the root cause and fix it. I feel like the latest doc is weirdly laid out as far as determining what the expected input-variable's type should be is concerned, but according to the Boost v1.75 doc, m.timed_lock(t) expects a type of boost::system_time, yet was still being fed a ...
67,898,785
67,900,402
Memory usage from C# apps using C++ DLLs
Just to get it right, I would like to have your opinion if I am right with my imagination of how the dataflow is between a C# programm calling a C++ dll with delegates as parameter. The System gives memory to the C# program The C# Program loads the .dll and gives some of its space to the C++ dll. In this space there w...
This should be described in the documentation for the marshaller if they are native types or a reference to the variables in the C++ memory, if it is a complex type. If we have native types I can just save it into the C# world and all will be fine. But if it is a reference and I just save it into my C# memory, I will ...
67,899,627
67,906,419
C++ SDL2 window not opening
i coded this. #include <iostream> #include "SDL.h" int main(int argc , char** args) { SDL_Init(SDL_INIT_EVERYTHING); SDL_Window* win = SDL_CreateWindow("my window", 100, 100, 640, 480, SDL_WINDOW_SHOWN); if (!win) { std :: cout << "Failed to create a window! Error: " << SDL_GetError() << "\n"; } SDL_...
Would there be any solution to get the Window to not close? Start up an event-handling loop and handle some events: // g++ main.cpp `pkg-config --cflags --libs sdl2` #include <SDL.h> #include <iostream> int main( int argc, char** argv ) { SDL_Init(SDL_INIT_EVERYTHING); SDL_Window* win = SDL_CreateWindow("my ...
67,899,818
67,899,952
How to iterate through a vector of vector in C++?
I would like to know if it is possible to access the elements of std::vector<std::vector<int>> via iterators: I cannot understand why this won't compile: #include<vector> #include<iostream> std::vector<std::vector<int>> vec {{1,2},{3,4}} ; // to access the single vector auto it = vec.begin() ; // to access the...
auto iit = it.begin(); doesn't compile because it is an iterator, not a vector. You should use the overloaded value-of operator to get the vector pointed to by it. auto iit = (*it).begin(); Then you can use the iterators as normal. You can also use range-based for-loops: for(auto &row : vec) { for(auto &col : row...
67,899,951
67,904,228
Change version of gcc which does not support compiling C++ programs using the compilers.yaml file
I am trying to install hpctoolkit using spack. In order to do that, I executed : git clone https://github.com/spack/spack.git cd spack/share/spack source setup-env.sh spack fetch -D hpctoolkit spack install hpctoolkit I can't execute the last command because I get the following error: Error: ProcessError: Command ex...
As you can see in the error, compiler 'gcc@10.2.0' does not support compiling C++ programs. In order to display the compilers, use the command: spack compiler list Before retiring the misleading version, I had the following result for the previous command: -- clang ubuntu20.04-x86_64 ---------------------------------...
67,900,261
67,900,480
How do I pass parameters to constructor multiple times
Below gives only the 1st parameter list, (4,5); the 2nd (5,8) does not work. Please suggest. #include<iostream> #include<string> using namespace std; using std::cout; using std::endl; using std::string; class Rectangle { public: Rectangle(int length, int breadth) { cout << "Area = " << length * breadth << endl; } }; ...
When you call: Rectangle rect(4,5); You're defining a Rectangle accesible through the rect variable . If you call: Rectangle rect(5,8); after the first definition it's going to throw an error (rect already defined). Instead you have to use two different variable names: Rectangle rectA(4,5); Rectangle rectB(5,8); Unl...
67,900,391
67,901,094
Access violation writing location during ifstream read
So I'm making basic CRUD create work fine but when the code reach file.read(code) VS display Read Access Violation When I try to run each line 1 by 1 in read function there's no error until I reach file.read I'm not able to figure out the causes I suspect the problem is in here: Mahasiswa read(fstream &file, int pos) {...
From language lawyer's point of view an UB happens here: file.write(reinterpret_cast<char*>(&mhs), sizeof(Mahasiswa)); and here: file.read(reinterpret_cast<char*>(&result), sizeof(Mahasiswa)); What happens here is an equivalent of memcpy. memcpy is an equivalent of shallow copy, but can be used only on so-called "POD...
67,900,767
67,908,681
Debugging multiprocess project with GDB
I'd like to to debug a multiprocess C++ project with GDB, specifically I'd like to know if there is a way to achieve the following Attach multiple processes to a single instance of GDB while letting all the processes run Setting up a breakpoint in the source code of one of the processes stops all the attached processe...
In order to be able to run inferiors in the background, one needs to issue this gdb command set target-async on after start up and before running anything. With this option in effect, one ca issue continue& (or just c&) and this will send the inferior to the background, giving an opportunity to switch to run another ...
67,901,254
67,901,289
Elements don't show up on Dialog
I am trying to implement a Dialog using QT. This is my first time to write down a Dialog instead of using the designer. This is because this dialog will have some fields which will depend on some selections to appear or not. I following this guide so far but using it for my own Fields: https://www.informit.com/articles...
The problem is that the layout is not assigned to a widget, the solutions are PlanetsVLayout = new QVBoxLayout(this); or PlanetsVLayout = new QVBoxLayout(); setLayout(PlanetsVLayout);
67,901,424
67,901,724
Providing a correct std::copy_if predicate
The aim of the example program is to copy every third item from source to target with std::copy_if. Based in the reference, the copy should happen whenever the predicate returns with true, but this is not the case with the below code. #include <iostream> #include <vector> #include <algorithm> using std::vector; int m...
Unfortunately, sometimes cplusplus has wrong/misleading information. They write: result Output iterator to the initial position of the range where the resulting sequence is stored. The range includes as many elements as [first,last). And that is wrong. The output range has as many elements as the predicate returns tr...
67,901,592
67,901,622
How to define a template function with the help of std::enable_if
What I'm trying to do is to define a template function, which can only be specializd by the class, which inherits some classes. For example, I have already had two class Base1 and Base2. I'm trying to define such a template function: template<typename T> // if (std::is_base_of<Base1, T>::value || std::is_base_of<Base2...
C++11 template <typename T, typename = typename std::enable_if< std::is_base_of<Base1, T>::value || std::is_base_of<Base2, T>::value>::type> std::ostream &operator<<(std::ostream &os, const T &t) { // os << t.member1 << t.member2...; return os; } or: template <ty...
67,901,885
67,922,078
How to handle Datachange signal for circle diagram?
I'm drawing circle diagram using my own inbuilt libraries. I'm able to draw circles using table data (x1,y1 & r) ,sharing code I'm using datachange signal with table, whenever enter any table item data then its creating no. of graph with circles. Is there other signal I can use or what change can make in code ? I want ...
Thank you ..I have solved the problem .When anything changes in the table, I need to remove the existing curve containing all the circles and build/add a new one, or replace the data
67,901,964
67,902,225
Is it possible to use C++'s sort in C?
I am writing C code but have to do a lot of calls to qsort which is taking most of the time. I notice that C++'s sort is faster than qsort. Is it possible for me to use it somehow? Here is a MWE in C: #include <stdio.h> #include <stdlib.h> #include <time.h> #include <stdint.h> int cmpfunc (const void * a, const void *...
Yes, it is possible. C++ is designed to handle such things without much hassle. You need to compile the C++ function separately and then link it to your project: The header should be valid C and C++. You need to use extern "C" by checking if it's C++: // i32sort.h #pragma once #include <stdint.h> #include <stddef.h> ...