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,406,895
72,464,880
How to build cv2 binding
I have followed the opencv doc for creating my own bindings. I run the file gen2.py which generated some header files: ./ ../ pyopencv_generated_enums.h pyopencv_generated_funcs.h pyopencv_generated_include.h pyopencv_generated_modules_content.h pyopencv_generated_modules.h pyopencv_generated_types_content.h pyopencv_generated_types.h pyopencv_signatures.json How should I build this? I tried running cmake CMakeLists.txt directly in /opencv/modules/python but some defines were not found. and I tried on re-building running cmake CMakeLists.txt in /opencv/ , where I got: FATAL: In-source builds are not allowed. You should create a separate directory for build files. I think both approaches were quite wrong, but I haven't found any doc explaining how to build using the generated headers. I'm using opencv 4.5.5 which I cloned and built. EDIT I found this in /source/opencv/modules/python/bindings/CMakeLists.txt: string(REPLACE ";" "\n" opencv_hdrs_ "${opencv_hdrs}") file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/headers.txt" "${opencv_hdrs_}") add_custom_command( OUTPUT ${cv2_generated_files} COMMAND "${PYTHON_DEFAULT_EXECUTABLE}" "${PYTHON_SOURCE_DIR}/src2/gen2.py" "${CMAKE_CURRENT_BINARY_DIR}" "${CMAKE_CURRENT_BINARY_DIR}/headers.txt" DEPENDS "${PYTHON_SOURCE_DIR}/src2/gen2.py" "${PYTHON_SOURCE_DIR}/src2/hdr_parser.py" # not a real build dependency (file(WRITE) result): ${CMAKE_CURRENT_BINARY_DIR}/headers.txt ${opencv_hdrs} COMMENT "Generate files for Python bindings and documentation" ) I guess I have to add the path to my headers in ${CMAKE_CURRENT_BINARY_DIR}/headers.txt just not sure how to get the value of CMAKE_CURRENT_BINARY_DIR EDIT 2 As proposed by @berak, I tried CMAKE_EXTRA_MODULES_PATH=my/path this seems to get me really close to what I need. It compiles my sources and generates the .so files as libopencv_xxx.so and saves them in my /usr/local/lib (when running nm on it I see my class and method) BUT! when I import cv2 in a script I don't achieve to load my module. I tried print(cv2.__dict__) and greped on it, but it's not there. Any clue on how to add the compiled modules into my python-opencv installation?
There's not much documentation on how to create a bind (at least I only found this, which is very helpful but doesn't have all the information). First, your module must use the following tree structure (I did everything with cmake): . src └── modules └── your_module ├── CMakeLists.txt ├── include │   └── opencv2 │   └── your_module_bind_lib.hpp └── src └── your_module_bind_lib.cpp An example of my CMakeLists.txt (this of course may change according to your project): set(the_description "yourModule LIB") ocv_define_module(your_module opencv_imgproc WRAP python) include_directories(${OpenCV_INCLUDE_DIRS}) Then I cloned OpenCV with git clone https://github.com/opencv/opencv.git Make a build folder mkdir wherever/build And run the following command for cmake cd wherever/build cmake -DOPENCV_EXTRA_MODULES_PATH=/project_from_previous_tree/src/modules/ -D BUILD_EXAMPLES=OFF -D BUILD_opencv_apps=OFF -D BUILD_DOCS=OFF -D BUILD_PERF_TESTS=OFF -D BUILD_TESTS=OFF -D CMAKE_INSTALL_PREFIX=/usr/local/ your_opencv_location/opencv/ make -j8 make install In that command the only "special" thing was DOPENCV_EXTRA_MODULES_PATH (thanks to @berak for the idea). And then? what happens in python level? Make sure your python installation actually points to the built opencv, or use something like: import sys sys.path.append('/usr/local/lib/python3.8/site-packages/cv2/python-3.8') import cv2 where /usr/local/lib/python3.8/site-packages/cv2/python-3.8' is where the generated .so is located in my PC. With this you will be able to use things like cv2.my_cpp_function() cv2.my_cpp_class.some_method() ... Where my_cpp stuff was declared and defined in the module project following the doc and can "easily" have OpenCV typed objects as parameters. Et voila, now you can use your c++ functions in python. Notice that this solution does not do any modification to the opencv directory cloned from Git.
72,407,954
72,408,126
why doesn't GCC place a statically-initialized C++ class object into .data
here are two similar declarations of an object type in C++: struct Obj { int x; }; struct ObjC { int x; ObjC(int x) : x(x) {}; }; Obj obj1 = {100} ObjC obj2(200); using a recent version of gcc (riscv64-unknown-elf-toolchain-10.2.0-2020.12.8) i find that the variable obj1 is correctly placed in the .data section.... the variable obj2, however, is placed in the .bss section where it is not initialized.... i know there are provisions in GCC to run constructors at startup; but in this case, the initial state of obj2 is known at compile time.... FWIW, my IAR compiler has no problem with this code.... is there some sort of "hint" i need to provide to GCC????
Not marking the constuctor with constexpr seems to prevent optimizations here. The following type seems to get initialized properly, see godbolt: struct ObjC2 { int x; constexpr ObjC2(int x) : x(x) { } }; ObjC2 obj3(300);
72,408,158
72,408,348
when passing std::allocator<type>::pointer to my own wrap_iter i'm getting **type instead of *type
I'm trying to create a vector class and my own wrap_iter class here is my vector.hpp #ifndef VECTOR_HPP #define VECTOR_HPP namespace ft { template <class _Iter> struct iterator_traits { }; template <class T> struct iterator_traits<T*> { typedef T* pointer; }; template <class T> class wrap_iter { public: typedef T iter_type; typedef typename ft::iterator_traits<iter_type>::pointer pointer; private: pointer ptr; unsigned int sz; int index; public: wrap_iter(pointer arr, unsigned int sz, int begin): ptr(arr), sz(sz) { if (begin) this->index = 0; else this->index = sz; } ~wrap_iter() {} T &operator*() const { if (this->index == (int)this->sz) throw std::out_of_range("Trying to access wrong index"); return (ptr[this->index]); } }; template <class T, class A = std::allocator<T> > class vector { public: typedef typename A::size_type size_type; typedef typename A::pointer pointer; typedef ft::wrap_iter<pointer> iterator; private: pointer arr; size_type capacity; size_type sz; public: vector() : arr(new T[1]), capacity(1), sz(0) { } vector(iterator begin, iterator end) { for (iterator it = begin; it != end; ++it) { if (this->sz == this->capacity) { this->reserve(2 * this->capacity); } this->arr[sz] = *it; sz++; } } void push_back(T element) { if (this->sz == this->capacity) { this->reserve(2 * this->capacity); } this->arr[sz] = element; sz++; } void reserve(size_type am) { if (am > this->capacity) { T *temp = new T[am]; for (size_type i = 0; i < this->capacity; ++i) temp[i] = this->arr[i]; delete[] this->arr; capacity = am; this->arr = temp; } } iterator begin() { return (iterator(this->arr, this->sz, 1)); } iterator end() { return (iterator(this->arr, this->sz, 0)); } }; } #endif and here is my main.cpp #include <iostream> #include "vector.hpp" #include <vector> int main() { ft::vector<int> vec; vec.push_back(5); vec.push_back(10); vec.push_back(15); vec.push_back(14); ft::vector<int>::iterator it = vec.begin(); std::cout << *it << std::endl; } i'm getting this error when trying to compile ./vector.hpp:40:11: error: non-const lvalue reference to type 'int *' cannot bind to a value of unrelated type 'int' return (ptr[this->index]); So why is the member variable ptr an int ** instead of int*. I'm passing the pointer as a template to wrap_iter. Even when I change pointer ptr; to T ptr; and the parameter pointer arr to T arr I still get the same error. Even when I change typedef typename A::pointer pointer; to typedef T* pointer I get the same error.
The problem is that your overloaded operator* returns an int*(for T=int*) by reference but the actual argument ptr[this->index] that you're returning is of type int and thus the compiler gives the error: error: invalid conversion from ‘int’ to ‘int*’ [-fpermissive] 41 | return (ptr[this->index]); | ~~~~^~~~~~~~~~~~~~ | | | int why is the member variable ptr an int ** instead of int*. ptr is an int* and not int** as opposed to your claim.
72,408,180
72,408,217
What is the benefit of using static thread_local with std::mt19937?
I have seen several usages of std::mt19937 like following: #include <random> size_t get_rand() { static thread_local std::mt19937 generator(time(0)); std::uniform_int_distribution<int> distribution(0, 10); return distribution(generator); } I want to find out what benefits comes from using static thread_local rather than static here. // first static is redundant I understand that in the second case generator has lifetime until thread is finished. Are there other benefits/differences in common or this particular case?
If it wasn't thread_local, then calling get_rand from multiple threads would cause a data race and therefore undefined behavior. Although the static initialization is always safe, even with multiple threads calling it, the call to the generator in distribution(generator), which modifies the generator's internal state, is not. With thread_local each thread has its own generator and so there is no issue with them calling the function unsynchronized. Also note that time(0) is a bad idea. General issue with that as a seed aside, if multiple threads call the function at a similar time, they are likely to be seeded with the same value and then the random numbers in the threads will all be identical (which is very likely not what you want). A somewhat better seeding would be thread_local std::mt19937 generator(std::random_device{}()); instead, assuming your platform implements std::random_device as a proper source of randomness (which should generally be the case, but e.g. is not on some versions of MinGW). (Be careful though if your platform does not properly implement std::random_device. In that case it might always produce the same sequence of numbers.) For more details on seeding the standard library random number generators see e.g. this question. Also note that even with platform support, this is still a mediocre seeding since it (typically) uses only 32bits of entropy. See e.g. this blog post for some details about these issues. Correct seeding is a quite non-trivial problem. For a declaration at block scope static is redundant by the way when using thread_local.
72,408,660
72,408,743
tbb::parallel_for passing ‘const value_type’ as ‘this’ argument discards qualifiers
Started learning TBB recently. I'm trying to implement compressed sparse row multiplication (datatype std::complex<int>) in parallel using TBB. Here is my code : struct CSR { std::vector<std::complex<int>> values; std::vector<int> row_ptr={0}; std::vector<int> cols_index; int rows; int cols; int NNZ; }; std::vector<std::complex<int>> tbb_multiply(const CSR& A, const CSR& B) { // B here is transpose std::vector<std::complex<int>> result(A.rows * B.rows, 0); tbb::parallel_for(0,A.rows,[=](int i){ for (int j = A.row_ptr[i]; j < A.row_ptr[i + 1]; j++) { int Ai = A.cols_index[j]; std::complex<int> Avalue = A.values[j]; for (int k = 0; k < B.rows; k++) { std::complex < int > sum(0, 0); for (int l = B.row_ptr[k]; l < B.row_ptr[k + 1]; l++) if (Ai == B.cols_index[l]) { sum += Avalue * B.values[l]; break; } if (sum != std::complex < int >(0, 0)) { result[i * B.rows + k] = sum; } } } }); return result; } When compiling it I get the next error : error: passing ‘const value_type’ {aka ‘const std::complex’} as ‘this’ argument discards qualifiers [-fpermissive] result[i * B.rows + k] = sum;
You capture by-value which makes result const (since a lambda isn't mutable by default). Since you also aim to return result, I suggest that you capture by-reference instead: tbb::parallel_for(0, A.rows,[&](int i){ // ^
72,409,091
72,412,791
Define a static constexpr member of same type of a template class
A similar question of non-templated class For a template class, template <typename T> struct Test { T data; static const Test constant; }; it's fine when defining a static constexpr member variable of specialized type: template <> inline constexpr Test<int> Test<int>::constant {42}; https://godbolt.org/z/o4c4YojMf While results are diverged by compilers when defining a static constexpr member directly from a template class without instantiation: template <typename T> inline constexpr Test<T> Test<T>::constant {42}; https://godbolt.org/z/M8jdx3WzM GCC compiles. clang ignores the constexpr specifier in definition. MSVC... /std:c++17 works well, but /std:c++20 rejects due to redefinition. I have learnt that constexpr can be applied to the definition a variable or variable template And in this example, which one is right? Why?
I think GCC is correct in accepting the given example. This is because the static data member named constant is an ordinary data member variable(although it is still considered a templated entity). And since constant is an ordinary data member variable, dcl.constexpr#1.sentence-1 is applicable to it: The constexpr specifier shall be applied only to the definition of a variable or variable template or the declaration of a function or function template. (emphasis mine) Thus, as the construct that you have provided after the class template is nothing but an out-of-class definition for the ordinary static data member constant, the given example is well-formed. template <typename T> constexpr Test<T> Test<T>::constant {42}; //this is an out-of-class definition for the ordinary static data member variable `constant` Note Note that dcl.constexpr#1.sentence-1 doesn't mention templated entity, but instead only mention "variable" and "variable template" and since constant is a variable(ordinary), the same should be applicable to constant.
72,409,129
72,410,933
Overload operator+ to increase IP addresses on boost::asio::ip
I would like to do math operations with IP addresses from boost::asio. Specifically I need to increment and/or add a given integer on an existing address to ease IP list generation in a software that I'm writing. As today I'm using custom classes to handle IP addresses and networks, but I would like to move to boost::asio so I can rely on them to properly check/validade addresses and network attributes. I have this working code as example (except for the operator+ part): using boost::asio::ip::make_address_v4; using boost::asio::ip::address_v4; auto add(const address_v4& address, std::size_t value = 1) { return make_address_v4(address.to_uint() + value); } // This is definitely wrong auto operator+(std::size_t value, const address_v4& address) { return add(address, value); } int main() { auto ip1 = make_address_v4("192.168.1.1"); fmt::print("IP address: {}\n", ip1.to_string()); auto ip2 = make_address_v4(ip1.to_uint() + 1); fmt::print("IP address: {}\n", ip2.to_string()); // Add function fmt::print("Added IP: {}\n", add(ip2, 8).to_string()); fmt::print("Added IP: {}\n", add(ip2).to_string()); // operator+ fmt::print("Added IP: {}\n", (ip2 + 4).to_string()); return 0; } add function works as expected, but I don't know how to overload it so I can do things like: ip++ or ip + 4. Also is there a better way to do math with boost::asio::ip::address_v4? I'm always getting values as uint and doing the math there. Another solution that I was thinking was to inherit boost::asio::ip::address_v4 and create the custom operators, but I don't know if this would work and if it works, this seems overkill, or even worse, I don't know if this is a good practice, it looks like it doesn't. Thank you.
To technically work you need the overload: // This is morally wrong auto operator+(const address_v4& address, std::size_t value) { return add(address, value); } That's because the left-hand operand is address_v4, not size_t. Live demo However, please don't do this. See e.g. What are the basic rules and idioms for operator overloading?. There is no clear and undisputed meaning of the operation here. There is much room for surprises. Depending on subnetting, incrementing an address can make a regular address into a broadcast address, or even cross over into different subnets. E.g. "10.10.9.254" + 0x01010101 == 11.11.10.255 makes little sense, and "255.255.255.255" + 0x01010101 == "1.1.1.0" even less. What you probably want here is a subnet-aware enumerator/iterator interface, perhaps even with random sampling if you need non-sequential traversal. If you abstract this away as if address_v4 is "just an arithmetic type" you're lying about your domain information.
72,409,198
72,409,414
How to get item from list by giving index number?
I'm making program that will read text file and place each word in list named content and I have problem I don't know how to get words from that list in python it is 'content[index_number]'. thanks in advance! //importing// #include <iostream> #include <sstream> #include <list> #include <fstream> using namespace std; using std::ifstream; int main() { std::string str = ""; std::list <string> content; std::cout << "enter file name to read" << endl; std::cin >> file; //reading data// ifstream indata; std::string str; indata.open(file); indata >> str; while (!indata.eof()) { indata >> str; content.push_back(str);} indata.close(); return 0; }
Python lists are arrays and allow random access. So do the same in C++ and put your words in std::vector<std::string> content and you have content[i] just like in python, although content.at(i) is safer so use that.
72,409,376
72,409,648
Please help me find what case am I missing
This is the question: In a far away Galaxy of Tilky Way, there was a planet Tarth where the sport of Tompetitive Toding was very popular. According to legends, there lived a setter known to give advanced string manipulation problems disguised as cakewalk problems. thef, the king of thefland loved the letter 't'. And now, he has made a game on it with his ministers! His ministers would give him 2 strings, a and b. thef has to make them exactly same, for which he can do the following- Step 1 - He MAY reverse at most one of the strings. (This step is optional, and he can choose to reverse any one of the strings, or leave both of them as it is.) Step 2 - He replaces the first character of both the current strings to 't'. This operation is compulsory. He wins if he is able to make both the strings same (i.e. an exact match) after doing these two steps. Given the strings a and b, tell if thef can win or not! Input: The first line of input contains T - The number of test cases in the file. The first and only line of every test case contains the 2 strings, a and b separated by a single space. Output: For each test case, print Yes if thef wins, else print No Constraints 1≤T≤104 1≤|a|,|b|≤100, where |a| refers to the length of string a. a and b will have ONLY lower case English alphabets. Subtasks 100 points- Original Constraints. Sample Input: 3 man nam abcd ebcd abd ebf Sample Output: Yes Yes No EXPLANATION: For the first test case, you can reverse man to nam and then replace both first characters of both strings to get tam. You could also have reversed nam to man, and then replaced the first two characters to get tan. Either of these two methods leads thef to win the game. For the second test case, you can simply skip reversing any of the strings and just replace the first characters by t to get both the strings as tbcd. The 2 strings cannot be made equal in the third test case. My code is: #include <iostream> using namespace std; #include <bits/stdc++.h> #include<string.h> int main() { int test; cin>>test; while(test--){ string str1{},str2{},str3{}; cin>>str1>>str2; str3=str2; str1[0]='t'; str3[0]='t'; if(str1==str3){ cout<<"Yes"<<endl; } else{ int len=str2.length(); int n=len-1; for(int i=0;i<len/2;i++){ swap(str2[i],str2[n]); n=n-1; } str2[0]='t'; if(str2==str1){ cout<<"Yes"<<endl; } else{ cout<<"No"<<endl; } } } return 0; } Now when I run it with the test case provided, I get the expected output. But since I'm doing this problem on Codechef, when I submit it, it runs its own test cases (which is not visible) which my code does not pass. I have tried thinking a lot on what possible case i am not considering.
There is no need to insert the letter 't' to determine that two strings can coincide. It is enough to write the if statement #include <iterator> #include <algorithm> //... auto win = []( const auto &s1, const auto &s2 ) { return ( std::size( s1 ) == std::size( s2 ) ) && ( std::equal( std::next( std::begin( s1 ) ), std::end( s1 ), std::next( std::begin( s2 ) ) ) || std::equal( std::next( std::begin( s1 ) ), std::end( s1 ), std::next( std::rbegin( s2 ) ) ) ); }; if ( win( s1, s2 ) ) { std::cout << "Yes\n"; } else { std::cout << "No\n"; } That is at first you need to compare that two strings have the same length std::size( s1 ) == std::size( s2 ) The above record can be also written like s1.sisze() == s2.size() Then you need to compare the two strings starting from their second characters using the standard algorithm std::equal This exapression std::next( std::begin( s1 ) ) positions the iterator to the second character of the string. And if this condition will return false you should compare the first string starting from its second character with the second string in the reverse order. This expression std::next( std::rbegin( s2 ) ) position the reverse iterator of the second string to the second character of the string starting from its end. This compound condition is written as a lambda expression that is called in the if statement. Here is a demonstration program. #include <iostream> #include <string> #include <iterator> #include <algorithm> int main() { auto win = []( const auto &s1, const auto &s2 ) { return ( std::size( s1 ) == std::size( s2 ) ) && ( std::equal( std::next( std::begin( s1 ) ), std::end( s1 ), std::next( std::begin( s2 ) ) ) || std::equal( std::next( std::begin( s1 ) ), std::end( s1 ), std::next( std::rbegin( s2 ) ) ) ); }; std::string s1( "abcd" ), s2( "ebcd" ); if ( win( s1, s2 ) ) { std::cout << "Yes\n"; } else { std::cout << "No\n"; } s1 = "man"; s2 = "nam"; if ( win( s1, s2 ) ) { std::cout << "Yes\n"; } else { std::cout << "No\n"; } s1 = "abd"; s2 = "ebf"; if ( win( s1, s2 ) ) { std::cout << "Yes\n"; } else { std::cout << "No\n"; } } The program output is Yes Yes No
72,409,685
72,420,618
WSAPoll vs Overlapped WSARecv Performance?
I'm creating a server that must handle 1000+ clients, the method I'm currently using is: One thread will use WSAAccept to handle incoming connections, it has a threads pool of which each thread will handle multiple clients at a time using WSAPoll. For example, if a Client has just connected, the Server will find a poller thread that is free and add it to the fdset of WSAPoll of that poller thread, thus the poller thread will handle the new Client connection. The poller thread will use non-blocking WSAPoll to handle the connections, but then it will use (blocking) recv() to receive the packets. Server: WSAAccept Thread Poller #1: WSAPoll [1, 2, 3, 4, 5] // max out recv[1, 2, 3, 4, 5] Thread Poller #2: WSAPoll [6, 7, 8, 9, 10] // max out recv[6, 7, 8, 9, 10] Thread Poller #3: WSAPoll [11, 12] // free recv[11, 12] // create more pollers if all maxed out It is working fine for me, but then I came across a (might be) better solution using Overlapped socket with WSARecv. The idea here is to use a non-blocking WSARecv completion callback instead of WSAPoll CompletionCallback(){ WSARecv(socket, CompletionCallback); } Loop: socket = WSAAccept(); WSARecv(socket, CompletionCallback); // CompletionCallback will handle the connection. Therefore eliminating the need for multithreading and/or WSAPoll I've made a PoC and it seems to be working just fine, but it is one-threaded, I wonder what's the performance of this compared to the old method. Thanks!
OVERLAPPED I/O scales remarkably well - scaling down/scaling up/scaling out. My tooling uses AcceptEx with OVERLAPPED I/O + Nt Threadpool. And it scales well to hundreds of thousands of connections. https://github.com/Microsoft/ctsTraffic
72,410,052
72,412,243
Given a template class (A) and a parameter pack of types (T1, T2...), convert to a tuple like A<T1>, A<T2>, A<T3>
How do you implement this: template <class A, class ... T> struct wrapper { template <int depth> A<depth>& get(); // returns a reference to the Nth item wrapped in A; }; e.g. wrapper<vector, int, double, string> example; int x=example.get<0>[7]; // return the vector of `int` at position 0 and call operator[] auto y=example.get<1>.size(); // return the vector of `double` at position 1 and get it's size This is what I tried: template<class A, class ... T> struct wrapper { using WRAPPED=decl_type(std::apply( [](auto ...x){ std::make_tuple(A[x], ...); }, T...)); WRAPPED elems; template <int depth> decl_type(std::get<depth>(elems))& get() { return std::get<depth>(elems); } }; But the compiler was not happy: <source>:71:23: error: expected type-specifier before 'decl_type' 71 | using WRAPPED=decl_type(std::apply( | ^~~~~~~~~ <source>:74:14: error: expected unqualified-id before ',' token 74 | }, | ^ <source>:76:9: error: 'WRAPPED' does not name a type 76 | WRAPPED elems; | ^~~~~~~ <source>:79:24: error: 'std::get' is not a type 79 | decl_type(std::get<depth>(elems))& get() { return std::get<depth>(elems); } | ^~~~~~~~~~ <source>:79:44: error: expected constructor, destructor, or type conversion before 'get' 79 | decl_type(std::get<depth>(elems))& get() { return std::get<depth>(elems); } | ^~~ Compiler returned: 1
You need template-template parameter. std::tuple might help too: template <template <typename, typename...> class C, typename... Ts> struct wrapper { template <std::size_t I> std::tuple_element_t<I, std::tuple<C<Ts>...>>& get() { return std::get<I>(data); } std::tuple<C<Ts>...> data; }; // Possible usage void test(wrapper<std::vector, int, double, std::string>& example) { [[maybe_unused]]int x = example.get<0>()[7]; // vector of `int` [[maybe_unused]]auto y = example.get<1>().size(); // vector of `double` } Demo Note: std::vector has more than 1 template parameter (there is allocator which is defaulted).
72,410,259
72,411,494
Add up those fractions that have a common denominator
I have a file with fractions. I have to write fractions from it into a structure. Then I need to create a dynamic data structure in order to add those fractions that have a common denominator, but I should not use dynamic arrays. Can you please help me with the fraction addition part? (the link contains a photo of the file with fractions and the result I want to get, but for now I can only display fractions on the screen, but not add them up) enter image description here #include <iostream> #include <stdio.h> #include <Windows.h> #include <string.h> using namespace std; struct fraction { int numerator, denominator; }; struct Node { fraction fr; Node* next; }; Node* newNode(fraction fr) { Node* p; p = new Node; p->fr.numerator = fr.numerator; p->fr.denominator = fr.denominator; p->next = NULL; return p; } void addNode(Node* curr, Node** head, Node** tail) { if (*head == NULL) { *head = *tail = curr; // *tail = curr; } else { (*tail)->next = curr; *tail = curr; } } void outList(Node* head) { Node* curr; curr = head; while (curr != NULL) { cout << curr->fr.numerator << "/" << curr->fr.denominator << endl;; curr = curr->next; } } int main() { fraction fr; int n; Node* curr = NULL; Node* head = NULL; Node* tail = NULL; FILE* f; fopen_s(&f, "testfile.txt", "r"); if (f) { while (!feof(f)) { fscanf_s(f, "%d", &n); for (int i = 0; i < n; i++) { fscanf_s(f, "%d", &fr.numerator); fscanf_s(f, "%d", &fr.denominator); curr = newNode(fr); addNode(curr, &head, &tail); } } fclose(f); outList(head); } }
If you build it up from the bottom and use constructors and operators it can turn into this: #include <string> #include <iostream> #include <cassert> struct Fraction { // construct a Fraction from whole number or n, d constexpr Fraction(int n, int d=1) noexcept : numerator(n), denominator(d) { } // add other Fraction with matching denominator constexpr Fraction operator +=(const Fraction &other) noexcept { assert(denominator == other.denominator); numerator += other.numerator; return *this; } // denominator may not change but numerator does int numerator; const int denominator; }; // print Fraction nicely std::ostream & operator <<(std::ostream &out, const Fraction &fr) { out << "(" << fr.numerator << " / " << fr.denominator << ")"; return out; } struct List { struct Node { // create Node containing fraction and attach to parent constexpr Node(Node **parent, const Fraction &fr_) noexcept : next{*parent}, fr(fr_) { *parent = this; } // printing node just prints fraction std::ostream & print(std::ostream &out) const { return out << fr; } // Nodes are always constructed as tail so initialize to nullptr Node *next{nullptr}; Fraction fr; }; // construct empty List List() { } // no copying List List(const List &) = delete; // no copy asignment List & operator =(const List &) = delete; // move construct List by taking over Nodes from other List(List && other) : head(other.head) { other.head = nullptr; } // move assign List by swapping Nodes with other List & operator =(List &&other) { std::swap(head, other.head); return *this; } // deconstruct List by deleting all Nodes ~List() noexcept { while(head) { Node *t = head; head = head->next; delete t; } } // print List as sum of fractions std::ostream & print(std::ostream &out) const { for (Node *node = head; node; node = node->next) { node->print(out); if (node->next) out << " + "; } return out; } // add Fraction to list: Either adds to existing Fraction or // adds new Node. Fractions are sorted by denominator. List & operator +=(const Fraction &fr) { Node **tail; for (tail = &head; *tail; tail = &((*tail)->next)) { int d = (*tail)->fr.denominator; if (d > fr.denominator) break; // denominator too large, insert Fraction before if (d == fr.denominator) { // denominator matched, += Fraction (*tail)->fr += fr; return *this; } } // no matching denominator, add new node new Node(tail, fr); return *this; } // add Fraction to List and move result to return value List && operator +(const Fraction &other) && { (*this) += other; return std::move(*this); } // initialize as empty list Node *head{nullptr}; }; // print list std::ostream & operator <<(std::ostream &out, const List &list) { return list.print(out); } // sum of 2 fraction gives a List List operator +(const Fraction &lhs, const Fraction &rhs) { return List{} + lhs + rhs; } // tired of typing so much, shorten name using F = Fraction; int main() { // You can just print sums of fractions like this // std::cout << F{1, 5} + F{4, 7} + F{3, 5} + F{1, 2} + F{2, 2} + F{2, 5} << std::endl; // or read from stdin List list; int count; std::cin >> count; while(count-- > 0) { int n, d; std::cin >> n >> d; list += F{n, d}; } std::cout << list << std::endl; }
72,410,262
72,431,707
Incremental ListView with ScrollBar
I want to implement a ListView that loads new content when is scrolled (it will have over 2000 elements) with a scrollbar. This is what I have: <ListView Width="500" MaxHeight="400" IsItemClickEnabled = "False" SelectionMode ="None" IncrementalLoadingThreshold="5" IncrementalLoadingTrigger="Edge" ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollMode="Enabled"/> The list works perfectly fine but the scrollbar is not visible. How can I make it work?
The problem was with a fixed with. After removing it, the scrollbar is visible.
72,410,364
72,410,472
Reversing an array by recursively splitting the array in C++
string recursion(int arr[], int arrSize) { if(arrSize == 1){ return to_string(arr[0]); } string letterLeft, letterRight, letterFull; //logic1: Normal Recursion //letterFull = to_string(a[n-1]) + " " + recursion(a, n-1); //logic2: D&C ------------------------------------------------------ < letterLeft += recursion(arr, arrSize/2); letterRight += recursion(arr + arrSize/2, arrSize-arrSize/2) + " "; letterFull += letterRight + letterLeft; return letterFull; } I recently used the 'logic2: D&C' for splitting an array recursively to reverse them (more like Divide and Conquer). (i.e. if 2,5,4,1 is given as input, output should be 1,4,5,2). It passed all test case like the example I just gave. Yet, I felt like I don't really understand the flow of recursion. I am here to get help from someone in explaining what happens in the 'logic2: D&C' step-by-step with an example flowchart & values if possible? PS: I took help from https://stackoverflow.com/a/40853237/18762063 to implement this 'logic2: D&C'. Edits - Made little changes to argument list.
It is unclear why there are used objects of the type std::string. To reverse an array of objects of the type char there is no need to use the class sdt::string. This is just inefficient. The function can look the following way void recursion( char arr[], size_t arrSize ) { if ( not ( arrSize < 2 ) ) { std::swap( arr[0], arr[arrSize-1] ); recursion( arr + 1, arrSize - 2 ); } }
72,410,480
72,410,697
How to get the padding position of a long double value in C++?
The number of bits for the mantissa, exponent and sign of a long double value can be detected in the following way (supposing iec559): template <typename T> constexpr uint32_t bitsInExponent() { static_assert(std::numeric_limits<T>::is_iec559); return std::ceil(std::log2(std::numeric_limits<T>::max_exponent-std::numeric_limits<T>::min_exponent+1)); } // outputs 15 for long double on my machine/compiler template <typename T> constexpr uint32_t bitsInMantissa() { static_assert(std::numeric_limits<T>::is_iec559); static_assert(std::numeric_limits<T>::radix == 2); return std::numeric_limits<T>::digits-1; } // outputs 63 for long double on my machine/compiler template <typename T> constexpr uint32_t bitsInSign() { return 1; } Consequently, the total number of bits for the long double is (on my machine and compiler) 79 (63+15+1), probably a IEEE-754 binary64 extended format. However, the memory footprint of the long double (sizeof(long double)) is 16, thus 128 bits. The padding of the float value (those 128-79, 49bits) seems to be at the higher bits on my machine with my compiler, and mostly filled with garbage. My question is: Are those 1-63 bits always at the higher bits of the 128 bits? In case the padding of the extended IEEE-754 binary-64 format is not guaranteed to be at the highest bits, how to detect where is the padding? Try it: https://onlinegdb.com/doL6E7WYL
The authoritative answer can only come from reading the ABI for your implementation. However, if your long double is 80-bit extended precision, then you are almost certainly on x86, since AFAIK it's the only major architecture with hardware support for that format. In that case, unless you have a very unusual compiler with a very unusual ABI, the data is going to be in the low 10 bytes, with the padding in the high 6 bytes. The x87 load and store instructions don't account for the padding, which is a more recent innovation to provide better alignment, so they will expect a pointer to the 10-byte data itself. By putting the data at the low end of the 16 bytes, a long double * is a pointer to the data, and can be used directly with an x87 load or store. If it were anywhere else, every memory access to a long double would require adding the appropriate offset, which would be inefficient. Non-x86 platforms usually implement long double in one of two ways: Either it is just an alias for double (the C++ standard allows this), in which case it would normally be binary64 double precision with no padding, and sizeof(long double) == 8. MSVC++ on x86-64 does this too, and doesn't give you access to the hardware's 80-bit extended precision support. Or, it is binary128 quadruple precision, in which case you have sizeof(long double) == 16 and again no padding.
72,410,860
72,411,364
Do I need to call async_shutdown on beast::ssl_stream<beast::tcp_stream> when experience issues?
https://www.boost.org/doc/libs/1_72_0/libs/beast/example/http/client/async-ssl/http_client_async_ssl.cpp std::unique_ptr<tcp::resolver> resolver_{nullptr}; std::unique_ptr<beast::ssl_stream<beast::tcp_stream>> stream_{nullptr}; void address_failure() { // without calling stream_.async_shutdown // resolver_ = std::make_unique<tcp::resolver>(strand); stream_ = std::make_unique<websocket::stream<beast::ssl_stream<beast::tcp_stream>>>(strand, ctx); ... } void on_handshake(beast::error_code ec) { if(ec) { address_failure(); return; } ... } Question> When I saw connection issues, can I directly start from scratch without calling the stream_.async_shutdown? Thank you
You can start from scratch, but it's good practice to try and do a graceful shutdown if possible. Note that, conversely, some servers might forego clean shutdown. This often leads to short reads (stream_truncated) or, in some situations, sockets in the LINGERING state. It's something that some servers do get away with, but if you do it, you might cause resource exhaustion on the other end.
72,410,931
72,410,978
How to handle "warn_unused_result [-Wunused-result]"?
I am new to C++ and am getting a compiler warning that I am not sure how to address. When I compile INBAND1->RasterIO(GF_Read, 0, y, xsize, 1, agc_data, xsize, 1, GDT_Float32, 0, 0); with c++ calc_emissions.cpp -o calc_emissions.exe -lgdal I get the warning /usr/local/app/emissions/cpp_util/calc_gross_emissions_generic.cpp: In function 'int main(int, char**)': /usr/local/app/emissions/cpp_util/calc_gross_emissions_generic.cpp:382:18: warning: ignoring return value of 'CPLErr GDALRasterBand::RasterIO(GDALRWFlag, int, int, int, int, void*, int, int, GDALDataType, GSpacing, GSpacing, GDALRasterIOExtraArg*)', declared with attribute warn_unused_result [-Wunused-result] INBAND1->RasterIO(GF_Read, 0, y, xsize, 1, agc_data, xsize, 1, GDT_Float32, 0, 0); ~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ My code runs fine with the warning, but I'd like to suppress or resolve the warning. My understanding is that the warning is due to RasterIO() not having a return value (based on this). To suppress the warning, I tried INBAND1->(void)!RasterIO(GF_Read, 0, y, xsize, 1, agc_data, xsize, 1, GDT_Float32, 0, 0); as suggested here. However, that produces the following error /usr/local/app/emissions/cpp_util/calc_gross_emissions_generic.cpp: In function 'int main(int, char**)': /usr/local/app/emissions/cpp_util/calc_gross_emissions_generic.cpp:382:10: error: expected unqualified-id before '(' token INBAND1->(void)!RasterIO(GF_Read, 0, y, xsize, 1, agc_data, xsize, 1, GDT_Float32, 0, 0); ^ /usr/local/app/emissions/cpp_util/calc_gross_emissions_generic.cpp:382:11: error: expected primary-expression before 'void' INBAND1->(void)!RasterIO(GF_Read, 0, y, xsize, 1, agc_data, xsize, 1, GDT_Float32, 0, 0); ^~~~ My impression is that adding (void)! (or (void)) doesn't work here because of the INBAND1-> part of the line. Any suggestions for how to handle this warning? Thanks.
how to handle this warning? Handle the error CPLErr errcode = INBAND1->RasterIO(GF_Read, 0, y, xsize, 1, agc_data, xsize, 1, GDT_Float32, 0, 0); if (errcode != 0) { std::err << "och no rasterIO failed!\n"; std::exit(1); } how to silence the compiler? Put (void) in front of the line. (void)INBAND1->RasterIO(GF_Read, 0, y, xsize, 1, agc_data, xsize, 1, GDT_Float32, 0, 0);
72,411,051
72,412,404
Compiling mutiple c++ files with vscode on mac
I'm fairly new to c++ and programming in general and was watching the free tutorial on the freecodecamp.org youtube channel and when I got up to the point where I used multiple c++ files, I got multiple compiler errors with g++ and clang. Here is main.cpp #include <iostream> #include "compare.h" int main(){ int maximum = max(134,156); std::cout << "max : " << maximum << std::endl; return 0; } This is compare.cpp: int max( int a, int b){ if(a>b) return a; else return b; } And the compare.h file int max( int a, int b);//Declaration When I try and build with clang I get: Undefined symbols for architecture arm64: "max(int, int)", referenced from: _main in main-e30ba6.o ld: symbol(s) not found for architecture arm64 clang-13: error: linker command failed with exit code 1 (use -v to see invocation) When I build with g++ I get: Undefined symbols for architecture arm64: "__Z3maxii", referenced from: _main in cc3V4eOt.o ld: symbol(s) not found for architecture arm64 collect2: error: ld returned 1 exit statu I've searched all over youtube and stack overflow and the only solution I found was to link the files with g++ main.cpp compare.cpp -o main But this only worked once and never again. Any help would be greatly appreciated thanks! Edit After some more research the only thing that gave me a definitive answer was to build with clang, get the error, then run: clang++ main.cpp compare.cpp -o main But I have to do this every time I make changes to the code and that just seems tedious and there has to be a better way. Also if I were to have multiple .cpp files I would have to run those into the command as well.
You could build multiple cpp file in VScode by shortcut . Create a build task by following the documentation Update the tasks.json to support build multiple cpp file: { // See https://go.microsoft.com/fwlink/?LinkId=733558 // for the documentation about the tasks.json format "version": "2.0.0", "tasks": [ { "type": "shell", "label": "C/C++: clang++ build active file", "command": "/usr/bin/clang++", "args": [ "-std=c++17", "-g", "${workspaceFolder}/*.cpp", "-o", "${fileDirname}/main" ], "options": { "cwd": "${workspaceFolder}" }, "problemMatcher": ["$gcc"], "group": { "kind": "build", "isDefault": true }, "detail": "Task generated by Debugger." } ] } Build with command Tasks: Run build task or shortcut.
72,411,169
72,411,243
the output is throwing large numbers
the question is: Chef has gone shopping with his 5-year old son. They have bought N items so far. The items are numbered from 1 to N, and the item i weighs Wi grams. Chef's son insists on helping his father in carrying the items. He wants his dad to give him a few items. Chef does not want to burden his son. But he won't stop bothering him unless he is given a few items to carry. So Chef decides to give him some items. Obviously, Chef wants to give the kid less weight to carry. However, his son is a smart kid. To avoid being given the bare minimum weight to carry, he suggests that the items are split into two groups, and one group contains exactly K items. Then Chef will carry the heavier group, and his son will carry the other group. Help the Chef in deciding which items should the son take. Your task will be simple. Tell the Chef the maximum possible difference between the weight carried by him and the weight carried by the kid.Chef has gone shopping with his 5-year old son. They have bought N items so far. The items are numbered from 1 to N, and the item i weighs Wi grams. Chef's son insists on helping his father in carrying the items. He wants his dad to give him a few items. Chef does not want to burden his son. But he won't stop bothering him unless he is given a few items to carry. So Chef decides to give him some items. Obviously, Chef wants to give the kid less weight to carry. However, his son is a smart kid. To avoid being given the bare minimum weight to carry, he suggests that the items are split into two groups, and one group contains exactly K items. Then Chef will carry the heavier group, and his son will carry the other group. Help the Chef in deciding which items should the son take. Your task will be simple. Tell the Chef the maximum possible difference between the weight carried by him and the weight carried by the kid. Input: The first line of input contains an integer T, denoting the number of test cases. Then T test cases follow. The first line of each test contains two space-separated integers N and K. The next line contains N space-separated integers W1, W2, ..., WN. Output: For each test case, output the maximum possible difference between the weights carried by both in grams. Sample Input 1 2 5 2 8 4 5 2 10 8 3 1 1 1 1 1 1 1 1 Sample Output 1 17 2 Explanation Case #1: The optimal way is that Chef gives his son K=2 items with weights 2 and 4. Chef carries the rest of the items himself. Thus the difference is: (8+5+10) ? (4+2) = 23 ? 6 = 17. Case #2: Chef gives his son 3 items and he carries 5 items himself. my code is: #include <iostream> using namespace std; #include<bits/stdc++.h> int main() { int t=0,n=0,k=0,j=0; cin>>t; while(t--){ cin>>n>>k; int arr[n],son=0,father=0; for(int i=0;i<n;i++){ cin>>arr[n]; } sort(arr,arr+n); for(j=0;j<n;j++){ if(j>=n-1-k){ father+=arr[j]; } else{ son+=arr[j]; } } cout<<father-son<<endl; } return 0; } the ouput im getting is this: 1007357324 1389213724
you are getting bigger numbers because on this line for(int i=0;i<n;i++){ cin>>arr[n]; } You are changing the value on arr[n] (that doesn't exist because you array goes from 0 to n-1). Basically you are not changing any value inside the array so its using trash values that were stored on the memory. The fix to not get those big number is change the line cin>>arr[n]; to cin>>arr[i];. I didnt test your code to check if you will have a correct answer to the problem that you are trying to solve but the big numbers will go away. Cheers!
72,411,265
72,411,873
If atomic_compare_exchange isn't atomic on its own thread, how can it implement a lock?
If I have std::atomic<uint64_t> guard; // ... if (std::atomic_compare_exchange_strong( &guard, &kExpected, kValue, std::memory_order_acquire, std::memory_order_relaxed)) { int foo = *non_atomic_thing; // ... } I know that the read of non_atomic_thing can't be re-ordered before the read of guard. But is it possible for it to be re-ordered before the write? That is, if some other thread reads guard with std::memory_order_acquire, observes that it's not equal to kValue, and writes to it, is this a data race? (cppreference.com isn't very clear on this, but the docs for Rust, which has the same semantics, specifically says that acquire only applies to the load part and release only applies to the store: "Using Acquire as success ordering makes the store part of this operation Relaxed") If this is true, how can I tell other threads not to overwrite my value while I'm reading it?
The C++ standard is a little vague on this point. But what they probably intended, and what happens in practice on many implementations, is that your non-atomic read can be reordered before the write. See For purposes of ordering, is atomic read-modify-write one operation or two?. However, for the usual locking idiom, this is not a problem, and does not lead to a data race. In taking a lock, it's tempting to think of the essential operation as the store of the "locked" value, which tells other threads that the lock is ours and they can't have it. But actually, what's important is the load of the "unlocked" value. This proves that the lock belongs to our thread. The atomicity of the read-modify-write operation guarantees that no other thread will load that value until we reset it, and so we can safely enter the critical section, even if our store of the "locked" value doesn't become visible until some time later. You could imagine this happening on an LL/SC architecture. Suppose the load-link is done and returns the "unlocked" value. The store-conditional hasn't been done yet, and it could fail, in case some other core accessed the lock variable and we lost our exclusive ownership of it. However, in the meantime, we can perform a speculative load of the non-atomic variable, with the understanding that it won't retire unless the SC succeeds. If the SC fails, the LL/SC pair will have to be redone, and in that case our non-atomic load will also be redone. So by the time we finally do get a success, the non-atomic load will be visible after the LL, but possibly before the SC. To see how this follows from the C++ memory ordering rules, let's consider a more fleshed-out example: std::atomic<int> lock{0}; int non_atomic; void reader() { int expected = 0; if (lock.compare_exchange_strong(expected, 1, std::memory_order_acquire, std::memory_order_relaxed)) { int local = non_atomic; // ... lock.store(0, std::memory_order_release); } } void writer() { int expected = 0; if (lock.compare_exchange_strong(expected, 2, std::memory_order_acquire, std::memory_order_relaxed)) { non_atomic = 42; // ... lock.store(0, std::memory_order_release); } } The atomicity promise of a read-modify-write operation comes from C++20 [atomics.order p10]: Atomic read-modify-write operations shall always read the last value (in the modification order) written before the write associated with the read-modify-write operation. The modification order of lock is a total order. The critical sections will only be entered if both compare-exchanges read the value 0. The 0 loaded by reader must be immediately followed in the modification order by a 1, and the 0 loaded by writer must be immediately followed by 2. So 0 has to occur twice. The modification order of lock must therefore either be 0 1 0 2 0 or 0 2 0 1 0. If it's 0 1 0 2 0, then the second 0 must come from the release store in reader. It can't be from the store in writer, because that one must come after 2 in the modification order (because writers store of 0 is sequenced after its store of 2; this is write-write coherency, [intro.races p15]). So the acquire load in writer reads the second 0 in the order, which was put there by the release store in reader, and so they synchronize. This ensures that the access to non_atomic in reader happens before the access in writer, and there is no data race. If it's 0 2 0 1 0, the logic is reversed, and the access in writer happens before the access in reader; again no data race.
72,411,491
72,411,517
Global int alternative
i have an int linked list, and a function called filter which receives a list and a condition function. The filter function goes through the nodes in the list and if the condition is true, it adds it to a new list. I've created this so that it filters the list through a number i choose to be divided by while the program is running, but it uses a global int, is there an alternative without changing the function filter, I've thought about making it call for a function to be called once to setup the number but didn't succeed, static int choosenDividedBy = 1; static bool dividedBy(int n); int main() { Queue<int> q4; for (int i = 1; i <= 10; i++) { q4.pushBack(i); } std::cout << "Choose a number to divide by:" << std::endl; std::cin >> choosenDividedBy; q4 = filter(q4, dividedBy); for (Queue<int>::Iterator i = q4.begin(); i != q4.end(); ++i) { std::cout << *i << std::endl; } return 0; } static bool dividedBy(int n) { return (n % choosenDividedBy) == 0; } Edit: filter: template<class T> Queue<T> filter(const Queue<T>& queue, bool (*condition)(T)) { Queue<T> newQueue; for(typename Queue<T>::ConstIterator i = queue.begin();i != queue.end();++i) { try { if(condition(*i)) { newQueue.pushBack(*i); } } catch(typename Queue<T>::ConstIterator::InvalidOperation& exception) { throw exception; } } return newQueue; }
You would create a a filter class that has a normal (non-static) member that stores your int and has the filter method you also have.
72,411,692
72,411,887
How do i write inside of a txt file with c++
I have been trying to insert the hardware id inside of a file called hardwareid2.txt, this is where the hardware id that i am extracting should be inserted, however it doesn't seem to be doing that and im not sure why, All the code seems to be doing is creating the file but not writing inside of the file. could someone help me debug this? #include <windows.h> #include <stdio.h> #include <iostream> #include <fstream> using namespace std; HW_PROFILE_INFO hwProfileInfo; std::string hwid = hwProfileInfo.szHwProfileGuid; int main() { if(GetCurrentHwProfile(&hwProfileInfo) != NULL){ std::ofstream hwidfile { "hardwareid2.txt" }; hwidfile.open("hardwareid2.txt"); hwidfile <<hwid; hwidfile.close(); printf("Hardware GUID: %s\n", hwProfileInfo.szHwProfileGuid); printf("Hardware Profile: %s\n", hwProfileInfo.szHwProfileName); }else{ return 0; } getchar(); }
In the original code HW_PROFILE_INFO hwProfileInfo; std::string hwid = hwProfileInfo.szHwProfileGuid; The call to GetCurrentHwProfile that will load the system profile into hwProfileInfo is conspicuously absent between the definition of hwProfileInfo and its usage to initialize hwid. That means hwProfileInfo; is sitting in its default state, a big block of zeros because its been declared at global scope. szHwProfileGuid will be an empty, immediately null-terminated string, and that emptiness will be used to initialize hwid. Much later hwidfile <<hwid; will write the empty string to the file stream. printf("Hardware GUID: %s\n", hwProfileInfo.szHwProfileGuid); prints the correct value because hwProfileInfo has been updated since hwid was initialized with the empty string. Fix: Get rid of hwid. We don't need it. #include <windows.h> #include <stdio.h> #include <iostream> #include <fstream> using namespace std; int main() { HW_PROFILE_INFO hwProfileInfo; // unless we have a very good reason, this should // not be global if(GetCurrentHwProfile(&hwProfileInfo) != NULL) { // update info was a success. NOW we have a GUID and can do stuff with // hwProfileInfo std::ofstream hwidfile { "hardwareid2.txt" }; hwidfile.open("hardwareid2.txt"); if (!(hwidfile << hwProfileInfo.szHwProfileGuid)) { // will fail if can't write for any reason, like file didn't open std::cout << "File write failed\n"; return -1; } // hwidfile.close(); don't need this. hwidfile will auto-close when it exists scope printf("Hardware GUID: %s\n", hwProfileInfo.szHwProfileGuid); printf("Hardware Profile: %s\n", hwProfileInfo.szHwProfileName); } else { std::cout << "GetCurrentHwProfile failed\n"; return -1; } getchar(); } But if we do need it, it must be updated after the GUID has been successfully gotten with GetCurrentHwProfile blah blah blah... if(GetCurrentHwProfile(&hwProfileInfo) != NULL) { hwid = hwProfileInfo.szHwProfileGuid; std::ofstream hwidfile { "hardwareid2.txt" }; ...blah blah blah
72,412,173
72,417,633
Unexpected invalid padding error with RSA_private_encrypt() and RSA_public_decrypt()
I'm trying to encrypt with private key and decrypt with public key, with RSA_PKCS1_PADDING as padding. The encryption works fine, but when I do the decryption I got an invalid padding error: processed 9 of 256 bytes, RSA_public_decrypt() error:0407008A:rsa routines:RSA_padding_check_PKCS1_type_1:invalid padding Anyone know what's wrong here? Attached full source code: void encrypt_stdout(const char *from_file, int to_base64, int padding) { unsigned char *input = NULL, *output = NULL, *output2 = NULL; int output_fd = -1, input_len = 0, output_len = 0, output2_len = 0; if (readfile(from_file, &input, &input_len) != 0) { goto end; } output = malloc(RSA_size(rsa)); if (output == NULL) { fprintf(stderr, "malloc() on output: %s\n", strerror(errno)); goto end; } output_len = RSA_private_encrypt(input_len, input, output, rsa, padding); if (output_len == -1) { fprintf(stderr, "RSA_private_encrypt() %s\n",ERR_error_string(ERR_get_error(), errbuf)); } else { if (to_base64) { } write(1, output, output_len); } end: if (input != NULL) { free(input); } if (output != NULL) { free(output); } } void decrypt_stdout(const char *from_file, int is_base64, int skip_bytes, int padding) { unsigned char *input = NULL, *output = NULL, *output2 = NULL; int output_fd = -1, input_len = 0, output_len = 0, output2_len = 0, total_read = skip_bytes; if (readfile(from_file, &input, &input_len) != 0) { goto end; } if (is_base64) { if (base64_decode(input, input_len, &output2, &output2_len) != 0) { if (output2 != NULL) free(output2); goto end; } free(input); input = output2; input_len = output2_len; } output = malloc(RSA_size(rsa)); if (output == NULL) { fprintf(stderr, "malloc() on output: %s\n", strerror(errno)); goto end; } while (total_read < input_len) { memset(output, 0, RSA_size(rsa)); output_len = RSA_public_decrypt(RSA_size(rsa), input + total_read, output, rsa, padding); if (output_len == -1) { fprintf(stderr, "\nprocessed %d of %d bytes, RSA_public_decrypt() %s\n", total_read, input_len, ERR_error_string(ERR_get_error(), errbuf)); break; } else { write(STDOUT_FILENO, output, output_len); } total_read += output_len; } end: if (input != NULL) { free(input); } if (output != NULL) { free(output); } }
The problem is caused by the while loop in decrypt_stdout(). To me the sense of this loop is not clear. Instead of the loop it should be quite analogous to encrypt_stdout(): output_len = RSA_public_decrypt(input_len, input, output, rsa, padding); if (output_len == -1) { fprintf(stderr, "RSA_public_decrypt() %s\n", ERR_error_string(ERR_get_error(), errbuf)); } else { _write(1, output, output_len); } With this, decryption works on my machine. However, if the loop is used, the first decryption succeeds and returns the plaintext, while the subsequent decryption fails and returns a -1, resulting in the output of the error message. A few notes on the logic used in the code: Since you talk about encryption and decryption: RSA_private_encrypt() and RSA_public_decrypt() are not really meant for encryption and decryption, but for low level signing and verification. Typically, when signing with RSA_private_encrypt(), it is not the data itself that is passed, but a hash of the data prefixed with a digest ID (more precisely, the DER encoding of the DigestInfo value). In the posted code, there is neither hashing nor prepending a digest ID. Of course, the loaded file might already contain the concatenation of digest ID and hash, but that cannot be said without sample data. If this is not the case, the generated signature is not compliant with PKCS#1 v1.5 padding. If no hashing takes place, care must be taken that the length criterion is met, i.e. the data to be signed must be smaller than the key size minus the minimum space required by the padding (11 bytes for PKCS#1 v1.5 padding or flag_padding = 1). For completeness: PKCS#1 v1.5 padding is determinstic (in the context of signing). The padded data looks like this: 0x00 || 0x01 || PS || 0x00 || T, where PS consists of so many 0xff values that the size is equal to the key size. T is the data or, if compliant with the specification, the concatenation of digest ID and hashed data, s. RFC8017.
72,412,754
72,412,814
creating minheap for structure in c++
#include <vector> #include <algorithm> struct doc { double rank; explicit doc(double r) : rank(r) {} }; struct doc_rank_greater_than { bool operator()(doc const& a, doc const& b) const { return a.rank > b.rank; } }; int main() { std::vector<doc> docvec; docvec.push_back( doc(4) ); docvec.push_back( doc(3) ); docvec.push_back( doc(2) ); docvec.push_back( doc(1) ); std::make_heap(docvec.begin(),docvec.end(),doc_rank_greater_than()); std::cout << docvec.front().rank << '\n'; } The above is a code for creating minheap for a user defined data type using custom comparator. why are we using a.rank>b.rank instead of a.rank<b.rank for creating minheap ?
As suggested by the documentation of std::make_heap, the function constructs a max heap by default. Reversing the comparison function makes it construct a min heap instead.
72,412,802
72,412,857
C++ Constructor setting all values to zero
struct AnimationData { struct Frame { int x1, y1, x2, y2; float dt; // seconds Frame() : x1(0), y1(0), x2(1), y2(1), dt(1) {} } * frames; int frame_count; std::string name; AnimationData(int fc, std::string n) : frame_count(fc), name(n) { frames = new Frame[fc]; for (int i = 0; i < fc; i++) { std::cout << frames[i].x2 << '\n'; } } }; int main() { AnimationData data{10, "test"}; data.frames[1].x1 = 666; std::cout << "Start" << '\n'; for (int i = 0; i < data.frame_count; i++) { std::cout << data.frames[i].x1 << '\n'; } return 0; } This outputs: 1 1 1 1 1 1 1 1 1 1 Start 0 666 0 0 0 0 0 0 0 0 Why Does it turn everything to zero except for the one I set? (Note I know nothing about copy and move constructors idk if they are related to this)
Why Does it turn everything to zero except for the one I set? Because the default constructor Frame::Frame() will initialize x1, y1 to 0 and x2, y2, dt to 1 when you wrote: frames = new Frame[fc]; //default ctor will initialize x1, y1 to 0 and x2, y2, dt to 1 That is, the 10 Frame objects that will be allocated on the heap will be created using the default constructor of Frame which will initialize x1, y1 to 0 and x2, y2 and dt to 1. This is why when you wrote: std::cout << frames[i].x2 << '\n'; //prints 1 becasue default ctor initialized `x2` to `1` the above statement will print 1 as default ctor initialized x2 to 1 For the same reason when you wrote: std::cout << data.frames[i].x1 << '\n'; //will print 0 as default ctro initialized x1 to 0 except for `data.frames[1].x1` which you set to `666`. the above statement will print 0 since the default ctor initialized x1 to 0 except for data.frames[1].x1 which you specifically set to 666. You can confirm that the default ctor is used by adding a cout statement inside it as done below: Frame() : x1(0), y1(0), x2(1), y2(1), dt(1) { std::cout<<"default ctor called"<<std::endl; } The output of the modified program is: default ctor called default ctor called default ctor called default ctor called default ctor called default ctor called default ctor called default ctor called default ctor called default ctor called 1 1 1 1 1 1 1 1 1 1 Start 0 666 0 0 0 0 0 0 0 0
72,412,824
72,412,887
Errors after updating to GCC 12
I have a project where I'm using the datetimepp library and it has been working fine. However I recently did a pacman -Syu and updated gcc. I then compiled the project (which had been compiling properly before that) and compiled it. I got multiple errors complaining "default argument redefinition" datetimepp/datetime.h:311:96: error: redefinition of default argument for ‘typename std::enable_if<std::is_floating_point<_Tp>::value>::type* <anonymous>’ 311 | template<class Scalar, typename std::enable_if<std::is_floating_point<Scalar>::value>::type* = nullptr> | ^~~~~~~ datetimepp/datetime.h:73:96: note: original definition appeared here 73 | template<class Scalar, typename std::enable_if<std::is_floating_point<Scalar>::value>::type* = nullptr> | ^~~~~~~ datetimepp/datetime.h:323:90: error: redefinition of default argument for ‘typename std::enable_if<std::is_integral<_Tp>::value>::type* <anonymous>’ 323 | template<class Scalar, typename std::enable_if<std::is_integral<Scalar>::value>::type* = nullptr> | ^~~~~~~ datetimepp/datetime.h:76:90: note: original definition appeared here 76 | template<class Scalar, typename std::enable_if<std::is_integral<Scalar>::value>::type* = nullptr> | ^~~~~~~ datetimepp/datetime.h:335:96: error: redefinition of default argument for ‘typename std::enable_if<std::is_floating_point<_Tp>::value>::type* <anonymous>’ 335 | template<class Scalar, typename std::enable_if<std::is_floating_point<Scalar>::value>::type* = nullptr> | ^~~~~~~ datetimepp/datetime.h:79:96: note: original definition appeared here 79 | template<class Scalar, typename std::enable_if<std::is_floating_point<Scalar>::value>::type* = nullptr> | ^~~~~~~ datetimepp/datetime.h:342:90: error: redefinition of default argument for ‘typename std::enable_if<std::is_integral<_Tp>::value>::type* <anonymous>’ 342 | template<class Scalar, typename std::enable_if<std::is_integral<Scalar>::value>::type* = nullptr> | ^~~~~~~ datetimepp/datetime.h:82:90: note: original definition appeared here 82 | template<class Scalar, typename std::enable_if<std::is_integral<Scalar>::value>::type* = nullptr> Just to confirm that the program was indeed working before I updated, I rolled back the gcc update and the program compiled successfully. Is this a problem with my program that I should fix, or is it a problem with g++?
Default arguments can only be specified at either declaration or definition but in your case you've specified them at both places. void foo(int x = 10); void foo(int x = 10){} // error. redefinition of default arg void foo(int x){} foo(); // ok. default arg is 10 So you should remove them from either declaration or definition, definition would be preferred because in between definition and declaration, you wouldn't be able to use those default arguments. void foo(int x); foo(); // error. no default arg void foo(int x = 10){} foo(); // ok
72,412,840
72,413,183
Should we prefer Qt's private slots over public slots?
Qt "private slots:" what is this? AFAIK @Andrew's answer to the question above addresses the point. And @borges mentions the important detail When the method is called via signal/slot mechanism, the access specifiers are ignored. But slots are also "normal" methods. When you call them using the traditional way, the access specifiers are considered So I'm leaning towards write slots as private, in principle. And only mark them as public when the expectation is to also call them in a non connect context, I mean a direct call. In other works, that will be like prefer private slots. However, I don't record having seen this kind of mentality on Qt's documentation. They seem to just use public slots everywhere. Am I missing something? Does anything change when we do multithreading and a method (slot) might be called in an object which is in another thread?
Slots are a part of your class interface and thus should be public. Private slots are possible with the old connection syntax only due to the peculiarities of how the metasystem works. So they are a byproduct not some first-class citizens to support in the long run. You also can't use the new connection syntax (which is preferred) if you have private slots because you need the pointer to the member function which you for no reason made private. So no, you should not make slots private by default. Only if some specific need arises and with a comment of why you did it that way.
72,412,938
72,413,006
Conditionally enable member function depending on template parameter
I'm struggling to get the below code to compile. I want to enable foo function for class A only when N=3. #include <iostream> template <size_t N> class A { public: template <size_t n = N, std::enable_if_t<(n == 3)>* = nullptr> int foo(int a); }; template<size_t N> template <size_t n = N, std::enable_if_t<(n == 3)>* = nullptr> int A<N>::foo(int a) { return a * 4; } int main() { A<3> a1; std::cout << a1.foo(10) << std::endl; // the below should fail to compile // A<4> a2; // std::cout << a2.foo(7) << std::endl; } Output <source>:12:20: error: default argument for template parameter for class enclosing 'int A<N>::foo(int)' 12 | int A<N>::foo(int a) | ^
Whenever you separate a function's declaration and definition, whether it is a template function or not, default argument values can only be in the declaration, not in the definition. So, simply remove the default values from foo's definition, eg: #include <iostream> template <size_t N> class A { public: template <size_t n = N, std::enable_if_t<(n == 3)>* = nullptr> int foo(int a); }; template<size_t N> template <size_t n, std::enable_if_t<(n == 3)>*> int A<N>::foo(int a) { return a * 4; } Online Demo
72,413,153
72,432,091
Area-based CGAL smoothing turned off but smoothing not performed
I more or less copied this CGAL example, mainly except that instead of PMP::smooth_mesh(mesh, PMP::parameters::number_of_iterations(nb_iterations) .use_safety_constraints(false) .edge_is_constrained_map(eif)); I set the area-based smoothing to false, because I don't have the Ceres library: PMP::smooth_mesh(mesh, PMP::parameters::number_of_iterations(niters) .use_area_smoothing(false) .use_Delaunay_flips(false) .use_safety_constraints(false) .edge_is_constrained_map(eif)); However when trying my code, this message is thrown: Area-based smoothing requires the Ceres Library, which is not available. No such smoothing will be performed! I don't understand since I set use_area_smoothing(false). How to tell to CGAL that I don't want the area-based smoothing?
There is no way to disable it. This excessive verbosity was a bug and it has been fixed recently in the following pull request: https://github.com/CGAL/cgal/pull/6502. It will be part of the upcoming release CGAL 5.5; you can apply the patch locally until then.
72,413,180
72,413,683
openGL rectangle rendering triangle instead?
So i'm trying to render a rectangle in openGL using index buffers however instead i'm getting a triangle with one vertex at the origin (even though no vertex in my rectangle is suppsoed to go at the origin). void Renderer::drawRect(int x,int y,int width, int height) { //(Ignoring method arguments for debugging) float vertices[12] = {200.f, 300.f, 0.f, 200.f, 100.f, 0.f, 600.f, 100.f, 0.f, 600.f, 300.f, 0.f}; unsigned int indices[6] = {0,1,3,1,2,3}; glBindVertexArray(this->flat_shape_VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,this->element_buffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(indices),indices,GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER,this->render_buffer); glBufferData(GL_ARRAY_BUFFER,sizeof(vertices),vertices,GL_DYNAMIC_DRAW); glEnableVertexAttribArray(0); glUseProgram(this->shader_program); glUniformMatrix4fv(this->model_view_projection_uniform,1,GL_FALSE,glm::value_ptr(this->model_view_projection_mat)); glUniform3f(this->color_uniform,(float) this->color.r,(float)this->color.g,(float)this->color.b); glDrawElements(GL_TRIANGLES,6,GL_UNSIGNED_INT,nullptr); } My projection matrix is working fine I can still render a triangle at the correct screen coords. I suspect maybe I did index buffering wrong? Transformation matrices also work fine, atleast on my triangles. Edit: The VAO's attributes are set up in the class constructor with glVertexAttribPointer(); Edit 2: I disabled shaders completely and something interesting happened. Here is the shader source code: (vertex shader) #version 330 core layout (location = 0) in vec3 aPos; uniform mat4 mvp; uniform vec3 aColor; out vec3 color; void main() { gl_Position = mvp * vec4(aPos, 1.0); color = aColor; } (fragment shader) #version 330 core in vec3 color; out vec4 FragColor; void main() { FragColor = vec4(color,1.0f); } My projection matrix shouldn't work with shaders disabled yet I still see a triangle rendering on the screen..??
What is the stride argument of glVertexAttribPointer? stride specifies the byte offset between consecutive generic vertex attributes. In your case it should be 0 or 12 (3*sizeof(float)) but if you look at your images it seems to be 24 because the triangle has the 1st (200, 300) and 3rd (600, 100) vertices and one more vertex with the coordinate (0, 0). glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), nullptr); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), nullptr);
72,413,387
72,413,738
how to level-traverse while using `fs::filesystem` in c++
By using fs::filesystem I can pre-order traverse Like below code for (const auto& file : fs::recursive_directory_iterator(paths)) cout << file.path() << endl; And, I found that recursive_directory_iterator only supports for pre-order. Then How Can I use "level-order traversal" in c++? I think I have to use <vector> . Any hints?
In loop you can push paths into std::vector after that loop sort this vector by '/' character count in paths.
72,413,454
72,413,771
Dynamic allocation/deallocation of array of pointers
Via stackoverflow threads like this one, I discovered that you could use an array of pointers to manage a 2D array. In the past I used to use pointer to pointer to store 2D arrays, but now I have a requirement to store my data in contiguous memory, so pointer to pointer format doesn't work anymore. A raw 2D array is an alternative to array of pointers, but raw 2D array doesn't work for me because I want to be able to allocate storage in the heap and not on the stack because my container can be very large and I might encounter stack overflow if I use vanilla 2D array. My question is about how memory is allocated for array of pointers. I use new operator like below (see my constructor) to allocate my array of pointers #include <iostream> using namespace std; template<typename DataType, unsigned numRows, unsigned numCols> class Container2D { public: Container2D() { m_data = new DataType[numRows][numCols]; } ~Container2D() { delete [] m_data; } DataType* getData() { return &m_data[0][0]; } private: DataType (*m_data)[numCols]; }; int main() { Container2D<int, 3, 3> container; return 0; } Does new DataType[numRows][numCols] allocate the entire 2D array on the heap or does it allocate numRows pointers on the heap while allocating numCols objects of type DataType on the stack? In a pointer to pointer scenario (where I'd define my storage as DataType** m_data), I know for a fact that both dimensions of my array are allocated on the heap and I would call delete m_data[i] for each column and then call delete[] m_data to free my row data. In the array of pointers scenario, I'm not sure if my destructor above is freeing up data correctly.
One way is to use a 1D contiguous array and implement the 2D index to 1D index mapping instead: #include <iostream> #include <cassert> using namespace std; template<typename DataType, unsigned numRows, unsigned numCols> class Container2D { public: Container2D() { m_data = new DataType[numRows * numCols]; } ~Container2D() { delete [] m_data; } inline DataType operator()(unsigned i, unsigned j) const { assert( 0 <= i && i < numRows); assert( 0 <= j && j < numCols); return m_data[i*numCols+j]; } inline DataType& operator()(unsigned i, unsigned j) { // same as above, but this allows inplace modifications assert( 0 <= i && i < numRows); assert( 0 <= j && j < numCols); return m_data[i*numCols+j]; } private: DataType* m_data; }; int main() { Container2D<int, 3, 3> container; int x = container(0,0); // retrieve the element at (0,0); container(1,2) = 9; // modify the element at (1,2); // int y = container(3,0); // triggers assertion errors for out-of-bound indexing return 0; } Notes: If numRows and numCols do not change for a specific class instance, new and delete are not necessary in this case. If they do dynamically change, it is better to store them as member variables instead of template parameters. If numRows and numCols are too large, one can dynamically allocate Container2D objects as a whole. As @GoswinvonBrederlow commented, there is no difference between this and new m_data[numRows][numCols] in terms of memory layout, but this convention makes it easier to extend to higher dimensions.
72,413,858
72,429,097
#include <ranges>, but no namespace 'ranges' found
I want to use std::ranges:views::filter, but VS2019 failed to find std::ranges even #include <ranges>. I'll show you this problem with test project. I've created 'Console App' project on Visual Studio 2019 community, and set up C++ Language Standard to ISO C++20 Standard (/std:c++20). Now the problem : if I type #include <ranges> & std::ranges;, an error comes out : error C2039: 'ranges': is not a member of 'std'. How do I get VS2019 to include ranges correctly?
C++20 Standard Library features are available in Visual Studio 2022 version 17.2 and Visual Studio 2019 version 16.11.14. devblog link I update Visual Studio 2019 from 16.11.9 to 16.11.15, then <ranges> works.
72,414,022
72,414,092
C++ - response is int%
I decide 2D Dinamic Coding on C++, i'm decide task about count of ways to bottom-right field in table, and my program return %. Why? Program: #include <iostream> using namespace std; int main() { int n, m; cin >> n >> m; int arr[n][m]; for (int i = 0; i < n; i++) arr[i][0] = 1; for (int i = 0; i < m; i++) arr[0][i] = 1; for (int i = 1; i < n; i++) { for (int j = 1; j < m; j++) arr[i][j] = arr[i-1][j] + arr[i][j-1]; } cout << arr[n-1][m-1]; } I would like answer Request: 1 10 Response: 1
Your program has undefined behavior for any other sizes than n = 1 and m = 1 because you leave the non-standard VLA (variable length array) arr's positions outside arr[0][0] uninitialized and later read from those positions. If you want to continue using these non-standard VLA:s, you need to initialize them after constructing them. Example: #include <cstring> // std::memset // ... int arr[n][m]; std::memset(arr, 0, sizeof arr); // zero out the memory // ... Another approach that would both make it initialized and be compliant with standard C++ would be to use std::vectors instead: #include <vector> // ... std::vector<std::vector<int>> arr(n, std::vector<int>(m)); // ... A slightly more cumbersome approach is to store the data in a 1D vector inside a class and provide methods of accessing the data as if it was stored in a 2D matrix. A class letting you store arbitrary number of dimensions could look something like below: #include <utility> #include <vector> template <class T, size_t Dim> // number of dimensions as a template parameter class matrix { public: template <class... Args> matrix(size_t s, Args&&... sizes) // sizes of all dimensions : m_data(s * (... * sizes)), // allocate the total amount of data m_sizes{s, static_cast<size_t>(sizes)...}, // store sizes m_muls{static_cast<size_t>(sizes)..., 1} // and multipliers { static_assert(sizeof...(Args) + 1 == Dim); for (size_t i = Dim - 1; i--;) m_muls[i] *= m_muls[i + 1]; // calculate dimensional multipliers } template <size_t D> size_t size() const { return m_sizes[D]; } size_t size(size_t D) const { return m_sizes[D]; } // access the data using (y,z) instead of [y][x] template <class... Args> T& operator()(Args&&... indices) { static_assert(sizeof...(Args) == Dim); return op_impl(std::make_index_sequence<Dim>{}, indices...); } private: template <std::size_t... I, class... Args> T& op_impl(std::index_sequence<I...>, Args&&... indices) { return m_data[(... + (indices * m_muls[I]))]; } std::vector<T> m_data; size_t m_sizes[Dim]; size_t m_muls[Dim]; }; With such a wrapper, you'd only need to change the implementation slightly: #include <iostream> int main() { int n, m; if(!(std::cin >> n >> m && n > 0 && m > 0)) return 1; matrix<int, 2> arr(n, m); for (int i = 0; i < arr.size<0>(); i++) arr(i, 0) = 1; for (int i = 0; i < arr.size<1>(); i++) arr(0, i) = 1; for (int i = 1; i < n; i++) { for (int j = 1; j < m; j++) arr(i, j) = arr(i - 1, j) + arr(i, j - 1); } std::cout << arr(n - 1, m - 1) << '\n'; }
72,414,928
72,417,171
Pointer not inheriting base class methods
I just started learning polymorphism and am stuck with smth. I have a base class Object, and a derived class Ball. I would like to achieve polymorphism and use Ball methods on an Object pointer as such: Object *ball = new Ball(P, dPdt, s, Forces); cout << ball->getP() << " position\n" << ball->getdPdt() << " speed\n"; The first one, getP(), works fine because it's a method of the Object class and Ball's constructor calls Object's constructor to initialize it. Now, when it comes to getdPdt(), the compiles complains that no member named getdPdt in Object, which is obvious since I defined it in Ball. What am i doing/understanding wrong here ? PS: I need by *ball to be an Object since this is for a physics simulation and everything must be an Object in order to simulate it. Later on, I guess I'll add a vector<unique_ptr<Object>> to keep track of
C++ is a statically typed language. If the static type of an expression is Object, then it can do whatever an Object can do (and nothing else). If it's a Ball, then it can do whatever a Ball can do. You want it to be an Object but be able to do what Ball can do. You cannot have both, you need to decide one way or another. Polymorphism is not about making properties that are exclusively defined for Ball magically available through an Object pointer. It is about Ball properties inherited from Object behave in a Ball-specific way. Note that Object *ball = new Ball(P, dPdt, s, Forces); dynamic_cast<Ball*>(ball)->getdPdt(); can only be read this way: Object *ball = new Ball(P, dPdt, s, Forces); // I want to create a Ball but forget that it's a Ball // I want to only remember that it's an Object dynamic_cast<Ball*>(ball)->getdPdt(); // No! It's really a Ball after all! // My decision to forget it was wrong! I regret it! Now anyone looking at these two lines of code would wonder whether you really know what you want, and rightfully so. Don't do things that you regret at the next line. The situation is more complicated if these two lines are not next to each other. For example, you may have a vector of Object*: std::vector<Object*> objects; objects.push_back(new Ball(whatever)); // in a totally different function in a totally different file dynamic_cast<Ball*>(objects[i])->getdPdt(); Now the questions that the astute reader would be asking are different, but no less difficult. Why is it known that objects[i] points to a Ball? Why isn't this knowledge encoded in the type of the variable? That's what types are for in C++. Recall that C++ is a statically typed language. Any exception to this (and dynamic_cast is naturally an exception, what with it having the word "dynamic" in it) should be extremely well justified. If there is some code that decides what to do based on the type of the variable, that code should generally be a method in the base class. In the end there are only two different things you can do while staying in the object-oriented design paradigm. Either add getdPdt to Object, so that it is available for all Objects; or put your Balls in a separate basket whose type says that there are Balls inside, and not just Objects. dynamic_cast is a deviation from the OO paradigm. Whether a deviation is acceptable to you is up to you to decide, but if you find yourself deviating from it a lot, then perhaps you want to consider a different paradigm.
72,414,979
72,415,073
Is there a function that can jump over outside of a function?
Is there a function like example: goto that can jump over functions? Lets say I have this code : #include <iostream> void function1() { //dothis1 //dothis2 //jump to other function } int main() { std::cout<<"a"; //go to here (jump) std::cout<<"b"; }
You can just call the another function to which you want to jump to as shown below. In the below program we call function1 from inside main and when function1 finishes the control will be automatically returned to the calling function main. Then from inside function1 we call dothis1 and dothis2 and when dothis1 and dothis2 finishes control will be automatically returned to the calling function function1. void dothis1() { std::cout<<"entered dothis1"<<std::endl; } void dothis2() { std::cout<<"entered dothis2"<<std::endl; } void function1() { std::cout<<"entered function1"<<std::endl; //call dothis1 dothis1(); //now call dothis2 dothis2(); } int main() { //call function1 function1(); return 0; } The output of the above program can be seen here: entered function1 entered dothis1 entered dothis2
72,415,115
72,415,152
Is there a canonical way to handle explicit conversion between two externally-defined classes?
I'm using two external libraries which define classes with identical contents (let's say Armadillo's Arma::vec and Eigen's Eigen::VectorXd). I would like to be able to convert between these classes as cleanly as possible. If I had defined either class, it would be trivial to include a constructor or conversion operator in that class' definition, to allow me to write e.g. Arma::vec foo(/*some constructor arguments*/); Eigen::VectorXd bar = Eigen::VectorXd(foo); but since both classes are from external libraries, I cannot do this. If I attemt to write a naive conversion function, e.g. class A{ public: int value_; A(int value) : value_(value) {} }; class B{ public: int value_; B(int value) : value_(value) {} }; A A(const B& b){return A(b.value_);} int main(void){ A a(1); B b(2); a = A(b); } then the function shadows the class definition, and suddenly I can't use the A class at all. I understand that allowing A a=b to be defined would be a bad idea, but I don't see why allowing A a=A(b) would cause any problems. My question: Is it possible to write a function or operator to allow the syntax A a=A(b)? And if not, is there a canonical way of doing this kind of conversion? I've seen A a=toA(b) in a few libraries, but this isn't used consistently, and I dislike the inconsistency with the usual type conversions.
Is it possible to write a function or operator to allow the syntax A a=A(b)? No, it is not possible. The two classes involved define what conversions are possible and you can't change a class definition after it has been defined. You will need to use a function as in your given example, although I would avoid repeating the type name and write auto a = toA(b);
72,415,177
72,415,707
C++ type complementation in vscode extensions
I am learning C++ on docker using the template project at https://github.com/cpp-best-practices/gui_starter_template in C++. I have the following code, where name: and text:are not originally written code, but it is completed so that I can see which type it is. It is not a problem because it disappears when it is executed. Which extension is this? It is useful, but I would like to know which extension it is. I use C++ better syntax, Clang tidy and Clang Format. struct IMG : Tag { explicit IMG(std::string url) : Tag{ name : "img", text : "" } { attributes.emplace_back(make_pair("src", std::move(url))); } }; }// namespace html
I think the inlay hints is a built-in feature now. And VS Code introduced some new values to control how inlay hints behaves since v 1.67 : Editor › Inlay Hints: Enabled value: on - Inlay hints are enabled. off - Inlay hints are disabled. onUnlessPressed - Inlay hints shown and hidden with Ctrl+Alt. offUnlessPressed - Inlay hints hidden and shown with Ctrl+Alt. Check this GitHub issue for more detail about inlay hints When I set inlay hints to offUnlessPressed, it looks like this while I press Ctrl + Alt(Please ignore that it's a Rust project):
72,415,211
72,415,511
How to get IntPtr of c# unsafe struct to free its memory initialized in c++ dll
Please, advise me on how to free memory from the created unsafe C# struct(s) using some standard C# toolset or how get I get the IntPtr of those objects to use the default provided custom C++ library? The problem details (UPD): I create the C# unsafe struct and pass it to C++ dll that I can't change TH_ExtractBimTemplate(ref createdStruct). The dll updates its content. And in addition to that, the dll saves the reference to the struct object inside of it in an internal list. Here is the struct definition: public unsafe struct BIM_Template { public ushort ImageSizeX; public ushort ImageSizeY; public fixed uint Mint[MAX_MINUTIAE_SIZE]; public uint Reserve; } After the API call returns, I use the data in the struct populated by the C++ dll in my C# code. I need to free the memory used by the struct and C++. The dll has an API to do this, TH_FreeMemory. For step #3 I need to pass the object reference (I presume IntPtr) to C++ library or I need to Free the memory it was occupying with some C# instrument. The Garbage Collection doesn't work even if there are no reference in my C# code to the object, I assume, because of the struct object reference is stored in the list in the dll that I don't control. When TH_FreeMemory on the struct object is called, it removes it from the list and release the memory with delete, but I can't generate the C# IntPtr to pass it to the TH_FreeMemory for that... How can I do that - release the memory with just C# tools, ignoring the list dll or generate the IntPtr for this struct? The implementation details: This is how I create and initialize it: BIM_Template template = default; var template = TH_ExtractBimTemplate(ref template) Where TH_ExtractBimTemplate(...) is the method that is pulled from the C++ dll in this way: [DllImport("TemplateHelper.dll")] private static extern int TH_ExtractBimTemplate( ref BIM_Template out_template); The TemplateHelper.dll provides me a C++ method to release the memory - TH_FreeMemory: int WINAPI TH_FreeMemory( void *memblock, BIM_MemBlockType memblock_type ) This is how I plug it into C# [DllImport("TemplateHelper.dll")] private static extern int TH_FreeMemory( IntPtr memblock, BIM_MemBlockType memblock_type ); Current solutions I tried: I need IntPtr of the created unsafe struct (the template variable) but I don't know how to get it, to free allocated memory with TH_FreeMemory dll method I have tried to create a bunch of these unsafe struct type templates in the method that create them and return void, leaving no references to the created templates, but the garbage collector doesn't free memory. I assume that is, because of the object type is unsafe struct. At least, I've waited for 40 minutes and memory wasn't released. I have tried the approach below to release the memory with Marshal.FreeHGlobal(IntPtr ptr) but that doesn't reduce the amount of unmanaged memory used by the app as well here is the code: [Fact] public void TestDisposalIsCalledOnOutOfContext() { // Create templates var templates = LoadTemplates(m, Output); // Release the allocated memory using Marshal templates.ForEach( t => MarshaFreeMemory(ref t)); // Wait Thread.Sleep(new TimeSpan(hours: 1, 0, 0)); } private static IntPtr MarshaFreeMemory(ref BIM_Template? template) { IntPtr ptr; ptr = Marshal.AllocHGlobal(Marshal.SizeOf<BIM_Template>()); Marshal.StructureToPtr(template, ptr, true); Marshal.FreeHGlobal(ptr); return ptr; } private static List<BIM_Template?> LoadTemplates() { var templates = new List<BIM_Template?>(); for (int j = 0; j < 1000; j++) templates.Add(LoadTemplate()); return templates; } public static BIM_Template LoadTemplate() { BIM_Template template = default; var template = TH_ExtractBimTemplate(ref template); return template; } So, the question is how can I prevent these memory leaks and free memory from the created templates using some standard C# toolset or how get I get the IntPtr of the template object to use the library?
You don’t need to call TH_FreeMemory. Your structure doesn’t have any pointers inside. In C++, the Mint field should be std::array<uint32_t, MAX_MINUTIAE_SIZE> or an equivalent. Your template local variable is on the stack, it does not use any heap memory, and the stack memory will be freed automatically just before the LoadTemplate() method returns. if you wanna free the memory used by the list in TestDisposalIsCalledOnOutOfContext, do this: templates = null; // Collect all generations of memory GC.Collect();
72,415,239
72,415,591
How do I store the compile-time dynamically allocated memory so that it can be used in run-time?
Say, I have a constexpr variable that contains all primes less than 216. constexpr auto primes = [] { constexpr int N = 1 << 16; std::array<int, 6542> ret; bool not_prime[N] = {}; int prime_cnt = 0; for (int i = 2; i < N; i++) { if (!not_prime[i]) { ret[prime_cnt++] = i; for (int j = 2 * i; j < N; j += i) not_prime[j] = true; } } return ret; }(); Here I manually specified the ret's array size. When I want to change N, I have to re-run this loop to see what the final prime_cnt value is and manually specify it. Particularly, if I increase N, I have to first give an upper-bound guess to avoid segfault. In C++20, we can dynamically allocate memory in compile-time, and thus we have constexpr vector now. So we no longer need to worry about the upper-bound problem. But such a value cannot be used in run-time, which means, this code is invalid. constexpr auto primes = [] { constexpr int N = 1 << 16; std::vector<int> ret; bool not_prime[N] = {}; for (int i = 2; i < N; i++) { if (!not_prime[i]) { ret.push_back(i); for (int j = 2 * i; j < N; j += i) not_prime[j] = true; } } return ret; // invalid here }(); So here comes the problem, how do I store such a vector? An obvious solution is to split this process into two phases. The first one calculates the array size and the second one does the normal calculation. But this needs extra code and computing resources. Is there an elegant and automatic way to achieve this goal?
Create a lambda that makes a vector, and use another lambda to create an array #include <array> #include <vector> #include <algorithm> constexpr auto primes_num_vector = [] { constexpr int N = 1 << 16; std::vector<int> ret; bool not_prime[N] = {}; for (int i = 2; i < N; i++) { if (!not_prime[i]) { ret.push_back(i); for (int j = 2 * i; j < N; j += i) not_prime[j] = true; } } return ret; }; constexpr auto primes = [] { std::array<int, primes_num_vector().size()> ret; std::ranges::copy(primes_num_vector(), ret.begin()); return ret; }();
72,415,546
72,415,682
How to fix: double free or corruption (out) Aborted (core dumped) in C++
I've recently been working on a C++ project of mine, and I ran into a problem with the executable: std::string commanddata; std::string input; std::string cmdname; int commandlength = 0; if (commandlength == 0){}else{} // This is so that G++ doesn't complain that I have got a variable and never used it (I'm compiling at -Werror) while (true) { input = DS_IO.kscanf(">>>"); // This is a specific function to get input from the user // Record the command length int commandlength = sizeof(input); // Make sure that the user doesn't just send us nothing if (commandlength <= 0) { continue; } else { // Get the first word from the command std::stringstream sstream(input); sstream >> cmdname; // Loops through the input string to remove everything up to and including a space delimiter for (int i = 0; i <= commandlength; i++) { if (input[i] == 32) { commanddata = input; commanddata.erase(input.begin(), input.begin() + i); break; } else { continue; } } // print out the data to make sure it's all working std::cout << "What you entered: " << input << std::endl; std::cout << "The command name: " << cmdname << std::endl; std::cout << "The command metadata: " << commanddata << std::endl; } } The code works fine, but my problem is as soon as it reaches the end of the loop, it freaks out and gives this error: EXPECTED BEHAVIOUR: chemeriov@mikumputer:~/dev/DigitalSledgehammer$ ./a.out >>>echo Hello world What you entered: Hello world The command name: echo The command metadata: Hello world >>> EXPERIENCED BEHAVIOUR: chemeriov@mikumputer:~/dev/DigitalSledgehammer$ ./a.out >>>echo Hello world What you entered: Hello world The command name: echo The command metadata: Hello world double free or corruption (out) Aborted (core dumped) chemeriov@mikumputer:~/dev/DigitalSledgehammer$ How to fix this?
Thanks very much to @Soonts, who fixed my problem! Another issue, commanddata.erase( input.begin() is obviously wrong, a container can’t erase ranges inside other unrelated containers. A correct usage is something.erase(something.begin(), .. You can clearly tell I'm a noob at this :)
72,415,733
72,416,045
How to know if sub directory exist in c++?
I want to stack directory until directory hits max-depth. Therefore, I tried to use fs::filesystem. At first, I approach by depth() like for (auto itr = fs::recursive_directory_iterator(fs::current_path()/path); itr != fs::recursive_directory_iterator(); itr++) { (itr.depth() == ???) } But Since I don't know max-depth. I failed. how can I know if directory has sub-directory or not?
Try this snippet to find max-depth in the current directory: int max_depth = 0; // use as first pass for(auto itr = filesystem::recursive_directory_iterator(filesystem::current_path()); itr != filesystem::recursive_directory_iterator(); itr++) { if (is_directory(itr->path())) { if (itr.depth() > max_depth) max_depth = itr.depth(); } }
72,415,909
72,416,302
issue while writing and reading array of objects C++
facing an issue while writing and reading array of objects, when I put and write data of array object [0] and object 1, it puts object [0] data in object 1 as well, I think their many other issues with code, if anyone can guide me, I would be really grateful. #include<iostream> #include<fstream> using namespace std; class A { private: int num; public: void putdata(){ cout<<"Enter Num: "; cin>>num; this->num=num; } void getdata(){ cout<<"The num is : " << num; } void ReadFunc(A[],int i); void WriteFunc(A[], int i); }; // void A :: ReadFunc(A ob1[],int i){ ifstream R; R.open("File9.txt", ios::in | ios :: binary); cout<<"\nReading the object from a file : \n"; R.read( (char *) & ob1[i], sizeof(ob1[i])); ob1[i].getdata(); R.close(); } void A :: WriteFunc(A ob1[],int i){ ofstream W; W.open("File9.txt", ios::out | ios::app ); ob1[i].putdata(); W.write( (char *) & ob1[i], sizeof(ob1[i])); W.close(); cout<<"Congrats! Your object is successfully written to the file \n"; } int main() { A ob1[100]; ob1[0].WriteFunc(ob1,0); ob1[1].WriteFunc(ob1,1); cout<<"\n"; ob1[0].ReadFunc(ob1,0); ob1[1].ReadFunc(ob1,1); return 0; } Output
Rough implementation of index plus object. #include<iostream> #include<fstream> using namespace std; class A { private: int num; public: void putdata(){ cout<<"Enter Num: "; cin>>num; this->num=num; } void getdata(){ cout<<"The num is : " << num; } void ReadFunc(A[],int i); void WriteFunc(A[], int i); }; struct A_withIndex { size_t index; A data; }; void A :: ReadFunc(A ob1[],size_t i){ ifstream R; R.open("File9.txt", ios::in | ios :: binary); A_withIndex buffer; bool found=false; while(R){ R.read( (char *) &buffer, sizeof(buffer)); if(R.gcount()!=sizeof(buffer)) break; if(buffer.index==i){ found =true; obj[i]=buffer.data; } } if(found){ cout<<"\nReading the object from a file : \n"; ob1[i].getdata(); } else{ cout<<"\nObject not found \n"; } R.close(); } void A :: WriteFunc(A ob1[],size_t i){ ofstream W; W.open("File9.txt", ios::out | ios::app ); ob1[i].putdata(); A_withIndex buffer = {i,ob1[i]}; W.write( (char *) &buffer, sizeof(buffer)); W.close(); cout<<"Congrats! Your object is successfully written to the file \n"; } Hopefully I kept enough of your code intact to make this legible. Also, I did not run this code through a compiler so it may contain a few errors such as case sensitivity. Method is pretty simple: include an index with your data when reading or writing. This implementation is by no means efficient since it always appends even when it could have overwritten and reads the whole file to find the last at index. The size_t is also a large overhead. Depending on index range, you may want to reduce to unsigned char and #pragma pack, but if it is that small, you would be better off writing the whole array. I leave making those improvements to you once you understand the concept.
72,415,949
72,415,984
Variable resetting problem in a list of objects
Today I was writing some SDL C++ program, with squares called particles. My problem is that, for some reason, variable y in instances of class Particle is always resetting to the value passed into the constructor after incrementing it by 1. I'm storing objects in a list. That's a method called every frame: void everyFrame(){ this->y+=1; std::cout<<"update y: "<<this->y<<std::endl; } And this method is also called every frame, after the everyFrame() method: void blit(){ this->rect.x=this->x*10; this->rect.y=this->y*10; std::cout<<"blitting y: "<<this->y<<std::endl; SDL_BlitSurface(this->image,NULL,screen,&this->rect); } This is part of the code, where I'm adding an object/objects to the list: std::list<Particle> particles; particles.push_back(Particle(2,10,5)); And there I'm executing these 2 methods in the main loop: for(Particle x:particles){ x.everyFrame(); } for(Particle x:particles){ x.blit(); } The console output of the program when y 5 is passed into the constructor is just: update y: 6 blitting y: 5 looped around. I also found out that when I'm storing an object in a normal variable, not in the list, then it works. Is there any reason/fix for it not working in the list?
These lines: for(Particle x:particles){ x.everyFrame(); } are not modifying the particles list. This is because Particle x:particles is creating a copy of each element before calling x.everyFrame(). You need to change it to: for(Particle & x:particles){ // NOTE: added & x.everyFrame(); } Taking a refernce to the list element will modify the element in the list. The same applied to the second loop applying blit(). A side note: Using the auto keywoard is usually recomended in this case. You need to keep in mind that auto does not include CV qualifiers, and pointerness/referenceness. Therefore you need: for(auto & x:particles){ ... } And if you are traversing a container without modifying the elements, it is rcomended to use: for(auto const & x:particles){ ... }
72,415,982
72,418,210
dynamically allocated struct array for open hash table
I am trying to implement a simple open hash in c++ for the sake of learning. I am getting very confused about the interaction of functions with array pointers, and I am at the end of my wits. The code: struct node{ int data; node* next; node* prev; bool state; node(){ prev = next = NULL; state = true; } }; //state true means empty, state false means full. void insert(node *array,int value){ node *current = array; if(array->state == true){ array->data = value; array->state = false; } else { node* add = new node(); add->data = value; add->state = false; while(current->next != NULL){ current = current->next; } current->next = add; add->prev = current; } } void display(node *array, int size){ node *show = new node(); for(int i = 0; i< size; i++){ if(array->state == false){ cout<<array->data; show = array; while(show->next != NULL){ show = show->next; cout<<" --> "<<show->data; } } else { cout<<"Empty."; } cout<<"\n\n"; } } int main(){ int size; cout<<"Enter size of the hash table: "; cin>>size; node *array = new node[size]; int value; cout<<"Enter Value: "; cin>>value; int index = value%size; //inserting single value insert(&array[index],value); //Hash table output. display(array,size); return 0; } When I run this code, instead of showing "empty" in places where the array's state is empty, it seems as if the entire array has the same value. The problem lies in the insert function, but I cannot figure it out.
You can simplify this by making the Hashtable an array of pointers to Node. A nullptr then means the slot is empty and you don't have empty and full nodes. Also Nodes only need a next pointer and usually new entries are added to the beginning of the buckets instead of the end (allows duplicate entries to "replace" older ones). Inserting at the beginning of a list becomes real easy with Node **. #include <cstddef> #include <iostream> struct Table { struct Node { Node * next; int data; Node(Node **prev, int data_) : next{*prev}, data{data_} { *prev = this; } }; std::size_t size; Node **tbl; Table(std::size_t size_) : size{size_}, tbl{new Node*[size]} { } ~Table() { for (std::size_t i = 0; i < size; ++i) { Node *p = tbl[i]; while(p) { Node *t = p->next; delete p; p = t; } } delete[] tbl; } void insert(int value) { Node **slot = &tbl[value % size]; new Node(slot, value); } void display() const { for(std::size_t i = 0; i < size; i++) { std::cout << "Slot " << i << ":"; for (const Node *node = tbl[i]; node; node = node->next) { std::cout << " " << node->data; } std::cout << std::endl; } } }; int main(){ std::size_t size; std::cout << "Enter size of the hash table: "; std::cin >> size; Table table{size}; int value; std::cout << "Enter Value: "; std::cin >> value; //inserting single value table.insert(value); //Hash table output. table.display(); return 0; }
72,415,993
72,418,674
The definition of lock-free
There are three different types of "lock-free" algorithms. The definitions given in Concurrency in Action are: Obstruction-Free: If all other threads are paused, then any given thread will complete its operation in a bounded number of steps. Lock-Free: If multiple threads are operating on a data structure, then after a bounded number of steps one of them will complete its operation. Wait-Free: Every thread operating on a data structure will complete its operation in a bounded number of steps, even if other threads are also operating on the data structure. Herb Sutter says in his talk Lock-Free Programming: Informally, "lock-free" ≈ "doesn't use mutexes" == any of these. I do not see why lock-based algorithms can't fall into the lock-free definition given above. Here is a simple lock-based program: #include <iostream> #include <mutex> #include <thread> std::mutex x_mut; void print(int& x) { std::lock_guard<std::mutex> lk(x_mut); std::cout << x; } void add(int& x, int y) { std::lock_guard<std::mutex> lk(x_mut); x += y; } int main() { int i = 3; std::thread thread1{print, std::ref(i)}; std::thread thread2(add, std::ref(i), 4); thread1.join(); thread2.join(); } If both of these threads are operating, then after a bounded number of steps, one of them must complete. Why does my program not satisfy the definition of "Lock-free"?
Your quote from Concurrency in Action is taken out of context. In fact, what the book actually says is: 7.1 Definitions and consequences Algorithms and data structures that use mutexes, condition variables, and futures to synchronize the data are called blocking data structures and algorithms. Data structures and algorithms that don’t use blocking library functions are said to be nonblocking. Not all these data structures are lock-free ... Then it proceeds to further break down nonblocking algorithms into Obstruction-Free, Lock-Free and Wait-Free. So a Lock-Free algorithm is a nonblocking algorithm (it does not use locks like a mutex) and it is able to make progress in at least one thread in a bounded number of steps. So both Herb Sutter and Anthony Williams are correct.
72,416,188
72,416,388
Finding heaviest path (biggest sum of weights) of an undirected weighted graph? Bellman Ford --
There's a matrix, each of its cell contains an integer value (both positive and negative). You're given an initial position in the matrix, now you have to find a path that the sum of all the cells you've crossed is the biggest. You can go up, down, right, left and only cross a cell once. My solution is using Bellman Ford algorithm: Let's replace all the values by their opposite number, now we've just got a new matrix. Then, I create an undirected graph from the new matrix, each cell is a node, stepping on a cell costs that cell's value - it's the weight. So, I just need to find the shortest path of the graph using Bellman-Ford algorithm. That path will be the longest path of our initial matrix. Well, there's a problem. The graph contains negative cycles, also has too many nodes and edges. The result, therefore, isn't correct. This is my code: Knowing that xd and yd is the initial coordinate of the robot. void MatrixToEdgelist() { int k = 0; for (int i=1;i<=n;i++) for (int j=1;j<=n;j++) { int x = (i - 1) * n + j; int y = x + 1; int z = x + n; if (j<n) { edges.push_back(make_tuple(x, y, a[i][j+1])); } if (i<n) { edges.push_back(make_tuple(x, z, a[i+1][j])); } } } void BellmanFord(Robot r){ int x = r.getXd(); int y = r.getYd(); int z = (x-1)*n + y; int l = n*n; int distance[100]; int previous[100]{}; int trace[100]; trace[1] = z; for (int i = 1; i <= l; i++) { distance[i] = INF; } distance[z] = a[x][y]; for (int i = 1; i <= l-1; i++) { for (auto e : edges) { int a, b, w; tie(a, b, w) = e; //distance[b] = min(distance[b], distance[a]+w); if (distance[b] < distance[a] + w)// && previous[a] != b) { distance[b] = distance[a] + w; previous[b] = a; } } } //print result int Max=INF; int node; for (int i=2;i<=l;i++) { if (Max < distance[i]) { Max = distance[i]; node = i; } } if (Max<0)cout << Max << "\n"; else cout << Max << "\n"; vector<int> ans; int i = node; ans.push_back(i); while (i != z) { i = previous[i]; ans.push_back(i); } for (int i=ans.size()-1;i>=0;i--) { int x, y; if (ans[i] % n == 0) { x = ans[i] / n; y = n; } else{ x = ans[i] / n + 1; y = ans[i] - (( x - 1 ) * n); } cout << x << " " << y << "\n"; } } Example matrix The result Clearly that the distance should have continued to update, but it doesn't. It stops at the final node.
"Let's replace all the values by their opposite number" Not sure what you mean by an opposite number. Anyway, that is incorrect. If you have negative weights, then the usual solution is to add the absolute value of the most negative weight to EVERY weight. Why Bellman-Ford? Dijkstra should be sufficient for this problem. ( By default Dijkstra finds the cheapest path. You find the most expensive by assigning the absolute value of ( the original weight minus the greatest ) to every link. )
72,416,354
72,416,476
Make difference between copy and direct initialization
Create an “UnusualClass” class in which direct and copy initialization produce different effects throughout. In particular, the attempt of direct or copy initialization should produce on the screen the print "Direct initialization" or "Copy initialization" #include <iostream> class UnusualClass{ public: UnusualClass(const int &n){ std::cout<<"Copy initialization"; } UnusualClass &operator=(const int &n){ std::cout<<"Direct initialization"; } }; int main () { UnusualClass k1(5); // Should print "Direct initialization" UnusualClass k2 = 5; // Should print "Copy initialization" return 0; } Why do I get copy initialization for both cases? How to make UnusualClass k1(5); prints "Direct initialization" and UnusualClass k2 = 5; prints "Copy Initialization"?
I believe it's impossible in general, but if you only want to support the two ways of initialization you listed, there are hacky solutions. You need two constructors, one explicit and the other non-explicit. As you were already told in comments, operator= won't help you, since both lines perform initialization and not assignment. However, if the there are no other differences between the two constructors, the code won't compile. You need to make the explicit constructor "better" than its non-explicit counterpart, so that it will be preferred if possible (i.e. for direct-initialization), so the other is used as a fallback. Figuring out how exactly to make one constructor "better" than the other is left as an exercise to the reader. There are at least three approaches: Using lvalue references vs rvalue references. Using .... Using a helper class with a constructor with an int parameter.
72,416,401
72,416,995
Printing A Circular Linked List
I am doing an Assignment which is about Creating and Printing a Circular Linked List. Here is my Code: #include <iostream> #include <conio.h> using namespace std; class node { public: int data; node *next; node() : data(0), next(NULL) {} }; class list { private: node *first; node *last; public: list() : first(NULL), last(NULL) {} void add_last(int n) { if (first == NULL) { first = new node; first->data = n; first->next = NULL; last = first; } else { node *ptr = new node; last->next = ptr; last = ptr; last->data = n; // cout<<last->data; } } void add_first(int n) { if (first == NULL) { first = new node; first->data = n; first->next = NULL; last = first; } else { node *ptr = new node; ptr->data = n; ptr->next = first; first = ptr; last->next = ptr; // cout << last->data; } } void show() { if (first == NULL) { cout << "List is Empty."; return; } else { node *ptr = first; while (ptr != last) { cout << ptr->data << " "; ptr = ptr->next; } cout << ptr->data << " "; } } }; int main() { list l; l.add_last(1); l.add_last(2); l.add_last(3); l.add_last(4); l.add_last(5); cout << "Contents of the List:\n"; l.show(); l.add_last(11); l.add_last(12); l.add_last(13); l.add_last(14); l.add_last(15); cout << "\nContents of the List:\n"; l.show(); return 0; } After Adding 1 2 3 4 5 at last Nodes in list When I print the list then Output is 1 2 3 4 5 After That When I add 11 12 13 14 15 into code Then The output came is 1 2 3 4 5 11 12 13 14 15 But I do not want Previous value. How can I clear Previous List to store New values? Question May be seems stupid To seniors But I am a beginner. So please Humbly Help me. I will be thankful.
You can call a deletelist method before displaying next added elements as follows: void deleteList() { node* current = first; node* next = NULL; while (current != NULL) { next = current->next; delete(current); current = next; } first = NULL; }
72,416,421
72,416,488
Having trouble making a map with different types
I want to make a map that has string keys that have string values and with the second data type being string keys with a list value. I tried following the solutions mentioned under this thread: Store multiple types as values in C++ dictionary? but I keep on getting these errors. Any help is appreciated, I've been at this for quite some time. 'variant' is not a member of 'std' even though I have it included on top template argument 1 is invalid on the string syntax no operator "=" matches these operands on the equal signs #include <iostream> #include <map> #include <string> #include <list> #include <variant> typedef std::map<std::variant<std::string, std::list<std::string>>, std::variant<std::string, std::string>> Dict; int main(){ std::list<std::string> List1 {"Teamwork", "Hate"}; Dict d; d["TIME"] = "8:15"; d["TAGS"] = List1; return 0; }
std::map<std::variant<std::string, std::list<std::string>>, std::variant<std::string, std::string>> Is a map with (string or list keys) and (string or string) of values. Having variant with duplicate types is allowed but unnecessary and it will complicate things. You want std::map<std::string,std::variant<std::string, std::list<std::string>>> i.e. map with string keys and (string or list) values. This compiles: #include <iostream> #include <map> #include <string> #include <list> #include <variant> // Prefer using in C++ to typedef. using Dict = std::map<std::string,std::variant<std::string, std::list<std::string>>>; int main(){ std::list<std::string> List1 {"Teamwork", "Hate"}; Dict d; d["TIME"] = "8:15"; d["TAGS"] = List1; return 0; } Variants are c++17, make sure you have it set if you are getting include errors.
72,417,046
72,419,193
C++ error: intrinsic function was not declared in scope
I want to compile code that uses the intrinsic function _mm256_undefined_si256() (returns a vector of 8 packed double word integers). Here is the reduced snipped of the affected function from the header file: // test.hpp #include "immintrin.h" namespace { inline __m256i foo(__m256i a, __m256i b) { __m256i res = _mm256_undefined_si256(); // some inline asm stuff // __asm__(...); return res; } } Compiling via gcc -march=native -mavx2 -O3 -std=c++11 test.cpp -o app throws the following error >>_mm256_undefined_si256<< was not declared in this scope. I can not explain why this intrinsic function is not defined, since there are other intrinsics used in the header file which work properly.
Your code works in GCC4.9 and newer (https://godbolt.org/z/bajMsKvK9). GCC4.9 was released in April 2014, close to a decade ago, and the most recent release of GCC4.8.5 was in June 2015. So it's about time to upgrade your compiler! GCC4.8 was missing that intrinsic, and didn't even know about -march=sandybridge (let alone tuning options for Haswell which had AVX2), although it did know about the less meaningful -march=corei7-avx. It does happen that GCC misses some of the more obscure intrinsics that Intel adds along with support for a new instruction set, so support for _mm256_add_epi32 won't always imply _mm256_undefined_si256(). e.g. it took until GCC11 for them to add _mm_load_si32(void*) unaligned aliasing-safe movd (which I think Intel introduced around the same time as AVX-512 stuff), so that's multiple years late. (And until GCC12 / 11.3 for GCC to implement it correctly, Bug 99754, and still not aliasing-safe for _mm_load_ss(float*) (Bug 84508). But fortunately for the _mm256_undefined_si256, it's supported by non-ancient versions of all the mainstream compilers.
72,417,186
72,418,527
How can I know if directory have children directories in c++?
I want to check if directory have a child directory. I thought I can find by ++operator But it didn't work. for (auto itr = fs::recursive_directory_iterator(fs::current_path() / path); itr != fs::recursive_directory_iterator(); itr++) { if (!(* itr++).exists()) cout <<*itr << endl; } any tips?
A (recursive_)directory_iterator gives you access to a list of child items, both files and directories. It is up to you to differentiate between files and directories, eg: bool has_child_directory(const fs::path &dir) { for (auto itr = fs::directory_iterator(dir); itr != fs::directory_iterator(); ++itr) { if (itr->is_directory()) { string s = itr->path().string(); if ((s != ".") && (s != "..")) return true; } } return false; }
72,417,198
72,417,258
Get number of active class instances
I need to get a number of created and the number of active class instances. #include <iostream> #include <stdexcept> class Set { double value; int created = 0; int active = 0; public: Set(); Set(double num); static int NumberOfCreated(); static int NumberOfActive(); }; Set::Set() : value(0) {} Set::Set(double num) : value(num) { created++; active++; } int Set::NumberOfCreated() { return created; } int Set::NumberOfActive() { return active; } int main() { Set s1, s2(100); { Set s3(50); } // After "}", "s3" doesn't exist anymore std::cout << Set::NumberOfCreated(); // Should print 3 std::cout << Set::NumberOfActive(); // Should print 2 return 0; } I get two errors: invalid use of member ‘Set::created’ in static member function invalid use of member ‘Set::active’ in static member function Also, this logic would always give the same output for active and created class instances. Could you give me a better approach to how to find number of active elements? Note: main function cannot be changed! Only class should be changed to enable this functionality.
you have multiple problems, here is how it can be done, check comments: #include <iostream> #include <stdexcept> class Set { double value; static int created; // you need single variable for all instances, this is why static static int active; public: Set(); Set(double num); ~Set() { --active; // destructor is called when object is destroyed, so number of active instances is decreased } static int NumberOfCreated(); static int NumberOfActive(); }; int Set::created = 0; int Set::active = 0; Set::Set() : Set(0) {} // this constructor should increase created/active counters as well, this can be achieved via calling another ctor Set::Set(double num) : value(num) { created++; active++; } int Set::NumberOfCreated() { return created; } int Set::NumberOfActive() { return active; } int main() { Set s1, s2(100); { Set s3(50); } std::cout << Set::NumberOfCreated() << std::endl; std::cout << Set::NumberOfActive() << std::endl; return 0; } and of course follow @user17732522 comments about copy/move and thread safety
72,417,491
72,459,851
My c++ program crashes instantly when using SFML/Audio.hpp (Building works)
I am using the following c++ compiler MinGW-W64-builds-4.3.4 on Windows 10 with the following SFML library SFML-2.5.1-windows-gcc-7.3.0-mingw-32-bit and CLion 2021.2 Build #CL-212.4746.93 My CMakeLists.txt looks like this: cmake_minimum_required(VERSION 3.20) project(SFML_Audio_Error) set(CMAKE_CXX_STANDARD 14) add_executable(SFML_Audio_Error main.cpp) set(SFML_STATIC_LIBRARIES TRUE) set(SFML_DIR C:/SFML/lib/cmake/SFML) find_package(SFML COMPONENTS system window graphics audio network REQUIRED) include_directories(c:/SFML/include) target_link_libraries(SFML_Audio_Error sfml-system sfml-window sfml-graphics sfml-audio) And I use the following Code: #include <iostream> #include <SFML/Audio.hpp> int main() { sf::Music test; std::cout << "Hello, World!" << std::endl; return 0; } When taking away the line sf::Music test; the code works normally, when using the line I get the following Clion error Process finished with exit code -1073741515 (0xC0000135) This is my first stackoverflow post because I really need some advice I couldnt find anything online either, except importing .dll files but there were no clear instructions on how to do that. Im not even sure if thats my problem. If someone can help me out im really grateful, I just wanted to add some funny sound effects to my programs. I hope i provided everything you need to know :). *Edit: I added 2 .dll files to the working Directory: Working Directory
So I solved the issue. Thanks to the help of Retired Ninja. I put the openal32.dll file into the same directory as the executable (.exe) this resolved the issue and i can play sound now. Thanks again all of you. :) Picture of the working Directory with the .dll
72,417,624
72,417,775
Sorting a map by values - keys
I'm writing a code that counts the number of occurrences of each word in a file, and print out these words in order of number of occurrences. After each word, it prints its number of occurrences. Words occurring the same number of times in the file are listed in alphabetical order. I don't know how to modify that code to get the words in order of number of occurrences, and that words occurring the same number of times in the file are listed in alphabetical order. Limitations: I can use only headers like <iostream>, <map>, <string>, <fstream> and <utility> Example of how it should work: In: one two three one two four two one two Out: four 1 three 1 one 3 two 4 By now, I've done something like that: #include <iostream> #include <fstream> #include <map> #include <string> typedef std::map<std::string, int> StringIntMap; void count_words(std::istream &in, StringIntMap &words) { std::string text; while (in >> text) { ++words[text]; } } int main(int argc, char **argv) { std::ifstream in("readme.txt"); StringIntMap words_map; count_words(in, words_map); for (StringIntMap::iterator it = words_map.begin(); it != words_map.end(); ++it) { std::cout << it->first << " " << it->second << std::endl; } }
A solution using std::map to perform the sorting. Readability may be further improved by replacing std::pair<string, int> with a struct with a meaningful name. #include <fstream> #include <iostream> #include <map> #include <string> #include <utility> using std::cout; using std::ifstream; using std::map; using std::pair; using std::string; struct Dummy {}; struct Compare { bool operator()(const pair<string, int> &p1, const pair<string, int> &p2) const { if (p1.second < p2.second) { return true; } else if (p1.second > p2.second) { return false; } else { return p1.first < p2.first; } } }; int main(int argc, char **argv) { ifstream in("readme.txt"); map<string, int> occurences; string word; while (in >> word) { occurences[word]++; } map<pair<string, int>, Dummy, Compare> sorted; for (const auto &p : occurences) { sorted.insert({p, Dummy{}}); } for (const auto &p : sorted) { cout << p.first.first << ": " << p.first.second << "\n"; } }
72,417,631
72,418,141
Infix to Postfix Converter in C++ gives no output
I made a function infixToPostfix() which converts an infix expression to a postfix expression. But my program generates no output on running. Please point out the errors in my program. Code: #include <iostream> #include <cstring> #include <stack> #include <cstdlib> using namespace std; int isOperator(char x) { return (x == '-' || x == '+' || x == '/' || x == '*'); } int precedenceOfOperators(char x) { if (x == '+' || x == '-') { return 1; } else if (x == '/' || x == '*') { return 2; } return 0; } char *infixToPostfix(char infix[]) { int i = 0, j = 0; stack<char> lobby; char *postfix = (char *)malloc((strlen(infix + 1)) * sizeof(char)); while (infix[i] != '\0') { if (!isOperator(infix[i])) { postfix[j] = infix[i]; i++; j++; } else { if (!lobby.empty()) { if (precedenceOfOperators(infix[i]) > precedenceOfOperators(lobby.top())) { lobby.push(infix[i]); } else { postfix[j] = lobby.top(); lobby.pop(); j++; } } else if (lobby.empty()) { lobby.push(infix[i]); } } } while (!lobby.empty()) { postfix[j] = lobby.top(); lobby.pop(); j++; } return postfix; } Implementation: int main() { char infix[] = {'a', '-', 'b', '+', 'c', '*', 'd'}; char *postfix = infixToPostfix(infix); for (int j = 0; postfix[j] != '\0'; j++) { cout << postfix[j]; } return 0; } Logic: I created a character pointer variable that will hold our postfix expression. Now, we iterate over our infix expression. If we receive an operand, we concatenate it to the postfix variable. Else if we encounter an operator, we proceed with the following steps: Keep in account the operator and its relative precedence ('/' and '*' have more precedence than '+' and '-'). If either the stack is empty or its topmost operator has lower relative precedence, push this operator-precedence pair inside the stack 'lobby'. Else, keep popping operators from the stack 'lobby' and concatenate them to the postfix expression until the topmost operator becomes weaker in precedence relative to the current operator. If you reach the EOE, pop every element from the stack 'lobby', if there is any, and concatenate them as well to the postfix expression.
Your code is exceeding the time limit because it is stuck in the infinite loop. You have not updated the i variable- which is the index of the infix array in the else part of the loop i.e when infix[i] is an operator. i.e. in this part of the code else { if (!lobby.empty()) { if (precedenceOfOperators(infix[i]) > precedenceOfOperators(lobby.top())) { lobby.push(infix[i]); } else { postfix[j] = lobby.top(); lobby.pop(); j++; } } else if (lobby.empty()) { lobby.push(infix[i]); } } Here is the updated code which is giving perfect output. ( I have made some minor changes as per my convenience, you can keep the code the same and add the i++ in the else part) #include <iostream> #include <cstring> #include <stack> #include <cstdlib> using namespace std; int isOperator(char x) { return (x == '-' || x == '+' || x == '/' || x == '*'); } int precedenceOfOperators(char x) { if (x == '+' || x == '-') { return 1; } else if (x == '/' || x == '*') { return 2; } return 0; } string infixToPostfix(char infix[]) { int i = 0, j = 0; if(sizeof(infix)==0) { return ""; } int n=sizeof(infix)/sizeof(infix[0]); stack<char> lobby; string postfix = ""; while (i < n) { if (!isOperator(infix[i])) { postfix=postfix+infix[i]; i++; j++; } else { if (!lobby.empty()) { if (precedenceOfOperators(infix[i]) > precedenceOfOperators(lobby.top())) { lobby.push(infix[i]); } else { postfix = postfix+lobby.top(); lobby.pop(); j++; } } else if (lobby.empty()) { lobby.push(infix[i]); } i++; } } while (lobby.empty()==false) { postfix = postfix+lobby.top(); lobby.pop(); j++; } return postfix; } int main() { char infix[] = {'a', '-', 'b', '+', 'c', '*', 'd'}; string postfix = infixToPostfix(infix); for (int j = 0; j < postfix.size() ; j++) { cout << postfix[j]; } return 0; }
72,417,657
72,417,764
Freetype Exception thrown: read access violation. face was nullptr
''' FT_Face face = nullptr;; FT_GlyphSlot g = face->glyph; FT_Library ft; if (FT_Init_FreeType(&ft)) std::cout << "ERROR::FREETYPE: Could not init FreeType Library" << std::endl; if (FT_New_Face(ft, "fonts/arial.ttf", 0, &face)) std::cout << "ERROR::FREETYPE: Failed to load font" << std::endl; FT_Set_Pixel_Sizes(face, 0, 48); if (FT_Load_Char(face, 'X', FT_LOAD_RENDER)) std::cout << "ERROR::FREETYTPE: Failed to load Glyph" << std::en ''' When I compile the program, I get this error. "Unhandled exception thrown: read access violation.face was nullptr."
The problem(mentioned error) is that somewhere in your program you're dereferencing face when it is nullptr which leads to undefined behavior. To solve this add a check to see if face is nullptr or not before dereferencing it as shown below: //go inside the if block only if face is not nullptr if(face !=nullptr) { //you can safely dereference face here } //otherwise print a message to the console else { //at this point face is nullptr so don't dereference it at this point std::cout<<"cannot dereference face "<<std::endl; } Additionally make sure(if not already) that face is initialized i.e., it points to an object of appropriate type.
72,417,985
72,418,043
Segment fault upon calling method of class
I was able to safely call builder, but builder2 exits with a segment fault. The compiler does not output any warnings. I would like to know the cause of the segment fault. This code is a builder pattern to compose html. ul and li are collected with emplace_back and finally str() is called to build the parts and return them as string. #include <memory> #include <sstream> #include <string> #include <vector> using namespace std; struct HtmlBuilder; struct HtmlElement { string name; string text; vector<HtmlElement> elements; const size_t indent_size = 2; HtmlElement() {} HtmlElement(const string& name, const string& text) : name(name), text(text) {} string str(int indent = 0) const { ostringstream oss; string i(indent_size * indent, ' '); oss << i << "<" << name << ">" << endl; if (text.size() > 0) oss << string(indent_size * (indent + 1), ' ') << text << endl; for (const auto& e : elements) oss << e.str(indent + 1); oss << i << "</" << name << ">" << endl; return oss.str(); } static unique_ptr<HtmlBuilder> build(string root_name) { return make_unique<HtmlBuilder>(root_name); } }; struct HtmlBuilder { HtmlBuilder(string root_name) { root.name = root_name; } // void to start with HtmlBuilder& add_child(string child_name, string child_text) { HtmlElement e{child_name, child_text}; root.elements.emplace_back(e); return *this; } // pointer based HtmlBuilder* add_child_2(string child_name, string child_text) { HtmlElement e{child_name, child_text}; root.elements.emplace_back(e); return this; } string str() { return root.str(); } operator HtmlElement() const { return root; } HtmlElement root; }; int main() { // easier HtmlBuilder builder{"ul"}; builder.add_child("li", "hello").add_child("li", "world"); cout << builder.str() << endl; auto* builder2 = HtmlElement::build("ul") ->add_child_2("li", "hello") ->add_child_2("li", "world"); cout << (*builder2).str() << endl; return 0; } The output results are as follows hello world Segmentation fault (core dumped)
You dynamically create a std::unique_ptr object holding the builder with HtmlElement::build("ul"). This std::unique_ptr object gets destroyed at the end of the full expression which means the object builder2 points to is destroyed and dereferencing it is undefined behaviour resulting in the crash you observed. I recommend not returning a dynamically allocated builder object at all. Instead move the definition of the HtmlElement::build below the definition of HtmlBuilder. You may also want to consider allowing for move semantics to avoid creating unnecessary copies of the objects: struct HtmlElement { ... static HtmlBuilder build(string root_name); }; struct HtmlBuilder { HtmlBuilder(string root_name) { root.name = std::move(root_name); } // void to start with HtmlBuilder& add_child(string child_name, string child_text) & { HtmlElement e{ child_name, child_text }; root.elements.emplace_back(e); return *this; } HtmlBuilder&& add_child(string child_name, string child_text) && { HtmlElement e{ child_name, child_text }; root.elements.emplace_back(e); return std::move(*this); } string str() { return root.str(); } operator HtmlElement() && { return std::move(root); } HtmlElement root; }; inline HtmlBuilder HtmlElement::build(string root_name) { return { root_name }; } int main() { HtmlBuilder builder{ "ul" }; builder.add_child("li", "hello").add_child("li", "world"); cout << builder.str() << endl; auto builder2 = HtmlElement::build("ul") .add_child("li", "hello") .add_child("li", "world"); cout << builder2.str() << endl; HtmlElement product = std::move(builder2); // use move constructor for creating product here (works without std::move if HtmlElement::build is in the same full expression as the conversion to HtmlElement) return 0; }
72,418,001
72,418,121
if/else statement with arrays is failing
So the code is really simple, its just a main(), but there is something wrong in the if/else statement in the while cycle and I dont't know what it is, I thought this is how it supposed to work, but clearly its not. The code is creating a 11-element array, but the 0th element of the array is typed in by the user. So for example I type in 5, the array have the numbers from 5 to 15. Then the program shows you the numbers in the array. Then you can type in any numbers, and if your number is equal to any of the numbers in the array, then the program should say: "YEES!!!". The problem is, the program always says, what it should only if the input number is not equal to any number in the array... So can please someone explain me why the if/else statement is failing? I also wrote this in Code::Blocks if that changes something... The code: #include <iostream> using namespace std; int main(){ int numbers[11]; int input; cout << "Type in a number: "; cin >> input; for (int i=0; i<11; i++){ numbers[i] = input +i; } for (int i=0; i<11; i++){ cout << numbers[i] <<endl; } while (true){ cout<<endl; cout << "Type in a number:" <<endl; cin.sync(); cin >> input; if (input <= numbers[11] && input >= numbers[0]) cout << "YEES!!!" << endl; else{ cout << "Number is out of range!" <<endl; cout << "Please try again!" <<endl; } } return 0; }
Indexing starts with zero, so if you create an array with a size of N last index always will be N-1. In your case, the index of the last element is 10. if (input <= numbers[10] && input >= numbers[0]) // accurate
72,418,169
72,418,202
Creating a sub-namespace with the name of another namespace
I want to do something like this: namespace someModule { int someInt = 4; } namespace test::someModule { void f() { someModule::someInt = 2; } } But it looks like the compiler searches for someInt in test::someModule and not in someModule. I could create test as test::someModule_, but it looks pretty ugly. Isn't there a better option?
you can always refer to the global namespace using :: as prefix, i.e., ::someModule::someInt = 2; Note that the fact you're having multiple identically named namespaces is probably pretty confusing! Unless you have a very good architectural reason that you explained why proposing to add such to a project I'm maintaining, I would reject this code – code like this is easy to misunderstand. In fact, it almost seems intentionally misleading! Your job as programmer is to write code that can be read and understood not only by machines, but also by yourself in a year or other developers tomorrow. When describing two different things (namespaces), use two different names. Using the same name is only fine if something does the same thing.
72,418,578
72,421,662
Why is a 1 being printed at the end of BFS?
Here's a simple Breadth First Search on an undirected graph. The question is to find whether or not a path exists between a source and a destination node. The code works, but I don't understand why a 1 is being printed at the very end. Program: #include <iostream> #include <unordered_map> #include <vector> #include <queue> #include <algorithm> using namespace std; bool BFS(unordered_map<int, vector<int>> &umap, int source, int dest) { queue<int> q; vector<int> v; q.push(source); while (!q.empty()) { int front = q.front(); if (find(v.begin(), v.end(), front) == v.end()) {//element is not visited yet cout << static_cast<char>(front) << " -> "; if (front == dest) return true; v.push_back(front); for (auto &i: umap[front]) q.push(i); } q.pop(); } return false; } int main() { unordered_map<int, vector<int>> umap; umap['i'] = {'j', 'k'}; umap['j'] = {'i'}; umap['k'] = {'i', 'm', 'p'}; umap['m'] = {'k'}; umap['p'] = {'k'}; umap['o'] = {'n'}; umap['n'] = {'o'}; cout << endl << "------------BFS------------" << endl; cout << BFS(umap, 'j', 'm'); } Output: ------------BFS------------ j -> i -> k -> m -> 1 Process finished with exit code 0
The first comment on this question sums it up - I overlooked the fact that I am printing a bool (cout << BFS(umap, 'j', 'm');), so a 1 is expected in this case where a path is found (the value is true).
72,418,756
72,418,832
How to skip (not output) tokens in Boost Spirit?
I'm new to Boost Spirit. I haven't been able to find examples for some simple things. For example, suppose I have an even number of space-delimited integers. (That matches *(qi::int_ >> qi::int_). So far so good.) I'd like to save just the even ones to a std::vector<int>. I've tried a variety of things like *(qi::int_ >> qi::skip[qi::int_]) https://godbolt.org/z/KPToo3xh6 but that still records every int, not just even ones. #include <stdexcept> #include <fmt/format.h> #include <fmt/ranges.h> #include <boost/spirit/include/qi.hpp> namespace qi = boost::spirit::qi; // Example based off https://raw.githubusercontent.com/bingmann/2018-cpp-spirit-parsing/master/spirit1_simple.cpp: // Helper to run a parser, check for errors, and capture the results. template <typename Parser, typename Skipper, typename ... Args> void PhraseParseOrDie( const std::string& input, const Parser& p, const Skipper& s, Args&& ... args) { std::string::const_iterator begin = input.begin(), end = input.end(); boost::spirit::qi::phrase_parse(begin, end, p, s, std::forward<Args>(args) ...); if (begin != end) { fmt::print("Unparseable: \"{}\"\n", std::string(begin, end)); } } void test(std::string input) { std::vector<int> out_int_list; PhraseParseOrDie( // input string input, // parser grammar *(qi::int_ >> qi::skip[qi::int_]), // skip parser qi::space, // output list out_int_list); fmt::print("test() parse result: {}\n", out_int_list); } int main(int argc, char* argv[]) { test("12345 42 5 2"); return 0; } Prints test() parse result: [12345, 42, 5, 2]
You're looking for qi::omit[]: *(qi::int_ >> qi::omit[qi::int_]) Note you can also implicitly omit things by declaring a rule without attribute-type (which make it bind to qi::unused_type for silent compatibility). Also note that if you're making an adhoc, sloppy grammar to scan for certain "landmarks" in a larger body of text, consider spirit::repository::qi::seek which can be significantly faster and more expressive. Finally, note that Spirit X3 comes with a similar seek[] directive out of the box. Simplified Demo Much simplified: https://godbolt.org/z/EY4KdxYv9 #include <fmt/ranges.h> #include <boost/spirit/include/qi.hpp> // Helper to run a parser, check for errors, and capture the results. void test(std::string const& input) { std::vector<int> out_int_list; namespace qi = boost::spirit::qi; qi::parse(input.begin(), input.end(), // qi::expect[ // qi::skip(qi::space)[ // *(qi::int_ >> qi::omit[qi::int_]) > qi::eoi]], // out_int_list); fmt::print("test() parse result: {}\n", out_int_list); } int main() { test("12345 42 5 2"); } Prints test() parse result: [12345, 5] But Wait Seeing your comment // Parse a bracketed list of integers with spaces between symbols Did you really mean that? Because that sounds a ton more like: '[' > qi::auto_ % +qi::graph > ']' See it live: https://godbolt.org/z/eK6Thzqea //#define BOOST_SPIRIT_DEBUG #include <fmt/ranges.h> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/qi_auto.hpp> //#include <boost/fusion/adapted.hpp> // Helper to run a parser, check for errors, and capture the results. template <typename T> auto test(std::string const& input) { std::vector<T> out; using namespace boost::spirit::qi; rule<std::string::const_iterator, T()> v = auto_; BOOST_SPIRIT_DEBUG_NODE(v); phrase_parse( // input.begin(), input.end(), // '[' > -v % lexeme[+(graph - ']')] > ']', // space, out); return out; } int main() { fmt::print("ints: {}\n", test<int>("[12345 USD 5 PUT]")); fmt::print("doubles: {}\n", test<double>("[ 1.2345 42 -inf 'hello' 3.1415 ]")); } Prints ints: [12345, 5] doubles: [1.2345, -inf, 3.1415]
72,419,442
72,419,482
creating a project on mingw under windows
I am creating a project using mingw under windows. When run on another PC (without wingw in PATH, respectively), get errors, missing: libwinpthread-1.dll, libgcc_s_seh-1.dll, libstdc++-6.dll. How can I build the project so that everything starts up normally?
A C++ program needs runtime libraries to run. They're usually not part of the program itself! So you'd need to ship these libraries alongside with your program (which is what most software does). You can, for many things, however, also use "static linking", which means that the parts of the libraries used by your program are included in your program itself! The -static flag supplied to executable-generating step in your project will do that. If your program consists of but a single file, that would be g++ -o test -static test.c (your g++ might be called x86_64-w64-mingw32-g++ or so).
72,419,514
72,423,554
deferred selection of types during compile-time
Is there a standard way for me to select a type at compile-time in c++20 when the type depends on compile-time information available later in the function, i.e. the type is "deferred" because of intermediate compile-time dependencies. For example something like this which depends on the auto keyword but does not compile: template<bool value, typename ...> struct bool_type : std::integral_constant<bool , value> {}; template<typename T> void function(T* v) { auto r; bool different_type = false; if constexpr (...) r = (T)subfunc_a(v); else if constexpr (...) r = (T)subfunc_b(v); else if constexpr (...) r = (T)subfunc_c(v); else if constexpr (...); r = (T)subfunc_d(v); else if constexpr (...) r = (T)subfunc_e(v); // This condition depends on previous conditions. Extracting the condition // to the top of this function for use with `std::conditional` would be // burdensome. Decoupling the conditional in this way also risks errors. I // want to depend on the type system to enforce code correctness. else if constexpr (...) { r = (long)subfunc_f(v); different_type = true; } else if constexpr (...) { r = (unsigned long)subfunc_g(v); different_type = true; } else { static_assert(bool_type<false, T>::value, "Unsupported type"); } do_common_work(); if (different_type) do_more_work(); *v = r; } Or this example which depends on the static if proposal which prevents if constexpr conditionals from creating a new scope. The proposal didn't pass so the code doesn't compile. template<typename T> void function(T* v) { bool different_type = false; if constexpr (...) T r = subfunc_a(v); else if constexpr (...) T r = subfunc_b(v); else if constexpr (...) T r = subfunc_c(v); else if constexpr (...); T r = subfunc_d(v); else if constexpr (...) T r = subfunc_e(v); else if constexpr (...) { different_type = true; long r = subfunc_f(v); } else if constexpr (...) { different_type = true; unsigned long r = subfunc_g(v); } else { static_assert(bool_type<false, T>::value, "Unsupported type"); } do_common_work(); if (different_type) do_more_work(); *v = r; }
auto variable can only infer its type from the initialization expression in C++. If you don't want to explicitly specify its type, you can extract the initialization into a separate function which returns the necessary value (type is auto) and initialize with this function's call. In particular, the extracted function can be a lambda expression, so you get an immediately invoked function expression or IIFE: #include <iostream> #include <type_traits> template <bool value, typename...> struct bool_type : std::integral_constant<bool, value> {}; template <typename T> void function(T *v) { bool different_type = false; auto r = [&] { // create a function if constexpr (std::is_same_v<T, int>) { return 10; } else if constexpr (std::is_same_v<T, double>) { return 10.0; } else if constexpr (std::is_same_v<T, long>) { different_type = true; return 10LL; } else { static_assert(bool_type<false, T>::value, "Unsupported type"); } }(); // immediately invoke the created function std::cout << typeid(r).name() << " " << different_type << "\n"; *v = r; } int main() { int a; double b; long c; [[maybe_unused]] float d; function(&a); // int 0 function(&b); // double 0 function(&c); // long long 1 // function(&d); // compilation error } In the code above, the lambda expression has a return type of auto, i.e. it's automatically deduced from the return chosen by if constexpr. Only a single return is chosen, so the return type is unambiguous, so r's type is also inferred correctly.
72,419,746
72,420,148
How do I check that a particular template parameter is the same
I have a class with three template parameters: template<typename A, typename B, typename C> class Unit; Then I have a concept representing this class and all its specialization: template <typename T> struct is_unit : std::false_type {}; template<typename A, typename B, typename C> struct is_unit<Unit<A, B, C>> : std::true_type {}; template <typename T> constexpr bool is_unit_v = is_unit<T>::value; template <typename T> concept Unit_T = is_unit_v<T>; In the definition of the Unit class, I want a function that returns a Unit with a different specialization from the one through which the function is called. I want the user to provide the desired return type. I have this working so far: template<typename A, typename B, typename C> class Unit { public: // Other member stuff... template<Unit_T U> U as() { return U(*this); } } Unit<MyType, long double, MyOtherType> unit; // Do stuff to unit. auto unit2 = unit.as<Unit<MyType, long int, AnotherType>(); That all works as expected. There's one more requirement, however, that I can't figure out how to implement. The first template parameter of the desired type must match the first template parameter of the type through which it was called. So this: Unit<MyType, long double, MyOtherType> unit; // Do stuff to unit. auto unit2 = unit.as<Unit<YetAnotherType, long int, AnotherType>(); should not compile. I would think that the correct way to do this would look something like: template<typename A, typename B, typename C> class Unit { public: // Other member stuff... template<Unit_T U> requires std::is_same_v<U<D>, D> // or maybe std::is_same_V<U::D, D> ? U as() { return U(*this); } } But that doesn't work. And, as I understand, even if that was the right way to require a template parameter be the right type, I can't further constrain a concept. I tried writing another concept for a Unit with a specific first template parameter: template<typename U, typename D> concept UnitFirstType = is_unit_v<U> && std::is_same_v<U<D> /* or U::D */, D>; But that doesn't work. The problem seems to lie in how I'm using std::is_same_v. I just don't know how to use it with a template parameter. So what is the proper way to achieve this: Unit<MyType, long double, MyOtherType> unit; auto unit2 = unit.as<Unit<MyType, long int, AnotherType>(); // will compile // auto unit3 = unit.as<Unit<YetAnotherType, long int, AnotherType>(); // should not compile
This is probably what you want template<typename A, typename B, typename C> class Unit; template<typename U, typename A> constexpr bool unit_first_type = false; template<typename A, typename B, typename C> constexpr bool unit_first_type<Unit<A, B, C>, A> = true; template<typename U, typename A> concept UnitFirstType = unit_first_type<U, A>; template<typename A, typename B, typename C> class Unit { public: // Other member stuff... template<UnitFirstType<A> U> U as(); }; Demo
72,420,355
72,420,530
CMake undefined reference to `pthread_create` in Github Action Ubuntu image
When I was using Github Action CI, I found that no matter what method I used to link, there was no way to link pthread_create But this error only appears in the Ubuntu environment, Windows, macOS are no problem I tried: Not Working set(CMAKE_THREAD_PREFER_PTHREAD TRUE) set(THREADS_PREFER_PTHREAD_FLAG TRUE) find_package(Threads REQUIRED) add_executable(xxx xxx.c) target_link_libraries(xxx PRIVATE Threads::Threads) Not Working set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -pthread") You can view the compiled log here: https://github.com/YuzukiTsuru/lessampler/runs/6640320037?check_suite_focus=true
If you read the build log carefully /usr/bin/ld: CMakeFiles/GenerateAudioModelTest.dir/__/src/GenerateAudioModel.cpp.o: in function `GenerateAudioModel::GenerateModelFromFile()': GenerateAudioModel.cpp:(.text+0x27aa): undefined reference to `pthread_create' You notice the error has happened while linking the target GenerateAudioModelTest that is located in the directory test and CMakeLists.txt there does not have the compiler flags you shown. Just add -pthread in test/CMakeLists.txt. This is a bad idea. set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread") Use target_compile_options(GenerateAudioModelTest PRIVATE -pthread) See What is the modern method for setting general compile flags in CMake?
72,420,382
72,420,417
Issue filling a 2d array of chars in c++
I was writing a program that involves a two dimensional array of values, and I was planning on printing them to terminal with ANSI escape codes. To test my code to for printing values with ANSI escape codes, I filled the array with a gradient. However, when I tried this, only the top row had the gradient. I have no idea what I am doing wrong here. I have tried using ints instead of chars, but nothing I tried has worked. My code: #include <iostream> char grid[64][64]; void printGrid(void) { for (char i = 0; i < 64; i++) { for (char j = 0; j < 64; j++) { char currentCell = grid[(int)i][(int)j]; std::cout << '\033' << "[48;2;" << std::to_string(currentCell) << ';' << std::to_string(currentCell) << ';' << std::to_string(currentCell) << "m "; } std::cout << '\033' << "[0m" << std::endl; } } int main(void) { for (char i; i < 64; i++) { for (char j; j < 64; j++) { grid[(int)i][(int)j] = ((j+1)*2)-1; } } printGrid(); return 0; }
The issue was hiding in plain sight. I forgot to initialize my iterators to 0 in some of my for loops. for (char i; i < 64; i++) forgot to set initial value to 0, the same for J loop – Iłya Bursov
72,420,933
72,422,071
creating a vector with user defined class and int In instantiation of ‘struct std::_Vector_base....no type named ‘value_type’ in ‘class MyClass’
I am creating a simple class #include <iostream> #include <vector> #include <algorithm> using namespace std; class MyClass { int p; public: MyClass( int q ) { p = q; } }; but when I try to create this vector vector<int, MyClass> vec1(1); my code breaks and throws this exception vector<int,MyClass> vec1(1); In instantiation of ‘struct std::_Vector_base<int, MyClass>’: /usr/include/c++/9/bits/stl_vector.h:386:11: required from ‘class std::vector<int, MyClass>’ vector_class.cpp:19:26: required from here /usr/include/c++/9/bits/stl_vector.h:84:21: error: no type named ‘value_type’ in ‘class MyClass’ 84 | rebind<_Tp>::other _Tp_alloc_type; Can I resolve this means can I use int type with user defined types in vector like this vector<int,MyClass>
how to print p if I am using pair in vector as u shown You can iterate through the pair elements of the vector and print the data member p as shown below: class MyClass { public: int p; public: MyClass( int q ):p(q) { } }; int main() { std::vector<std::pair<int, MyClass>> vec1{{1, MyClass(44)}, {2,MyClass(45)}, {3,MyClass(46)}}; //iterate through the vector and print data member p for(const auto&myPair: vec1) { //-----------------vvvvvvvvvvvvvv-------------->print the data member p std::cout<<myPair.second.p<<std::endl; } } Working demo
72,421,352
72,422,723
How to restrict generic class method template parameter to certain types?
I have checked out std::enable_if to conditionally compile a member function However it doesn't work for me. I need to restrict T of a class method to some types. template<typename T = typename enable_if_t< is_same_v<T, long> || is_same_v<T, int> || is_same_v<T, double> || is_same_v<T, float> || is_same_v<T, size_t>> > shared_ptr<Node<T>> LinkedList<T>::AddNumbers( shared_ptr<Node<T>> p1, shared_ptr<Node<T>> p2, T carry) { <snip> } I get build error: identifier T is undefined I am using C++20. Any advice and insight is appreciated. I try out concepts suggested by @JeJo, but get the following build error on the line performing arithmetics: error C2676: binary '/': 'T' does not define this operator or a conversion to a type acceptable to the predefined operator I have the template class declaration in header file and implementation in .cpp file. Header file: template <typename T> class LinkedList { public: <snip> shared_ptr<Node<T>> AddNumbers( shared_ptr<Node<T>>, shared_ptr<Node<T>>, T carry = 0); }; When I use the suggestion by @JeJo, I bump into error C3855: 'LinkedList<T>': template parameter 'T' is incompatible with the declaration
Despite what the other answers say, the member function doesn't need to (and shouldn't) be a template, assuming you use requires. That's only necessary when you use the classical SFINAE. #include <cstddef> #include <iostream> #include <memory> #include <type_traits> template <typename T, typename ...P> concept one_of = (std::is_same_v<T, P> || ...); template <typename T> struct Node {}; template <typename T> class LinkedList { public: std::shared_ptr<Node<T>> AddNumbers(std::shared_ptr<Node<T>>, std::shared_ptr<Node<T>>, T carry = 0) requires one_of<T, int, long, std::size_t, float, double> { // ... } }; int main() { LinkedList<int> s; s.AddNumbers(nullptr, nullptr, 0); LinkedList<char> t; // t.AddNumbers(nullptr, nullptr, 0); } Any boolean condition can be spelled after requires, but I've added a concept for brevity.
72,421,374
72,421,509
match against template template type parameter
Say I would like to type-match any container with a specific member (a constraint) - but also bind type variables to both the container and the member. For example let T and U be the template type variables corresponding to class and member Someclass.member. Is this possible? Let's simplify things by templating the container. This moves the member type into the type system as the template type parameter which allows removing the constraint. Now can I bind the type variables to both the template type and the template type parameter? For example let T and U be the template type variables corresponding to the templated container T<U>. Is this possible? For example, template <typename T> struct S1 { T a; int b; }; struct S2 { S1<int> a; S1<double> b; }; void cb(auto*); // Many things have been tried template<T<U>> template<template<typename U> typename T> void caller(T<U>*, void (*)(U*)); template<S1<T>> void caller(S1<T>*, void (*)(T*)); template<T> void caller<S1<T>>(S1<T>*, void (*)(T*));
The caller's template list should be template <typename T> struct S1 { T a; int b; }; void cb(auto*); template<template<typename...> typename Temp, typename U> void caller(Temp<U>*, void (*)(U*)); int main() { S1<int> a; caller(&a, cb); S1<double> b; caller(&b, cb); } Demo
72,421,646
72,422,815
Unqualified name lookup
This is from the standard (C++20) - unqualified name lookup 6.5.2. Can anyone please explain what's going on here ? Note: this is not ADL. I am specifically looking for an elucidation of this brief sentence: "In some cases a name followed by < is treated as a template-name even though name lookup did not find a template-name" int h; void g(); namespace N{ struct A{}; template <class T> int f(T); template <class T> int g(T); template <class T> int h(T); } int x = f<N::A>(N::A()); // OK: lookup of f finds nothing; f treated as template name int y = g<N::A>(N::A()); // OK: lookup of g finds a function, g treated as template name int z = h<N::A>(N::A()); // error: h< does not begin a template-id
In f<N::A>(N::A()), the < can either be a less-than operator or start a template argument list. To disambiguate, compilers need to see whether f (the name before <) names a template. Note that it's impossible to perform ADL at this point, because when compilers see <, they do not even know whether there are arguments. C++20 specifies that if usual name lookup finds nothing, f is treated as a template-name. Thus < in question is considered to start a template argument list, which means f<N::A> is parsed as a template-id, which means f<N::A>(N::A()) is parsed as a function call expression, which means ADL is performed to see what f really is. Before C++20, the name before < is treated as a template-name if and only if usual name lookup finds a template, so none of these happen, < is considered as an operator, and f<N::A>(N::A()) is treated as an error. The change was made by P0846R0. C++20 [temp.name]/2: An identifier is a template-name if it is associated by name lookup with a template or an overload set that contains a function template, or the identifier is followed by <, the template-id would form an unqualified-id, and name lookup either finds one or more functions or finds nothing. C++20 [temp.names]/3: When a name is considered to be a template-name, and it is followed by a <, the < is always taken as the delimiter of a template-argument-list and never as the less-than operator. The latest draft arguably makes it clearer ([temp.names]/3): A < is interpreted as the delimiter of a template-argument-list if it follows a name that is not a conversion-function-id and [...] that is an unqualified name for which name lookup either finds one or more functions or finds nothing, or [...].
72,421,916
72,422,480
Having trouble setting background of an event with its ID | WxWidgets
I believe I've done something similar in wxPython where I've changed an event by grabbing the Id or object and setting the object's background from there. In WxWidgets I seem to be having trouble though, I keep on getting errors like operator -> or ->* applied to "int" instead of to a pointer type. I'd like to be able to get the event's parent's Id/object and the event's Id/object in order to change their background/properties. I also had no luck in finding anything that mentioned an event's parent in the documentation. I've tried different using different methods like GetEventObject() and GetEventUserData() and making the EventId a pointer. I'm new to C++ so pointers are still new to me so I didn't expect anything to work. Any help is much appreciated. Code: void MyFrame::OnMenuTxtBtnLeftClick(wxMouseEvent& event) { int EventId = event.GetId(); EventId->SetBackgroundColour(wxColour(217, 217, 217, 19));
The problem is that EventId is an int and thus the operator -> cannot be used with it. You can try out the following that uses GetEventOjbect: wxObject *obj = event.GetEventObject(); ((myPanel *) obj)->SetBackgroundColour(wxColour(217, 217, 217, 19)); //^^^^^^^----------------------------->use your own type here
72,422,048
72,422,086
How can I call the specialized template overloaded function from the main template one?
I have a method inside a templated class that creates a hash of a variable. I have specialized its template to int, double and std::string like this template<> class Hash<int> { public: unsigned long operator()(const int& d) const noexcept { return d * d; } }; template<> class Hash<double> { public: unsigned long operator()(const double& d) const noexcept { long intera = floor(d); long frazionaria = pow(2, 24) * (d - intera); return intera * frazionaria; } }; template<> class Hash<std::string> { public: unsigned long operator()(const std::string& d) const noexcept { unsigned long hash = 5381; for (unsigned long i = 0; i << d.length(); i++) { hash = (hash << 5) + d[i]; } return hash; } }; I then created a generic version of the same method which takes a template parameter and tries to convert it to std::string and then tries to call operator() on it (which I'd expect would call the specialized template one) unsigned long operator()(const Data& d) const noexcept { std::cout<<"Special hash! "; void *v = (void *)&d; size_t j = sizeof(d); std::string s = ""; for (size_t k = 0; k < j; k++) { s += (((char *)v)[k]); } std::cout<<"Pre-hash: "<<s<<std::endl; return operator()(s); } (it's inside the class declaration while the other 3 are in a different file) So when I call operator() of the Hash class on a int, double or std::string it works fine, but the moment I try to call it on a different class of mine i get this error: error: cannot convert ‘std::string’ {aka ‘std::__cxx11::basic_string<char>’} to ‘const lasd::BST<int>&’ 35 | return operator()(s); | ^ | | | std::string {aka std::__cxx11::basic_string<char>} So it seems to me that it's trying to call operator(BST) again, even though i've passed a string to it. Is there a way I can solve this? I don't care about the hash function being incorrect, I have a uni assignment to do it this way, I only need to understand if it is even possible to call a specialized template function from a normal template one. I also tried using return operator()<std::string>(s); as I've seen in some other answers of a similiar question, but I get the following error: error: expected primary-expression before ‘>’ token 35 | return operator()<std::string>(s); | ^ https://gcc.godbolt.org/z/9oz8Gf9aM
If I understood correctly, your operator() needs a Hash instance to call its specialized operator() auto operator()(const Data& d) const noexcept { // .... std::string s = ""; return Hash<std::string>{}.operator()(s); // ^^^^^^^^^^^^^^^^^^^ // OR simply // return Hash<std::string>{}(s); } Update From the updated post/ error message, you are using the specialization Hash<std::string> before it has been declared as well as defined. That is at the line: return Hash<std::string>{}(s); compiler does not know about the Hash specialization for std::string. Hence, the error! (One way) to fix it, you need to split the declaration and the definition as follows: template<typename Data> class Hash { public: // declare the operator() auto operator()(const Data& d) const noexcept; }; template<> class Hash<int> { /* ...code... */ }; template<> class Hash<double> { /* ...code... */ }; template<> class Hash<std::string> { /* ...code... */ }; // define the operator() template<typename Data> auto Hash<Data>::operator()(const Data& d) const noexcept { // code! return Hash<std::string>{}(s); } See a demo
72,422,112
72,422,146
parameter difference between C++ and Python
C++ #include <iostream> using namespace std; void doSomething(int y) { cout << y << " "<< & y << endl; } int main() { int x(0); cout << x << " " << & x << endl; doSomething(x); return 0; } Python def doSomething(y): print(y, id(y)) x = 0 print(x, id(x)) doSomething(x) I think their code should return same result however C ++ result is 0 00000016C3F5FB14 0 00000016C3F5FAF0 Python result is 0 1676853313744 0 1676853313744 i don't understand why variable's address isn't changed in Python while variable's address is changed in C++
i don't understand why variable's address isn't changed in Python while variable's address is changed in C++. Because in python, we pass an object reference instead of the actual object. While in your C++ program we're passing x by value. This means the function doSomething has a separate copy of the argument that was passed and since it has a separate copy their addresses differ as expected. It is possible to make the C++ program produce the equivalent output as the python program as described below. Demo If you change the function declaration of doSomething to void doSomething(int& y) you will see that now you get the same result as python. In the modified program below, i've changed the parameter to be an int& instead of just int. //------------------v---->pass object by reference void doSomething(int& y) { cout << y << " "<< & y << endl; } int main() { int x(0); cout << x << " " << & x << endl; doSomething(x); return 0; } The output of the above modified program is equivalent to the output produced from python: 0 0x7ffce169c814 0 0x7ffce169c814
72,422,474
72,422,563
Creating multiple randomly named files on a desktop doesn't work with C++
This program should create 10 randomly named files with unicode string names on a desktop but it only creates just 1. I tried using delete[] statements at the end of the createfiles function to deallocate the memory for output, file and desktop but it still doesn't work. Am I doing something wrong? #include "shlobj_core.h" #include <fstream> #include <iostream> #include <Windows.h> wchar_t* generateRandomUnicodeString(size_t len, size_t start, size_t end) { wchar_t* ustr = new wchar_t[len + 1]; size_t intervalLength = end - start + 1; srand(time(NULL)); for (auto i = 0; i < len; i++) { ustr[i] = (rand() % intervalLength) + start; } ustr[len] = L'\0'; return ustr; } void createfiles(int number) { if (number == 0) { return; } wchar_t* output = generateRandomUnicodeString(5, 0x0400, 0x04FF); LPWSTR desktop; LPWSTR file; SHGetKnownFolderPath(FOLDERID_Desktop, 0, 0, &desktop); PathAllocCombine(desktop, output, 0, &file); std::wofstream ofs(file); ofs << "File Description"; delete[] output; output = nullptr; delete[] file; file = nullptr; delete[] desktop; desktop = nullptr; createfiles(number - 1); } int main() { createfiles(10); return 0; }
If the function call time(NULL) is executed several times in the same second (which is probably happening in your case), then it will return the same value every time. This means that you are seeding the random number generator with the same value every time you attempt to generate a random string. As a consequence, rand will generate the same sequence of random numbers every time. This means that you are generating the same random string every time you call the function generateRandomUnicodeString. If you attempt to create the same filename 10 times, then only the first time will succeed and the remaining 9 times will fail, because that file already exists. The simplest fix to your problem would therefore be to only call srand only once in your program, not every time generateRandomUnicodeString is called. This is best done at the start of the function main. That way, you will only have the problem of generating the same sequence of random numbers if you call main more than once in the same second (i.e. if you start the program twice in the same second). It will no longer be a problem if you call generateRandomUnicodeString several times in the same second.
72,422,602
72,423,267
How to get if User pressed Enter wxWidgets
I want to get the Input from a field wxTextCtrl* upperOnly = new wxTextCtrl(this, wxID_ANY, wxT("Test"),wxPoint(5,260), wxSize(630,30)); and this i want every Time the user Pressed Enter
Use wxTE_PROCESS_ENTER when creating the control, i.e. wxTextCtrl* upperOnly = new wxTextCtrl(this, wxID_ANY, wxT("Test"),wxPoint(5,260), wxSize(630,30), wxTE_PROCESS_ENTER); Then catch wxEVT_TEXT_ENTER and do your validation in its event handler, i.e. upperOnly->Bind(wxEVT_TEXT_ENTER, [](wxCommandEvent&) { // Do something useful });
72,422,738
72,422,802
Difference Between "struct Obj* obj" and "Obj* obj"
struct Element{ Element() {} int data = NULL; struct Element* right, *left; }; or struct Element{ Element() {} int data = NULL; Element* right, *left; }; I was working with binary trees and I was looking up on an example. In the example, Element* right was struct Element* right. What are the differences between these and which one would be better for writing data structures? I was looking up from this website: https://www.geeksforgeeks.org/binary-tree-set-1-introduction/
In C++, defining a class also defines a type with the same name so using struct Element or just Element means the same thing. // The typedef below is not needed in C++ but in C to not have to use "struct Element": typedef struct Element Element; struct Element { Element* prev; Element* next; }; You rarely have to use struct Element (other than in the definition) in C++. There is however one situation where you do need it and that is when you need to disambiguate between a type and a function with the same name: struct Element {}; void Element() {} int main() { Element x; // error, "struct Element" needed }
72,423,058
72,423,276
Memory leak in the implementation of the matrix multiplication operation
Memory leak in the implementation of the matrix multiplication operation: template <typename T> class Matrix { private: T *data = nullptr; size_t rows; size_t cols; Here is the multiplication operation itself: Matrix<T> operator*(const Matrix<T> &other) { Matrix<T> result(rows, other.cols); if (cols == other.rows) { for (size_t i = 0; i < rows; i++) { for (size_t j = 0; j < other.cols; j++) { for (size_t k = 0; k < cols; k++) { result.data[i * other.cols + j] += data[i * cols + k] * other.data[k * other.cols + j]; } } } } else { throw std::logic_error("Matrix sizes do not match"); } return result; } How can I change this method so that it works correctly (and does not fall on tests)? Here is a link to the class https://godbolt.org/z/4PPYx4Y3j. For some reason, everything works well here, but when I start doing a test: TEST(testMatrixCalculations, testMultiplication) { myMatrix::Matrix<int> mat1(3, 3); myMatrix::Matrix<int> mat2(3, 3); for (auto &it: mat1) { it = 3; } for (auto &it : mat2) { it = 3; } mat1.printMatrix(); mat2.printMatrix(); myMatrix::Matrix<int> mat3 = mat1 * mat2; mat3.printMatrix(); for (auto it : mat3) { ASSERT_EQ(it, 27); } } Outputs this: 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 -1119477653 32718 -1119477653 32718 775685387 21966 775685387 21966 27 Failure Expected equality of these values: it Which is: -1119477653 27
Your result.data is not initialized to 0 but you apply a += operation to it. You must either initialize your Matrix::data member to zero in the Matrix main constructor function, or initialize it preliminary in your multiplication loop. for (size_t i = 0; i < rows; i++) { for (size_t j = 0; j < other.cols; j++) { result.data[i * other.cols + j] = 0; for (size_t k = 0; k < cols; k++) { result.data[i * other.cols + j] += data[i * cols + k] * other.data[k * other.cols + j]; } } }
72,423,103
72,423,553
Is there a way I can run c++ functions inside Java without using SWIG?
I want to create a wrapper for c++ so I can run code that I wrote in Java. Is there a way to achieve this without using SWIG?
As far as I know, JNI is the only way to run foreign language code inside Java app. Other solutions like SWIG are just JNI wrappers. If you have only 1-2 functions to call from Java code, SWIG may be an overkill. Try reading SWIG documentation: https://www.swig.org/Doc1.3/Java.html#java_overview Summarizing you can use raw JNI or try JNI wrappers like SWIG
72,423,148
72,423,171
C++ pass an array to a function without knowing its type
I want to make a function that takes an array as an argument with ANY type and returns its length like the following example: unsigned int getLength(array) { return sizeof(array) / sizeof(array[0]) } I don't know if it's possible to even possible to pass an array without knowing its type, I hope I explained my question well, thank you...
You can use templates as shown below. In particular, we can make use of template nontype parameter N to represent the length of the passed array and template type parameter T to represent the type of the element inside the array. template<typename T, std::size_t N> //--------------------------v--------------->type of elements inside array named arr std::size_t getLength(const T (&arr)[N]) //-----------------------------------^------>length of the array { return N ; } int main() { int arr[] = {1,2,3}; std::cout<<getLength(arr)<<std::endl; std::string arr2[] = {"a", "b"}; std::cout<<getLength(arr2)<<std::endl; return 0; } Working demo Note with C++17 there is also an option to use std::size.
72,423,418
72,423,621
How do I tell CMake to link the C standard library, not the C++ one?
I have a simple C++ file, but I do not want to use the C++ standard library, just the C one. Can this be done using CMake? Basically disabling access to the c++ headers, and only allowing linking to the C standard.
You can use target_compile_options(yourprog PRIVATE -nostdinc++) for clang and GCC based toolchains and /X with the path to its STL headers with msvc
72,423,513
72,424,844
Multi-threaded C++ code slower with more physical cores? (threaded C++ mex function)
I am running multi-threaded C++ code on different machines right now. I am using it within a Matlab mex function, so the overall program is run from MatLab. I used the code in this link here, only changed what is done in "main_loop" to fit to my task. The code is running perfectly fine on two of my computers and it is many times faster than running the same C++ code as single thread. So I think that the program itself is fine. However, when I run the same things on a third machine, it is suddenly extremely slow. The single threaded version is fine, but the multi-threaded one takes 10-15 times longer. Now, since everything seems fine on the other computers, my guess is that it has something to do with the specs of the third machine (details see below). My guess: The third computer has two physical processors. I guess this requires to copy everything physically to both processors? (The original code is intentionally written such that no hard-copy of any involved variable is required) If so, is there a way to control on which processor the threads are opened? (It would already help if I can just limit myself to one CPU and avoid copying everything) I already tried to set the number of threads down to 2, what did not help. Specs of 2-CPU computer: Intel Xeon Silver 4210R, 2.40Ghz (2 times), 128 GB Ram 64bit, Windows 10 Pro Specs of other computers: Intel Core i7-8700, 3.2Ghz, 64 GB Ram 64bit, Windows 10 Pro Intel Core i7-10750H, 2.6Ghz, 16 GB Ram 64bit, Windows 10 Pro, Laptop
TL;DR: NUMA effects combined with false-sharing are very likely to produce the observed effect only on the 2-socket system. Low-level profiling information to confirm/disprove the hypothesis. Multi-processors systems are subject to NUMA effect. Non-uniform memory access platforms are composed of NUMA nodes which have their own local memory. Accessing to the memory of another node is more expensive (higher latency or/and smaller throughput). Multiples threads/processes located on multiple NUMA nodes accessing to the same NUMA node memory can saturate it. Allocated memory is split in pages that are are mapped to NUMA nodes. The exact mapping policy is very dependent of the operating system (OS), its configuration and the one of the target processes. The first touch policy is quite usual. The idea is to allocate the page on the NUMA node performing the first access on the target page. Regarding the target chosen policy, OS can migrate pages from one NUMA node to another regarding the amount of remote NUMA node access. Controlling the policy is critical on NUMA platforms, especially if the application is not NUMA-aware. The memory of multiple NUMA nodes is kept coherent thanks to a cache coherence protocol and an high-performance inter-processor communication network (Ultra Path Interconnect in your case). Cache coherence also applies between cores of the same processor. The thing is moving a cache line from (the L2 cache of) one core to another (L2 cache) is much faster than moving it from (the L3 cache of) one processor to another (L3 cache). Here is an analogy for human communication: neurons of different cortical area communicate faster than two humans together. If your application operate in parallel on the same cache line, the false-sharing can cause a cache-line bouncing effect which is much more visible between threads spread on different processors. This is a very complex topic. That being said, you can analyse these effects using low-level profilers like VTune (or perf on Linux). The idea is to analyse low-level performance hardware counters like L2/L3 cache misses/hit, RFOs, remote NUMA accesses, etc. This can be complex and tedious to use for someone not familiar with how processors and OS works but VTune help a bit. Note that there are some more specific tools of Intel to analyse (more easily) such specific effects that usually happens on parallel applications. AFAIK, they are part of the Intel XE set of applications (which is not free). The best to do is to avoid false-sharing using padding, design your application so each thread should operate on its own memory location as much a possible (ie. good locality), to control the NUMA allocation policy and finally to bind threads/processes to core (to avoid unexpected migrations). Experimental benchmarks can also be used to quickly check if NUMA effect and false sharing occurs. For example, you can bind all the threads/processes on the same NUMA node and tell the OS to allocate pages on this NUMA node. This enable you to find issues related to NUMA effects. Another example is to bind two threads/processes on two different logical cores (ie. hardware thread) of the same physical cores, and then on different physical cores so to see if performance is impacted. This one help you to locate false sharing issues. That being said, such experiments can be impacted by many other effects adding noise and making the analysis pretty complex in practice for large applications. Thus, a low-level analysis based on hardware performance counters is better. Note that some processors like AMD Zen ones are composed of multiple sub-parts (called CCD/CCX) that can be seen has multiple NUMA nodes even though there is only one processor and one socket. Such architectures will certainly become more widespread in the future. In fact, Intel also started to go in this direction with Sub-NUMA Clustering.
72,423,582
72,424,096
Forward declarations and incomplete types in C++ modules
I have been experimenting with C++20 modules, and there seems to be something different with the usual hpp/cpp approach. The following doesn't compile (I'm using the latest preview of MSVC). foo.ixx export module foo; import std.memory; export struct Bar; export struct Foo { std::unique_ptr<Bar> ptr; }; bar.ixx export module bar; import std.core; import foo; struct Bar { void func(Foo& f) {} }; main.cpp import foo; import bar; int main() { Foo f; } My questions: Is there a better way to resolve this other than putting Foo and Bar into one file? Does this imply that template instantiation is done before module "linking"?
Modules own the declarations placed into them. And if a module owns a declaration, all other declarations must also be part of the same module. Bar was declared to be in foo. Therefore, any other declarations of it (and a definition is a declaration) must also be within foo. They don't have to be in the same file, but they do have to be in the same module. If you want the definition of Bar to be accessible by users of the module foo, you should use a module interface unit partition: export module foo:BarDef; import std.core; export struct Bar { void func(Foo& f) {} }; And the module's primary interface unit must import this partition: export module foo; import std.memory; export struct Bar; export struct Foo { std::unique_ptr<Bar> ptr; }; export import :BarDef; MSVC's naming convention for module files says that .ixx should be used for any interface units, so both of these files should be .ixx files.
72,423,613
72,427,875
gdb: how to learn which shared library loaded a shared library in question
I need to get the list of shared libraries used by an app in runtime. Most of them can be listed by ldd, but some can be seen only with gdb -p <pid> and by running the gdb command info sharedlib. It would really help, if I could learn in some way: for a chosen library (in the list, output by info sharedlib), which library (of the same list) had caused to load it. Is there any way to learn it in gdb or in some other way? Because sometimes, I see a loaded library in the list and cannot get why it is there and which (probably, previously loaded in memory) library loaded it. UPDATE: I attach a screen shot of gdb showing the info that I need. I used breakpoint on dlopen, as it was suggested in comments and in the answer. The command x/s $rdi prints out the first argument of dlopen, as by Linux System V ABI, i.e. it prints the name if the library, about which I want to learn who loaded it (libdebuginfod.so.1). I put it here just for those who are curious. In my case, it can be seen, that the libdebuginfod.so.1 was loaded by libdw.so.1 (as shown by bt command).
Is there any way to learn it in gdb or in some other way? There are a few ways. You can run the program with env LD_DEBUG=files /path/to/exe. This will produce output similar to: LD_DEBUG=files /bin/date 76042: 76042: file=libc.so.6 [0]; needed by /bin/date [0] It is the needed by part that you most care about. You could also use GDB and use set set stop-on-solib-events 1. This will produce output similar to: Stopped due to shared library event: Inferior loaded /lib/x86_64-linux-gnu/libc.so.6 At that point, you could execute where command and observe which dlopen() call caused the new library to be loaded. You could also set a breakpoint on dlopen() and do the same. The stop-on-solib-events may be better if your executable repeatedly dlopen()s the same library -- the library set will not change when you dlopen() the same library again, and you'll stop when you don't care to stop. Setting stop-on-solib-events avoids such unnecessary stops.
72,424,353
72,424,404
Why does it not display the final product?
I want to write a program on where the user gets asked a quiz and then they get assigned on one of the Harry Potter houses, but in the end the output for the house doesn't show. I am using c++ for this project and I also using Visual Studio Code as my IDE. I want to be able to put the alternatives and when the user inputs them, it takes an average and assigns them a house in the end. On the code displayed here, I used ... to show repetition and to shorten the code a lot. So in the answer variables, there are 10 variables, from one to 10 with a value of 0 for each of them. On the questions, there are ten, but I have only displayed the first and the last. There are 4 choices and each is 1, 2, 3 and 4. There is one if statement representing the corresponding answer(question1, answer1; question2, answer2 and so on and so forth). Also, sorry if the code is a little unclear, because I have to show most of the code, but it doesn't let me post if there is more code than description. How can I fix the issue where the house doesn't display now? Any tips would be appreciated a lot, thanks! This is the code: #include <iostream> using namespace std; int main() { int gryffindor = 0; ... int slytherin = 0; int answer1 = 0; ... int answer10 = 0; cout << "Let's test which house you belong to. Test beginning in: \n 3 \n 2 \n 1 \n 0 \n Good luck \n"; cout << "What colour do you like most? \n 1. Red ... \n 4. Yellow \n"; cin >> answer1; if (answer1 == 1) { gryffindor++; } else if (answer1 == 2) { hufflepuff++; } else if (answer1 == 3) { ravenclaw++; } else if (answer1 == 4) { slytherin++; } else { cout << "Try again, answer invalid: "; cin >> answer1; } ... cout << "If the sorting hat put you in what you think is the wrong house you would \n 1. Softly make a comment \n ... 4. Go happily to the house you were assigned to \n"; cin >> answer10; if (answer10 == 1) { gryffindor++; } ... else { cout << "Try again, answer invalid: "; cin >> answer10; } // Finding the houses int MaxPoints; string YourHouse; if (gryffindor > MaxPoints) { MaxPoints = gryffindor; YourHouse = "Gryffindor"; } if (hufflepuff > MaxPoints) { MaxPoints = hufflepuff; YourHouse = "Hufflepuff"; } if (ravenclaw > MaxPoints) { MaxPoints = ravenclaw; YourHouse = "Ravenclaw"; } if (slytherin > MaxPoints) { MaxPoints = slytherin; YourHouse = "Slytherin"; } cout << "The Hat has decided...Your house is: " << YourHouse << "! \n"; system("pause"); return 0; }
When you write "but in the end the output for the house doesn't show", do you mean the other text does show, but specifically not the house name? Or does none of the text show. In the former case, you might want to give the variable MaxPoints an initial value, because currently its value is undefined: int MaxPoints = -1;
72,424,888
72,425,649
Bouncing Ball Collision -SFML
I'm making a simple simulation of a ball bouncing. I already implemented gravity, but I don't know how to handle for collisions (make the ball change direction). I tried reverting the velocity, but that didn't work. // random start velocity float v = 2.f; // force float f = 0.f + (v*t) + (1/2.f)*G*t; std::cout << f << "\n"; // collision happened if ((ball.getPosition().y + ball.getRadius()) > 400.f) { // revert the velocity v = -v; } ball.setPosition(sf::Vector2f(ball.getPosition().x, f)); Here is the full code: #include <iostream> #include <SFML/Graphics.hpp> #include <cmath> //calculate the distance between the ball and the ground float distance_to_ground(float ball_y, float ground_y){ return (float)(ball_y - ground_y); } int main() { // gravity constant const float G = 9.807; // create the window sf::RenderWindow window(sf::VideoMode(800, 600), "My window"); window.setFramerateLimit(60); sf::CircleShape ball(30); ball.setPosition(window.getSize().x/2.f, 100); ball.setOrigin(ball.getRadius(),ball.getRadius()); //mass of the ball const float m1 = ball.getRadius(); sf::Clock TimeDelta; // run the program as long as the window is open while (window.isOpen()) { // check all the window's events that were triggered since the last iteration of the loop sf::Event event; while (window.pollEvent(event)) { // "close requested" event: we close the window if (event.type == sf::Event::Closed) window.close(); } sf::Time elapsed = TimeDelta.getElapsedTime(); float t = elapsed.asSeconds(); // distance between the ball and the ground float R = distance_to_ground(ball.getPosition().y, window.getSize().y); // random start velocity float v = 2.f; // force float f = 0.f + (v*t) + (1/2.f)*G*t; std::cout << f << "\n"; // collision happened if ((ball.getPosition().y + ball.getRadius()) > 400.f){ // change the velocity to negative v = -v; } ball.setPosition(sf::Vector2f(ball.getPosition().x, f)); // clear the window with black color window.clear(sf::Color::Black); // draw everything here... window.draw(ball); // end the current frame window.display(); } return 0; }
//collision happened if ((ball.getPosition().y + ball.getRadius()) > 400.f){ // revert the velocity v = -v; } This can result in the ball bouncing up and down, and falling through. You need: //collision happened if ((ball.getPosition().y + ball.getRadius()) > 400.f){ // make sure the velocity is downwards. v = -std::abs(v); }
72,425,106
72,425,143
Print front and back from an array c++
how can i print from array once from back and once from front c++? for examble: char c[] = { 'A','B','C','D' }; for (int i = 0; i < size(arr); i++) { cout << c[i]; } the output will be ABCD but the output that i want should be ADBC print one from front and one from end c[0],c[3],c[1],c[2]
You can use. Here we iterate for only half number of times the size of the array. Note that this assumes you have even number of elements in the array. int main() { char c[] = { 'A','B','C','D','E' }; std::size_t len = std::size(c); //---------------------v------------->divide by 2 so that we iterate only half the size times for (int i = 0; i < len/2; i++) { std::cout << c[i]<<c[len - i - 1]; } if (len % 2) {//in case we have odd number of elements std::cout << c[len/2]; } } Working demo
72,425,275
72,425,360
how to solve this question when a day is set to the first day of the month and decremented, it should become the last day of the previous month?
This is my first time trying such question .It has been so difficult for me to solve this question as I wasn't able to attend my classes when this was taught due to some reasons.Can anyone help me how do I use decrement operators as I have no idea where and how to add such operators to get the desirable output. I am already two days late for submitting this assignment :( #include <iostream> using namespace std; class Date{ private: int day; int month; int year; public: Date() { day; month; year; } Date(int d, int m , int y) { day = d; month = m; year = y; } void displayDate() { cout << "Day: " << day << " Month:" << month <<" Year:"<<year<<endl; } // overloaded prefix ++ operator Date operator++ () { ++day; ++year; ++month; if(day >= 31) { day -= 31; } if (month>=12) { month -= 12; } return Date(day, month,year); } }; int main () { int day; int month; int year; string month_name[20] = {"January","February","March","April","May","June","July","August","September","October","November","December"}; do{ cout << "Enter a day: "; cin >> day; if (day > 31 || day < 1) cout<<"This is invalid "<<endl; } while (day > 31 || day < 1); do{ cout << "Enter a month: " ; cin >> month; if (month > 12 || month < 1) cout<<"This is invalid "<<endl; } while (month > 12 || month < 1); cout << "Enter a year: "; cin >> year; cout << month << "/" << day << "/" << year << endl; cout << month_name[month-1]<< " " << day << ", " << year << endl; cout << day << " " << month_name[month-1] << "," << year << endl; Date D1(day,month,year); ++D1; // increment D1 D1.displayDate(); // display D1 ++D1; // increment of D1 again D1.displayDate(); // display D1 return 0; }
You can basically do the same thing with the increment operator but do it backwards. The C++ operator for decrement is --variable so the code would look as follows Date operator--(){ --day; --year; --month; if(day <= 0) { day += 31; } if (month<=0) { month += 12; } return Date(day, month,year); }
72,425,404
72,435,709
Still unsure about signed integer overflow in C++
In the following code I tested which form of overflow results in UB and causes therefore an hard error in a constexpr context: #include <cstdint> #include <limits> using T = int8_t; int main() { constexpr bool b = []{ T x = std::numeric_limits<T>::max(); ++x; // GCC: UB, Clang: no UB // x += 1; // x = x + 1; return (x > std::numeric_limits<T>::max()); }(); return b; } The preincrement gives an error (as I expected) for gcc but not for clang. More strange is that the standard says that ++x is the same as x += 1, but using this gives no more an error on gcc (and clang as before). And further x += 1 should be the same as x = x + 1, so the rhs is promoted to int and the result is implicitly converted. So, this should newer be UB. So, the question is, which of the three statement really should be UB (I think only ++x) and which compiler is correct?
[expr.pre.incr]/1 The expression ++x is equivalent to x+=1. [expr.ass]/6 The behavior of an expression of the form E1 op= E2 is equivalent to E1 = E1 op E2 except that E1 is evaluated only once. But x = x + 1 is not UB (integer promotion and narrowing integer conversion), so the original is well-formed. Therefore, GCC is wrong.
72,425,473
72,425,702
(MSVC) When implementing template method of template class outside of the class, C2244: Unable to match function definition to an existing declaration
Running into an issue with some code that compiles on GCC and Clang, but not MSVC (VS2022). Seems similar to this, but that was several years ago and this issue is specifically caused by the use of derived_from_specialization_of in the method template, so I'm not sure if it's the same issue. I'm wondering what the reason for this is, and if the issue is with my code or MSVC. DEMO Example: #include <concepts> template <template <class...> class Template, class... Args> void derived_from_specialization_impl(const Template<Args...>&); template <class T, template <class...> class Template> concept derived_from_specialization_of = requires(const T& t) { derived_from_specialization_impl<Template>(t); }; template <class T> class A { public: A() = default; }; template <derived_from_specialization_of<A> T> class B; template <derived_from_specialization_of<B> T> class C { public: C() = default; }; template <derived_from_specialization_of<A> T> class B { public: B() = default; template <derived_from_specialization_of<B> U> C<U> Foo(); template <derived_from_specialization_of<B> U> C<U> Bar() { return C<U>(); } }; template <derived_from_specialization_of<A> T> template <derived_from_specialization_of<B> U> C<U> B<T>::Foo() { return C<U>(); }
what the reason for this is, and if the issue is with my code or MSVC. This seems to be a bug in MSVC. You've correctly provided the out-of-class definition for the member function template Foo<>. Using auto and trailing return type doesn't seem to solve the issue in msvc. You can file a bug report for this.
72,426,064
73,679,518
Fast copying between random addresses
I'm developing an application which needs to perform a massive copying data byte-by-byte from one addresses to another addresses. Now'm using for loop in multithread. Size of arrays can be from 100k elements to 2M elements. It works relatively fast, but not enough. Is there a faster way to perform this task? std::vector<uchar*> src, dst //Filling src and dst vectors with pointers. src.size() and dst.size() are equal. for (int i=0; i<src.size();i++) *dst[i]=*src[i] UPD: It's an image processing task where pixel is 8-bit grayscale. Ready-to-use solutions such as OpenCV isn't suitable because it's even slower (up to 20 times). Maybe GPU solution is possible?
I moved entire project on GPU, using GLSL. Arrays are replaced with 2D samplers. Even low-end Intel UHD can handle high resolutions at high framerate.
72,426,626
72,426,818
Trouble creating an SFML Window
When trying to create an SFML window, sf::VideoMode(800, 600) gives a constructor not viable error. Source code: #include <SFML/Window.hpp> int main() { sf::Window window(sf::VideoMode(800, 600), "Pong"); return 0; } Error log: Consolidate compiler generated dependencies of target pong-cpp [ 50%] Building CXX object CMakeFiles/pong-cpp.dir/src/main.cpp.o /Users/larrymason/Desktop/repos/pong-cpp/src/main.cpp:4:23: error: no matching constructor for initialization of 'sf::VideoMode' sf::Window window(sf::VideoMode(800, 600), "Pong"); ^ ~~~~~~~~ /usr/local/include/SFML/Window/VideoMode.hpp:61:14: note: candidate constructor not viable: no known conversion from 'int' to 'const sf::Vector2u' (aka 'const Vector2<unsigned int>') for 1st argument explicit VideoMode(const Vector2u& modeSize, unsigned int modeBitsPerPixel = 32); ^ /usr/local/include/SFML/Window/VideoMode.hpp:42:23: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 2 were provided class SFML_WINDOW_API VideoMode ^ /usr/local/include/SFML/Window/VideoMode.hpp:42:23: note: candidate constructor (the implicit move constructor) not viable: requires 1 argument, but 2 were provided /usr/local/include/SFML/Window/VideoMode.hpp:52:5: note: candidate constructor not viable: requires 0 arguments, but 2 were provided VideoMode(); ^ 1 error generated. make[2]: *** [CMakeFiles/pong-cpp.dir/src/main.cpp.o] Error 1 make[1]: *** [CMakeFiles/pong-cpp.dir/all] Error 2 make: *** [all] Error 2 To my understanding and from the tutorials I've read/watched, this is the standard way of creating a window. I can successfully create the window using a sf::Vector2<unsigned int> however from looking at the SFML tutorials, this doesn't appear to be necessary. Is this just the new way? Or am I missing something?
Is this just the new way? Yes, they have made some changes. Here are the changes from the source file: This: VideoMode(unsigned int modeWidth, unsigned int modeHeight, unsigned int modeBitsPerPixel = 32); is now this: explicit VideoMode(const Vector2u& modeSize, unsigned int modeBitsPerPixel = 32); Take a look at it here.
72,427,124
72,464,185
double quotes problems in Qstring
QProcess p; QString aa = "tasklist /FI 'IMAGENAME x32dbg.exe' /FO LIST | findstr 'PID:'"; aa.replace(0x27,0x22); qInfo() << aa; p.start(aa.toStdString().c_str()); p.waitForFinished(); qInfo() << "Output:" << p.readAllStandardOutput() << "Error:" << p.readAllStandardError(); // returned error <ERROR: Invalid argument/option - 'x32dbg.exe\"'.\r\nType \"TASKLIST /?\" for usage.\r\n"> qebug return {tasklist /FI \"IMAGENAME x32dbg.exe\" /FO LIST | findstr \"PID:\"} the correct text must be {tasklist /FI "IMAGENAME eq x32dbg.exe" /FO LIST | findstr "PID:"} i tried with \" and add the command line in const char * all return same result
bool isRunning(const QString &process) { QProcess tasklist; tasklist.start( "tasklist", QStringList() << "/NH" << "/FO" << "CSV" << "/FI" << QString("IMAGENAME eq %1").arg(process)); tasklist.waitForFinished(); QString output = tasklist.readAllStandardOutput(); qInfo() << output ;
72,427,210
72,427,269
no match for ‘operator[]’ (operand types are ‘QJsonDocument’
I built a quick server using QT Creator on Windows, everything worked perfectly, I tried running The same code on my other Machine(Ubuntu) and I get errors, specially, in this line: QString max_colorbar = doc["colorbar"].toString(); The error I am getting is: no match for ‘operator[]’ (operand types are ‘QJsonDocument’ and ‘const char [9]’) The thing that confuses me is why do I need to change anything if the same code worked on Windows(It's cross platforms), I thought it may be because of QT versions but I checked my version on linux and it is: QMake version 3.1 Using Qt version 5.9.5 Am I doing anything wrong?
It's because const QJsonValue QJsonDocument::operator[](const QString &key) const function was introduced in Qt5.10 and you ran in on Qt5.9.5. You could change your code from QString max_colorbar = doc["colorbar"].toString(); to as follows which builds on Qt5.9.5 too QString max_colorbar = doc.object().value("colorbar").toString();
72,427,260
72,427,275
Access variable from one file from multiple files without copy
I'm trying to declare a variable in a header file Declarations.h which will be accessed from multiple files... like in C# it's a public static uint variableXXX then you can access it from everywhere. Declarations.h: #pragma once #ifndef CLIENT_CONST_H #define CLIENT_CONST_H static DWORD LocalPlayerPointer, LocalPlayerAddress, battle_list = 0; So the variables LocalPlayerPointer, LocalPlayerAddress are those who I want to be accessible from everywhere. dllmain.cpp: #include "Includes.h" LocalPlayerPointer = (DWORD)((moduleBase + dwLocalPlayer)); LocalPlayerAddress = *(DWORD*)LocalPlayerPointer; if (LocalPlayerAddress == 0) return; Includes.h: #include <Windows.h> #include <iostream> #include <cassert> #include <vector> #include <list> #include <string> #include <cstdint> #include "Utils.h" #include "Hook/Minhook/include/MinHook.h" #include "ImGui/imgui.h" #include "ImGui/imgui_impl_opengl3.h" #include "ImGui/imgui_impl_win32.h" #include "functions/functions.h" #include "../Declarations.h" #include "../Constants.h" #include "../Offsets.h" #include <chrono> #include <sstream> #include "../hooks.h" #include "../targeting.h" #pragma region OpenGL #ifdef _WIN64 #define GWL_WNDPROC GWLP_WNDPROC #endif #define GLEW_STATIC #if defined _M_X64 #include "Hook/GLx64/glew.h" #pragma comment(lib, "Source/Hook/GLx64/glew32s.lib") #elif defined _M_IX86 #include "Hook/GLx86/glew.h" #pragma comment(lib, "Source/Hook/GLx86/glew32s.lib") #endif #include <gl/gl.h> #pragma comment(lib,"opengl32.lib") #pragma endregion extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); typedef BOOL(__stdcall* twglSwapBuffers) (_In_ HDC hDc); typedef LRESULT(CALLBACK* WNDPROC)(HWND, UINT, WPARAM, LPARAM); So, until here everything is fine. From dllmain.cpp I can access the variables LocalPlayerPointer, LocalPlayerAddress, battle_list and if I write to them, the values are reflected correctly. The problem is when I try to read/write those variables from another file. Let's put as example a new file called targeting.cpp. targeting.h #pragma once #include "Source/Includes.h" void Targeting(); targeting.cpp #include "Source/Includes.h" void Targeting(){ std::cout << LocalPlayerPointer << std::endl; std::cout << LocalPlayerAddress << std::endl; } From targeting.cpp the std::cout displays 0. What I'm doing wrong to access that variable like a public static var? I want to access the same variable doesn't matters from which file I access to it. EDIT: After changing static DWORD LocalPlayerPointer, LocalPlayerAddress, battle_list = 0; to extern DWORD LocalPlayerPointer, LocalPlayerAddress, battle_list = 0; I'm getting this errors: Error LNK2001 unresolved external symbol "unsigned long LocalPlayerPointer" (?LocalPlayerPointer@@3KA) Tibia OpenGL Imgui C:\Users\Adrian\Documents\Tibia OpenGL Imgui\OpenGLTemplate\dllmain.obj 1 Error LNK2005 "unsigned long battle_list" (?battle_list@@3KA) already defined in hooks.obj Tibia OpenGL Imgui C:\Users\Adrian\Documents\Tibia OpenGL Imgui\OpenGLTemplate\dllmain.obj 1 Here is my hooks.h: #pragma once #include "Source/Includes.h" void InitHooks(); extern DWORD BattleHookGateway; extern DWORD __fastcall BattleHook(DWORD* pThis, DWORD battleList, DWORD localplayer); My hooks.cpp: #include "Source/Includes.h" DWORD BattleHookGateway; #pragma region InitHooks void InitHooks() { // get battle list hook BattleHookGateway = (DWORD)TrampHook32((char*)BattleListHook, (char*)BattleHook, 5); } #pragma endregion #pragma region Target DWORD __fastcall BattleHook(DWORD* pThis, DWORD battleList, DWORD localplayer) { WriteLine("Hooked :D"); DWORD battle_list = *(DWORD*)battleList; Targeting(battle_list); return ((_BattleListHook)BattleHookGateway)(battleList, localplayer); } #pragma endregion EDIT 2: My problem now was that I was trying to declare them with = 0; So after removing the inizialization in header file and init in another cpp file it worked.
In the header file put extern DWORD battle_int; in one C++ file put the definition DWORD battle_int = 0; dont put 'static' thats specifically means 'private to this file'
72,427,424
72,427,714
Boost Spirit x3 - parser doesn't recognize end of line
I am trying to parse an .obj file, but i can't figure out how to make x3 stop at the end of a line. My code looks like this: #include <iostream> #include <boost/config/warning_disable.hpp> #include <boost/spirit/home/x3.hpp> #include <boost/spirit/home/support/iterators/istream_iterator.hpp> #include <boost/spirit/include/support_multi_pass.hpp> #include <fstream> #include <sstream> namespace x3 = boost::spirit::x3; namespace ascii = boost::spirit::x3::ascii; namespace objParser { template <typename Iterator> bool parse_obj(Iterator first, Iterator last) { using boost::spirit::x3::char_; using boost::spirit::x3::eol; using boost::spirit::x3::eps; using boost::spirit::x3::_attr; using boost::spirit::x3::phrase_parse; auto printText = [&](auto& ctx) { std::cout << _attr(ctx) << std::endl; }; bool result = phrase_parse(first, last, // Begin grammar ( *( char_('#') >> *(~char_('\r\n'))[printText] >> eol) ), // End grammar eps(false)); if (!result || first != last) // fail if we did not get a full match return false; return result; } } int main() { std::string modelPath = "file.obj"; std::ifstream inFile(modelPath, std::ifstream::in); if (inFile.good()) { std::cout << "input found" << std::endl; } typedef std::istreambuf_iterator<char> base_iterator_type; typedef boost::spirit::multi_pass<base_iterator_type> forward_iterator_type; base_iterator_type in_begin(inFile); base_iterator_type in_end; forward_iterator_type fwd_begin = boost::spirit::make_default_multi_pass(in_begin); forward_iterator_type fwd_end = boost::spirit::make_default_multi_pass(in_end); objParser::parse_obj(fwd_begin, fwd_end); return 0; } The grammar is supposed to take the comment preceded by an "#" and print everything until the end of line. Instead the parser prints everything until the end of the file. Also how can I pack the *(~char_('\r\n'))[printText] so, that it takes the line content as a string? currently every char is printed separately.
Like the commenter said. This is why you enable warnings: <source>:33:43: warning: multi-character character constant [-Wmultichar] 33 | *( char_('#') >> *(~char_('\r\n'))[printText] >> eol) | ^~~~~~ Next up, simplify-time: https://compiler-explorer.com/z/hdWhsndMe return parse(first, last, // *('#' >> *(~x3::char_("\r\n"))[printText] >> x3::eol) // >> x3::eoi // ); Using the eoi directive instead, and not using phrase_parse if the intent is not to skip. Also how can I pack the *(~char_('\r\n'))[printText] so, that it takes the line content as a string? currently every char is printed separately. Just say so: https://compiler-explorer.com/z/GaPMdzoGr return parse(first, last, // *('#' >> (*~x3::char_("\r\n"))[printText] >> x3::eol) // >> x3::eoi); Demo #include <boost/spirit/home/support/iterators/istream_iterator.hpp> #include <boost/spirit/home/x3.hpp> #include <sstream> #include <iostream> namespace x3 = boost::spirit::x3; namespace ascii = boost::spirit::x3::ascii; namespace objParser { template <typename Iterator> bool parse_obj(Iterator first, Iterator last) { auto printText = [&](auto& ctx) { std::cout << _attr(ctx) << std::endl; }; return parse(first, last, // *('#' >> (*~x3::char_("\r\n"))[printText] >> x3::eol) // >> x3::eoi); } } // namespace objParser int main() { std::istringstream inFile(R"(# this is presumably a comment # and so is this )"); boost::spirit::istream_iterator b(inFile >> std::noskipws), e; objParser::parse_obj(b, e); } Prints this is presumably a comment and so is this
72,427,693
72,428,424
convert struct to unsigned char through overloaded operator << and >> (see update)
I have this struct with 2 attributes (one char and one int, for a memory usage of 3 bytes: struct Node { char data; int frequency; } I try overload the operators << and >> for this struct, for being able to read and write this struct from and into a file using fstream . For the operator << I got: friend std::ostream& operator<<(std::ostream& output, const HuffmanNode& e) { string data = string(1, e.data) + to_string(e.frequency); output << data.data(); return output; }; which makes wondering how much space this returns to the output (3 bytes, as expected? - 1 from the char and 2 from the int?) when I want save the struct to the file, I got this: List<Node> inOrder = toEncode.inOrder(); for(int i=1; i<=inOrder.size(); i++) { output << inOrder.get(i)->getData(); where each node of the list inOrder and the tree toEncode above are the struct listed before, and iNOrder.get(i)->getData() return it. output is the fstream. Now, how I do the reading from the file? with the operator >>, what I understand is that it need take an unsigned char array with 3 elements as input, and take the first element (1 byte) and convert to char, and the 2 other elements and convert for an int. Is this correct? Do I can do that with this method: friend std::istream& operator>>(std::istream& input, HuffmanNode& e) { ... }; or I need change the method signature (and parameters)? And for the file reading itself, taking in consideration the characters I need to read are all in the first line of the file, what the code for make the program read 3 characters each time from this line and generating a struct from this data? update what I got so far: for write to file, I implement this operator <<: friend std::ostream& operator<<(std::ostream& output, const HuffmanNode& e) { union unsigned_data data; data.c = e.data; union unsigned_frequency frequency; frequency.f = e.frequency; output << data.byte << frequency.byte; return output; }; used this way: List<HuffmanNode> inOrder = toEncode.inOrder(); for(int i=1; i<=inOrder.size(); i++) output << inOrder.get(i)->getData(); this seems to work, but I can't be sure without a way to read from the file, which I got this: operator>>: friend std::istream& operator>>(std::istream& input, HuffmanNode& e) { union unsigned_data data; data.c = e.data; union unsigned_frequency frequency; frequency.f = e.frequency; input >> data.byte >> frequency.byte; return input; }; used this way: string line; getline(input, line); HuffmanNode node; stringstream ss(line); long pos = ss.tellp(); do { ss >> node; toDecode.insert(node); ss.seekp (pos+3); } while(!ss.eof()); this seems to get stuck on a infinite loop. both operator are using this unions: union unsigned_data { char c; unsigned char byte; }; union unsigned_frequency { int f; unsigned char byte[sizeof(int)]; };
how much space this returns to the output (3 bytes, as expected? - 1 from the char and 2 from the int?) No. You are converting the values to std::strings, so they have variable lengths depending on the particular values (ie, "123" takes up a different length than "1234567890"). What you describe applies to the binary storage of the values, not to the textual representation of the values. Now, how I do the reading from the file? with the operator >>, what I understand is that it need take an unsigned char array with 3 elements as input, and take the first element (1 byte) and convert to char, and the 2 other elements and convert for an int. Is this correct? No. operator<< and operator>> are primarily meant to be used for formatted (textual) I/O. Your operator<< is actually writing formatted output (though, you don't need to convert the values to std::strings first, you can write them as-is using relevant overloads of operator<<). You just need to write the formatted data in such a way that your operator>> can reverse it. For example: friend std::ostream& operator<<(std::ostream& output, const HuffmanNode& e) { output << int(e.data) << ' ' << e.frequency << ' '; return output; } friend std::istream& operator>>(std::istream& input, HuffmanNode& e) { int i; input >> i >> e.frequency; e.data = char(i); input.ignore(); return input; } Alternatively: friend std::ostream& operator<<(std::ostream& output, const HuffmanNode& e) { output << e.data << e.frequency << '\n'; return output; } friend std::istream& operator>>(std::istream& input, HuffmanNode& e) { e.data = input.get(); input >> e.frequency; input.ignore(); return input; } The formatting is really up to you, based on your particular needs. However, the operators can also be used to read/write binary data, too (just be sure to open the streams in binary mode), eg: friend std::ostream& operator<<(std::ostream& output, const HuffmanNode& e) { output.write(&e.data, sizeof(e.data)); output.write(reinterpret_cast<const char*>(&e.frequency), sizeof(e.frequency)); return output; } friend std::istream& operator>>(std::istream& input, HuffmanNode& e) { input.read(&e.data, sizeof(e.data)); input.read(reinterpret_cast<char*>(&e.frequency), sizeof(e.frequency)); return input; } This is more in line with what you were thinking of.
72,427,809
72,427,891
How to define compile time ternary literal in C++?
In Chapter 19 of the 4th edition of the C++ Programming Language book, there is an example of defining a ternary number literal using a template technique, but the example does not compile. I tried to fix it in the way it looks right to me, but it still does not compile. #include <cstdint> #include <iostream> using namespace std; constexpr uint64_t ipow(uint64_t x, uint64_t n) { return n > 0 ? x * ipow(x, n - 1) : 1; } template <char c> constexpr uint64_t base3() { static_assert(c >= '0' && c <= '2', "Not a ternary digit."); return c - '0'; } template <char c, char... tail> constexpr uint64_t base3() { static_assert(c >= '0' && c <= '2', "Not a ternary digit."); return ipow(3, sizeof...(tail)) * (c - '0') + base3<tail...>(); } template <char... chars> constexpr uint64_t operator""_b3() { return base3<chars...>(); } int main() { cout << 1000_b3 << endl; return 0; } Clang gives the following error: error: call to 'base3' is ambiguous return ipow(3, sizeof...(tail)) * (c - '0') + base3<tail...>(); ^~~~~~~~~~~~~~ <source>:22:49: note: in instantiation of function template specialization 'base3<'0', '0'>' requested here <source>:22:49: note: in instantiation of function template specialization 'base3<'0', '0', '0'>' requested here <source>:28:10: note: in instantiation of function template specialization 'base3<'1', '0', '0', '0'>' requested here return base3<chars...>(); ^ <source>:33:15: note: in instantiation of function template specialization 'operator""_b3<'1', '0', '0', '0'>' requested here cout << 1000_b3 << endl; ^ <source>:12:20: note: candidate function [with c = '0'] constexpr uint64_t base3() ^ <source>:19:20: note: candidate function [with c = '0', tail = <>] constexpr uint64_t base3() ^ 1 error generated. What is the right way to define it?
Currently, when tail only has 1 character (when called with the last digit '0' of your user defined literal), it could call either overload of base3 template <char c> constexpr uint64_t base3() // With c as '0' template <char c, char... tail> constexpr uint64_t base3() // With c as '0' and tail as an empty parameter pack There is no reason to prefer one over the other, so it is ambiguous. You need the second overload to not work with exactly 1 argument, so you can make sure it takes at least 2 arguments: template <char c, char second, char... tail> constexpr uint64_t base3() { static_assert(c >= '0' && c <= '2', "Not a ternary digit."); return ipow(3, 1+sizeof...(tail)) * (c - '0') + base3<second, tail...>(); } Or do it with SFINAE: template <char c, char... tail> constexpr typename std::enable_if<sizeof...(tail) != 0, uint64_t>::type base3() { static_assert(c >= '0' && c <= '2', "Not a ternary digit."); return ipow(3, sizeof...(tail)) * (c - '0') + base3<tail...>(); } Or change it to a base case of 0 characters: template <typename = void> // Can be called with an empty set of template args constexpr uint64_t base3() { return 0; } template <char c, char... tail> constexpr uint64_t base3() { static_assert(c >= '0' && c <= '2', "Not a ternary digit."); return ipow(3, sizeof...(tail)) * (c - '0') + base3<tail...>(); }
72,428,029
72,428,097
Default argument for template not working
I have a chain of nested templated using declarations. It looks something like this: template <typename A, typename B, typename C, typename D> class Foo { public: Foo() : value{0} {}; template <typename AC, typename BC, typename CC, typename DC> Foo(const Foo<AC, BC, CC, DC>& rhs) : value{rhs.value} {} template <typename AC, typename BC, typename CC, typename DC> Foo& operator=(const Foo<AC, BC, CC, DC>& rhs) { value = rhs.value; return *this; } template <typename F> F convertTo() { return F(*this); } C value; }; template <typename ThingC, typename ThingD> using Bar = Foo<int, float, ThingC, ThingD>; template <typename ThingD = long double> using Bif = Bar<char, ThingD>; The following gives me trouble: int main(int argc, char* argv[]) { Bif bifDefault; Bif<long> bifLong; Bif<unsigned> bifUnsigned = bifDefault.convertTo<Bif<unsigned>>(); Bif<long double> bifLongDouble = bifLong.convertTo<Bif>(); // ERROR... // expected a type, got 'Bif' } I also get an error at the F convertTo line : template argument deduction/substitution failed. And the weirdest error, at the ERROR line: no instance of function template "Foo<A, B, C, D>::convertTo [ with A=int, B=float, C=char, D=long int]" matches the argument list D=long int! What's going on here? Changing it to just double doesn't work either. Clearly, the default template argument is propagating through to the function, but it's doing it wrong for long double, and doesn't work even when it does get the type correct. How do I get this to work?
The issue is that Bif isn't a type, it's a templated type. You're getting away with it when you declare bifDefault because of CTAD, but it doesn't apply when you call convertTo (you're not passing a non-type template parameter). The code compiles as expected when replaced with bifLong.convertTo<Bif<>>().
72,428,165
72,428,203
Redefinition and fail to use ifned/def/endif
I'm trying to make a program that follows the following UML diagram I've divided each class into its respective header and cpp. However, while doing some tests on it I found plenty of messages of redefinition so I tried using ifndef, def and endif however as you can see in this image (my commission worker header) it seems as if I wasn't including the employee header at all I'm using Visual Studio Code if that's relevant (Also, I doubled checked my file's name so that's not the problem)
You include the header file for the Employee Class by using the preprocessor directive #include "HEADERNAME.h/hpp" In your case: #include "Employee.h", if your header file is called like that. You used so called "Include/Header guards" which are used to prevent multiple header inclusions. Those should be put in the respective header file, not in other header files that include it. Alternatively you can use #pragma once. It's non-standard, but should be widely supported. For your strings you wanna address the namespace std as such: std::string