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
72,161,504
72,163,631
Does std::atomic<> gurantee that store() operation is propagated immediately (almost) to other threads with load()?
I have std::atomic<T> atomic_value; (for type T being bool, int32_t, int64_t and any other). If 1st thread does atomic_value.store(value, std::memory_order_relaxed); and in 2nd thread at some points of code I do auto value = atomic_value.load(std::memory_order_relaxed); How fast is this updated atomic value propagate...
The C++ standard says only this [C++20 intro.progress p18]: An implementation should ensure that the last value (in modification order) assigned by an atomic or synchronization operation will become visible to all other threads in a finite period of time. Technically this is only a "should", and "finite time" is not ...
72,161,614
72,167,256
identifier D3DReadFileToBlob is undefined?
#include<D3Dcompiler.h> void Init() { D3DReadFileToBlob(L"", nullptr); } it gives D3DReadFileToBlob is undefined error, i don't think it is a linking error and i read this which i don't get what am i suppose to do (i think that might be the cause) so what should i do to fix this?
The problem was that i was using both Windows Kits and Directx SDK at the same time and that caused this error, Because i was watching old tutorials i didn't know that i really don't need Directx SDK and i could use Windows Kits which already has everything in it for development of directx 11.
72,161,866
72,162,062
cannot be used as a member pointer, since it is of type 'void (*)()'
I'm trying to dereference a method pointer stored in a static array and call it from within a method, but I'm getting the following error: error: 'chip8::Chip8::table[0]' cannot be used as a member pointer, since it is of type 'void (*)()' (this->*table[0])(); ^ Here is my class declaration (c...
The problem is that when you wrote: static void (*table[16])(); you're declaring a static data member named table that is an array of size 16 whose elements are pointers to free function with no parameter and return type of int. But what you actually want is a table that is an array of size 16 whose elements are point...
72,162,158
72,162,205
Why does not std::priority_queue constructor work?
Why is it that when I call the same constructor, it works in one case, but not in the other? std::vector<ulli> v(n); for(int i = 0; i < n; i++){ inf >> v[i]; } std::priority_queue<ulli> q1(std::greater<ulli>(), v); // fails std::priority_queue<ulli> q2(std::less<ulli>(), v); // works
Because of the default template parameter, the Compare of std::priority_queue<ulli> is of type std::less, and in your first example, you use std::greater to initialize std::less, which is not correct. With help of CTAD, just std::priority_queue q1(std::greater<ulli>(), v);
72,162,197
72,162,263
How to assign base class shared_ptr object to child class shared_ptr object
in below scenario, I need to invoke child class B function (fun1) from Base class A shared pointer returned by setup function and for the same have used dynamic_cast_pointer so that derived class shared_ptr object can be assigned to Base class shared_ptr but during compilation I am not allowed to do so. Can anybody sug...
I presume the question is cut down from the real problem. Presuming you're not expecting this example to work at runtime (you are casting a pointer to A as a pointer to B when it's an instance of A - so you're in undefined behaviour territory), the issue is that you have no virtual methods. The compiler tells you this...
72,162,281
72,162,546
C++ Vector subscript out of range when assigning values
I am making a simple algorithm that counts how many times each number is represented in a vector. However, on compile it gives me the following error in popup: Vector subscript out of range and it is referencing to: File: C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.31.31103\include\vector...
On the input [-3, -2, -1], your program will: Set mx=-1. Set mn=-3. Create a vector vl of size 3, so with the positions vl[0], vl[1] and vl[2]. Try to set vl[3] += 1, which throws the error you are seeing, as vl[3] does not exist. You should have std::vector<int> vl(mn * -1 + 1); to avoid out-of-range exceptions.
72,162,309
72,162,428
How to call a templated function for each type in a tuple (acting as type list) with tuple b as argument
How to call a template function for each type in a typelist with arguments (e.g. another tuple)? Given is a typelist std::tuple<T1, T2, T3, ...> and a std::tuple containing data. template <typename T> void doSomething (const auto& arg) { std::cout << __PRETTY_FUNCTION__ << '\n'; } template <typename T> struct w {T...
Use template partial specialization to extract the type of typelist, then use fold-expression to invoke doSomething with different template parameters template<typename Tuple> struct someFunctor; template<typename... Args> struct someFunctor<std::tuple<Args...>> { template<class T> constexpr void operator()(T&& x)...
72,162,366
72,162,519
Change image range using linear interpolation
so I want to change an image from lets say width=500 to width=100, using linear interpolation. How can I do that?
I'll try to help even though the question requires improvements: You can use cv::resize to resize the image. The interpolation parameter can be set to cv::INTER_LINEAR for linear interpolation. Code example: cv::Mat bigImg(cv::Size(500, 500), CV_8UC1); // Initialize bigImg in some way ... cv::Mat smallImg; cv::resize(b...
72,163,114
72,173,789
Segmentation fault when trying to pass dynamic array to processes
I tried to pass dynamic array from 0 process to 1 and vice versa. Getting segmentation fault in process 1. All matrices printed as expected. What could be the problem in this situation? int main(int argc, char **argv){ MPI_Init(&argc,&argv); int n; cin >> n; int *matrix = new int[n*n]; int *matrix2 = new int...
Interactive input in parallel programs is always dangerous. Your MPI processes are often started through an ssh connection, and so they will probably not get the terminal input. Process zero most likely will, so I'd advocate reading n only on process zero and then broadcasting it.
72,163,357
72,164,530
SDL mingw static lib linking errors
I'm trying to compile a simple SDL program using Mingw w64. Here is my code: test.c #include "SDL2/SDL.h" #include <stdio.h> int main( int argc, char* args[] ) { SDL_Window *window; SDL_Init(SDL_INIT_VIDEO); window = SDL_CreateWindow("SDL2 Window", 100, 100, 640, 480, 0); if(window==NULL) { printf...
You have two options, depending on your intent: If you want to link SDL2 dynamically (this should be your default course of action), you need to add libSDL2.dll.a to your library directory. Then libSDL2.a will be ignored and can be removed. It should just work, no other changes are needed. If you want to statically l...
72,163,466
72,168,683
Using C++ libraries in VS Code (Winsock)
I'm coding on Visual Studio for a simple UDP socket application on windows, for which I need the ws2_32.lib library. Now, in Visual Studio I'm using #pragma comment (lib, "ws2_32.lib") to link the needed library. What about moving on VS Code? How can I use that library then? Aside from the C++ extension, do I need a p...
You can add properties in tasks.json in VS Code. This is the test demo DLLProject.lib { "tasks": [ { ... ... "args": [ ...... "${fileDirname}\\${fileBasenameNoExtension}.exe", "${file}", "DLLProject.lib" ...
72,163,822
72,163,939
Q: remaining 0 printed after using "\r" in C++ code
I created a program that works like a countdown and I ran into an error: Everything is printed fine until the seconds fall (counter.second) bellow 10, then it prints 90 instead of 9 ( or 09 ), 80 instead of 8 and so on. If I remove "\r" the "Time remaining text" will be printed the "counter" amount of times besides one...
Well, take a look: If you write I like cats. And then cover it with I like dogs. Everything's fine. But if you cover it with I like. Then cats. remain uncovered. I like.cats. This is what happens. You try to cover 10 with 9. The 0 remains uncovered. You can fix it with a space after that for example.
72,164,120
72,164,181
Why is returning a const from a function not being detected as a const?
I have a program which depends on the result of std::is_same_v <const value_t, decltype(value)>. However, I have found that when functions are passed to this expression the result is unexpected, causing me bugs. I thought that functions returning const value_t were going to be treated as being the same as const value_t...
y() is a prvalue expression. The type of this expression is not const int, but int. This is because the type of prvalue non-class non-array expressions have their cv-qualifiers stripped. In other words, it will work if you use a class type, but not with non-class types. This is just how the language works. There is no ...
72,164,146
72,164,275
Is there a way to use logical operations as templates in C++?
For example, I want to control the operator between A and B to something depending on the template I'm assigning it to (in main). // Theoretical operation template function template <OPERATION> void Example(int A, int B) { A OPERATION B; } int main(void) { Example< += >(10, 20); Example< -= >(10, 20); Example<...
You could template Example on the operation, and pass the operation as a third parameter. An easy way to pass the operation is as a lambda or, as @Yksisarvinen commented above, as one of the function objects available in std::functional. The example below works with arithmetic operators instead of logical operators (yo...
72,164,254
72,164,520
How to extract type list from tuple for struct/class
I want to use a static method in a class that gets a type list in the form std::tuple<T1, T2, T3,...>. Instead of working with std::tuple<...> I want to have <...>. How to implement example struct x resulting in Ts == <T1, T2, T3,...> template<template <typename...> typename TL, typename... Ts> struct x { static vo...
It seems to me that you're looking for template specialization. Something as // declaration (not definition) for a template struct x // receiving a single template parameter template <typename> struct x; // definition for a x specialization when the template // parameter is in the form TL<Ts...> template<template<typ...
72,164,839
72,164,915
Why is appending an int to a std::string undefined behavior with no compiler warning in C++?
In my code I use logging statements in order to better see what's going on. Sometimes I write code like the following: int i = 1337; // More stuff... logger->info("i has the following value: " + i); When compiled and executed in debug mode this does not print out i as expected (this is how it would work in Java/C# for...
The problem is that in logger->info("i has the following value: " + i); you are not working with std::string. You are adding an int to a string literal, ie a const char[] array. The const char[] decays into a const char* pointer in certain contexts. In this case, the int advances that pointer forward by 1337 character...
72,164,964
72,165,021
Vector as value in JSON (C++/nlohmann::json)
I want to have something like that: { "rooms": [ "room1", "room2", "room3", etc ] } I have an std::vector<std::string> of the name of the rooms, and I would like to convert it so the key of the JSON will be 'rooms', and its value will be a list of all the rooms. For conclusion, How to convert a std::vector to JSON a...
You can create a Json array directly from the std::vector<std::string> so something like this will work: #include <nlohmann/json.hpp> #include <iostream> #include <string> #include <vector> using json = nlohmann::json; int main() { std::vector<std::string> rooms{ "room1", "room2", "room3"...
72,165,365
72,165,416
All instances of a class share the same values
I've got a class called Data, whenever I declare a new instance of this class and change something in it, it changes all instances of that class. I'm not sure how to fix this, or why it is even happening. (Note, I've stripped back a lot of what was in my data class, but this example still produces the error) Data.h #in...
data is not defined in the class, so you create a global variable. Create a member variable. class Data{ public: struct Ts{ volatile int64_t unixTimestamp; } data; int ReturnTimestamp() volatile; void SetTimestamp(int) volatile; }; instead of volatile Data::Ts data;
72,165,736
72,165,894
How can I load an image in C++ using SFML library?
How can I load an image in C++ using SFML library? I am making a game using C++, and for textures of bonuses I want to upload *.png from directory instead of creating them in *.cpp file. How can I do this using SFML library?
Try something like: sf::Texture texture; if (!texture.loadFromFile("path/to/myTexture.png")) { perror("Couldn't load texture \"myTexture\"."); return; } You can then put it on spirte: sf::Sprite sprite; sprite.setTexture(texture); and finally display it: sprite.setPosition(x,y); window.draw(sprite);
72,165,914
72,166,047
How do I create a program that replaces the CODE to VALUE?
I just wanted to help with my code here's my questions How can I input "computer" in any in any order and case insensitively and still get the correct output? Here are the replacement COMPUTERS.X 1234567890.X If I input other letters that is not included in the COMPUTERS.X the program will terminate and ask again if i ...
Use a array to save convert rules. And both convert to upper to ignore case. #include <algorithm> #include <cstring> #include <iostream> using namespace std; bool encode(string& old, const char* replace_rules[]) { int i = 0; int replaced = 0; while (replace_rules[0][i] != '\0') { for (int j = 0; j < old.si...
72,166,085
72,166,327
Why does std::is_invocable_r reject functions returning non-moveable types?
I'm curious about the definition of std::is_invocable_r and how it interacts with non-moveable types. Its libc++ implementation under clang in C++20 mode seems to be wrong based on my understanding of the language rules it's supposed to emulate, so I'm wondering what's incorrect about my understanding. Say we have a ty...
So is clang wrong about accepting this initialization, or is the implementation of std::is_invocable_r_v wrong? This is a bug of libc++. In the implementation of is_invocable_r, it uses is_convertible to determine whether the result can be implicitly converted to T, which is incorrect since is_convertible_v<T, T> is ...
72,166,104
72,166,168
I want to use cout more comfortably
I want to use cout to print out this sentence: "You can build piramid which floor is only odd. not even", but I want to do it more comfortably. Just like the way below. But, when I use this way, an error occurs. So, is there any way to use it like this? cout << "You can build piramid which floor is only odd. n...
Adjacent string literals will automatically be concatenated, even if they are on different lines. So you can write it this way instead: std::cout << "You can only build pyramids whose floor is odd, " "not even.\n";
72,166,189
72,166,247
Issues with outputs for dynamic arrays
I'm working with a template class for dynamic arrays, and my code has compiled successfully, however my get function for a given element in the dynamic array does not seem to be working. Nothing seems to be outputted whenever I output the function, but this doesn't make sense, because my size function works fine, and s...
Just to collect the findings, if you delete this line from addEntry: string *array = new string[returnSize()]; and change your final for loop to: for(int i = 0; i < w.returnSize(); i++){ cout<<w.getEntry(i)<<"\n"; } then this does exactly what you expect. I've run it myself.
72,166,255
72,169,576
When does the compiler need to compute an alias?
Consider the following code: template <class T> struct computation { using type = /* something based on T that takes time to compile */; }; Now consider two codes: using x = computation<T>; and: using y = typename computation<T>::type; I am wondering whether the standard implies that: Option A) Any "reasonable"...
I am assuming that T is an actual non-dependent type here and not another template parameter. The line using x = computation<T>; does not cause implicit instantiation of computation<T>. There is therefore no reason for a compiler to try to compute type at this point, in particular since any instantiation failure woul...
72,166,534
72,172,406
Parameter pack referenced but not expanded in a using declaration: compiler bugs or not?
Consider the following code (also available here on compiler explorer) #include <utility> #include <type_traits> template <std::size_t N, class = std::make_index_sequence<N>> struct type; template <std::size_t N, std::size_t... I> struct type<N, std::index_sequence<I...>> : std::integral_constant<std::size_t, I>... {...
I am wondering whether: it's completely c++17 valid code and it just took a long time for some vendors to implement it it is not purely c++17 valid code The code is valid but the compiler version you are listing are either very old and did not yet support this particular feature, or claimed to support this feature ...
72,166,606
72,166,664
How to make data from a text file be filtered into a vector
I have a little program I don't know how to make. Basically, it is a function to create a vector with data from a text file that meets a parameter in its text. text_in_vector("file.txt", "10") text example: Karen10, Lili12, Stacy13, Mack10 vector results {"Karen10","Mack10"}
Try something like this: #include <fstream> #include <vector> #include <string> #include <iomanip> std::vector<std::string> text_in_vector(const std::string &fileName, const std::string &searchStr) { std::vector<std::string> vec; std::ifstream inFile(fileName); std::string str; while (std::getline(inFi...
72,166,696
72,167,112
Using "string_view" to represent the "string" key
When I use map<string, string> kv; in protobuf 3.8.0, the next code works: std::string_view key("key"); kv[key] = "value"; While in protobuf 3.19.4, the above code doesn't work. The error msg is: error: no match for 'operator[]' (operand types are 'google::protobuf::Map<std::__cxx11::basic_string , std::__cxx11::basi...
In 3.8.0, Map::operator[] is declared as: Value& operator[](const Key& k) Where, in your case, Key is std::string. std::string_view is convertible to std::string, which is why the code works in 3.8.0. In 3.19.4, Map::operator[] is declared as: template <typename K = key_type> T& operator[](const key_arg<K>& key) temp...
72,166,787
72,271,356
Why there is no implicit conversions to pointers of member functions
When used std::bind, I found & is necessary to get the address of member functions, while isn't necessary for regular functions, for example: class Obj{ public: void member_func(int val); }; void func(int val); int main(){ Obj obj; auto mf1 = std::bind(&Obj::member_func, &obj, 1); // ok auto mf2 = std...
I still don't fully understand why there is no implicit conversions to pointers of member functions. It's primarily to stop you making mistakes like this: if (MyClass::MyFunc) ... // oops! would always be true, if legal when you meant to type: if (MyClass::MyFunc ()) ... // ^^ An...
72,166,814
72,166,900
How to return an error message from a fuction?
I have a function in a C++ code which should return a certain type of data (vector in this case, I have the definition typedef Eigen::VectorXd vector from the eigen library) but I have a condition where, if one of the parameters of the fuction is not valid to the kind of data I'm managing, that function should return a...
Usually you handle this kind of errors by throwing an exception. here an example: Eigen::VectorXd Foo(int p1, int p2) { ..... if (!IsParamsValid(p1,p2)) { throw std::invalid_argument("p1 or p2 is invalid"); } ..... }
72,166,859
72,208,434
Errors linking to tdh.lib
I'm trying to use functions from the Microsoft TDH library building with Visual Studio 2019. The project is using WindowsApplicationForDrivers10.0 Platform Toolset and the program is very simple: #include <windows.h> #include <tdh.h> #pragma comment(lib, "tdh.lib") int __cdecl wmain(_In_ int argc, _In_ wchar_t* argv[])...
Finally found the Visual Studio settings:
72,166,886
72,167,085
Preventing the timer from updating the counter variable for more than once
I have a qt application with cpp. The application is Falling ball game, when the ball is catched by basket the score needs to be incremented. The application uses some timerEvent to update the score. The slot for timeout is called for every 10 msec. My problem is the score is updated more than once and is very random i...
So with all the debugging cruft removed, onScoreTimer() looks like this: void MainWindow::onScoreTimer() { if( (((sprite->y - 15) >= 500)&& sprite->y <530 ) && ( (sprite->x <= (basket->x1 + 80)) && (sprite->x >= (basket->x1 - 80)) ) ) { sprite->dy *= -1; sprite->dx *= -1; score++; ui->scor...
72,166,923
72,168,379
C++ Linked List Queue pointers causing undefined behavior
I've read the questions and not seen answer to mine. Most people use structs for these and after testing reference code I see the struct version is functional but, why is class version not? #include <iostream> using namespace std; // I'm still bad at pointer logic but it makes sense. // REFERENCES // https://www.geeks...
The problem is here: Queue yay; yay.isEmpty(); yay.deQueue(); cout << endl; yay.enQueue(5); yay.enQueue(6); cout << "Queue Front : " << (yay.front)->data << endl; yay.deQueue(); cout << "After deqQueue " << endl; cout << "Queue Front : " << (yay.front)->data << endl; yay.de...
72,166,934
72,172,082
mmap's worst case memory usage when using MAP_PRIVATE vs MAP_SHARED
I haven't seen this explicitly anywhere so I just wanted to clarify. This is all in the context of a single threaded program: say we have a 10GB text file when we open with mmap, using the MAP_PRIVATE option. Initially of course, I should expect to see 0GB resident memory used. Now say I modify every character in the f...
MAP_SHARED creates a mapping that is backed by the original file. Any changes to the data are written back to that file (assuming a read/write mapping). MAP_PRIVATE creates a mapping that is backed by the original file for reads only. If you change bytes in the mapping, then the OS creates a new page that is occupies p...
72,167,059
72,167,327
Are pointers to non-static member function "formally" not considered pointers
I came across this which states: Member function pointers are not pointers. Pointers to non-member functions, including static member functions, are pointers. The above quote seems to suggest that pointers to non-static member function are not pointers. Similarly, i read here: A member pointer is a different type ca...
The quoted statements in question seems to be validated by the following statements from the standard. From dcl.mptr#3's note: [ Note: See also [expr.unary] and [expr.mptr.oper]. The type “pointer to member” is distinct from the type “pointer”, that is, a pointer to member is declared only by the pointer to member dec...
72,168,300
72,168,439
Is there still a need to provide default constructors to use STL containers?
I remember that back in C++98, if you wanted to make an STL container of MyClass, you needed to provide default constructor to MyClass. Was this specific to some implementations of STL? or was it mandated by the standard? Q: Is this not necessary anymore? Because it is not a good practice to provide default construct...
This quote is from the C++ Programming Language, Special edition , 2005 by Bjarne Stroustrup in section 16.3.4: If a type does not have a default constructor, it is not possible to create a vector with elements of that type, without explicitly providing the value of each element. So it was indeed a standard requireme...
72,168,537
72,168,838
C++, template class as function's return type problem
static absl::StatusOr<ImageFrame> ReadTextureFromFile() { ImageFrame image_frame(width, height); return image_frame; } Why return type is ImageFrame, not absl::StatusOr ?
This is just a "syntactic sugar". The return type is abseil::StatusOr<ImageFrame>. abseil::StatusOr<T> allows you to return both abseil::Status and the type T from your function. When there is an error you can directly return the error status. On success, you return the object with type T. So you could also write somet...
72,168,834
72,168,855
How can I make a std::vector of function pointers?
I have seen some similar questions but I can't get this to work. This fails: std::vector<void (CChristianLifeMinistryEntry::* pfnSetAssignName)(CString)> = xx; I want a vector so that I can pre-fill it with a series of &CChristianLifeMinistryEntry::SetXXX functions. This is so that I can quickly determine the right fu...
std::vector<void (CChristianLifeMinistryEntry::*)(CString)> pfnSetAssignName = xx;
72,169,038
72,169,103
QInputDialog with suffix
I'm getting double value quickly from user with QInputDialog. Actually, everything is fine just wondering if there is a way to write suffix next to this value. My code: double value = QInputDialog::getDouble(this, tr("Change World Box Size"), ...
That seems to work; auto dialog = new QInputDialog(this); dialog->setWindowTitle("Change World Box Size"); dialog->setLabelText("Set each axis length:"); dialog->setDoubleDecimals(2); dialog->setDoubleMaximum(10000); dialog->setDoubleMinimum(0); dialog->setDoubleValue(projectJson.value("worl...
72,170,102
72,171,177
Cast an array of strings to an array of char*
I'm trying to get rid of the ISO C++ forbids converting a string constant to ‘char*’ warning, my code looks like the following: char* var[] = {"abc", "def"}; // many more lines like this ... One solution is to prepend each string literal with (char*) however that's ugly and unmaintainable. Ideally I'd like to be able ...
I have arrived at a solution. It requires two arrays one of which needs to be cleaned up afterwards so it can surely be improved. template<size_t N, size_t... Is> constexpr char** array_cast(const std::array<const char*, N>& arr, std::index_sequence<Is...>) { return new char*[]{const_cast<char*>(std::get<Is>(arr))....
72,170,302
72,171,164
Does constexpr really imply const?
Compare the following: I have a static member in a class that is either const constexpr or just constexpr. According to this explanation on MS Docs constexpr implies constness: All constexpr variables are const. However, this issues a warning in gcc 8.4: #include <iostream> #include <string> struct some_struct { ...
Does constexpr really imply const? Yes. Constexpr variables are always const. What is the difference? const T* is a non-const pointer to const. It is not const. T* const is a const pointer to non-const. It is const. const T* const is a const pointer to const. It is const. constexpr T* is a const pointer to non-cons...
72,170,444
72,170,708
Why is there a signedness issue when comparing uint16_t and unsigned int?
I have a code like this : #include <iostream> using std::cout; using std::endl; int main() { uint16_t a = 0; uint16_t b = 0; if ( a - b < 3u ) { cout << "cacahuète" << endl; } return 0; } When I compile it using g++ with -Wall, I get : temp.cpp: In function ‘int main()’: temp.cpp:9:13...
So what's going on, here ? Where does the int come from? Integer promotion is going on here. On systems where std::uint16_t is smaller than int, it will be promoted to int when used as an operand (of most binary operations). In a - b both operands are promoted to int and the result is int also. You compre this signe...
72,170,645
72,171,041
Using boost::counting_iterator with an existing vector?
At the moment I am doing this: const int n = 13; std::vector<int> v(boost::counting_iterator<int>(0), boost::counting_iterator<int>(n + 1)); std::copy(v.begin(), v.end(), back_inserter(m_vecAssignmentIndex)); m_vecAssignmentIndex is defined liek this: ByteVector m_vecAssignmentIndex; And, ByteVector: using ByteVecto...
I have now found the samples in the official docs: int N = 7; std::vector<int> numbers; typedef std::vector<int>::iterator n_iter; std::copy(boost::counting_iterator<int>(0), boost::counting_iterator<int>(N), std::back_inserter(numbers)); std::vector<std::vector<int>::iterator> pointers; std::copy(bo...
72,170,819
72,183,642
How is Phong Shading implemented in GLSL?
I am implementing a Phong Shader in GLSL for an assignment, but I don't get the same specular reflection as I should. The way I understood it, it's the same as Gouraud Shading, but instead of doing all the calculations in the vertex shader, you do them in the fragment shader, so that you interpolate the normals and the...
The problem is the way how the light source position is calculated. The following code vec3 l = normalize(mat3(VMatrix)*light); treats light as a direction (by normalizing it and because the translation part of the view matrix is ignored), but it actually is a position. The correct code should be something like vec3 l...
72,171,380
72,171,505
How do I access Sound Hardware in Dev-C++?
I was following a video tutorial for playing music in c++: https://www.youtube.com/watch?v=tgamhuQnOkM&t=1030s I am using Dev-C++ and I keep getting an error in the header file that "I'm not supposed to worry about" The line is: auto d = std::find(devices.begin(), devices.end(), sOutputDevice); And the error says: >92...
This is a bug in the linked header file. It should include <algorithm> which is required for std::find, but doesn't. I haven't checked the rest of the header file or your posted code for bugs, but I also noticed while (1) { } Infinite loops without IO, atomic, volatile or synchronization operations have undefine...
72,171,848
72,171,977
move semantics for `this`?
Imagine the following situation: class C { public: C(std::vector<int> data): data(data) {} C sub_structure(std::vector<size_t> indices){ std::vector<int> result; for(auto i : indices) result.push_back(data[i]); // *** return C(result); } std::vector<int> data; }; C f(){ ... } ... C c = f()...
If my call was something like sub_structure(f(), ...), I could overload sub_structure by rvalue reference; however, as a class method, I'm not aware how to do that, basically based on if *this is an rvalue reference. Do you mean overloading on value category? Not sure if this is what you mean, but if get your problem...
72,171,889
72,171,985
Exactly how are parameters initialized by the arguments passed in the function call in C++?
In the following code : #include<iostream> using namespace std; void fun(T1 x, T2 y, T3 z){ // some code } int main(){ T1 a; T2 b; T3 c; fun(a,b,c); } I wanted to understand, how the parameters(x, y, and z) in the function "fun" are getting initialized by the arguments(a,b, and c) passed during the fu...
Is the copy constructor invoked and then initialization happens like T1 x = a; T2 y = b; T3 z = c; Yes, it happens exactly like this. Which, given the amount of different kinds of initializations in C++, is an impressive guess. It's called copy-initialization: (which in general doesn't necessarily imply that a copy c...
72,172,104
72,175,002
How to do color filtering with PCL
I am learning to use pcl.I want to filter out point clouds whose color is red(rgb 255,0,0),But not work.what should I do? The PCL version I am using is 1.12.1. #include <pcl/point_types.h> #include <pcl/filters/conditional_removal.h> int main() { pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud(new pcl::PointCloud<pcl:...
The warning message gives you a hint: "field not found!" (three times). PointXYZRGB does not have r, g, and b fields. You can use getFields() to find out which fields a point type has. PointXYZRGB has a combined field rgb that you can use for filtering. However, you might want to consider using PointXYZRGBA instead (wi...
72,173,127
72,173,754
SFINAE doesn't work in recursive function
Let's create currying function. template <typename TFunc, typename TArg> class CurryT { public: CurryT(const TFunc &func, const TArg &arg) : func(func), arg(arg ) {} template <typename... TArgs> decltype(auto) operator()(TArgs ...args) const { return func(arg, args...); } pri...
Your operator() overload is completely unconstrained and therefore claims to be callable with any set of arguments. Only declarations, not definitions, are inspected to determine which function to call in overload resolution. If substitution into the definition then fails, SFINAE does not apply. So, constrain your oper...
72,173,184
72,173,260
How to assign two dimensional initializer list in c++?
I inherited my class from vector and I would like to be able to assign list to my class like to vector. My code is as follows: #include <vector> using namespace std; template<typename T> class Matrix : public vector<vector<T>> { public: Matrix( vector<vector<T>> && m ) : vector<vector<T>>( m ) {} ...
Just bring std::vector constructor to your class scope: template <typename T> class Matrix : public vector<vector<T>> { public: using vector<vector<T>>::vector; }; https://godbolt.org/z/b3bdx53d8 Offtopic: inheritance is bad solution for your case.
72,173,334
72,173,499
Unable to get CMake Tutorial example to compile... Why?
I'm trying to follow the official tutorial for CMake for adding a version number and configured header file. I have two directories: Step1 Step1_build Step1 contains CMakeLists.txt, TutorialConfig.h.in and tutorial.cxx. Contents of each file follow: CMakeLists.txt cmake_minimum_required(VERSION 3.10) # set the proje...
In CMake targets need to be defined before any modification of their properties (like include directories), so this line: # add the executable add_executable(Tutorial tutorial.cxx) should be moved before the call to target_include_directories.
72,173,769
72,174,691
VS reporting error with every variable of a class
I have realized a typical class called "FCB", and VS didn't report any problem while I was coding, and can recognize its members when referred to. Yet as I try to compile it, it shows that every variable whose type is FCB or FCB* appear to be unrecognizable. Here is my class. FileControlBlock.h #pragma once #include <...
Like @RichardCritten ’s comment, I wrongly declared POS_POINTER before FCB. Just move it after the class and before the member functions will fix most of the porbl
72,174,209
72,174,322
Testing implementation details for automated assessment of sorting algorithms
I'm looking at automated assignments for an introductory algorithms and data structures course. Students submit code, I run boost tests on them, the number of passed tests gives a grade, easy. But I want to assess sorting algorithms, for example "Implement bubble-, insertion-, selection- and merge-sort". Is there a cle...
Is there a clever way to test the implementations of each to know they did in fact implement the algorithm requested? Make them write a generic sort that sorts (say) a std::vector<T>, and then in your unit test provide a class where you overload the comparison operator used by the sorting algorithm to log which objec...
72,174,397
72,188,590
Force creation of method on intel compiler with optimization level 3
Working on a +95% C++ 11 code (the rest is C) that is generally used compiled w/ optimization level 3 we profiled it and found a really time-consuming method. Toy code: myClass::mainMethod() { // do stuff here / ... // do more stuff here / ... } We splitted its inner sections into other methods in orde...
As the comments suggested, splitting with attribute noinline did the trick. void __attribute__((noinline)) myClass::mainMethod() { this->auxiliaryMethod1(); this->auxiliaryMethod2(); } void __attribute__((noinline)) myClass::auxiliaryMethod1() { // do stuff here // ... } void __attribute__((noinline)) m...
72,174,473
72,174,553
Call db.close() on Button_Click (QT/C++)
how can i close a database connction from Button_onClick funktion? Artikelverwaltung::Artikelverwaltung(QWidget *parent) : QDialog(parent), ui(new Ui::Artikelverwaltung) { ... QSqlDatabase db = QSqlDatabase::addDatabase("QODBC"); ... } void Artikelverwaltung::...
It is not working because db is a local variable in Artikelverwaltung::Artikelverwaltung you need to make it a class attribute. class Artikelverwaltung { private: QSqlDatabase m_db; }; Artikelverwaltung::Artikelverwaltung(QWidget *parent) : QDialog(parent), ui(new Ui::Artikelverwaltung) { ... m...
72,174,644
72,175,260
OpenMP parallel reduction (min) incorrect result
i am using OpenMP reduction(min) to get the minimum number of lock acquisitions in a parallel section over all participating threads. When printing each threads counter inside the parallel section, I get correct results but after the parallel section, the min counter is at 0. This is the code: int counter = 0, maxV...
You have a confusion between the init value that OMP uses internally, and the init value from the user code. The partial reductions are done with the internal value, but at some point there also has to be a reduction against the user-supplied initial value. If you don't set that, anything can happen. Here is a cute pic...
72,174,690
72,174,740
How to not use friend declaration when equipping a class with `operator<<`
I understand that we'd want to do something like this to override operator<< #include <iostream> class Point { private: double m_x{}; double m_y{}; double m_z{}; public: Point(double x=0.0, double y=0.0, double z=0.0) : m_x{x}, m_y{y}, m_z{z} { } friend std::ostream& operator<< (std...
You can just declare operator<< as a free function in the same namespace as Point (in this case, the global namespace) and ADL will take care of it: #include <iostream> class Point { private: double m_x{}; double m_y{}; double m_z{}; public: Point(double x = 0.0, double y = 0.0, double z = 0.0) ...
72,174,838
72,182,783
Indirect perfect forwarding via function pointer?
Lets consider ordinary perfect forwarding: class Test { public: Test() = default; Test(Test const&) { std::cout << "copy\n"; } Test(Test&&) { std::cout << "move\n"; } }; void test(Test) { } template <typename T> void f(T&& t) { test(std::forward<T>(t)); } int main() { std::cout << "expect: c...
Background of the question is a mis-reading of Scott Meyer's article about forwarding references (called 'universal references' there). The article gave the impression of such forwarding references existing as a separate type in parallel to ordinary l-value and r-value references. This is not the case, though, instead ...
72,174,984
72,211,349
SFML setFillColor doesn't work to a class member
I think I should write implementation for my Circle class, but I'm not sure and I don't know, how to transfer Color as function parameter in main bcz compiler doesn't work with sf::Color::Red or just Red as function parameter in main function #include <SFML/Graphics.hpp> using namespace sf; const int APPLICATION_WID...
sf::Color is a class that can be passed as a parameter. You can read how sf::Color works in the documentation: https://www.sfml-dev.org/documentation/2.5.1/classsf_1_1Color.php Example: #include <SFML/Graphics.hpp> class MyCircle { public: MyCircle() { mCircle.setRadius(50.f); }...
72,175,072
72,176,111
Multithreading in C++ - Display animation until another thread has completed
Preface: this is my first attempt at writing a program in any language with multi-threading. I have no prior experience with std::thread, or with describing multi-threaded programs at all. Please let me know if you need more information to answer this question, or if I can reword anything to make my question clearer. S...
I've taken your example code and tried to fill in the blanks from your intention with std::thread. I've added some comments inline to explain what's going on. If something's not clear, or I got it wrong, feel free to ask in the comments. I want to stress though that this example only uses std::thread to create and join...
72,175,338
72,175,608
Why are we using currsum[n+1] and then on line no. 23 currsum[i] = currsum[i-1] + arr[i-1];?
Why is she using [n+1] instead of N directly and then that line no. 23 what is that equality? Why do we use INT_MIN for Maximum numbers or arrays, and `INT_MAX for minimum things? #include <bits/stdc++.h> using namespace std; //Question is of Find the Subarray with Maximum sum// int main(){ int n; cin ...
Have you heard of prefix sums? (aka running totals, cumulative sums, scans). N+1 is used because prefix sums also needs to include an empty subarray. You use INT_MIN for maximum because the max() function takes the larger of the two values, so MaxSum is always increasing. If you make MaxSum = 0 at the beginning, or so...
72,175,611
72,202,473
How to save last BFS of Edmonds-Karp algorithm?
I have implemented the following C++ Edmonds-Karp algorithm: #include <iostream> // Part of Cosmos by OpenGenus Foundation // #include <limits.h> #include <string.h> #include <queue> using namespace std; #define V 6 /* Returns true if there is a path from source 's' to sink 't' in * residual graph. Also fills parent[...
Okay so I found a solution. We need to have the visited array as a global array (or you can pass it through every single parameter list). This way, every time the array is refreshed, it is also saved in the whole program. From there, all we have to do is write the output function for the minimal cut: void printMinCut()...
72,175,650
72,177,636
openmp increasing number of threads increases the execution time
I'm implementing sparse matrices multiplication(type of elements std::complex) after converting them to CSR(compressed sparse row) format and I'm using openmp for this, but what I noticed that increasing the number of threads doesn't necessarily increase the performance, sometimes is totally the opposite! why is that t...
You can try to improve the scaling of this algorithm, but I would use a better algorithm. You are allocating a dense matrix (wrongly, but that's beside the point) for the product of two sparse matrices. That's wasteful since quite often the project of two sparse matrices will not be dense by a long shot. Your algorithm...
72,175,652
72,175,962
brace-inititialisation of boost::json::value converts it from an object to an array
In the below example I parse a json object using boost::json. When I print the type of the returned boost::json::value it is of type object, as expected. I then have 2 classes which are identical in every way, other than in BraceInit I initialise my member boost::json::value using brace initialisation and in ParenInit ...
From [class.base.init]/7 The expression-list or braced-init-list in a mem-initializer is used to initialize the designated subobject (or, in the case of a delegating constructor, the complete class object) according to the initialization rules of 11.6 for direct-initialization. 11.6 here refers to [dcl.init], which, ...
72,176,747
72,176,929
cpp - alias for member functions` return types
I've been watching this CppCon talk where the speaker was talking about writing classes resistant to future changes. He provided the following code as an example (that I show here abridged): template< typename Type, size_t Cap > class FixedVector final { using iterator = Type*; iterator begin(); } My ques...
The point they are trying to make is if they had template< typename Type, size_t Cap > class FixedVector final { Type* begin(); } and later they decide that instead of a Type*, they want to use a my_custom_iterator<Type>, then they need to make that change to all places that use Type*. By using class FixedVector ...
72,176,779
72,176,955
How to return objects of different types from RcppArmadillo function
l would like to return objects of different types from the function RcppArmadillo. For example, below is a code where I've tried returning both a vector and function using std::tuple. #include <RcppArmadillo.h> #include <tuple> // [[Rcpp::depends(RcppArmadillo)]] using namespace arma; // [[Rcpp::export]] std::tuple<a...
I'm not sure what you mean by "tried unsuccessfully" to use List::create. Does the following work for you? #include <RcppArmadillo.h> // [[Rcpp::depends(RcppArmadillo)]] // [[Rcpp::export]] Rcpp::List test_tuple(arma::vec avec, arma::mat amat) { arma::vec bvec = avec; arma::mat bmat = amat; return Rcpp::List::c...
72,176,896
72,176,942
How to open fli files
I'm new to C++ and was tasked with processing a fli file, but have no idea how to open them correctly. So far my code looks like this: #include <iostream> #include <fstream> #include <string> using namespace std; int main() { fstream newfile; newfile.open("testvid.fli", ios::in);object if (newfile.is_open()...
I haven't worked with .fli files before. Is it a FLIC file (used to store animations)? Then it makes sense that trying to reading them as strings produces gibberish. You could try either the Aseprite FLIC Library or LibFLIC. EDIT: I used the Asperite's library and gif-h to convert a FLIC file to a GIF. Sorry for the in...
72,176,917
72,206,586
HDF5: How to read an array from a dataset
I have never seen this before, but I have a file with a 1x1 dataset where the only value is a Array[3] of 64-bit floating point. I can see this using the HDFView tool, but no matter what I try, I get errors. Is there a special type I need to create for this to work? Edit if I use H5Sget_simple_extent_npoints() to get t...
I figured out that there is an array type that can be made that is required: hsize_t size = { 3 }; hid_t type = H5Tarray_create(H5T_NATIVE_DOUBLE, 1, &size); hid_t dataset = H5Dopen(...); double var[3]; hsize_t memdim[] = { 1 }; // or how many arrays[3]'s to read hid_t space = H5Screate_simple(1, memdim, nullptr); au...
72,177,171
72,177,230
What does *&Var - 1.0f means?
Working with some tutorial, I met a strange C++ expression: uint64_t var = .... return (*&var) - 1.f; What does this mean? Is it a reference to a pointer? What's the point of substracting 1 from reference? It should be an implementation of the LCG algorithm.
var is an identifier. It names a variable. The unary & operator is the addressof operator. The result of addressof operator is a pointer to the object named by its operand. &var is a pointer to the variable var. The unary * operator is the indirection operator. Given a pointer operand, it indirects through that pointer...
72,177,241
72,181,588
How to add C library to Visual Studio project
I am trying to add https://github.com/mlabbe/nativefiledialog this C library to my C++ project in visual studio 2022. I've built and generated the .lib file and added it to my project by going to Project->Properties->Linker. I added the path to this .lib file to Additional Library Directories. After doing this, I am st...
I just forgot to add the path to the generated .lib file (nfd.lib) to Projects->Properties->Linker->Input Additional Dependencies. After doing this, everything worked perfectly.
72,177,535
72,177,598
How can I include a C header that uses a C++ keyword as an identifier in C++?
I've been using C++ and compiling with clang++. I would like to include the <xcb/xkb.h> header for an X11 program I am writing. Unfortunately this header uses explicit for some field names (such as line 727) and that is a keyword in C++. Is there anyway to deal with this? xcb/xkb.h: // ... #ifdef __cplusplus extern "C...
Use a macro to rename the fields: #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wkeyword-macro" #endif #define explicit explicit_ #ifdef __clang__ #pragma clang diagnostic pop #endif #include <xcb/xkb.h> #undef explicit Using a keyword as a macro name is ill-formed in standard C++...
72,177,561
72,177,779
OpenCV / C++ - OpenCV detect mouse click position and displays it, but doesn't draw a circle
I have this OpenCV Code where I want to draw a circle on a image each time i left click my mouse. It detect the position of my mouse at the time I pressed the left button and displays it aswell, but it doesn't draw a circle at the position. Here is the code: #include <iostream> #include <vector> #include <string> #in...
Simply put: cv::imshow("Image", inputImage); into a while loop, so that it updates the image being displayed after drawing the circle.
72,177,691
72,177,958
Designing a C++ concept with multiple invocables / predicates
I'm trying to make a C++20 concept by using an existing class as a blueprint. The existing class has 8 member functions that each take in a predicate: struct MyGraphClass { auto get_outputs(auto n, auto predicate) { /* body removed */ }; auto get_output(auto n, auto predicate) { /* body removed */ } auto ge...
I would do it this way. First, your graph concept has several associated types. Similar to how a range in C++ has an iterator type (amongst others). We don't write range<R, I>, we just write range<R>. If R is a range, then it has some iterator type - we don't ask if R is a range with iterator I. We may not know I ex an...
72,178,357
72,178,439
Inheriting from template instanciated with incomplete type
I have a struct template like the following: // S.h #pragma once #include <vector> template <typename T> struct S { std::vector<T*> ts; virtual ~S() { for (auto* t : ts) t->foo(); } void attach(T& t) { this->ts.push_back(&t); } }; Then, I inherit a non-template struct, ConcreteS, from S<A>; struct A be...
Using S<A> as base class causes it to be implicitly instantiated. Generally that wouldn't be a problem since your class doesn't require A to be complete when it is instantiated. However, the definition of your destructor for S<A> requires A to be complete (because of the member access). That would normally also not be ...
72,178,685
72,178,798
Counter for unique types where instances are independent from each other
I am attempting to create a counter for each unique template argument that the counter receives. For example, I pass an int. The counter returns zero. I pass a float. The counter returns one. I pass an int again. The counter returns zero. Essentially, it generates a unique integer for each templated type. struct Counte...
You want the counter values to be computed at compile time, where different instances of Counter have separate counters. The main obstacle here is that it can't always be determined at compile time whether the counter instance that you're using is the same as some other counter instance that has already been used. In o...
72,179,302
72,493,183
Capturing post data from C++ application in Codeigniter 4
I am upgrading our site from Codeigniter 3 to Codeigniter 4. So far it has been tedious, but mostly gone well. I am running into an issue now with a controller that will not recognize posted values from an app written in C++. This app has been working with CI 3 for many years now, but... well, CI4. I don't know all the...
Codeigniter 4 has the following in the public .htaccess file: # Redirect Trailing Slashes... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} (.+)/$ RewriteRule ^ %1 [L,R=301] which removes the trailing slash from urls. REMming out those three lines # Redirect Trailing Slashes... # RewriteCond %{REQUEST_...
72,179,447
72,179,926
Alias that transforms a template type to the same type but templated on something different
I have a template <typename T, typename U> struct A; and a template <typename U> struct B; How do I make an alias that transforms an A<T, U> type to a A<T, B<U>> type? i.e. something that looks like this: template <typename TypeA> using ModifiedTypeA = TypeA<T, B<U>>; // <--- I don't know how to get T and U from Type...
Try template <typename TypeA, template<typename> typename TemplateB> struct ModifiedTypeAWtihImpl; template <template<typename, typename> typename TemplateA, typename T, typename U, template<typename> typename TemplateB> struct ModifiedTypeAWtihImpl<TemplateA<T, U>, TemplateB> { using type = Tem...
72,179,641
72,202,870
using LLVM-C api from MSYS2 returns exit code 1, but using WSL works fine
i installed llvm+clang using MSYS2, and all the tools work fine for me, but the LLVM-C always returns exit code 1, here is my sample code: #include <llvm-c/Core.h> #include <stdlib.h> int main(int argc, char const *argv[]) { LLVMModuleRef mod = LLVMModuleCreateWithName("my_module"); LLVMPrintModuleToFile(mod,...
nvm i fixed it, my solution is that instead of using powershell, i used the MSYS2 (MinGW-w64) shell.
72,180,103
72,187,635
How to get a control's handle in WinUI3 in C++?
I am working on a C++ WinUI3 project and got this problem. How do I obtain the handle of a XAML grid? Something like this in QT can achieve it: HWND m_hWnd; m_hWnd = (HWND)(ui.label->winId()); But I couldn't find the similar thing in WinUI3. I look up on the Internet, but only find this solution which is in C#: Get-a-c...
How do I obtain the handle of a XAML grid? You can't because there is none. All XAML controls on the screen are ultimately backed by a single HWND that belongs to the parent window, i.e. an individual control doesn't have its own handle in Win UI. There is only a single top-level handle and the controls are rendered ...
72,180,112
72,180,141
When should I mark the static method of a specific class as private other than public?
When should I mark the static method of a specific class as private other than public? What aspects should I consider when making such considerations. What are the advantages for mark the static method as private? Any simple example would be appreciated, which could help me fully understand this matter. UPDATE: As per ...
The general rule for methods (static or otherwise) is to make them private if possible — i.e. unless you absolutely need them to be callable from other classes (which is to say, you need them to be part of your class’s public API) The reason for making as much as possible private is simple: in the future, you’ll be ab...
72,180,366
72,181,790
I run `"crash_demo.run"` by `spawn-fcgi` . How to collect `core` file
1. Question I run "crash_demo.run" by spawn-fcgi . How to collect core file . 2. Background & Environment I'm exolore C++ Web Programming . web-server : nginx CGI(FastCGI) : fastcgipp 3.0 CGI Wrapper : spawn-fcgi I didn't use FCGI Wrap which ngifix supplied . I understand FCGI Wrap be drive by spawn-fcgi , Of course ...
This question is probably more for askubuntu.com or serverfault.stackexchange.com. You likely need to configure core dump. Since we don't know the platform, I'm assuming likely a Linux. See e.g. core(5): There are various circumstances in which a core dump file is not produced In my experience what's required is sett...
72,180,865
72,180,947
Is there any in-built function or header file I need to add for Single Inheritance?
This Single Inheritance code has no error but when I run this void the function void B::get_ab() gets executed first as expected, but the line which is second in the function(cin>>a>>b;) gets executed first and then the first line, anyone know whats happening here? #include<iostream> #include<stdio.h> using std::equal...
The reason for this is that you untied the cin from the cout, in the cin.tie(0);. You can't expect the output to be flushed before the program prompts input from the user. If you need to preserve this configuration for some reason (i.e. untied streams) and still need the prompt to be printed, you need to flush the out...
72,181,800
72,188,787
C++ Variadic function with inherited objects references and base class
I am writing a class to implement and signal-slot mechanism. The signal can emit a series of events that are all derived from a base struct called "base_event". Below is how I defined the base_event and an example of a derived struct: struct base_event { std::string _id = "base_event"; }; struct select_next_ev...
There are two problems here. First, emit_async(Args... args) is pass by value, so Args... is always a value type, you need to add forwarding reference to it. Second and more important, you construct args with init-capture [... args = std::forward<Args>(args)], but since lambda's operator() is implicitly const, you cann...
72,181,983
72,182,759
After running qmake, how to make debug/release?
The qmake project file (.pro) contains CONFIG -= debug_and_release I would like to keep project file as it is but decide later (from the command line) to do debug or release build. Currently, when I build from command line qmake project.pro make It does a release build. How can I choose debug/relase from the command ...
You can simply do this by followed command qmake project.pro "CONFIG+=debug" make
72,182,067
72,182,135
Reversing vectors in a vector error troubleshoot
vector<vector<string>> Reverse(vector<vector<string>> a){ vector<string> dd; for(int i = 0; i < a.size()/2; i++){ dd = a[i]; a[i] = a[-1*(i) - 1]; a[-1*(i) - 1] = dd; } return a; } I want to make a Reverse function that reverses vectors in a vector but i get and error: libc++abi...
You are trying to access negative positions in a vector. Positions starts from 0 to vector.size(). It's very bad what you are doing.You are getting a matrix and try to transform it in a vector? You should review your code. Maybe you meant something like this? vector<vector<string>> reverseRows(vector<vector<string>> a)...
72,182,138
72,182,190
Calling C++ standard header (cstdint) from C file
I have an external library written in C++ such as external.h #ifndef OUTPUT_FROM_CPP_H #define OUTPUT_FROM_CPP_H #include <cstdint> extern "C" uint8_t myCppFunction(uint8_t n); #endif external.cpp #include "external.h" uint8_t myCppFunction(uint8_t n) { return n; } Currently I have no choice but use this C++ li...
The c prefix in cstdint is because it's really a header file incorporated from C. The name in C is stdint.h. You need to conditionally include the correct header by detecting the __cplusplus macro. You also need this macro to use the extern "C" part, as that's C++ specific: #ifndef OUTPUT_FROM_CPP_H #define OUTPUT_FROM...
72,182,178
72,183,940
Converting a Console Program into an MFC app (Thread issues) (Pleora SDK)
Back to stackoverflow with another question after hours of trying on my own haha. Thank you all for reading this and helping in advance. Please note the console program has following functionalities: connect to a frame grabber apply some configs store the incoming data (640 * 480 16-bit grayscale imgs) in a stream of...
Worker threads do not have message-queues, the (typically one and only) UI one does. The message-queue for a thread is created by the first call of the GetMessage() function. Why use messages to control processing in a worker thread? You would have to establish a special protocol for this, defining custom messages and ...
72,182,371
72,182,462
How to overload the operator[] with multiple subscripts
C++23 added support for overloading operator[] with multiple subscripts. It's now available on GCC 12. How should one make use of it? An example struct: struct Foo { int& operator[]( const std::size_t row, const std::size_t col, const std::size_t dep ) { return ...
fooObject[ 0, 0, 0 ] = 5; not fooObject.matrix[ 0, 0, 0 ] = 5; you should also add compile option --std=c++23.
72,182,444
72,184,703
How do I find the element by coordinate in VTK?
I have a mesh file generate by Gmsh(*.vtu), the mesh is a cube area and consist of tetrahedrons. Then I have a point (given by coordinate) in the cube, I want to find which tetrahedron contains the point, how did I do? with pygmsh.occ.Geometry() as geom: geom.add_box([0, 0, 0], [1, 1, 1], mesh_size...
You should be able to use the FindAndGetCell() method that vtkUnstructuredGrid inherits from vtkDataSet. The python documentation for this can be found using help(vtkUnstructuredGrid.FindAndGetCell) within your python shell (assuming you have imported vtkUnstructuredGrid, if not prepend with vtk. as usual. As a recomme...
72,182,753
72,187,449
How can I inspect DYLIB contents in terms of size?
After moving from a manually created Xcode project to a CMake-generated Xcode C++ project, my compiled binary DYLIB size has grown significantly: from about 35 MB to about 53 MB. All the compilation and linking settings I could compare in Xcode projects look pretty much the same (including vs. not including debug symbo...
I would personally go with nm tool. You can inspect any DYLIB file iteratively, section-by-section or just print everything: nm -a /path/to/my/lib.dylib
72,183,078
72,183,635
How to store a state of custom allocator used for allocation of different types
In a situation where one needs to work with custom stateful allocator, what is the idiomatic way to store the state, if the state should be used to allocate objects of different types? E.g. if one needs a allocator-aware object, that uses data-structures of different types, such as the following: struct Foo { std::...
Maybe you can use pmr. #include <vector> #include <memory_resource> struct foo { std::pmr::memory_resource& mem {*std::pmr::get_default_resource()}; std::pmr::vector<int> vi{&mem}; std::pmr::vector<double> vd{&mem}; };
72,183,897
72,184,096
setw() and setfill() not working...what am i doing wrong?
what i am trying to do is print double datatype with precision 2,setw(15),fill spaces with _(underscore) and with prefix - or +.for example if number is 2006.008 output should be _______+2006.01 my code is : cin>>b; if(b>0){ cout<<setw(15)<<setfill('_'); cout<<fixed<<setprecision(2)<<"+"<<b<<endl; } else{ ...
The io-manipulators apply to single insertions to the stream. When you insert "+" into the stream, then the width of it is 1 and the remaining 14 are filled with _ because of setfill('_'). If you want io-manipulators to apply to concatenated strings you can concatenate the strings. I use a stringstream here, so you can...
72,183,914
72,184,101
How copy initialization works in the case of argument passing to a function?
I googled about copy initialization and found out that whenever we write T a = b; ,copy initialisation takes place. It was also mentioned that copy initialization also takes when we pass arguments by value in a function call. I wanted to know that whenever we pass arguments to a function, is the " = " operator used by ...
Argument passing to the parameter of a function happens using copy initialization which is different than using copy assignment operator=. Note that initialization and assignment are two different things in C++. In particular, passing argument happens using "copy initialization" and not "copy assignment". From decl.ini...
72,184,084
72,184,282
Does declaring struct Name make Name equivalent to struct Name?
I am a bit confused when using struct in c/c++. Traditionally, when I use struct, I usually use it as: typedef struct Name{ int a; }; Name var; Although it is considered a bad practice from Linus, it's somehow common. Yet, I wonder struct Name{ int a; }; Name var; Seems to serve the same purpose, is typedef ...
For: typedef struct Name{ int a; }; Name var; The definition should be: typedef struct Name{ int a; } Name; Name var; Otherwise you are not aliasing the type. In C++ this doesn't make sense, when you declare struct Name you can already instantiate Name omitting the struct keyword, as you do in the second c...
72,184,108
72,193,723
Boost space in path not being handled correctly
I'm using the Boost process header and I can't seem to get the boost::process::system to take in my .cpp file path due to a space in the directory. auto path = bp::search_path("g++"); int result = bp::system(path, "\"C:\\Users\\Sachin Chopra\\Documents\\rchat\\console_process\\src\\main.cpp\""); I get the following er...
You're confusing shell script with the system interface. You can either use old style, error-prone system: bp::system(R"(bash -c "echo hello; echo world")"); Or you can pass raw arguments instead of relyng on shell escaping bp::system(bp::search_path("bash"), std::vector<std::string>{ "-c", ...
72,184,187
72,184,456
return address of dlsym and Address of Function Pointer assigned
void* l = dlsym(lib,"_ZN11Environment9LibLogger14log_processingEiNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEjS6_z"); *(void **)&log_fcn = l; std::cout<<"Address"<<<<l<<"LOG_FCN "<<log_fcn<<std::endl; I am trying to print address of l and log_fcn but both are not same. Why is that, and how can I get address ...
There is an operator << for void*, but not for function pointers. Function pointers are implicitly converted to bool, not void*, and bool prints as 0 or 1 by default. Your 1 output indicates that log_fcn is not the null pointer. Convert it when printing: std::cout << "Address" << l << "LOG_FCN "<< reinterpret_cast<void...
72,184,430
72,185,959
QT C++ access to a Class Member of another Class
i really dont understand the following behavior: 3 Code snippets to explain sqlconnection.h class SqlConnection { public: SqlConnection(); QSqlDatabase db; } ; sqlconnection.cpp SqlConnection::SqlConnection() { if (!db.open()){ //no different with or without that db = QSqlDatabase::addDatabase("QODBC"); ... } art...
In general, you do not need to use any wrapper class to hold database connections in Qt. You should create a database connection once using QSqlDatabase::addDatabase and open it. After that you can get a database connection anywhere by calling QSqlDatabase::database static method. So to close the database connection yo...
72,184,441
72,184,926
About the pimpl syntax
I have a question about the C++ usage used in the pimpl syntax. First, why is it not necessary to write pimpl( new impl ) as pimpl( new my_class::impl ) Second, why is the lifetime of new impl extended even though it is a temporary object? //my_class.h class my_class { // ... all public and protected stuff goes her...
First, why is it not necessary to write pimpl( new impl ) as pimpl( new my_class::impl ) Scope. When constructor is defined you are inside a cope of a class, so name lookup is able to find it without problems. Second, why is the lifetime of new impl extended even though it is a temporary object? You are passing tem...
72,184,458
72,508,759
How to canonicalize and digest the Body of SOAP with xmlib2
I am trying to sign manually a SOAP request. Using libxml2 in my cpp app I can canonicalize and digest the whole xml soap document using the xmlC14NDocDumpMemory function with xmlNodeSetPtr as null argument. However for the actual signature I need specifically process only the Body of the SOAP. xmlChar* canon; ...
My advice to anyone, who stumbles here is - DON'T try to canonicalize, digest and sign by yourself. Use xmlsec. Although it's pain in the ass to build (I'm on windows) and the documentation is almost non-existent, it gets the job done. The final answer can be found here: Sign part of XML using xmlsec
72,184,696
72,184,917
erasing nlohmann::json object during iteration causes segmentation fault
I have a simple database consisting of objects with strings containing unix time as keys and strings containing instructions as values I want to iterate though the database and erase any object who's key is smaller that current time ( so erase objects with dates before current date) for (auto it = m_jsonData.begin(); i...
It's extremely normal for mutating container operations to invalidate iterators. It's one of the first things you should check for. Documentation for nlohnmann::json::erase(): Notes Invalidates iterators and references at or after the point of the erase, including the end() iterator. References and iterators to...
72,185,086
72,185,169
use static var, it will block, how to explain this situation
int Test(int i) { i--; if(i <= 0 || i > 2) { return 0; } else { static int y = Test(i); return (y+1); } } int main() { cout << Test(3); return 0; } when run to Test(i), it will block. how to explain this situation?
It is undefined behaviour if during initialization of a static variable, the code reaches the initialization block again. Which happens for Test(3) -> y=Test(2)->y=Test(1).