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
69,516,690
69,516,912
Matlab and Eigen eigenvectors differ only by the sign
I am working with a project which consists in translating Matlab code to C/C++. At one point I have to calculate the eigenvectors of a matrix, in Matlab this is done using the eig function while in C++ I use EigenSolver from the Eigen library. The problem is that some eigenvectors (apparently random) have the opposite sign compared with the equivalent Matlab one and this could be a problem in my application. I know that eigenvectors are not unique, so is there any method to know which eigenvectors will have the sign changed and correct it simply multiplying by -1?
According to the documentation of eig, the sign of the eigenvectors is not guaranteed to be consistent between MATLAB releases and/or machines used: Different machines and releases of MATLAB® can produce different eigenvectors that are still numerically accurate: For real eigenvectors, the sign of the eigenvectors can change. For complex eigenvectors, the eigenvectors can be multiplied by any complex number of magnitude 1. Thus replicating what MATLAB does is not possible, because it is not defined. However, if you want to modify both the MATLAB code and the C++ code, then you can force the eigenvectors to be in a specific hemicircle/hemisphere, for example by requiring that the first component be positive (multiply the vector by -1 if the x-component is negative). I think this should be sufficient to get consistent results.
69,517,158
69,517,205
Trouble with GLSL dot product
So I was trying to implement basic diffuse lighting using OpenGL. I wrote a simple shader that would take a normal vector and a light vector and calculate the brightness of a pixel using the dot product of said vectors. Here are my outputs: Light coming from the left ([1, 0, 0] as light vector) Light coming down ([0, -1, 0] as light vector) Light coming from behind ([0, 0, 1] as light vector) As you can see, it works just fine for the first two cases, but it completely breaks for the third. By the way, [0, 0, -1] doesn't work either and [0, 1, 1] gives the same output as if the light was coming up ([0, 1, 0]). Here are my shaders : Vertex shader: #version 330 core layout (location = 0) in vec3 aPos; layout (location = 1) in vec3 aNormal; uniform mat4 model; uniform mat4 view; uniform mat4 projection; uniform vec3 lightDirection; out vec3 normal; out vec3 lightDir; void main() { normal = normalize(aNormal); lightDir = normalize(lightDirection); gl_Position = projection * view * model * vec4(aPos, 1.0f); } Fragment shader: #version 330 core in vec3 normal; in vec3 lightDir; out vec4 FragColor; void main() { float grey = max(dot(-lightDir, normal), 0.0f); FragColor = vec4(grey, grey, grey, 1.0f); } I assume the issue has something to do with the dot product, but I can't find why.
The diffuse light is calculated using the formula max(dot(-lightDir, normal), 0.0f);. So if dot (-lightDir, normal) is less than 0, the scene is completely black. The Dot product of 2 Unit vector is the cosine of the angle between the 2 vectors. Hence, if the angle is > 90° and < 270° the result is less than 0. This means, that when the object is lit at the back, it will appear completely black. The light direction is a vector in world space. dot(-lightDir, normal) only makes sense if normal is also a vector in world space. Transform normal from model space to world space: normal = inverse(transpose(mat3(model))) * normalize(aNormal); (Why transforming normals with the transpose of the inverse of the modelview matrix?)
69,517,191
69,533,886
CMake - Create executable for all *.cpp file in folder
I have this folder tree: benchmark/ ├─ pair/ │ ├─ benchmark_create.cpp │ ├─ benchmark_insert.cpp │ ├─ benchmark_remove.cpp ├─ set/ ├─ CMakeLists.txt And this is my current CMakeLists.txt file content: add_executable(dbg_pair_creation pair/benchmark_creation) target_link_libraries(pair_creation benchmark::benchmark) add_executable(dbg_pair_insert pair/benchmark_insert) target_link_libraries(pair_insert benchmark::benchmark) add_executable(dbg_pair_remove pair/benchmark_remove) target_link_libraries(pair_remove benchmark::benchmark) There is a compacxt way to do the same and to put this executable in a folder with name pair that is the folder name of the source?
You could use a foreach loop. set(benchmarks creation insert remove) foreach (benchmark IN LISTS benchmarks) add_executable(dbg_pair_${benchmark} pair/benchmark_${benchmark}.cpp) target_link_libraries(dbg_pair_${benchmark} PRIVATE benchmark::benchmark) set_property( TARGET dbg_pair_${benchmark} PROPERTY RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/dbg_pair_${benchmark}" ) endforeach () Then you would just need to add to the benchmarks list when you add a new benchmark.
69,517,456
69,517,646
How can I check(checkV) if a value exists in Binary search tree if does I output "true" else "false"
How can I check(checkV) if a value exists in Binary search tree if does I output "true" else "false" void search(Node* root, int checkV){ if(checkV > root->data){ search(root->right, checkV); } if(checkV < root->data){ search(root->left, checkV); } if(checkV == root->data){ cout << "true"<<endl; } else{ cout << "false"<<endl; } }
If you need to use function "search", then first you should check if root points the nullptr, then if you found data and only after that you should search. Something like this: void search(Node* root, int checkV) { if (root->data == nullptr) { cout << "false" << endl; } else if (checkV == root->data) { cout << "true" << endl; } else if (checkV > root->data) { search(root->right, checkV); } else { search(root->left, checkV); } } But it would be better, if you return bool from search and print result according to that bool search(Node *root, int checkV) { if (root == nullptr) return false; if (root->data == checkV) return true; return root->data < checkV ? check(root->left, checkV) : check(root->right, checkV); }
69,517,663
69,517,832
Correct parameter char *[] to call function?
I am trying to implement bubble sort the function bubbleSort(names, size) and test it with my driver code. I get error on the driver code when I call the function. I would like to know how to set the first parameter correctly when I call the function. I get two errors which is related to the first parameter "names". Error (active) E0167 argument of type "char *" is incompatible with parameter of type "char **" Error C2664 'void bubbleSort(char *[],const int)': cannot convert argument 1 from 'char [8]' to 'char *[]' I am using Windows 10 Pro (64 bit) with Visual Studio Community 2019. Thank you in advance for your help. #include <iostream> #include <string.h> using namespace std; enum Bool { TRUE, FALSE }; void bubbleSort(char *names[], const int size) { Bool swapped; char* temp; for (int i = 0; i < size; ++i) { swapped = FALSE; for (int j = 0; j < size - i - 1; ++j) { if (names[j] > names[j + 1]) { temp = names[j]; names[j] = names[j + 1]; names[j + 1] = temp; swapped = TRUE; } } // if no two elements were swapped by inner loop, then break if (swapped == FALSE) { break; } } } int main() { char names[] = {'s', 'a', 'c', 'd', 'i', 'd', 'm', 'o'}; int size = 8; bubbleSort(names, size); // i get error here for 'names' for (int i = 0; i < size; ++i) cout << names[i] << " " << endl; }
Your sort function wants an array of C-strings, but you are passing it an array of characters. Hence the error. To sort an array of characters, try this: #include <iostream> using namespace std; void bubbleSort(char names[], const int size) { bool swapped; char temp; for (int i = 0; i < size; ++i) { swapped = false; for (int j = 0; j < size - i - 1; ++j) { if (names[j] > names[j + 1]) { temp = names[j]; names[j] = names[j + 1]; names[j + 1] = temp; swapped = true; } } // if no two elements were swapped by inner loop, then break if (!swapped) { break; } } } int main() { char names[] = {'s', 'a', 'c', 'd', 'i', 'd', 'm', 'o'}; int size = 8; bubbleSort(names, size); for (int i = 0; i < size; ++i) cout << names[i] << " " << endl; } Alternatively, to sort an array of C-strings, try this: #include <iostream> #include <cstring> using namespace std; void bubbleSort(const char* names[], const int size) { bool swapped; const char* temp; for (int i = 0; i < size; ++i) { swapped = false; for (int j = 0; j < size - i - 1; ++j) { if (strcmp(names[j], names[j + 1]) > 0) { temp = names[j]; names[j] = names[j + 1]; names[j + 1] = temp; swapped = true; } } // if no two elements were swapped by inner loop, then break if (!swapped) { break; } } } int main() { const char* names[] = {"s", "a", "c", "d", "i", "d", "m", "o"}; int size = 8; bubbleSort(names, size); for (int i = 0; i < size; ++i) cout << names[i] << " " << endl; }
69,517,813
69,517,948
Iterate a string until int or char
I want to make to two vectors from a string. from : std::string input = "82aw55beA1/de50Ie109+500s"; to : std::vector<int> numbers = {82,55,1,50,109,500}; std::vector<char> notNumbers = {'a','w','b','e','A','/','d','e','I','e','+','s'}; How do I do this in the most efficient time complexitie?
You can make one pass over the string. You need to know if you're currently parsing a digit or not, whether you're "in" a number, and the current number you're in. It's a pretty straightforward process, but if you have questions, please ask. #include <string> #include <vector> #include <iostream> #include <cctype> int main() { std::string input = "82aw55beA1/de50Ie109+500s"; std::vector<int> numbers; std::vector<char> notNumbers; int currentNumber = 0; bool inNumber = false; for (auto ch : input) { if (std::isdigit(ch)) { if (!inNumber) { currentNumber = 0; inNumber = true; } currentNumber = currentNumber * 10 + (ch - '0'); } else { if (inNumber) { numbers.push_back(currentNumber); inNumber = false; } notNumbers.push_back(ch); } } if (inNumber) { numbers.push_back(currentNumber); } for (auto i : numbers) { std::cout << i << std::endl; } for (auto ch : notNumbers) { std::cout << ch << std::endl; } }
69,517,845
69,517,921
LEAKER: errors found! memory was not deallocated
I keep getting the same error: LEAKER: errors found! Leaks found: 2 allocations (48 bytes). unknown:unknown():0 memory leak: memory was not deallocated. unknown:unknown():0 memory leak: memory was not deallocated. I keep checking my destructor and my Clear() function, but I can't figure out what I am missing. I know I should delete something but I can't figure out what I am supposed to delete. When I try to delete head or tail, I get an error saying the pointer was never allocated. Please help!
This is a lot to digest, but at least one source of error here is likely that you have class LinkedList { ... private: Node* head = new Node; // Node pointer for the head Node* tail = new Node; // Node pointer for the tail unsigned int count; } And then in your constructor LinkedList<T>::LinkedList() { // Default Constructor count = 0; head = nullptr; tail = nullptr; } So you're causing the default initializer to invoke new, which is performing a heap allocation. And then in the constructor body, you overwrite these pointers with nullptr! This is immediately a leak, you now have no reference to those heap-allocated objects, and can't free the memory. The first thing I would try here is to just change your header code to class LinkedList { ... private: Node* head = nullptr; // Node pointer for the head Node* tail = nullptr; // Node pointer for the tail unsigned int count = 0; } And then refactor your constructors (they no longer need to set the pointers to nullptr or your count to 0). Even better, for your default constructor you can then just declare it as // Default Constructor LinkedList() = default;
69,517,879
69,522,013
Install tesseract + openCV Cmake C++
I've been trying to install Tesseract under OpenCV for a very long time now. Earlier I built OpenCV using CMake-gui and connected Contrib successfully. Now I can use add. libraries. I have cloned tesseract and leptonica repasitories. And I tried to connect it in the same way as Contrib, but nothing came of it .... I also tried to install Tesseract OCR and added it to Path, in the console I can use the Tess OCR functions, but this also did not help me build Opencv + Tesseract. I am writing under QT 5.15. After building OpenCV, I was unable to run the CMake project in QT, so I built a Qmake file using include ("libraries").
Is tesseract build included in opencv, or can you use already installed tesseract ? I strongly suggest to use the latest tesseract (a.k.a 5.0) (even not released yet) - there is plenty improvement and fixes especially for cmake build. AFAIK API calls are the same as in 4.x, so when you COMPILE opencv against it, it should work. Tesseract&leptonica cmake builds are easy on windows: just see some available tutorials like: https://bucket401.blogspot.com/2021/03/building-tesserocr-on-ms-windows-64bit.html (untill tesserocr installation part) or https://spell.linux.sk/building-tesseract-and-leptonica-with-cmake-and-clang-on-windows
69,517,894
69,518,411
Cannot play mp3 with mciSendString in C++ console application
I'm trying to play an mp3 file from a win32 C++ console application. From what I've read online, mciSendString is the API I'm looking for, and I expected the following to work but it doesn't. #include <cstdio> #include <array> #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <mmsystem.h> using namespace std; #pragma comment(lib, "Winmm.lib") int main() { std::array<char, MAXERRORLENGTH> errorString; mciGetErrorStringA( mciSendStringA( "open \"C:\\path\\to\\1_.mp3\" type mpegvideo alias click1", nullptr, 0, nullptr), errorString.data(), MAXERRORLENGTH); std::printf("%s\n", errorString.data()); mciGetErrorStringA( mciSendStringA("play click1", nullptr, 0, nullptr), errorString.data(), MAXERRORLENGTH); std::printf("%s\n", errorString.data()); } I created a new C++ console application in Visual Studio 2019, built this code, and ran it from the console. It prints: The specified command was carried out. The specified command was carried out. And in my headphones I hear a brief pop, but that's it. What could be happening? Do I first need to configure an audio device? Set the volume?
Your program is ending after you invoke the mci command. The music is going to stop playing when the process exits. Simply add something to the end of the program to keep it from exiting. Instead of this: std::printf("%s\n", errorString.data()); } This: std::printf("%s\n", errorString.data()); printf("press ctrl-c to exit"); while (1) { Sleep(1000); } }
69,517,949
69,518,007
I have a problem with array pointers (c++) in therms of functions
I'm new to pointers, and want to learn them. I created a script that should adopt Python's len() function for arrays to get the size of them for learning reasons. So I wrote the following code: int len(int *arrPtr){ int arrSize = *(&arrPtr + 1) - arrPtr; return arrSize; } int main(){ int arr[] = {1,2,3,4,5}; int lenArr = len(arr); cout << "lenght of array: " << lenArr; } When I execute the code, I get a random number: I tried to find the solution but I failed. I found out that by increasing the array's pointer index address by 1, I get a different address, when inside the function or outside the function. In the main() function, the same code works. #include <iostream> using namespace std; int len(int *arrPtr){ cout << "inside func: " << arrPtr << endl; cout << "inside func: " << &arrPtr + 1 << '\n' << endl; int arrSize = *(&arrPtr + 1) - arrPtr; return arrSize; } int main(){ int arr[] = {1,2,3,4,5}; cout << "outside func: " << arr << endl; cout << "outside func: " << &arr + 1 << '\n' << endl; int lenArr = len(arr); cout << "lenght of array: " << lenArr; } Here is the code with the outputs of the changing address: terminal output: outside func: 0x1f961ffb90 outside func: 0x1f961ffba4 inside func: 0x1f961ffb90 inside func: 0x1f961ffb78 lenght of array: 444072222 and there is the output, as we can see the addresses change differently: I hope someone can give me a solution.
This is how you can handle array sizes : #include <array> #include <iostream> //using namespace std; // don't do this. template<std::size_t N> void function(const int(&arr)[N]) { std::cout << "std::array from function, len = " << N << "\n"; std::cout << "arr[2] = " << arr[2] << "\n"; } void function2(const std::array<int, 5>& arr) { std::cout << "std::array from function2, len = " << arr.size() << "\n"; std::cout << "arr[2] = " << arr[2] << "\n"; } int main() { int arr[] = { 1,2,3,4,5 }; auto len1 = sizeof(arr) / sizeof(int); // do it where the size of the array is still known. std::cout << "len 1 = " << len1 << "\n"; function(arr); // or use std::array which behaves more like any other class // and which always knows its size std::array<int, 5> arr2{ 1,2,3,4,5 }; std::cout << "std::array len = " << arr2.size() << "\n"; function2(arr2); }
69,518,014
69,518,050
Problem with some hidden == operand when erasing shared_ptr from a vector
I wrote this AddressBook program in C++ as an exercise, and everything works fine except the removeContact method. The compiler (MSVC) reports an issue related, I think, to some sort of incompatible right operand with a == operator. Here's the compiler output: error C2679: binary '==': no operator found which takes a right-hand operand of type 'std::shared_ptr<Contact>' (or there is no acceptable conversion) note: could be 'bool std::_Vector_const_iterator<std::_Vector_val<std::_Simple_types<_Ty>>>::operator ==(const std::_Vector_const_iterator<std::_Vector_val<std::_Simple_types<_Ty>>> &) noexcept const' [synthesized expression 'y == x'] with [ _Ty=Database::ContactPtr ] note: while trying to match the argument list '(std::shared_ptr<Contact>, const _Ty)' with [ _Ty=std::_Vector_iterator<std::_Vector_val<std::_Simple_types<Database::ContactPtr>>> ] note: see reference to function template instantiation '_FwdIt std::remove<std::shared_ptr<Contact>*,_Uty>(_FwdIt,const _FwdIt,const _Ty &)' being compiled with [ _FwdIt=std::shared_ptr<Contact> *, _Uty=std::_Vector_iterator<std::_Vector_val<std::_Simple_types<Database::ContactPtr>>>, _Ty=std::_Vector_iterator<std::_Vector_val<std::_Simple_types<Database::ContactPtr>>> ] note: see reference to function template instantiation 'unsigned int std::_Erase_remove<std::vector<Database::ContactPtr,std::allocator<Database::ContactPtr>>,_Uty>(_Container &,const _Uty &)' being compiled with [ _Uty=std::_Vector_iterator<std::_Vector_val<std::_Simple_types<Database::ContactPtr>>>, _Container=std::vector<Database::ContactPtr,std::allocator<Database::ContactPtr>> ] note: see reference to function template instantiation 'unsigned int std::erase<Database::ContactPtr,std::allocator<Database::ContactPtr>,std::_Vector_iterator<std::_Vector_val<std::_Simple_types<_Ty>>>>(std::vector<_Ty,std::allocator<_Ty>> &,const _Uty &)' being compiled with [ _Ty=Database::ContactPtr, _Uty=std::_Vector_iterator<std::_Vector_val<std::_Simple_types<Database::ContactPtr>>> I don't know if the issue is something really simple, but this report is cryptic. Here's the code: #include "Database.h" #include "ContactNotFoundException.h" void Database::addContact(const Contact &contact) { contacts.push_back(std::make_shared<Contact>(contact)); } void Database::removeContact(const Contact &contact) { removeContact(findContact(contact.getName())); } void Database::removeContact(std::string_view name) { removeContact(findContact(name)); } void Database::removeContact(const size_t index) { auto iterator{contacts.begin()}; iterator += static_cast<int>(contacts.size() - index); std::erase(contacts, iterator); } size_t Database::findContact(std::string_view name) const { // TODO: algorithm for (size_t i = 0; i < contacts.size(); ++i) { if (contacts.at(i)->getName() == name) return i; } throw ContactNotFoundException(); } Database::ContactPtr Database::getContact(std::string_view name) const { return contacts.at(findContact(name)); } void Database::listContacts() const { for (const auto& contactPtr : contacts) { std::cout << contactPtr->getName() << std::endl; } } I also have to clarify that I put the compiler output in a code block because StackOverflow wouldn't let me post the answer, as it detects it as code.
std::erase takes a value which is searched in your container and then removed, not an iterator. Therefore trying to pass an iterator there triggers an error because std::erase is trying to compare your container elements with this iterator, but iterators and elements are normally not comparable. To erase an element you already have an iterator for, you need contacts.erase(iterator) instead.
69,518,490
69,518,582
Generic Linked List error: LinkedList is not a class template
// This is the Node.h file #ifndef NODE #define NODE template <typename T> class Node { private: T elem; Node *next; friend class LinkedList<T>; }; #endif // NODE This is the LinkedLilst.h file #ifndef LINKED_LIST #define LINKED_LIST #include "Node.h" template <typename T> class LinkedList { public: LinkedList(); ~LinkedList(); bool empty() const; const T &front() const; void addFront(const T &e); void removeFront(); private: Node<T> *head; }; #endif // LINKED_LIST This is the LinkedList.cpp file #include <iostream> #include "LinkedList.h" using namespace std; template <typename T> LinkedList<T>::LinkedList() : head(NULL) {} template <typename T> bool LinkedList<T>::empty() const // I don't want it to modify the data member of the function. { return head == NULL; } template <typename T> LinkedList<T>::~LinkedList() { while (!empty()) removeFront(); } ... ... ... This is my main.cpp file #include <iostream> #include "LinkedList.h" using namespace std; int main() { LinkedList<int> ls; ls.addFront(3); cout << ls.front(); return 0; } I don't know why I am getting the error: 'LinkedList' is not a class template friend class LinkedList<T>; in Node.h The problem is that Node.h file doesn't have anything related to LinkedList. I added LinkedList Declaration but it still showing errors. Please help.
You need to forward declare the LinkedList class template: #ifndef NODE #define NODE template<class> class LinkedList; // <- forward declaration template <typename T> class Node { private: T elem; Node *next; friend class LinkedList<T>; }; #endif // NODE The next problem you are going to run in to is probably a linking problem. I suggest moving the class member functions definitions into the header files. More on that here: Why can templates only be implemented in the header file?
69,518,605
69,718,949
VS Code - automatic namespace name generating
When I format my C++ code, it automatically adds comment with name of the namespace at the end of the namespace. How to turn off this automatically generating namespace comment at the end of the namespace in VS Code ? Example of my code: namespace test { int add(int a, int b) { return a + b; } } // namespace test # i dont want this line
If you're using the C/C++ extension with a recent version of clang-tidy, then they should be turned off by default. It's controlled by the clang-format setting FixNamespaceComments: false. It's possible you're using using another extension to format your code which doesn't have that default or your other clang-format settings are changing the default behavior.
69,519,227
69,520,140
How to calculate all generated permutations correctly and recursion included?
I am currently working on a little program that's supposed to find every combination. Fill the following place holders with digits in the range from 1 to 9. Each digit only appears once and make the equation sum up to 100. _ / _ * _ + _ * _ * _ / _ + _ * _ = 100 #include <bits/stdc++.h> #include <cmath> using namespace std; void print(int arr[], int n){ for (int i = 0; i < n; i++){ cout << arr[i] << " "; } cout << endl; } void findCombos(int arr[], int n){ std::sort(arr, arr + n); do{ if((arr[0] / arr[1] * arr[2] + arr[3] * arr[4] * arr[5] / arr[6] + arr[7] * arr[8]) == 100){ print(arr, n); } }while(next_permutation(arr, arr + n)); } int main(){ int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; int size = sizeof(arr) / sizeof(arr[0]); findCombos(arr, size); return 0; } I generated 900 solutions with this code. Some of the permutations are correct, but some of the combinations do not calculate exactly to 100. My if statement is matching up the operations correctly, but why are the incorrect permutations displaying? As an extension, how can I make this program run recursively?
As PiedPiper already mentioned about the integer division issue, you can simply declare the arr[] as double and it solves the issue. As an extension, you can also calculate the permutations using a recursive way. Please check the function findCombosRecursive() which have similar functionality as findCombos() but making the combinations recursively. The recursive algorithm partitions arr as two parts: the already permuted elements and the remaining unchanged elements. The parameter curr indicates the pivot in between these two parts. Every time we make a swap between the pivot element and the remaining unchanged elements and advance the pivot position by one. Once we reached to the end of the array, we get a new permutation of the array and check whether this permutation satisfy our necessary condition. Do not forget to restore the position after the recursive calls. This will ensure that the pivot position is exchanged with just another remaining elements in a single permutation construction. Here I have shared a sample implementation of constructing the solution recursively: #include <bits/stdc++.h> #include <cmath> using namespace std; void print(double arr[], int n, int sid) { cout << "Solution " << sid << ":"; for (int i = 0; i < n; i++){ cout << " " << arr[i]; } cout << endl; } void findCombosRecursive(double arr[], int size, int curr, int& sid) { if (curr == size) { // base-case of the recursion // check whether the current combination satisfy the following condition: // "_ / _ * _ + _ * _ * _ / _ + _ * _ = 100" if((arr[0] / arr[1] * arr[2] + arr[3] * arr[4] * arr[5] / arr[6] + arr[7] * arr[8]) == 100){ print(arr, size, sid); sid += 1; } } else { for (int i = curr; i < size; i+=1) { swap(arr[i], arr[curr]); findCombosRecursive(arr, size, curr + 1, sid); // placing next position swap(arr[i], arr[curr]); // restoring } } } void findCombos(double arr[], int n){ std::sort(arr, arr + n); int i = 0; do{ if((arr[0] / arr[1] * arr[2] + arr[3] * arr[4] * arr[5] / arr[6] + arr[7] * arr[8]) == 100){ print(arr, n, i); i += 1; } } while(next_permutation(arr, arr + n)); } int main(){ double arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; int size = sizeof(arr) / sizeof(arr[0]); int sid = 0; findCombosRecursive(arr, size, 0, sid); // findCombos(arr, size); return 0; }
69,519,672
69,519,771
2 int8_t's to uint16_t and back
I want to support some serial device in my application. This device is used with another program and I want to interact with both the device and the save files this program creates. Yet for some yet to be discovered reason, weird integer casting is going on. The device returns uint8's over a serial USB connection, the program saves them as int8 to a file and when you read the file, you need to combine 2 int8's to a single uint16. So when writing the save-file after reading the device, i need to convert an int8 to uint8, resulting in any value higher then 127 to be written as a negative. Then when I read the save file, I need to combine 2 int8's into a single uint16. (So convert the negative value to positive and then stick them together) And then when I save to a save file from within my application, I need to split my uint16 into 2 int8's. I need to come up with the functions "encode", "combine" and "explode" // When I read the device and write to the save file: uint8_t val_1 = 255; int8_t val_2 = encode(val_1); REQUIRE(-1 == val_2); // When I read from the save file to use it in my program. int8_t val_1 = 7; int8_t val_2 = -125; uint16_t val_3 = combine(val_1, val_2); REQUIRE(1923 == val_3); // When I export data from my program to the device save-file int8_t val_4; int8_t val_5; explode(val_3, &val_1, &val_2); REQUIRE(7 == val_4); REQUIRE(-125 == val_5); Can anyone give me a head start here?
Your encode method can just be an assignment. Implicit conversion between unsigned integer types and signed integer types is well defined. uint8_t val_1 = 255; int8_t val_2 = val_1; REQUIRE(-1 == val_2); As for combine - you'll want to cast your first value to a uint16_t to ensure you have enough bits available, and then bitshift it left by 8 bits. This causes the bits from your first value to make up the 8 most significant bits of your new value (the 8 least significant bits are zero). You can then add your second value, which will set the 8 least significant bits. uint16_t combine(uint8_t a, uint8_t b) { return ((uint16_t)a << 8) + b; } Explode is just going to be the opposite of this. You need to bitshift right 8 bits to get the first output value, and then just simply assign to get the lowest 8 bits. void explode(uint16_t from, int8_t &to1, int8_t &to2) { // This gets the lowest 8 bits, and implicitly converts // from unsigned to signed to2 = from; // Move the 8 most significant bits to be the 8 least // significant bits, and then just assign as we did // for the other value to1 = (from >> 8); } As a full program: #include <iostream> #include <cstdint> using namespace std; int8_t encode(uint8_t from) { // implicit conversion from unsigned to signed return from; } uint16_t combine(uint8_t a, uint8_t b) { return ((uint16_t)a << 8) + b; } void explode( uint16_t from, int8_t &to1, int8_t &to2 ) { to2 = from; to1 = (from >> 8); } int main() { uint8_t val_1 = 255; int8_t val_2 = encode(val_1); assert(-1 == val_2); // When I read from the save file to use it in my program. val_1 = 7; val_2 = -125; uint16_t val_3 = combine(val_1, val_2); assert(1923 == val_3); // When I export data from my program to the device save-file int8_t val_4; int8_t val_5; explode(val_3, val_4, val_5); assert(7 == val_4); assert(-125 == val_5); } For further reading on bit-manipulation mechanics, you could take a look here.
69,519,732
69,519,843
Make new instance of the template class of a c++ object
So if I have template <class T> class Object { // stuff }; and I receive an instance of object in a function I want to call the constructor of class T. void foo(Object object) { auto newT = object::T(); } Is this possible?
Typically the best solution is to template the inner type: template <class T> void foo(Object<T> object) { T newT; } However, sometimes (with more meta-programming) this sort of solution will be more verbose than the alternatives: Option 1: store the template variable in the Object class: template <class T> class Object { // stuff public: using inner_type = T; }; Then you can access the template type like so: template <class Obj> void foo(Obj object) { typename Obj::inner_type newT; } Option 2: make a type trait (no need to add inner_type to Object): template <class T> struct tag { using type = T; }; template <class> struct inner; template <template <class> class S, class T> struct inner <S<T>> : tag<T> {}; template <typename T> using inner_t = typename inner<T>::type; Which you can then use like so: template <class Obj> void foo(Obj object) { inner_t<Obj> newT; } It's probably best to generalise inner_type to take the first inner argument so that it could handle template types with more arguments, like std::vector (second argument has a default): template <class> struct front; template <template <class, class...> class R, class S, class ... Ts> struct front <R<S, Ts...>> : tag<S> {}; template <typename T> using front_t = typename front<T>::type; Demo
69,520,116
69,520,143
Reverse string using pointer arithmetic
I am trying to understand how the below function *reverseString(const char *str) reverses the string with pointer arithmetic. I have been Googling and watched videos which handle similar cases but unfortunately they didn't help me out. Could you please somebody help me what may be missing for me to understand how this function works? I am using Windows 10 Pro (64 bit) with Visual Studio Community 2019. Thank you in advance for your help as always. I appreciate it. #include <iostream> #include <cstring> using namespace std; char *reverseString(const char *str) { int len = strlen(str); // length = 10 char *result = new char[len + 1]; // dynamically allocate memory for char[len + 1] = 11 char *res = result + len; // length of res = 11 + 10 = 21? *res-- = '\0'; // subtracting ending null character from *res ? while (*str) *res-- = *str++; // swapping character? return result; // why not res? } int main() { const char* str = "Constantin"; cout << reverseString(str) << endl; }
char *result = new char[len + 1]; This line allocates a new string (length of the other string's characters, plus one for the terminating null), and stores it in result. Note that result points to the beginning of the string, and is not modified. char *res = result + len; This line is making res point to the end of result: res is a pointer that equals the address of result, but len characters after. *res-- = '\0'; This line: writes a terminating NULL to res, which currently points to the end of result, and decrements res so that it now points to the previous character of result while (*str) *res-- = *str++; // swapping character? These lines: loop until str points to a NULL write the character pointed to by str to the destination memory pointed to by res, and res--: decrement res to point to the previous location in memory, and str++: increment str to point to the next character of str return result; // why not res? Result is returned because it points to the (beginning of) the new string.
69,520,633
70,339,311
"Undefined symbols" of shrink_to_fit() when compiling Cronet on iOS 15 with Xcode 13
Error message: Undefined symbols for architecture arm64: "std::__1::basic_string<unsigned short, base::string16_internals::string16_char_traits, std::__1::allocator<unsigned short> >::shrink_to_fit()", referenced from: base::UTF8ToUTF16(char const*, unsigned long, std::__1::basic_string<unsigned short, base::string16_internals::string16_char_traits, std::__1::allocator<unsigned short> >*) in libbase.a(utf_string_conversions.o) base::WideToUTF16(wchar_t const*, unsigned long, std::__1::basic_string<unsigned short, base::string16_internals::string16_char_traits, std::__1::allocator<unsigned short> >*) in libbase.a(utf_string_conversions.o) ld: symbol(s) not found for architecture arm64 subprocess.CalledProcessError: Command '['clang++', '-B', '/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/', '-shared', '-Xlinker', '-install_name', '-Xlinker', '@rpath/Cronet.framework/Cronet', '-Xlinker', '-objc_abi_version', '-Xlinker', '2', '-arch', 'arm64', '-Werror', '-isysroot', '/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS15.0.sdk', '-stdlib=libc++', '-miphoneos-version-min=8.0', '-fembed-bitcode', '-Wl,-ObjC', '-o', 'obj/components/cronet/ios/arm64/Cronet', '-Wl,-filelist,obj/components/cronet/ios/arm64/Cronet.rsp', '-framework', 'UIKit', '-framework', 'CoreFoundation', '-framework', 'CoreGraphics', '-framework', 'CoreText', '-framework', 'Foundation', '-framework', 'JavaScriptCore', '-framework', 'CFNetwork', '-framework', 'MobileCoreServices', '-framework', 'Security', '-framework', 'SystemConfiguration', '-lresolv']' returned non-zero exit status 1
This was pretty tricky to track down, but I think I found the issue. First of all, string16.ii can be simplified to: template <class T> struct basic_string { __attribute__((internal_linkage)) void shrink_to_fit(); }; template <class T> void basic_string<T>::shrink_to_fit() { } template class basic_string<char>; utf_string_conversions.ii can be simplified to: template <class T> struct basic_string { __attribute__((internal_linkage)) void shrink_to_fit(); }; template <class T> void basic_string<T>::shrink_to_fit() { } extern template class basic_string<char>; int main() { basic_string<char> s; s.shrink_to_fit(); } Since shrink_to_fit has internal linkage, the compiler doesn't even bother emitting it inside string16.o, because it is not used in that TU. If it did emit it in string16.o, it would be dead code since no other TU can refer to it anyway. Then, from utf_string_conversions.o, we see an extern template instantiation declaration, which basically promises that we will be able to find shrink_to_fit() in some other TU (presumably string16.o). Of course, that can't be the case, since another TU can't "export" shrink_to_fit, which has internal linkage as explained above. As a result, we end up in a situation where utf_string_conversions.o expects to see shrink_to_fit() in some other TU, but the other TU that should provide it doesn't. Furthermore, if we compile the above, we can actually see that the compiler is warning us from exactly that: <stdin>:4:10: warning: function 'basic_string<char>::shrink_to_fit' has internal linkage but is not defined [-Wundefined-internal] void shrink_to_fit(); ^ <stdin>:14:7: note: used here s.shrink_to_fit(); ^ 1 warning generated. Undefined symbols for architecture x86_64: "basic_string<char>::shrink_to_fit()", referenced from: _main in main.o ld: symbol(s) not found for architecture x86_64 This warning does not show up in the original code because warnings inside system headers are suppressed. This really tripped me up initially, and I think it would make sense for the compiler to warn if the explicit template instantiation declaration appears outside of a system header, regardless of whether the class itself is declared inside a system header. I actually removed the system header directives from the original reproducer and I was able to get the same warning, see this. Now, you might be wondering why that doesn't happen with other methods of basic_string? Well, apparently, most if not all other methods of basic_string are either defined inside the class (and are hence implicitly inline), or defined outside the class but marked with inline explicitly, or not marked with __attribute__((internal_linkage)) I believe that's the reason why this issue is only showing up with shrink_to_fit(): it is a non-inline function because it is defined outside its class definition, despite the class being a template. Concretely: Chromium should consider removing their explicit instantiation -- those are brittle, as explained here. I will fix libc++'s shrink_to_fit() so it is inline. (edit: here) I will file a Clang bug to discuss the possibility of emitting that warning when the explicit template instantiation declaration appears outside of a system header. (edit: here) Thanks for reporting this tricky issue.
69,520,659
69,522,147
C++ Pointers and Memory Allocation
I am taking a C++ class in school and was give a few lines of code with errors and I'm having trouble finding all 4 errors. The code is supposed to print the number "302" I'm not good with pointers. Here is the code int main () { int* ptr; int* temp; int x; ptr = int; *ptr = 3; cout << ptr << endl; x=0; temp = x; cout<<*temp<< endl; ptr = int; *ptr = 2; cout<<*ptr-*temp <<endl; return 0; } The two errors i have found so far are cout and endl need to have ::std in front of them temp = x needs to be a pointer, *temp = x
Other answers already pointed out the problems, their explanation and a possible solution, except for problem in this: temp = x needs to be a pointer, *temp = x No, you are wrong here. Pointer temp is uninitialised and dereferencing an uninitialised pointer (*temp) will lead to Undefined Behaviour. Two ways you can solve it: First, allocate memory to temp temp = new int; and then you can do this *temp = x; In this, the memory allocated to temp will have an independent copy of value of x. Make any changes to value of x does not reflect in the content of memory pointed by temp pointer and vice versa. Make sure to deallocate the storage allocated to temp, once you done with it because the memory it is pointing to is allocated dynamically. Second, assign address of x to temp pointer temp = &x; temp pointer is pointing to x. Make any changes to the value of x and *temp will give the current value of x and vice versa. No need to deallocate the temp because the memory it is pointing to is not allocated dynamically.
69,520,866
69,521,176
How to construct a std::optional of a struct with std::shared_ptr
I'm trying to create an optional with a class that has a shared_ptr but the implicitly deleted constructor prevents me from using make_optional to create it. Is the only option to manually write that constructor? Here is a simple reproduction: https://onlinegdb.com/DcWzF1NAt #include <optional> #include <memory> class A { public: A(int v): val{v} {} int val; }; class B { public: B(std::shared_ptr<A>& a): a{a} {} const std::shared_ptr<A> a; }; int main() { std::shared_ptr<A> a = std::make_shared<A>(3); std::optional<B> b; b = std::make_optional<B>(a); } causes this compile error main.cpp:31:30: error: use of deleted function ‘std::optional& std::optional::operator=(std::optional&&)’ b = std::make_optional<B>(a); ^ In file included from main.cpp:4:0: /usr/include/c++/7/optional:453:11: note: ‘std::optional& std::optional::operator=(std::optional&&)’ is implicitly deleted because the default definition would be ill-formed: class optional ^~~~~~~~ /usr/include/c++/7/optional:453:11: error: use of deleted function ‘std::_Enable_copy_move& std::_Enable_copy_move::operator=(std::_Enable_copy_move&&) [with _Tag = std::optional]’ In file included from /usr/include/c++/7/optional:43:0, from main.cpp:4: /usr/include/c++/7/bits/enable_special_members.h:246:5: note: declared here operator=(_Enable_copy_move&&) noexcept = delete; ^~~~~~~~
It's not an implicitly deleted constructor causing a problem, it's the implicitly deleted copy assignment operator and has nothing to do with std::shared_ptr, it's because you've declared the B::a member to be const. The solution here is to not mark it as const: class B { public: B(std::shared_ptr<A>& a): a{a} {} std::shared_ptr<A> a; }; The reason the compiler deletes the copy assignment operator is because it has to be able to modify that member; we can see this with a slightly simpler example: class NoCopyAssign { public: NoCopyAssign(int a) : mA(a) {} private: const int mA; }; Ordinarily, the copy assignment operator would be roughly equivalent to this: NoCopyAssign &operator=(const NoCopyAssign &other) { mA = other.mA; return *this; } But this is impossible because mA is a const int, so you can't change its value. };
69,520,994
69,522,912
Is there a way to enable UNICODE formatting in Dev C++
This question has never been asked before. I am using Dev C++ version 5.11. so, I was surfing across youtube for game libraries, and I came across olcConsoleGameEngine.h. I do not like to use Visual C++ for some particular reasons, and olcConsoleGameEngine.h requires UNICODE support. This is not supported in Dev C++ by default. I burned through the dev c++ Manual but came nothing related to UNICODE support. So here I ask you, how to allow UNICODE formatting and UNICODE compiling in Dev C++. I've tried running olcConsoleGameEngine.h and I receive the following error: 127 2 [Error] Please enable UNICODE for your compiler! VS: Project Properties -> General -> Character Set -> Use Unicode. Thanks! - Javidx9 The following error says the options to enable UNICODE for VS, however I am not using VS, and I need a way to enable it for Dev C++. Help me and thanks in advance.
The "enable UNICODE" option is just a convenience to make sure #define UNICODE happens before #include windows. There's no magic.
69,521,679
69,523,288
Binary Strings are Printed Backwards
I have tried to search for a way to make bit representation of a variable work using macro. The code prints the binary strings backward as I am relatively new to c++ I thought it was the indexing that was the problem as it needs to start high and then count down. #include <iostream> #include <memory> #include <climits> #define EXTRACTBIT(ith,ch)(std::cout<<((*ch >> ith) & 1 ? 1 : 0)) template < typename T > void printlnbits (T v) { const int s = sizeof (T) * CHAR_BIT; auto const bytes_begining{reinterpret_cast<unsigned char const *>(std::addressof(v))}; auto byte{bytes_begining}; auto bit_index_in_byte{0}; for (int n = s - 1; n >=0; --n) { EXTRACTBIT(bit_index_in_byte, &(*byte)); ++bit_index_in_byte; if (CHAR_BIT == bit_index_in_byte){ std::cout << " "; bit_index_in_byte = 0; ++byte; } } std::cout << " " << s << " bits" << std::endl; } int main () { const char a = 'a'; const char b = 2; printlnbits (a); printlnbits (b); return 0; } Result: bit_index_in_byte = 0; ++bit_index_in_byte; 10000110 8 bits //correct 01100001 01000000 8 bits //correct 00000010 bit_index_in_byte = 8; --bit_index_in_byte; 00110000 8 bits //correct 01100001 00000001 8 bits //correct 00000010 What I have tried has failed, the first one is correct but backward, and the other is incorrect. I would also like to add that any help or other suggestions to simplify the solution would be appreciated
As -500 mentioned in the comment you should have the right result if you start with 7 like this auto bit_index_in_byte{7}; for (int n = s - 1; n >=0; --n) { EXTRACTBIT(bit_index_in_byte, &(*byte)); --bit_index_in_byte; if (-1 == bit_index_in_byte) { std::cout << " "; bit_index_in_byte = 7; ++byte; } }` Result: 01100001 8 bits 00000010 8 bits
69,521,734
69,523,524
Vector product of multiple vectors using meta function
Given a vector like: template<int... elements> struct vec; How is it possible to create a metafunction which can do multiply element by element all provided vectors. For example template<typename ...AllVecs> struct multiVecs { using type = .... } where type would execute all products element by element. For example given three vecs: multiVecs< vec<0,1,2>, vec<1,2,3>, vec<2,3,4> > i should get a vec<0*1*2, 1*2*3, 2*3*4>
Let's start with the two vector product, and go from there. template <typename lhs, typename rhs> struct multiplies; template <int... lhs, int... rhs> struct multiplies<vec<lhs...>, vec<rhs...>> { static_assert(sizeof...(lhs) == sizeof...(rhs), "Vector arity mismatch"); using type = vec<(lhs * rhs)...> }; template <typename lhs, typename rhs> using multiplies_t = typename multiplies<lhs, rhs>::type; This works fine, so now we just fold it over the pack. Unfortunately C++14 doesn't have fold expressions, so we have to do it longhand. template <typename...> struct multiVecs; template <typename... Ts> using multiVecs_t = typename multiVecs<Ts...>::type; template <typename result> struct multiVecs<result> { using type = result; }; template <typename first, typename second, typename... rest> struct multiVecs<first, second, rest...> { using type = multiVecs_t<multiplies<first, second>, rest...>; }; This is also fine
69,521,906
69,522,002
Random value at time of output
I have written this recursive function in C++ that prints array elements, but when I run it I get an extra number as output like 634, 389, etc. Can someone please tell me why this is happening and how can I fix this?
The first call to your function prints out arr[5] to which you didn't assign value so it takes the random value that is in that place in the memory. To fix your issue I would recommend calling function with array size - 1 so in your case func(arr, 4);
69,522,009
69,522,079
How to write functional interface with cmake language?
I found many project with CMake building system will create some_independent_function.CMake. For example, folly and other Facebook library. They use variable like FOLLY_INCLUDE with CMake recommended naming rules to mark input and output for function to find folly project. Obviously it uses implicit variable as output. How could I get some structured information for in and out, like A_Standard_Package_Info_Object, err = package.find_package(Findfolly.cmake) I want some closure feature with CMake. How could I set parameters as input and use return as output? Or could I encapsulate some function into a package rather than use scripts file with implicit variables?
That is not how the CMake language works. It is not designed to have such returns. Implicit variable names is the way to go. Feel free to dislike for this design choices, then you are in good company :-)
69,522,751
69,525,250
C++ string delimiter exception
I'm working on a piece of code and encountered a small problem here. In an overall the problem is with a string delimiter and a splitting of a C++ std::string. The string that I have is: std::string nStr = R"( "0000:ae:05.2: Address: 0000:ae:05.2 Segment: 0x0000 ")"; Normally the above is way larger and has many more data entries. The delimiter I have set is the ": " as it will be the most common delimiter I have in the data. What I aim to get is 2 strings i.e. string1 = Address and string2 = 0000:ae:05.2 but I also need the 1st line to be treated similarly so basically it all should start from string1 = header and string2 = 0000:ae:05.2 My code looks like that at the moment: int main(int argc, char* argv[]) { std::string nStr = R"( "0000:ae:05.2: Address: 0000:ae:05.2 Segment: 0x0000 ")"; std::string tLine1="", tLine2=""; //nStr = nStr.erase(nStr.find_last_not_of("\n\r\t")); const std::string delimiter = ": ", delim2=":"; std::string::size_type pos = nStr.find(delimiter); std::string::size_type pos2 = nStr.find(delim2); if(nStr.npos != pos){ tLine2 = nStr.substr(pos + 1); tLine1 = nStr.substr(0, pos); } else if(nStr.npos != pos2){ tLine1 = nStr.substr(0, pos2); tLine2 = "blank"; } else std::cout << "Delimiter not specified!\n"; What does it works for the "main" delimiter, the ": " and not for the ":". Also it does not read all the ": " delimiters. My output would be: tLine1= "0000:ae:05.2: Address tLine2= 0000:ae:05.2 Segment: 0x0000 Any thoughts on how this can be done correctly? Or how to approach this in a better way? Thanks in advance.
Okay, from what I can understand from your comments, you want to split the original string into lines, and then split the individual lines by using ":" as a delimiter. With the exception for the first line, which only has one value. Thus the resulting pair for this line should have the value from the line and the string literal "header". #include <iostream> #include <string> #include <utility> auto splitLine(const std::string& line) { using namespace std::string_literals; auto delimiterPos = line.find(": "); if (delimiterPos != std::string::npos) { return std::make_pair(line.substr(0, delimiterPos), line.substr(delimiterPos + 2)); } return std::make_pair(line.substr(1, line.size() - 2), "header"s); } int main(int argc, char* argv[]) { std::string nStr = R"( "0000:ae:05.2: Address: 0000:ae:05.2 Segment: 0x0000 ")"; std::size_t newLinePos; do { newLinePos = nStr.find("\n"); std::string line = nStr.substr(0, newLinePos); nStr = nStr.substr(newLinePos + 1); // To ignore empty lines and the last line that just contains a double quote if (line.size() == 0 || line == "\"") { continue; } auto lines = splitLine(line); std::cout << "line1: " << lines.first << "\n"; std::cout << "line2: " << lines.second << "\n"; } while (newLinePos != std::string::npos); } I'm not 100% sure which of the part of each line is considered the first value and which is the second. It seems you're switching this up between the question and each comment. But you should be able to change that according to your desire. Another aspect I did not fully grasp is the layout of the original string. It seems to start with an new line character. And the end with a new line followed by a double quote. I had to catch those specifically. And the first "header" line begins with a double quote and ends with a colon. I just expect this always to be the case and removed the first and last character from said line. It would help if we had a better example for the incoming data.
69,522,878
69,617,244
How to resolve this C6385 code analysis warning: Reading invalid data
I am trying to address a code analysis warning that appears in the following method: CStringArray* CCreateReportDlg::BuildCustomAssignArray(ROW_DATA_S &rsRowData) { INT_PTR iAssign, iNumAssigns, iUsedAssign; CStringArray *pAryStrCustom = nullptr; CUSTOM_ASSIGN_S *psAssign = nullptr; if (rsRowData.uNumCustomToFill > 0) { pAryStrCustom = new CStringArray[rsRowData.uNumCustomToFill]; iNumAssigns = m_aryPtrAssign.GetSize(); for (iAssign = 0, iUsedAssign = 0; iAssign < iNumAssigns; iAssign++) { psAssign = (CUSTOM_ASSIGN_S*)m_aryPtrAssign.GetAt(iAssign); if (psAssign != nullptr) { if (!psAssign->bExcluded) { pAryStrCustom[iUsedAssign].Copy(psAssign->aryStrBrothersAll); iUsedAssign++; } } } } return pAryStrCustom; } The offending line of code is: pAryStrCustom[iUsedAssign].Copy(psAssign->aryStrBrothersAll); I compile this code for both 32 bit and 64 bit. The warning being raised is: Warning (C6385) Reading invalid data from pAryStrCustom: the readable size is (size_t)*40+8 bytes, but 80 bytes may be read. I don't know if it is relevant, but the CUSTOM_ASSIGN_S structure is defined as: typedef struct tagCustomAssignment { int iIndex; CString strDescription; CString strHeading; BOOL bExcluded; CStringArray aryStrBrothersAll; CStringArray aryStrBrothersWT; CStringArray aryStrBrothersSM; BOOL bIncludeWT; BOOL bIncludeTMS; BOOL bFixed; int iFixedType; } CUSTOM_ASSIGN_S; My code is functional (for years) but is there a coding improvement I can make to address this issue? I have read the linked article and it is not clear to me. I have also seen this question (Reading Invalid Data c6385) along similar lines. But in my code I can't see how that applies.
Warning... the readable size is (size_t)*40+8 bytes, but 80 bytes may be read. The wording for this warning is not accurate, because size_t is not a number, it's a data type. (size_t)*40+8 doesn't make sense. It's probably meant to be: Warning... the readable size is '40+8 bytes', but '80 bytes' may be read. This warning can be roughly reproduced with the following example: //don't run this code, it's just for viewing the warning size_t my_size = 1; char* buf = new char[my_size]; buf[1]; //warning C6385: Reading invalid data from 'buf': //the readable size is 'my_size*1' bytes, but '2' bytes may be read The warning is correct and obvious. buf[1] is out of bound. The compiler sees allocation size for buf is my_size*1, and index 1 is accessing byte '2'. I think in other place the compiler prints it incorrectly, but the actual warning is valid. In any case, just make sure iUsedAssign is within range if (!psAssign->bExcluded && iUsedAssign < rsRowData.uNumCustomToFill) { ... }
69,523,092
69,523,741
std::pair gives "no matching function call" error in combination with const std:unique_ptr
I stumbled across a behaviour of std::make_pair that I do not understand. Given the following code #include <iostream> using namespace std; #include <memory> #include <utility> class TestClass { public: TestClass(const std::string& str) : str{std::make_unique<const std::string>(str)} {}; ~TestClass() = default; // (1) private: std::unique_ptr<const std::string> str{}; // (2) // const std::unique_ptr<const std::string> str{}; // (3) }; int main() { // is fine all the time TestClass myTestClass = TestClass("myTestClass"); // (4) // doesn't work at all std::make_pair("myTestClassKey", myTestClass); // (5) // works, but only wit (1) commented out and (2) instead of (3) std::make_pair("myTestClassKey", TestClass("myTestClass")); // (6) return 0; } Lines (1) to (3) in TestClass are causing me a headache. While line (4) works regardless of line (1) and (2) OR (3) uncommented, line (5) does not work at all and line (6) only compiles if line (1) is commented out and line (2) is used instead of line (3). The compiler error I receive is always something like: ||=== Build: Debug in test (compiler: GNU GCC Compiler) ===| /usr/include/c++/9/bits/stl_pair.h||In instantiation of ‘constexpr std::pair<typename std::__decay_and_strip<_Tp>::__type, typename std::__decay_and_strip<_T2>::__type> std::make_pair(_T1&&, _T2&&) [with _T1 = const char (&)[15]; _T2 = TestClass; typename std::__decay_and_strip<_T2>::__type = TestClass; typename std::__decay_and_strip<_Tp>::__type = const char*]’:| /home/johndoe/Coding/test/main.cpp|26|required from here| /usr/include/c++/9/bits/stl_pair.h|529|error: no matching function for call to ‘std::pair<const char*, TestClass>::pair(const char [15], TestClass)’| /usr/include/c++/9/bits/stl_pair.h|436|note: candidate: ‘template<class ... _Args1, long unsigned int ..._Indexes1, class ... _Args2, long unsigned int ..._Indexes2> std::pair<_T1, _T2>::pair(std::tuple<_Args1 ...>&, std::tuple<_Args2 ...>&, std::_Index_tuple<_Indexes1 ...>, std::_Index_tuple<_Indexes2 ...>)’| /usr/include/c++/9/bits/stl_pair.h|436|note: template argument deduction/substitution failed:| /usr/include/c++/9/bits/stl_pair.h|529|note: mismatched types ‘std::tuple<_Tps ...>’ and ‘const char [15]’| /usr/include/c++/9/bits/stl_pair.h|375|note: candidate: ‘template<class ... _Args1, class ... _Args2> std::pair<_T1, _T2>::pair(std::piecewise_construct_t, std::tuple<_Args1 ...>, std::tuple<_Args2 ...>)’| ... /usr/include/c++/9/bits/stl_pair.h|529|note: candidate expects 0 arguments, 2 provided| ||=== Build failed: 9 error(s), 2 warning(s) (0 minute(s), 0 second(s)) ===| In short, why's that? My only idea so far is that it could be related to move / copy construction of the std::unique_ptr? But why would line (1) cause trouble then?
Lets breakdown what your code does: ~TestClass() = default; // (1) You are explicitly defining the destructor as a defaulted destructor. This counts as a user-declared destructor. std::unique_ptr<const std::string> str{}; // (2) Declares a non-const unique_ptr field. This field can be mutated and therefore, moved from. // const std::unique_ptr<const std::string> str{}; // (3) Declares a constant unique_ptr field. You will not be able to move out from this field after object initialisation. TestClass myTestClass = TestClass("myTestClass"); // (4) Direct-initialises myTestClass via copy-elision. This means that there is no copy-/move-constructor or assignment happening here. (https://en.cppreference.com/w/cpp/language/copy_elision) std::make_pair("myTestClassKey", myTestClass); // (5) Create a std::pair with a copy of myTestClass as the second value. TestClass cannot be copied - no implicit copy constructor is defined because unique_ptr does not have one either! std::make_pair("myTestClassKey", TestClass("myTestClass")); // (6) Initialise a std::pair with a prvalue ("pure" rvalue), which is the result of the expression TestClass("myTestClass"). This type of initialisation requires a move-constructor to be available. An implicitly declared move constructor is defined automatically for you, provided that: there are no user-declared copy constructors; there are no user-declared copy assignment operators; there are no user-declared move assignment operators; there is no user-declared destructor. (https://en.cppreference.com/w/cpp/language/move_constructor) The explicitly defaulted destructor (1) is counted as a user-declared destructor, which means that no implicitly declared move constructor is emitted when (1) is uncommented, hence why the compilation error on (6).
69,523,130
69,523,294
C++ GamerServer Library with Unity Client
I made a simple C++ game server library(network session) and I wanted to use it for Unity client to make a simple MMORPG. I found that my library needs to be changed to DLL. So, I made a dll of my C++ game server library and found that my class cannot be used for Unity Client directly. Is there an easy way to use my c++ library class for Unity Client? I hope your wise answers. Thank you for reading.
You are trying to create a Unity native plugin. You have to make sure that you export your methods in the proper way and then you can "link" them to a C# method that will have the same signature. Tip: make sure to keep with the native/primitive types. Since it is a long topic to be explained here I am sharing a link that will help you: Working with Native Plugins from Unity: https://learn.unity.com/tutorial/working-with-native-plugins-2019-3
69,523,389
69,524,722
App closes before uploading data to database, Qt
So I have made a basic app that allows users to enter in data and then upon pressing submit the data is submitted to a firebase and the app closes. However for some reason the app is closing without submitting the data to the firebase. The code for the submit button is as follows: void checkinapp::on_pushButton_clicked() { checkinapp::post(); checkinapp::exit(); } post() and exit() are defined as follows: void post() { m_networkManager = new QNetworkAccessManager ( this ); QVariantMap newUser; newUser[ "Stress" ] = QString::number(stressed); newUser[ "Sleep" ] = QString::number(tired); newUser[ "Hungry" ] = QString::number(hungry); newUser[ "Happy" ] = QString::number(happy); newUser[ "Grade" ] = QString::number(grade); newUser[ "Date" ] = "1/10/21"; newUser[ "Gender" ] = QString::number(gender); newUser[ "Aid" ] = QString::number(help); QJsonDocument jsonDoc = QJsonDocument::fromVariant( newUser ); QNetworkRequest newUserRequest(Url( "url/User.json")); newUserRequest.setHeader( QNetworkRequest::ContentTypeHeader, QString( "application/json" )); m_networkManager->post( newUserRequest, jsonDoc.toJson() ); submitted = true; } void exit() { if(submitted==true) { QApplication::exit(); } } When I comment out checkinapp::exit() the app submits to the database but doesn't close. however when it's not commented out it closes the app without uploading to the database. Edit: Here is my class: class checkinapp : public QMainWindow { Q_OBJECT public: checkinapp(QWidget *parent = nullptr); ~checkinapp(); void databasehandler(QWidget *parent = nullptr); int stressed; int happy; int hungry; int tired; int gender; bool help; int grade; bool submitted; //bool QNetworkReply::isFinished() const; void post() { m_networkManager = new QNetworkAccessManager ( this ); QVariantMap newUser; newUser[ "Stress" ] = QString::number(stressed); newUser[ "Sleep" ] = QString::number(tired); newUser[ "Hungry" ] = QString::number(hungry); newUser[ "Happy" ] = QString::number(happy); newUser[ "Grade" ] = QString::number(grade); newUser[ "Date" ] = "1/10/21"; newUser[ "Gender" ] = QString::number(gender); newUser[ "Aid" ] = QString::number(help); QJsonDocument jsonDoc = QJsonDocument::fromVariant( newUser ); QNetworkRequest newUserRequest( QUrl( "url/User.jason")); newUserRequest.setHeader( QNetworkRequest::ContentTypeHeader, QString( "application/json" )); connect(m_networkManager, SIGNAL(finished(QNetworkReply*)), this,SLOT(myOnFinishSlot(QNetworkReply*))); m_networkManager->post( newUserRequest, jsonDoc.toJson() ); //submitted = true; } void myOnFinishSlot() { exit(); } void exit() { QApplication::quit(); } public slots: //void networkReplyReadyRead(); void myOnFinishSlot(QNetworkReply* x); private slots: void on_happy_valueChanged(int value); void on_hungry_valueChanged(int value); void on_sleep_valueChanged(int value); void on_stress_valueChanged(int value); void on_male_toggled(bool checked); void on_female_toggled(bool checked); void on_other_toggled(bool checked); void on_help_toggled(bool checked); void on_pushButton_clicked(); private: Ui::checkinapp *ui; QNetworkAccessManager * m_networkManager; QNetworkReply * m_networkReply; };
If I were you I would do this: void checkinapp::on_pushButton_clicked() { checkinapp::post(); //checkinapp::exit(); } then in the post method: void post() { m_networkManager = new QNetworkAccessManager ( this ); ... HERE connect the Manager to your custom slot, something like connect(mm_networkManager, SIGNAL(finished(QNetworkReply*)), this,SLOT(myOnFinishSlot(QNetworkReply*))); m_networkManager->post( newUserRequest, jsonDoc.toJson() ); //submitted = true; } and then after the response is received close all by calling exit: void myOnFinishSlot(QNetworkReply* x) { .... do some stuff exit(); } how to define the slot: in the header file of the checkinapp do class checkinapp : public QObject { Q_OBJECT public: //your public data public slots: void myOnFinishSlot(QNetworkReply* x); signals: //your signals if any private: //your private data };
69,523,550
69,523,637
Is a map containing addresses of out-of-scope objects undefined behavior?
If I have a map of object addresses to some other type e.g. string: std::map<unsigned long, std::string> index; // ^^^ This is a number representing address of an object // that may go out of scope while the map is still alive. Is pushing to it objects using addresses to objects that may go out of scope before the map, undefined behavior? Note that I'm only reading the address, and not modifying the addressed object through the map.
Assuming string is std::string, it is not an address. unsigned long is not an address either. In case you converted some pointer values to unsigned long and use that unsigned long as key in the map there is not problem with reading those integers. They have no implicit relation to the original pointers.
69,523,555
69,523,772
Writing an long integer to an string as char* in Arduino function
i am fighting with this problem for all night long, and nothing working for me... I have tried with alot of methods founded on the internet, but i'm still locked here. All I want is to write an number in the middle of an char string to display it on an oled screen using an nodemcu v3 based on ESP8266. This is what I want to have on my screen: S7:3.55V 3.55 could be an number between 3.02 and 4.87. Actual error is: invalid conversion from 'long int' to 'char*' [-fpermissive] #include <Wire.h> #include "OLED.h" #include <sstream> #include <iostream> #include <string> #include <cstring> #include <iomanip> #include <locale> OLED display(2, 14); //OLED Declarare SDA, SCL long randNumber; void setup() { Serial.begin(9600); Serial.println("OLED test!"); // Initialize display display.begin(); //display.off(); //display.on(); display.clear(); delay(3*1000); } void loop() { randNumber = random(3.02, 4.87); display.print("S7:", 5); display.print(randNumber, 5); display.print("V", 5); //display.print("Banc: ", 7); //display.print(randNumber1, 7); //display.print("V", 7); delay(3*200); }
sprintf is your friend here, write the number to a buffer first and then print that buffer. However you still need a different way to get to that number, random returns a long value, so to get your desired result you should adjust your parameters first: randNumber = random(302, 487); Don't worry about the decimals we'll get them back by appropriate formatting (in any case avoiding floating point entirely avoids at the same time quite a number of trouble mainly concerning rounding issues). char buffer[16]; snprintf ( buffer, sizeof(buffer), "S7:%ld.%.2ldV", randNumber / 100, randNumber % 100 // ^3^ ^55 ^ ^------ 3 -----^ ^----- 55 -----^ ); Now simply print out buffer... Alternatives involve e.g. std::ostringstream, but these are not as convenient (and not as efficient) as good old C stdio API: std::ostringstream buffer; buffer << "S7:" << randNumber / 100 << '.' << std::setw(2) << std::setfill('0') << randNumber % 100 << 'V'; print(buffer.str().c_str());
69,523,747
69,532,163
SWIG: Access Array of Structs in Python
Say I have the following static constexpr array of c struct: #include <cstdint> namespace ns1::ns2 { struct Person { char name[32]; uint8_t age; }; static constexpr Person PERSONS[] = { {"Ken", 8}, {"Cat", 27} }; } How can I access elements in ns1::ns2::PERSONS in python by using swig? One way I can think of is to create a accessor like const Person& get(uint32_t index) in the swig interface file. Tho, I wonder whether there is a more elegant way that I don't have to create an accessor function for each array of c struct. Thanks!
One way I can think of is to create a accessor like const Person& get(uint32_t index) in the swig interface file. According to 5.4.5 Arrays in the SWIG documentation, that's the way to do it: %module test %include <stdint.i> %inline %{ #include <cstdint> namespace ns1::ns2 { struct Person { char name[32]; uint8_t age; }; static constexpr Person PERSONS[] = { {"Ken", 8}, {"Cat", 27} }; } // helper function const ns1::ns2::Person* Person_get(size_t index) { if(index < sizeof(ns1::ns2::PERSONS) / sizeof(ns1::ns2::Person)) // protection return ns1::ns2::PERSONS + index; else return nullptr; } %} Demo: >>> import test >>> test.PERSONS.name # can only access the first element 'Ken' >>> test.Person_get(1).name 'Cat' >>> test.Person_get(2).name Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'NoneType' object has no attribute 'name' SWIG can also generate array wrappers for you with 11.2.2 carrays.i, but there is no bounds checking: %module test %include <stdint.i> %inline %{ #include <cstdint> namespace ns1::ns2 { struct Person { char name[32]; uint8_t age; }; static constexpr Person PERSONS[] = { {"Ken", 8}, {"Cat", 27} }; } %} %include <carrays.i> %array_functions(ns1::ns2::Person,arrayPerson); Demo: >>> import test >>> test.arrayPerson_getitem(test.PERSONS,1).name 'Cat'
69,524,622
69,524,700
Why I got garbage value after reclaring variable in a smaller scope
int tar = 0; { int tar = tar; cout<<tar; } It prints out 814005873, but what I expected was 0.
The variable in the outer scope is not relevant. You'd get the same with { int tar = tar; cout<<tar; } tar is not initialzed hence using its value to initialize itself is undefined behavior. All major compilers warn about such case of tar being used uninitialized. For example: https://godbolt.org/z/3x437P46K. Don't ignore warnings! It may look weird that this isnt an error, but for a custom type such initialization can be meaningful. For example: struct foo { foo& other; foo(foo& other) : other(other) {} }; int main() { foo f = f; } f holds a reference to itself.
69,524,675
69,525,272
unique_ptr deleter trick: which compiler is correct?
I was going through this particular SO on how to save memory space for custom deleter pointer. At the bottom of the answer, it provides a custom written version in C++11. After dozens of minutes trying to understand the code, I discover some compiler inconsistencies among the Big 3, where clang compiles, while the other two complain with compiler errors. (Live Demo) My code is a little different from the other SO answer. Here it goes: #include <cstdlib> #include <iostream> #include <memory> #include <type_traits> using namespace std; template <class T, T t> struct val { constexpr operator typename decay<T>::type() const noexcept { return t; } }; using default_free = val<decltype(free), free>; int main(void) { unique_ptr<void, default_free> p(malloc(42)); cout << p.get() << endl; p.reset(); cout << p.get() << endl; return 0; } Please correct me if I'm wrong here. The way I see it, the trick is to provide a constexpr function that can cast an object of type default_delete to a function pointer with the value of t (free as its instantiation). So the question: which compiler is correct?
It appears to be a gcc bug, and a completely different MSVC bug. gcc cannot do this: template <typename T, T t> struct foo {}; when instantiated with a function type. T has to be a template parameter for this bug to be triggered; template <void t(void*) noexcept> works. template <typename T, T* t> struct foo {}; fixes the problem. MSVC eats either of the previous constructs perfectly well, but it cannot use free as a non-type template argument. (Other standard C library functions as well.) A simple solution is to use a qualified name (either ::free or std::free, both work). Wrapping free in another function also fixes the problem. This is because MSVC apparently thinks (in this context) that ::free and std::free are different functions, and cannot disambiguate. One can reproduce this with no standard library: void foo(void*); namespace moo { using ::foo; } using namespace moo; Now plain foo cannot be used as a template parameter.
69,525,309
69,525,491
Emscripten: how to disable warning: explicit specialization cannot have a storage class
I am building my program by using the latest Emscripten compiler. It is based on Clang version 14. Actually it is a small test program which is the following: #include <iostream> struct Test { template<typename T> static inline void Dump(const T& value) { std::cout << "[generic] = '" << value << "'\n"; } template<> static inline void Dump<std::string>(const std::string& value) { std::cout << "[std::string] = '" << value << "'\n"; } }; int main() { std::string text = "hello"; Test::Dump(text); return 0; } When I build it by Emscripten compiler I got the warning: D:\em_test>emcc a.cpp a.cpp:10:24: warning: explicit specialization cannot have a storage class static inline void Dump<std::string>(const std::string& value) { ~~~~~~~ ^ 1 warning generated. If I just remove static keyword from void Dump<std::string> line then there will be no warning. However, this code will cause compilation error in Visual Studio: D:\em_test\a.cpp(17,11): error C2352: 'Test::Dump': illegal call of non-static member function But this error is expected and clear. I would like to write a cross-platform program. So, I think I should simple disable this warning in Emscripten. However, I can not find any Emscripten (which is based on clang version 14) command line option for that! And I am asking advice for that. Actually I tried to use -Wno-static-inline-explicit-instantiation command line option but it did not help: D:\em_test>emcc -Wno-static-inline-explicit-instantiation a.cpp a.cpp:10:24: warning: explicit specialization cannot have a storage class static inline void Dump<std::string>(const std::string& value) { ~~~~~~~ ^ 1 warning generated. However, I see in Clang version 13 user manual description about -Wstatic-inline-explicit-instantiation option but it is about a slightly another warning text. Also it seems that Clang version 14 is not fully released, so, there is no public Clang version 14 user manual. I can not find any Emscripten or Clang command line option to disable the above warning. Could somebody help me?
Explicit specialization of (both static and non-static) function templates cannot be put into class definitions. Just put it into the enclosing namespace(i.e somewhere after the class): #include <iostream> struct Test { template <typename T> static inline void Dump(const T& value) { std::cout << "[generic] = '" << value << "'\n"; } }; // Notice Test:: template <> inline void Test::Dump<std::string>(const std::string& value) { std::cout << "[std::string] = '" << value << "'\n"; } int main() { std::string text = "hello"; Test::Dump(text); return 0; } inline is never necessary for in-class function definitions but it has different meaning for member variables. inline for out-class is necessary in header files because the explicit specialization is not a template anymore.
69,525,592
69,571,412
Undefined Symbol error when linking pybind11 with a dynamic library that calls an external function
I'm trying to link a pybind11 module with a .so dynamic library, and the library calls functions not implemented in the .so file. It works fine in a normal c++ executable file, but raises Undefined Symbol error when imported in python. Here is a simple demo to reproduce my problem. The function Student::print() is complied to a dynamic library and it calls a function Student::setId() that is not included in the .so file. (If use nm command, it will show U _ZN7Student5setIdEi.) It works fine in main.cpp to call Student::print(), but in test.py, it raises ImportError: {mypath}/libstu_lib.so: undefined symbol: _ZN7Student5setIdEi To simplify, I set the external function to be its own member function. The problem still reproduces when calling functions belonging to another classes, so I think it doesn't matter. Is there any option in pybind11 to deal with this problem? Because it is difficult to modify the source code of the dynamic library. Thanks. Student.h #include <iostream> using namespace std; class Student { public: Student(int id); void setId(int id); void print(); private: int id; }; Student.cpp #include "Student.h" Student::Student(int id) { this->id = id; } void Student::setId(int id) { this->id = id; } Student_lib.cpp #include "Student.h" void Student::print() { cout << "id: " << this->id << endl; this->setId(111); cout << "id: " << this->id << endl; } Student_wrapper.cpp #include <pybind11/pybind11.h> #include "Student.h" namespace py = pybind11; PYBIND11_MODULE(stu, m){ py::class_<Student>(m, "Student") .def(py::init<int>()) .def("setId", &Student::setId) .def("print", &Student::print); } CMakeLists.txt cmake_minimum_required(VERSION 3.15) project(test) link_directories(${PROJECT_SOURCE_DIR}) add_library(stu_lib SHARED Student_lib.cpp) add_executable(main main.cpp Student.cpp) target_link_libraries(main stu_lib) find_package(pybind11 REQUIRED) pybind11_add_module(stu Student_wrapper.cpp Student.cpp) target_link_libraries(stu PUBLIC stu_lib) main.cpp #include "Student.h" int main(int argc, char** argv) { Student* s = new Student(1); s->print(); return 0; } test.py from stu import Student s = Student(1) s.print() Output of ldd libstu_core.so: linux-vdso.so.1 (0x00007ffcffdac000) libstdc++.so.6 => /lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f3def395000) libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f3def1a3000) libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f3def054000) /lib64/ld-linux-x86-64.so.2 (0x00007f3def593000) libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f3def039000)
I'll be honest: I don't know how pybind11 works internally well enough to tell you why this is happening. However, there is a workaround that makes your code works, which is to compile Student.cpp into a shared library of its own and link it to the pybind11 module. This is how you can modify your CMakeLists.txt to make it work: cmake_minimum_required(VERSION 3.15) project(test) link_directories(${PROJECT_SOURCE_DIR}) add_library(stu_lib SHARED Student_lib.cpp) add_executable(main main.cpp Student.cpp) target_link_libraries(main stu_lib) find_package(pybind11 REQUIRED) add_library(stu_class SHARED Student.cpp) pybind11_add_module(stu Student_wrapper.cpp) target_link_libraries(stu PUBLIC stu_lib stu_class)
69,525,866
69,525,992
Undefined symbols for architecture x86_64 with QNetworkReply
I keep getting the following error: Undefined symbols for architecture x86_64: "checkinapp::myOnFinishedSlot(QNetworkReply*)", referenced from: "checkinapp::qt_static_metacall(QObject*,QMetaObject::Call,int,void**) in moc_checkinapp.o I have looked through several times and can't figure out where I have gone wrong. (Im new to c++ so im sorry i probably missed something obvious). Any help is appreciated :) Here is my class: class checkinapp : public QMainWindow { Q_OBJECT public: checkinapp(QWidget *parent = nullptr); ~checkinapp(); void databasehandler(QWidget *parent = nullptr); int stressed; int happy; int hungry; int tired; int gender; bool help; int grade; bool submitted; void post() { m_networkManager = new QNetworkAccessManager ( this ); QVariantMap newUser; newUser[ "Stress" ] = QString::number(stressed); newUser[ "Sleep" ] = QString::number(tired); newUser[ "Hungry" ] = QString::number(hungry); newUser[ "Happy" ] = QString::number(happy); newUser[ "Grade" ] = QString::number(grade); newUser[ "Date" ] = "1/10/21"; newUser[ "Gender" ] = QString::number(gender); newUser[ "Aid" ] = QString::number(help); QJsonDocument jsonDoc = QJsonDocument::fromVariant( newUser ); QNetworkRequest newUserRequest( QUrl( "url/User.jason")); newUserRequest.setHeader( QNetworkRequest::ContentTypeHeader, QString( "application/json" )); connect(m_networkManager, &QNetworkManager::finished, this, &checkinapp::myOnFinishSlot); // the error is here m_networkManager->post( newUserRequest, jsonDoc.toJson() ); } void exit() { QApplication::quit(); } public slots: void myOnFinishSlot(QNetworkReply* x) { exit(); } private slots: void on_happy_valueChanged(int value); void on_hungry_valueChanged(int value); void on_sleep_valueChanged(int value); void on_stress_valueChanged(int value); void on_male_toggled(bool checked); void on_female_toggled(bool checked); void on_other_toggled(bool checked); void on_help_toggled(bool checked); void on_pushButton_clicked(); private: Ui::checkinapp *ui; QNetworkAccessManager * m_networkManager; QNetworkReply * m_networkReply; };
Your declaration void myOnFinishSlot(QNetworkReply* x) Does not match your definition: void myOnFinishSlot() You effectively defined two methods with different overloads. Either merge the definition and declaration: public slots: void myOnFinishSlot(QNetworkReply* x) { exit(); } or move the definition outside of the class block: void checkinapp::myOnFinishSlot(QNetworkReply* x) { exit(); } Additionally, don't use the SIGNAL/SLOT notation, since it leads to hard-to-debug errors at runtime. Your connect call should be: connect(m_networkManager, &QNetworkAccessManager::finished, this, &checkinapp::myOnFinishSlot);
69,525,870
69,526,532
Vertical Order Traversal using Iterative method
I'm trying to solve the problem of Vertical Order Traversal of Binary Tree using map and queue. I did solve it using a recursive way, but I'm not getting the same answer using the iterative way. 10 / \ 7 4 / \ / \ 3 11 14 6 Approach : First I declared an integer that stores horizontal distance from the root node. Horizontal distance means that the left part from the root will be considered as -1, -2 and so on, like a negative X axis, where the root is origin and starts from 0. So node 7 will be given -1, 3 will be given -2. However, 10, 11, 14 will be given 0 as they are not away from root node but lie in the same position. And towards the right, distance will become positive so 4 will get distance 1, 6 will get 2 and so on. At first, I pushed the root in the queue and updated the horizontal distance as 0. After that, I added horizontal distance as key and root data as value in the map. And finally, I poped the root from the queue and I checked for its left and right child, if left or right child was available, I pushed the left and right child in the queue respectively and updated horizontal distance accordingly. Then I followed the same procedure for the complete binary tree. And then, I just traversed through the second part of the map to get the answer. The Answer should be : 3 7 10 11 14 4 6 The Answer I received is : 10 7 4 3 11 14 6 Here is my Code : #include <iostream> #include <map> #include <queue> #include <vector> using namespace std; struct Node { int data; Node *left; Node *right; Node(int val) { data = val; left = NULL; right = NULL; } }; map<int, vector<int>> verticalPrint(Node *root) { queue<Node *> qi; map<int, vector<int>> mp; int Hd = 0; qi.push(root); while (!qi.empty()) { Node *temp = qi.front(); mp[Hd].push_back(temp->data); qi.pop(); if (temp->left != NULL) { qi.push(temp->left); Hd -= 1; } if (temp->right != NULL) { qi.push(temp->right); Hd += 1; } } return mp; } int main() { Node *root = new Node(10); root->left = new Node(7); root->right = new Node(4); root->left->left = new Node(3); root->left->right = new Node(11); root->right->left = new Node(14); root->right->right = new Node(6); map<int, vector<int>> mp = verticalPrint(root); map<int, vector<int>>::iterator it; for (it = mp.begin(); it != mp.end(); it++) { for (int i = 0; i < it->second.size(); i++) { cout << it->second[i] << " "; } cout << endl; } return 0; }
You cannot use a single Hd variable like that. Note how in the first iteration, Hd will go to -1 and back to 0 because the root has both a left and right child. So in the next iteration you start again with 0, yet the node that you pull from the queue has nothing to do with that value of Hd. Instead, put pairs in the queue: a combination of node and its corresponding horizontal distance. Then it will work fine: map<int, vector<int>> verticalPrint(Node *root) { queue<pair<int, Node *>> qi; map<int, vector<int>> mp; qi.push({0, root}); while (!qi.empty()) { pair<int, Node*> item = qi.front(); int hd = item.first; Node * temp = item.second; mp[hd].push_back(temp->data); qi.pop(); if (temp->left != NULL) { qi.push({hd - 1, temp->left}); } if (temp->right != NULL) { qi.push({ hd+1, temp->right}); } } return mp; }
69,525,922
69,528,963
Googletest: CLANG compiles where GCC fails
Here is a very simple script using gtest (saved in file gt.cpp) #include<gtest/gtest.h> double timesTwo(double x){return x*2;} TEST(testTimesTwo, integerTests){EXPECT_EQ(6, timesTwo(3));} int main(int argc, char* argv[]){ testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } The script compiles fine with CLANG (Apple clang version 11.0.3) clang++ -std=c++17 -lgtest gt.cpp -o gt but fails with GCC (g++ (GCC) 10.2.0) g++ -std=c++17 -lgtest gt.cpp -o gt gt.cpp:2:9: fatal error: gtest/gtest.h: No such file or directory 2 | #include<gtest/gtest.h> | Using the -H option in CLANG, I see the header file is included from /usr/local/include. Also, I can find the libgtest.a file in /usr/local/bin/. So, I did g++ -std=c++17 gt.cpp -o gt -I/usr/local/include/ -L/usr/local/lib/ -lgtest and got a long list of undefined symbols starting with Macavity:test remi$ g++ -std=c++17 gt.cpp -o gt -I/usr/local/include/ -L/usr/local/lib/ -lgtest Undefined symbols for architecture x86_64: "__ZN7testing8internal9EqFailureEPKcS2_RKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESA_b", referenced from: __ZN7testing8internal18CmpHelperEQFailureIidEENS_15AssertionResultEPKcS4_RKT_RKT0_ in ccrUwUPO.o "__ZNKSt3__112basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE4findEcm", referenced from: __ZN7testing8internal11SplitStringERKNSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEEcPNS1_6vectorIS7_NS5_IS7_EEEE in libgtest.a(gtest-all.cc.o) __ZN7testing8internalL21FormatDeathTestOutputERKNSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEE in libgtest.a(gtest-all.cc.o) "__ZNKSt3__112basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE7compareEmmPKcm", referenced from: Can you help me figure out why GCC fails to compile here?
Here is this error message passed through a http://demangler.com/ Undefined symbols for architecture x86_64: "_testing::internal::EqFailure(char const*, char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, bool)", referenced from: _testing::AssertionResult testing::internal::CmpHelperEQFailure<int, double>(char const*, char const*, int const&, double const&) in ccrUwUPO.o "_std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::find(char, unsigned long) const", referenced from: _testing::internal::SplitString(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, char, std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > >*) in libgtest.a(gtest-all.cc.o) _testing::internal::FormatDeathTestOutput(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&) in libgtest.a(gtest-all.cc.o) "_std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::compare(unsigned long, unsigned long, char const*, unsigned long) const", referenced from: Note that second and third error complains that linker can't find implementation of: std::string::find(char, unsigned long) and std::string::compare(unsigned long, unsigned long, char const*, unsigned long) const. Those are parts of standard C++ library. Since std::string is template some parts of it are part of library which uses that template, but is some cases it can be part of C++ runtime. Now I suspect that you compiled gtest with a clang and try use it when building test with gcc (or vice versa). A bit different implementations of std::string on both compilers lead to divergence in available symbols. So please make sure that gtest and test application are build with same compiler. Here is some description of binary compatibility between gcc and clang. There are some hints what problem is, but it is not very formal (maybe I will find better document).
69,526,375
69,530,583
Best way to store a pointer to base class, but be able to use derived class functions
I have a Cell, which can store objects of CellContent type. CellContent have to be a virtual class. From CellContent I have to derive classes Enemy and Item. So the idea is to store a pointer to a CellContent inside of Cell. The question is: what is the best way to store a pointer to a derived class in this circumstances? My current solution is not an elegant one and I want to improve it. class Cell { public: template<class T> void setCellContent(std::shared_ptr<T> cellContent) { _cellContent = std::dyanmic_pointer_cast<CellContent>(cellContent); if (std::is_same<T, Enemy>::value = true) { _cellContentType = CellContentType::ENEMY; } else if (std::is_same<T, Item>::value = true) { _cellContentType = CellContentType::ITEM; } } template<class T> std::shared_ptr<T> getCellContent() { return std::dynamic_pointer_cast<T>(_cellContent); } CellContentType getCellContentType() { return _cellContentType; } std::shared_ptr<CellContent> _cellContent; CellContentType _cellContentType; } int main() { auto enemy = std::make_shared<Enemy>(); Cell cell; cell.setCellContent<Enemy>(enemy); if (CellContentType::ENEMY == cell.getCellContentType()) { cell.getCellContent<Enemy>(); } else if (CellContentType::ITEM == cell.getCellContentType()) { cell.getCellContent<Item>(); } } How I can avoid use if this ugly if in main?
All functions of the derived-class, which: Need to be callable, While variable is of base-class-type, But without casting from base-class-type to derived-class-type manually, should be declared virtual in the base-class (and be overridden in derived-class).
69,527,038
69,527,398
How can I write variable definition without declaration?
I can write declaration or declaration with definition. Examples: int x = 1; // declaration and definition extern int x; // only declaration bool f(); // only declaration bool g() {} // declaration and definition class X; // declaration class X {}; // declaration and definition So we can see that this is possible to write only declaration and declaration with definition. But how I can write only definition? I heard that this is possible.
There is no definition without a declaration, since the meaning of the first term includes the second. Further, I provided some information from the C++ drafts (6.2. Declarations and definitions): A declaration is said to be a definition of each entity that it defines. Link: https://eel.is/c++draft/basic.def
69,527,302
69,527,911
How to get a list of objects with common attributes?
Given a class Movie (id, title, ranking, release date, character number, ticket price, comment etc.), enum type: ACTION, COMEDY, DRAMA, FANTASY etc. and a class Cinema (name, location). I need to write a function calculateProfit ( Movie*, day) that would calculate cinema's profit based on some particular day. Also I need to write a method of choosing a movie based on some parameters and sort the movies based on release date. I've been thinking over this problem for a few days already, but it seems like I just can't write the proper code. In order to be able to choose a movie based on parameters, I need to get a list of all objects of a Movie class that have the same particular attributes. How can I do this? Here is the brief template for my classes: using namespace std; class Movie{ public: int ID; string Title; int Ranking; string ReleaseDate; int CharacterNumber; int TicketPrice; string Comment; //SortingByDate enum type{ ACTION, COMEDY, DRAMA, FANTASY } Type; Movie(int, string, int, string, int, int, string, type); Movie(); }; Movie::Movie(int ID, string Title,int Ranking,string ReleaseDate,int CharacterNumber, int TicketPrice,string Comment, type Type){ this->ID=ID; this->Title=Title; this->Ranking=Ranking; this->ReleaseDate=ReleaseDate; this->CharacterNumber=CharacterNumber; this->TicketPrice=TicketPrice; this->Comment=Comment; this->Type=Type; class Cinema{ private: int calculateProfit(); public: //Vector with objects of Movie class string name; string location; };
Given a std::vector<std::shared_ptr<Movie>>, you can find by title as follows: using MovieCollection = std::vector<std::shared_ptr<Movie>>; MovieCollection find_by_title(const MovieCollection& collection, const std::string& fragment) { MovieCollection ret; for (auto movie: collection) { if (movie->title.find(fragment) != std::string::npos) { ret.push_back(movie); } } return ret; }
69,527,632
69,529,010
Qt GIF creation: Colours swapped when using gif-h library
Apparently, I am trying to use gif-h library for gif creation with qt 4.7 for a C++ project. After embedding the library to the project, I can generate GIF through my qt GUI app, however, the colours on the final/actual GIF are swapped. What I mean is that: below red frame becomes below blue frame and same goes for other way round (i.e. blue frame becomes red frame). Just like above, below orange frame becomes below sky blue frame and same goes for other way round (i.e. sky blue frame becomes orange frame). Could someone familiar with the library or graphics or gif creation in code guide me? I am happy to provide more information about image capturing and such, as and when needed. Thank you in advance.
Ok, I have managed to resolve the problem by using QImage::rgbSwapped() function. Thank you to @Pablo Yaggi particularly for the hint. I will have to remove the code snippet from the question due to security reasons.
69,527,715
69,648,292
Check whether OpenSSL supports certain curve via header/define in CMake
I need to check whether OpenSSL supports certain Elliptic Curve(s) via CMake. While cipher and hash availability may be checked via existence of functions from openssl/evp.h, like check_cxx_symbol_exists("EVP_md4", openssl/evp.h, _openssl_has_md4), I don't see a way to do the same for curves. Do I miss something, or there is no better way than checking the output of openssl ecparam list_curves? Update: Since my code doesn't require openssl executable, it would be quite desirable to avoid dependency on it for building. Update 2: thanks to the David's answer ended up with the following module: https://github.com/rnpgp/cmake-modules/blob/master/FindOpenSSLFeatures.cmake
This code (mostly taken from openssl) lists the available ECs: #include <stdio.h> #include <openssl/ec.h> #include <openssl/objects.h> int main () { int ret = 1; EC_builtin_curve *curves = NULL; size_t n, crv_len = EC_get_builtin_curves (NULL, 0); curves = OPENSSL_malloc((int)sizeof(*curves) * crv_len); if (curves == NULL) goto end; if (!EC_get_builtin_curves (curves, crv_len)) goto memfree; for (n = 0; n < crv_len; n++) { const char *comment = curves[n].comment; const char *sname = OBJ_nid2sn (curves[n].nid); if (comment == NULL) comment = "CURVE DESCRIPTION NOT AVAILABLE"; if (sname == NULL) sname = ""; printf ("%s\t%s\n", sname, comment); } ret = 0; memfree: OPENSSL_free (curves); end: return ret; } Output on my laptop: $ gcc -Wall -L /usr/lib64 -lcrypto -lssl eclist.c -o eclist $ ./eclist secp224r1 NIST/SECG curve over a 224 bit prime field secp256k1 SECG curve over a 256 bit prime field secp384r1 NIST/SECG curve over a 384 bit prime field secp521r1 NIST/SECG curve over a 521 bit prime field prime256v1 X9.62/SECG curve over a 256 bit prime field The openssl binary gives me the same output: $ openssl ecparam -list_curves secp224r1 : NIST/SECG curve over a 224 bit prime field secp256k1 : SECG curve over a 256 bit prime field secp384r1 : NIST/SECG curve over a 384 bit prime field secp521r1 : NIST/SECG curve over a 521 bit prime field prime256v1: X9.62/SECG curve over a 256 bit prime field Of course printing the values this way may not be very usefull, but the code can be hopefully the base for a test CMake.
69,527,976
69,528,907
Too much combination to expand a macro
I want to apply a function to data buffers and their types are known at runtime. I use for that a templated function template <typename T1, typename T2, typename T3> void myFunction(). myFunction is a member of a class, which also contains the data structures storing the buffers. The buffers are stored in a char* pointer, and I have an enumerate to know the actual data type of my buffer, allowing me to cast the pointer into the correct type. I also have a data structure to register all of the data type combination in that way : // functionPtr is declared earlier functionPtr = static_cast<void(*)(void)>( &myFunction< DataType1, DataType2, DataType3 >); registerFunction(functionPtr); Finally, I wrote a macro to parse each type combination. My problem is that it seems to be too much data to expand for the compiler. I reduced to the minimal example below : Preproc, 915 bytes #include <boost/preprocessor.hpp> // List the possible types #define STRIP_ALL_TYPES \ (eIBT_Int8)(eIBT_UInt8) \ (eIBT_Int16)(eIBT_UInt16) \ (eIBT_Int32)(eIBT_UInt32) \ (eIBT_Real32) \ (eIBT_Binary) \ (eIBT_Label16)(eIBT_Label32) # Generate all the combinations #define GENERATE_TYPE_COMBINATION(r, product) (product) // Generate the instruction for a given type combination #define TEMPLATE_SPECIFIC_TYPE_COMBINATION(r, data, elem)\ functionPtr = static_cast<void(*)(void)>(\ &CurProcessorType::myFunction< BOOST_PP_SEQ_ENUM(elem) >); // Generate all the possible instructions #define GENERATE_TEMPLATE(ST)\ BOOST_PP_SEQ_FOR_EACH(TEMPLATE_SPECIFIC_TYPE_COMBINATION, _, \ BOOST_PP_SEQ_FOR_EACH_PRODUCT(GENERATE_TYPE_COMBINATION, ST)) GENERATE_TEMPLATE((STRIP_ALL_TYPES)(STRIP_ALL_TYPES)(STRIP_ALL_TYPES)) Try it online! By expanding the macro, the generated lines compiled by the compiler should look like : functionPtr = static_cast<void(*)(void)>( &CurProcessorType::myFunction< eIBT_Label16, eIBT_Label16, eIBT_Label16 >); but when I test my code on TIO, I get the error .code.tio:23:1: error: macro "BOOST_PP_IIF_1" requires 2 arguments, but only 1 given GENERATE_TEMPLATE((STRIP_ALL_TYPES)(STRIP_ALL_TYPES)(STRIP_ALL_TYPES)) It works only with a few items in STRIP_ALL_TYPES. Is there a workaround I can use to be able to compile? Thanks
I'm not sure what you were trying to achieve with BOOST_PP_SEQ_FOR_EACH, as BOOST_PP_SEQ_FOR_EACH_PRODUCT already gives you all permutations of the template arguments: #include <boost/preprocessor.hpp> // List the possible types #define STRIP_ALL_TYPES \ (eIBT_Int8)(eIBT_UInt8) \ (eIBT_Int16)(eIBT_UInt16) \ (eIBT_Int32)(eIBT_UInt32) \ (eIBT_Real32) \ (eIBT_Binary) \ (eIBT_Label16)(eIBT_Label32) // Generate all the combinations #define GENERATE_TYPE_COMBINATION(r, product)\ functionPtr = static_cast<void(*)(void)>(\ &CurProcessorType::myFunction< BOOST_PP_SEQ_ENUM(product) >); #define GENERATE_TEMPLATE(ST)\ BOOST_PP_SEQ_FOR_EACH_PRODUCT(GENERATE_TYPE_COMBINATION, ST) GENERATE_TEMPLATE((STRIP_ALL_TYPES)(STRIP_ALL_TYPES)(STRIP_ALL_TYPES)) Try it online! Also, I should note that the cast to void(*)(void) is not valid if CurProcessorType::myFunction is a non-static member function. You should use a member function pointer type.
69,527,983
69,528,092
accessing operator overload functions using object pointer
I am implementing this class from https://isocpp.org/wiki/faq/operator-overloading class Matrix { public: Matrix(unsigned rows, unsigned cols); double& operator() (unsigned row, unsigned col); // Subscript operators often come in pairs double operator() (unsigned row, unsigned col) const; // Subscript operators often come in pairs // ... ~Matrix(); // Destructor Matrix(const Matrix& m); // Copy constructor Matrix& operator= (const Matrix& m); // Assignment operator // ... private: unsigned rows_, cols_; double* data_; }; inline Matrix::Matrix(unsigned rows, unsigned cols) : rows_ (rows) , cols_ (cols) //, data_ ← initialized below after the if...throw statement { if (rows == 0 || cols == 0) throw BadIndex("Matrix constructor has 0 size"); data_ = new double[rows * cols]; } inline Matrix::~Matrix() { delete[] data_; } inline double& Matrix::operator() (unsigned row, unsigned col) { if (row >= rows_ || col >= cols_) throw BadIndex("Matrix subscript out of bounds"); return data_[cols_*row + col]; } inline double Matrix::operator() (unsigned row, unsigned col) const { if (row >= rows_ || col >= cols_) throw BadIndex("const Matrix subscript out of bounds"); return data_[cols_*row + col]; } In my main program I am declaring Matrix *m = new Matrix(20,20) Now how to access the elements ? Normally Matrix m(20,20) will do the job. But how to access in the other case ? I tried *m(i,j) - didn't work m->operator()(i,j) - didn't work
(*m)(i,j) should do the trick. But then you might as well implement an equivalent at method so you can write m->at(i,j).
69,528,447
69,528,595
Why don't pointers have same address as the variable they are pointing to?
I am a beginner at C++ (and have no knowledge of C , coming form a Java and Python background). I was learning about pointers and ran the following code I am sharing from my self tutorial file: #include<iostream> using namespace std; int main() { //What is a pointer:- // A datatype that holds address of a variable in other datatype int a=3; int* b = &a; //CREATE A POINTER THAT POINTS TO A // '&'STANDS FOR ADDRESS OF OPERATOR // '*' IS CALLED DEREFERNCING OPERATOR cout<< b<<endl; //prints address of a cout<<&a<<endl; //does the same stuff //retrieving stored at a particular address // '*' GIVES VALUE AT THE ADDRESS STORED IN POINTER cout<<*b<<endl; cout<<*&a<<endl; //pointer to a pointer int** c = &b; // pointer to another pointer b cout<<"The address of b is"<<c<<endl; cout<<"The address of b is"<<&b<<endl; cout<<"The value at address c is"<<*c<<endl; cout<<"The value at address value stored in c is "<< **c<<endl; return 0; } Which returned me the following output:- 0x94ac7ff7d4 0x94ac7ff7d4 3 3 The address of b is 0x94ac7ff7c8 The address of b is 0x94ac7ff7c8 The value at address c is 0x94ac7ff7d4 The value at address value stored in c is 3 What sparked curiosity were the last four lines of the output we see that:- c points to b and b points to a They are not variables themselves then why don't they return the same address? Does that mean using multiple pointers for same variable can take up system resources thus resulting in bad design?
A picture is worth a thousand words. +----------------+ a: | 3 | 94ac7ff7d4 +----------------+ ^ | `-------------. | +--------------|-+ b: | 0x94ac7ff7d4 * | 94ac7ff7d8 +----------------+ ^ | `-------------. | +--------------|-+ c: | 0x94ac7ff7d8 * | 94ac7ff7dc +----------------+ I think of the variable a as a little box that can hold an integer. In C we know it by the identifier a, but actually, at the machine level the compiler has assigned it to sit at address 0x94ac7ff7d4. Similarly, b is a little box that can hold a pointer to an integer, which is typically implemented as the address (a number) where the integer is stored. We know it by the identifier b, but actually, the compiler has assigned it to sit at address 0x94ac7ff7d8. Finally, c is a box that can hold a pointer to a pointer to an integer, which is again implemented as the address where the pointer is stored. We know it by the identifier c, and although you didn't say so, I'm guessing that the compiler has assigned it to sit at address 0x94ac7ff7dc. For any variable, & gives you the address where the variable is stored — which is the sort of value you can store in a pointer variable. For a pointer value, * gives you the value that the pointer points to. (And for pointers to pointers, ** gives you the value that the pointer that the pointer points to, points to, etc.)
69,528,726
69,529,229
Why is this unordered_map not finding existing keys? (C++14)
I'm trying to use an unordered_map for a custom type. However, the map is storing duplicate entries, which have the same hash value and should evaluate as equal when using ==. I've reduced my code to the following proof of concept, where I can see that the hash function runs correctly, but the equals operator is never called. #include <unordered_map> // Define a class with a single integer member. class Example { public: int x; public: Example(int x) { this->x = x; } // Overload == and compare the single member. public: bool operator==(const Example &other) const { std::cout << "Comparing two objects\n"; return this->x == other.x; } }; // Define a hash function class class ExampleHash { public: size_t operator()(const Example* key) const { // simply return the member variable as the hash value. std::cout << "Returning hash value " << key->x << "\n"; return key->x; } }; int main() { // Create an empty map. std::unordered_map<Example*, int, ExampleHash> m; std::cout << "Inserting a new key\n"; // Insert an object with the value 1. m[new Example(1)] = 1; std::cout << "Existing hashes:\n"; ExampleHash fn; for (auto const &item : m) { size_t h = fn(item.first); std::cout << " " << h << ", "; } std::cout << "\n"; std::cout << "Finding the key\n"; // Check if the object is in the map. std::cout << ((m.find(new Example(1)) != m.end()) ? "Found" : "Not found") << "\n"; } Output: Inserting a new key Returning hash value 1 Existing hashes: Returning hash value 1 1, Finding the key Returning hash value 1 Not found (Note the absence of the "Comparing two objects" line when calling unordered_map::find, despite the hash value clearly being in the map already.)
Pointers are not the objects they point to. You are using pointers as keys. The objects equal operator will be ignored.
69,529,544
69,529,941
Is initializing char array from string literal considered to be a implicit conversion?
Is char x[10] = "banana"; considered to be a implicit conversion from const char[7] to char[10]? Since std::is_convertible<const char[7], char[10]>::value evaluates to false the obvious answer would be that it isn't, but I couldn't find a proper definition of implicit conversion anywhere. Reading cppreference I'd say that it is because: Implicit conversions are performed whenever an expression of some type T1 is used in context that does not accept that type, but accepts some other type T2; in particular: ... when initializing a new object of type T2, including return statement in a function returning T2; although I'm not sure why they didn't exclude explicit constructors from this case. Follow-up question (which may be useless): Are arrays completely excluded from any kind of conversions (meaning array-to-array conversions) ?
Language-lawyerly speaking, initializing char array from string literal is a implicit conversion. [conv.general]: An expression E can be implicitly converted to a type T if and only if the declaration T t=E; is well-formed, for some invented temporary variable t ([dcl.init]). Note that the core language only defines implicit conversion from an expression to a type. So the meaning of "implicit conversion from const char[7] to char[10]" is undefined. is_convertible<From, To>::value is false whenever To is an array type, because it is defined to produce false if To is not a valid return type, which an array is not. (This can be implemented in different ways.) [meta.rel]/5: The predicate condition for a template specialization is_­convertible<From, To> shall be satisfied if and only if the return expression in the following code would be well-formed, including any implicit conversions to the return type of the function: To test() { return declval<From>(); } Arrays can rarely be the destination of implicit conversions, since they can be neither parameter types nor return types. But they are not excluded from temporary materialization conversion.
69,531,076
69,532,358
C++ Async multi-thread file parsing store results in vector
I'm trying to speed up a file parser by using multi threading. I've created a function that reads and parses a json-file and returns a vector. Now, to speed things up, i tried to use async, so i created a future vector to store the results. When each thread is finished (ran the parsing function), i would like to append the results to a vector that stores all the results. #include <vector> #include <iostream> #include <future> std::vector<int> parsefilefunction(std::string filepath) { std::vector<int> vec{1, 2, 3}; return vec; } std::vector<std::string> s = { "file1.json", "file2.json", "file3.json", "file4.json", "file5.json"}; int main() { std::vector<int> results2; for (size_t i = 0; i < s.size(); i++) { std::future<std::vector<int>> results = std::async(std::launch::async, parsefilefunction, s[i]); results2.push_back(results); //this is not working, i already tried with move() } } It would be super cool if you can help me! Thank you! Edit: Indeed, "is not woking" is a terrible question desciption! Compiled with: c++ stackoverflow.cpp -std=c++14 -pthread Error message: error: no matching member function for call to 'push_back' results2.push_back(results); ~~~~~~~~~^~~~~~~~~ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/vector:713:36: note: candidate function not viable: no known conversion from 'std::future<std::vector<int>>' to 'const std::__vector_base<int, std::allocator<int>>::value_type' (aka 'const int') for 1st argument _LIBCPP_INLINE_VISIBILITY void push_back(const_reference __x); ^ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/vector:716:36: note: candidate function not viable: no known conversion from 'std::future<std::vector<int>>' to 'std::vector<int>::value_type' (aka 'int') for 1st argument _LIBCPP_INLINE_VISIBILITY void push_back(value_type&& __x);
You want to store ints in your vector, but have a std::future, that is not going to work. You have to get the vector out of the future and then copy its elements. But with that approach you would have no async operation, since you always wait for the single operation to finish before you start the next one. Here is an updated version which compiles: https://gcc.godbolt.org/z/jE171j7GG #include <algorithm> #include <future> #include <iterator> #include <vector> std::vector<int> parsefilefunction(std::string filepath) { std::vector<int> vec{1, 2, 3}; return vec; } std::vector<std::string> s = { "file1.json", "file2.json", "file3.json", "file4.json", "file5.json"}; int main() { std::vector<std::future<std::vector<int>>> futures; std::vector<int> results2; for (const auto& file : s) { //Start async operations futures.emplace_back(std::async(std::launch::async, parsefilefunction, file)); } for (auto& future : futures) { //Merge results of the async operations auto result = future.get(); std::copy(result.begin(), result.end(), std::back_inserter(results2)); } }
69,531,298
69,531,874
GL_LINEAR / GL_NEAREST equivalent in DirectX 11
I have a scene in which i load the same texture only depending on its resolution i use different filtering modes in OpenGL, these are GL_LINEAR, GL_NEAREST and so on. For example, for a texture with a resolution below 128 pixels, I set GL_TEXTURE_MIN_FILTER to GL_LINEAR, and for GL_TEXTURE_MAG_FILTER I set GL_NEAREST. And if the texture resolution is more than 128 pixels, then I set GL_TEXTURE_MIN_FILTER to GL_LINEAR_MIPMAP_LINEAR and for GL_TEXTURE_MAG_FILTER to GL_LINEAR. In general, I have a question what is the equivalent in DirectX 11 for this, because otherwise I have a texture that has a resolution of less than 128 pixels to become blurry. OpenGL: DirectX 11: This is how it looks in my code, only this is an example for both APIs. if (width > 128 || height > 128) { min = TextureFilteringMode::LINEAR_MIPMAP_LINEAR; mag = TextureFilteringMode::LINEAR; } else if (width <= 128 || height <= 128) { min = TextureFilteringMode::LINEAR; mag = TextureFilteringMode::NEAREST; }
You can find all of the filtering options here. Your code if you had written it only for DirectX API would look something like this: D3D11_SAMPLER_DESC sampler_desc{}; if (width > 128 || height > 128) { sampler_desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; sampler_desc.MinLOD = 0; sampler_desc.MaxLOD = D3D11_FLOAT32_MAX; //use all the mipmaps } else if (width <= 128 || height <= 128) { sampler_desc.Filter = D3D11_FILTER_MIN_LINEAR_MAG_MIP_POINT; sampler_desc.MinLOD = sampler_desc.MaxLOD = 0; } //fill the rest of desc Since GL_LINEAR/GL_NEAREST for GL_TEXTURE_MIN_FILTER don't use mipmaps and all of the DirectX filtering options use mipmaps, you need to combine the filter option with MinLOD/MaxLOD parameters in D3D11_SAMPLER_DESC (which is also where the filter parameter is located). You set them both to 0 to force using only the most detail mip level.
69,531,837
69,532,079
How to allocate memory to a 2D array of objects in c++?
Three classes Zoo, ZooObject and Animal are present.Is it valid to declare a 2D array of ZooObjects like mentioned below? If so, how do i initialise it? I am familiar with dynamically allocating a 2D array, but can't figure out this one. class ZooObject; class Zoo { public: int rows, cols; ZooObject ***zooArray; Zoo(int rows, int cols) { this->rows = rows; this->cols = cols; // dynamically initialize ***zooArray as a 2D array with each //element of type Animal // initially initialized to NULL. // initialize each row first. for (i = 0; i < rows; i++) { zooArray[i] = new ZooObject *[cols]; } // initialize each column. for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) { Animal animal; zooArray[i][j] = &animal; } } } }; class ZooObject { public: bool isAlive; }; class Animal : public ZooObject { public: bool isHerbivore; }; int main() { Zoo *zoo = new Zoo(3, 3); }
As already was mentioned, here is nice post where the general answer to the question was detailing explained. How do I declare a 2d array in C++ using new? In your case, if you want to store this as 2D array. You should allocate first all rows, where each row is a ZooObject**, which is ZooObject `s pointers array. And after, for each of the row, you should allocate the array (columns) of ZooObject*. You will have something like this: Zoo(int rows, int cols) { this->rows = rows; this->cols = cols; zooArray = new ZooObject**[rows]; for (int i = 0; i < rows; ++i) { zooArray[i] = new ZooObject*[cols]; for (int j = 0; j < cols; ++j) { zooArray[i][j] = nullptr; } } } However, consider using 1D arrays, you still can access it via 2 dimensions, via corresponding method, which converting rowId, colId pair to 1D dimension. Also, don't forget to delete which you new!
69,533,352
69,533,419
Not understanding setprecision function in c++
I'm learning C++ and am supposed to make a program which takes height in inches, weight in pounds, and age from the user, and gives them the size of their clothing. You get the size of their hat by dividing their weight by their height and multiplying that result with 2.9. I have been testing my code and the output is correct but always has an extra 1 (like 9.941 instead of 9.94) at the end. My answer should only have two digits after the decimal point, even if it's a zero. Does anyone have any tips? Thanks guys. Here is my code: #include<iostream> #include<iomanip> using namespace std; void HatSize(double userHeight, double userWeight) { cout << setprecision(2) << fixed << ((userWeight / userHeight) * 2.9); } int main(){ double height; double weight; double age; cout << "Give me your height in inches, weight in pounds, and age in years. I will give you your hat size, jacket size (inches at chest)\nand waist size in inches." << endl; cin >> height; cin >> weight; cin >> age; HatSize(height, weight); cout << HatSize; return 0; }
You're using setprecision correctly, the issue is that you have an additional statement that is generating the 1. Remove the cout << HatSize; line. HatSize is a function that returns void, so you're sending the actual function itself as input to cout, which is being interpreted as 1. I would also recommend adding a << endl to the cout in your HatSize function, so that your output finishes with a newline. void HatSize(double userHeight, double userWeight) { cout << setprecision(2) << fixed << ((userWeight / userHeight) * 2.9) << endl; // Newline to make output nicer } int main(){ double height; double weight; double age; cout << "Give me your height in inches, weight in pounds, and age in years. I will give you your hat size, jacket size (inches at chest)\nand waist size in inches." << endl; cin >> height; cin >> weight; cin >> age; HatSize(height, weight); // cout << HatSize !!!!!!!!! Get rid of this return 0; }
69,533,568
69,533,696
Assigning a std::string's c_str() result to that same std::string guaranteed safe by the standard?
Is the following code guaranteed safe by the standard, with regards to std::string? #include <string> #include <cstdio> int main() { std::string strCool = "My cool string!"; const char *pszCool = strCool.c_str(); strCool = pszCool; printf( "Result: %s", strCool.c_str() ); } I've seen statements that indicate the result of c_str is only guaranteed safe to use until another method call on the same std::string is made, but it's not clear to me whether it's safe to pass that const char * back into the assignment method or not. When tested using real-world compilers (GCC, Clang, and MSVC at their most recent versions) they all seem to support this behavior. Furthermore, the compilers also support assigning a suffix of the string back to itself, e.g. strCool = pszCool + 3 in this example; the result will be that the string has the same value as what was passed into it. Is this behavior guaranteed somehow, or am I just lucky that the standard libraries provided by the compilers I've tested support this case?
In C++17, this was specified as: basic_string& operator=(const charT* s); Returns: *this = basic_string(s). Remarks: Uses traits::length(). This sequence of operations guarantees that a copy is made before the original storage is destroyed. While a standard library is not required to implement this call using this exact sequence of operations, it is required to have the same behavior as described. In C++20, this wording was reworked, but I would be surprised if the meaning was changed.
69,533,671
69,534,481
C++ noise interpolation issue
I am attempting to generate noise similar to perlin or value noise. I am using stb_image_write library from here to write to image file (i write to disk as hdr and converted to png with GIMP to post on here). This code requires C++ 20 because I am using std::lerp(); Because I am generating a linear gradient as testing I am expecting a linear gradient as output. I know there are more steps to generating the desired noise but, this is where I'm having issues. #include <cmath> template <size_t size> void noise(float seed[size][size], float output[size][size], size_t octave); int main() { // generate test gradient float seedNoise[64][64] = {}; for ( size_t x = 0; x < 64; x++ ) { for ( size_t y = 0; y < 64; y++ ) { seedNoise[x][y] = ((((float)x) / 64.0f + ((float)y / 64.0f)) / 2.0f); } } float _map[64][64] = { 0 }; noise<64>(seedNoise, _map, 4); } template <size_t size> void noise(float seed[size][size], float output[size][size], size_t octave) { size_t step = size / octave; // went back to this // size_t step = (size - 1) / octave; // took this back out for ( size_t x = 0; x <= size - step; x += step ) { for ( size_t y = 0; y <= size - step; y += step ) { // each octave // extract values at corners octave from seed float a = seed[x][y]; float b = seed[x + (step - 1)][y]; // changed this float c = seed[x][y + (step - 1)]; // this float d = seed[x + (step - 1)][y + (step - 1)]; // and this for ( size_t u = 0; u < step; u++ ) { float uStep = ((float)u) / ((float)step); // calculate x step for ( size_t v = 0; v < step; v++ ) { // each element in each octave float vStep = ((float)v) / ((float)step); // calculate y step float x1 = std::lerp(a, b, uStep); // interpolate top edge float x2 = std::lerp(c, d, uStep); // interpolate bottom edge float y1 = std::lerp(a, c, vStep); // interpolate left edge float y2 = std::lerp(b, d, vStep); // interpolate right edge float x3 = std::lerp(x1, x2, vStep); // interpolate between top and bottom edges float y3 = std::lerp(y1, y2, uStep); // interpolate between left and right edges float odat = (x3 + y3) / 2; // average top/bottom and left/right interpolations output[x + u][y + v] = odat; } } } } } Source gradient I think this should be similar to what the output should be. Output As you can see here the right and bottom of the output is all messed up. new output
I think you're accessing the imago outside it's boundaries. X and y can go up to 60 in the loops: for ( size_t x = 0; x <= size - step; x += step ) And the you are accessing position y+step and x+step, which gives 64.
69,534,035
69,534,054
Problem when defining templates with c++ STL containers
I am trying to create a function that works with a template that is supposed to adapt to a container with a vector class by itself as default. T<int> for example. However, when I try to use this function in main I get the error that there is no matching function. #include<string> #include<iostream> #include<fstream> #include<vector> #include<list> #include<deque> #include<forward_list> using namespace std; template<template <typename> class Container = vector> Container<string> filter_codes(const string& route, const char& init) { Container<string> _return; vector<string> temp; ifstream file(route); string wd; while(file>>wd){ if(wd[0]==init) temp.push_back(wd); } _return.resize(temp.size()); copy(temp.begin(), temp.end(), begin(_return)); file.close(); return _return; } int main(){ vector<string> code = filter_codes("a.txt", 'c'); for(auto i : code) cout<<i<<' '; return 0; } The error is main.cpp:36:24: error: no matching function for call to 'filter_codes' vector<string> code = filter_codes("a.txt", 'c'); ^~~~~~~~~~~~ main.cpp:14:19: note: candidate template ignored: substitution failure : template template argument has different template parameters than its corresponding template template parameter Container<string> filter_codes(const string& route, const char& init) I'm planning to use the function through the following statements. vector<string> t1 = filter_codes("a.txt", 'x'); auto t2 = filter_codes<list>("a.txt", 'x');
Your code is valid, and is compiled by GCC and MSVC. However, a Clang bug means the template type you use needs to match exactly with the template template parameter*. Since std::vector has 2 template parameters, and the template template parameter you've written has only 1, it's not an exact match and it fails, even though it's at least as specialized, and is valid. *There's an exception to the exactly rule, which allows a match when the template parameter list is a variadic pack. You can use this exception to get your code to work on Clang. Just change your template template parameter to be templated on a variadic number of template parameters template<template <typename ...> class Container = vector> // ^^^ Container<string> filter_codes(const string& route, const char& init) { // ... } This works everywhere.
69,534,591
69,534,668
Cpp initialize std::map in header
I want to initialize a std::map in my_cpp.h header file: std::map<std::string, double> my_map; my_map["name1"] = 0; my_map["name2"] = 0; But there was a compile error showed up: error: ‘my_map’ does not name a type Can someone explain why this not work for a C++ newbie? Thanks
You can't initialize a map in a .h file like that. Those assignment statements need to be inside a function/method instead. Otherwise, initialize the map directly in its declaration, eg std::map<std::string, double> my_map = { {"name1", 0.0}, {"name2", 0.0} };
69,534,781
69,534,948
Size of struct with bit fields in C++ not adding up
Why is the sizeof a struct with bit fields not what I expected. #include <iostream> using namespace std; struct test { uint8_t x : 4; uint16_t y : 8; uint16_t z : 8; }; struct test2 { uint8_t x : 4; uint16_t y : 10; uint16_t z : 10; }; int main() { cout << sizeof(test) << endl; cout << sizeof(test2) << endl; } This prints 4 and 4. I don't understand why both of these do not have a size of 3. Test has 4+8+8 bits which is 20 and Test2 has 4+10+10 bits which is 24 bits, both less than or equal to 24 bits/3 bytes. I know that if in Test I use uint_8 it would result in a size of 3 but for my actual use case I need Test2(4,10,10 bits). Why is this and is there a way to get this to 3 bytes?
No only bitfields, but all the structures are aligned by the compiler to get the maximum efficiency. If you want to force them to the minimum size you need to use the gcc's attribute packed or the equivalent in compiler you are using, like following: #include <iostream> using namespace std; struct test { uint8_t x : 4; uint16_t y : 8; uint16_t z : 8; } __attribute__ ((packed)); struct test2 { uint8_t x : 4; uint16_t y : 10; uint16_t z : 10; } __attribute__ ((packed)); int main() { cout << sizeof(test) << endl; cout << sizeof(test2) << endl; }
69,535,076
69,536,088
Compiler cannot find header file within header file in C++
I have a header file provided by yaml-cpp library, yaml.h yaml.h: #include "yaml-cpp/parser.h" #include "yaml-cpp/emitter.h" #include "yaml-cpp/emitterstyle.h" #include "yaml-cpp/stlemitter.h" #include "yaml-cpp/exceptions.h" #include "yaml-cpp/node/node.h" #include "yaml-cpp/node/impl.h" #include "yaml-cpp/node/convert.h" #include "yaml-cpp/node/iterator.h" #include "yaml-cpp/node/detail/impl.h" #include "yaml-cpp/node/parse.h" #include "yaml-cpp/node/emit.h" main.cpp #include "./lib/yaml-cpp/include/yaml.h" int main() { YAML::Node config = YAML::LoadFile("config.yaml"); return 0; } All the header files are in the same directory (/home/user/application/libs/yaml-cpp/include), but the compiler is unable to find parser.h and all the other includes. Why is this so and how do I fix it? I have tried using g++ -I/home/user/application/libs/yaml-cpp/include main.cpp but that did not work. I am on a linux environment. Everything works fine when the header files are kept in /usr/lib64, but I am not allowed to do that for this project.
When you have a file yaml.h that itself includes other files like this: #include "yaml-cpp/parser.h" Then the expected directory layout is as follows: somewhere/ | +-- yaml.h | +-- yaml-cpp/ | +-- parser.h You are expected to pass -Isomewhere to your compiler and use the header file yaml.h like this in your own source code: #include <yaml.h>
69,536,258
69,566,175
CUDA Zeropadding 3D matrix
I have a integer matrix of size 100x200x800 which is stored on the host in a flat 100*200*800 vector, i.e., I have int* h_data = (int*)malloc(sizeof(int)*100*200*800); On the device (GPU), I want to pad each dimension with zeros such that I obtain a matrix of size 128x256x1024, allocated as follows: int *d_data; cudaMalloc((void**)&d_data, sizeof(int)*128*256*1024); What is the best approach to obtain the zero-padded matrix? I have two ideas: Iterate through individual submatrices on the host and copy them directly to the correct location on the device. This approach requires many cudaMemcpy calls and is thus likely to be very slow On the device, allocate memory for a 100x200x800 matrix and a 128x256x1024 matrix and write a kernel that copies the samples to the correct memory space This approach is probably much faster but requires allocating memory for two matrices on the device Is there any possibility for three-dimensional matrix indexing similar to MATLAB? In MATLAB, I could simply do the following: h_data = rand(100, 200, 800); d_data = zeros(128, 256, 1024); d_data(1:100, 1:200, 1:800) = h_data; Alternatively, if I copy the data to the device using cudaMemcpy(d_data, h_data, sizeof(int)*100*200*800, cudaMemcpyHostToDevice);, is it possible to reorder data in place such that I do not have to allocate memory for a second matrix, maybe using cudaMemcpy3D or cudaMemset3D?
As you hypothesize, you can use cudaMemcpy3D for this operation. Basically: Allocate your device array as normal Zero it with cudaMemset Use cudaMemcpy3D to perform a linear memory copy from host to device for the selected subarray from the host source to the device destination array. The cudaMemcpy3D API is a bit baroque, cryptically documented, and has a few common traps for beginners. Basically, linear memory transfers require a pitched pointer for both the source and destination, and a extent denoting the size of the transfer. The confusing part is that the argument meanings change depending on whether the source and/or destination memory is a CUDA array or pitched linear memory. In code you will want something like this: int hw = 100, hh = 200, hd = 800; size_t hpitch = hw * sizeof(int); int* h_data = (int*)malloc(hpitch * hh * hd); int dw = 128, dh = 256, dd = 1024; size_t dpitch = dw * sizeof(int); int *d_data; cudaMalloc((void**)&d_data, dpitch * dh * dd); cudaMemset(d_data, 0, dpitch * dh * dd); cudaPitchedPtr src = make_cudaPitchedPtr(h_data, hpitch, hw, hh); ​ ​cudaPitchedPtr dst = make_cudaPitchedPtr(d_data, dpitch, dw, dh); cudaExtent copyext = make_cudaExtent(hpitch, hh, hd); ​‎cudaMemcpy3DParms copyparms = {0}; ​copyparms.srcPtr = src; ​copyparms.dstPtr = dest; copyparms.extent = copyext; copyparms.kind = cudaMemcpyHostToDevice; cudaMemcpy3D(&copyparms); [Note: all done in the browser, never compiled or run use at own risk]
69,536,380
69,544,454
Link 1st-party library with CMake
I want to make a game in C++ and my goal is to isolate the game engine code from the game logic code, so I can potentially reuse some of the logic and have separate git repos: +-- MyPersonalProjects | +-- TheEngine (library) | | +-- src... | +-- TheGame (depends on TheEngine) | | +-- src... | +-- AnotherGame (depends on TheEngine) | | +-- src... I'm new to C++ (coming from Unity C#), so the build system is still something I'm trying to figure out. Using CMake, how would I go about linking the engine to the game? Using a relative path? Copying the .a file to each engine? Or is there a better way to go about this? IDE: CLion for Mac
If you just have an engine and a bunch of games, it's good enough to include the engine as a git submodule to each game and then call add_subdirectory on the engine from inside each. For a sketch: cmake_minimum_required(VERSION 3.21) project(Game) add_subdirectory(Engine) # ... target_link_libraries(Game PRIVATE Engine::Engine) The primary advantage of this method is that it is easy to use and maintain. There are no install rules to write or package managers to learn. The primary disadvantage is that you'll have to wait for the whole engine to build for each game. CCache is a partial mitigation (doesn't work on Windows, can fail for silly reasons). Another disadvantage is that it doesn't scale. A 1-to-N dependency graph is easy to track. An arbitrary dependency DAG is not. As you scale up and build times increase, the value prop of integrating with a package manager, like vcpkg (or Conan) increases significantly.
69,536,550
69,536,759
Initialize a matrix with constant string in c++
I'm trying to initialize this matrix with a constant string (i.e. "@"), in order to fill it later. Hence, the output is not what I'm expecting. Can you please tell me what I'm doing wrong? Can you give me some advice on how to better initialize the matrix with a constant string? #include <iostream> #include <string> using namespace std; char* Board[3][3]; char* PLAYER = "X"; char* COMPUTER = "O"; void displayBoard() { printf(" %c | %c | %c ", Board[0][0], Board[0][1], Board[0][2]); printf("\n---|---|---\n", Board[0][0], Board[0][1], Board[0][2]); printf(" %c | %c | %c ", Board[1][0], Board[1][1], Board[1][2]); printf("\n---|---|---\n", Board[0][0], Board[0][1], Board[0][2]); printf(" %c | %c | %c ", Board[2][0], Board[2][1], Board[2][2]); printf("\n---|---|---\n", Board[0][0], Board[0][1], Board[0][2]); } void FillBoard() { char* initialValue = "@"; for (int i=0; i<3; i++) { for (int j=0; j<3; j++) { Board[i][j] = initialValue; } } } int main () { FillBoard(); displayBoard(); } Output: f | f | f ---|---|--- f | f | f ---|---|--- f | f | f ---|---|---
There are many isssues. Explanation in comments. But as one of the a comments above says: get a good C++ book. BTW your code is rather C code than C++ code. #include <iostream> #include <string> using namespace std; char Board[3][3]; const char PLAYER = 'X'; // you don't need a pointer here, you need a char here const char COMPUTER = 'O'; // same as above void displayBoard() { printf(" %c | %c | %c ", Board[0][0], Board[0][1], Board[0][2]); printf("\n---|---|---\n"); // removed the extra arguments printf(" %c | %c | %c ", Board[1][0], Board[1][1], Board[1][2]); printf("\n---|---|---\n"); // removed the extra arguments printf(" %c | %c | %c ", Board[2][0], Board[2][1], Board[2][2]); printf("\n---|---|---\n"); // removed the extra arguments } void FillBoard() { const char initialValue = '@'; // you don't need a pointer here, you need a char here for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { Board[i][j] = initialValue; } } } int main() { FillBoard(); displayBoard(); }
69,537,024
69,541,554
Is it safe to mix UNICODE and non-UNICODE translation units?
I'm integrating a library which requires _UNICODE and UNICODE to be defined; I can't set these definitions globally on my project for now, so I was wondering if I can safely build only the library code with these definitions. I'm worried about ODR violations, but as far as I understand these definitions only impact macro definitions in the Windows and C runtime headers, so I would expect no ODR violations (as long as my own headers shared between translation units don't depend on UNICODE), but is it really a guarantee? Is it safe to mix translation units built with and without UNICODE/_UNICODE? In other words, is it safe to compile these two files into the same binary: // a.cpp #define _UNICODE #define UNICODE #include <tchar.h> // maybe other windows header inclusion // some code // b.cpp //#define _UNICODE //#define UNICODE #include <tchar.h> // maybe other windows header inclusion // some other code
If there is one inline function with _TEXT()/TCHAR/... in different translation unit, one with preprocessor defined and one not (even if function is not used), then you got ODR-violation. "is it safe?" No. Do you have currently ODR violations? Not sure, maybe, maybe not. Currently that tchar.h only #define/typedef some aliases. so doesn't do ODR-violation by itself. Can Microsoft change <tchar.h> or other windows headers in a way it might produce ODR violation for your code? Yes. Would they do it? Maybe, maybe not.
69,537,052
74,292,111
Clang-format array initializer one per line
Clang-format, given an array of structs with initializers, is putting two items per line: sym keywords[] = { {0, 0, "C"}, {0, 0, "T"}, {0, 0, "V"}, {0, 0, "ax"}, {0, 0, "bool"}, {0, 0, "break"}, ... {0, 0, "val"}, {0, 0, "vector"}, {0, 0, "version"}, {0, 0, "void"}, {0, 0, "while"}, }; How can I get it to just put one item per line? clang-format, array initialisers is the closest I have been able to find to a discussion of this problem, but neither of the proposed solutions has any effect; Cpp11BracedListStyle: false does the same thing except with extra spaces between the braces, and as you can see in the above, making sure there is a comma after the last item, doesn't help.
I'm not entirely sure, but ArrayInitializerAlignmentStyle set to left might achieve that result. This option was added with clang-format version 13. At least my current settings turn your code into: sym keywords[] = { {0, 0, "C" }, {0, 0, "T" }, {0, 0, "V" }, {0, 0, "ax" }, {0, 0, "bool" }, {0, 0, "break" }, {0, 0, "val" }, {0, 0, "vector" }, {0, 0, "version"}, {0, 0, "void" }, {0, 0, "while" }, }; If I remove that setting I get something similar to your result. My current settings, which probably don't do what you expect them at other locations: --- AlignAfterOpenBracket: Align AlignArrayOfStructures: Left AlignConsecutiveAssignments: true AlignConsecutiveDeclarations: true AlignConsecutiveMacros: true AlignEscapedNewlines: Left AlignOperands: true AlignTrailingComments: true AllowShortBlocksOnASingleLine: false AllowShortCaseLabelsOnASingleLine: false AllowShortFunctionsOnASingleLine: None AllowShortIfStatementsOnASingleLine: Never AllowShortLambdasOnASingleLine: None AllowShortLoopsOnASingleLine: false BreakBeforeBraces: Allman BreakConstructorInitializers: AfterColon BreakInheritanceList: AfterColon ColumnLimit: 120 EmptyLineBeforeAccessModifier: Always FixNamespaceComments: true IncludeBlocks: Regroup IndentCaseLabels: true IndentPPDirectives: BeforeHash IndentWidth: 4 IndentWrappedFunctionNames: true KeepEmptyLinesAtTheStartOfBlocks: false MaxEmptyLinesToKeep: 1 PackConstructorInitializers: NextLine PenaltyBreakAssignment: 10 PenaltyBreakBeforeFirstCallParameter: 10 PenaltyBreakComment: 10 PenaltyBreakFirstLessLess: 10 PenaltyBreakString: 10 PenaltyBreakTemplateDeclaration: 10 PenaltyExcessCharacter: 10 PenaltyReturnTypeOnItsOwnLine: 1000 PointerAlignment: Left ReflowComments: true SortUsingDeclarations: true SpaceAfterCStyleCast: false SpaceAfterLogicalNot: false SpaceBeforeAssignmentOperators: true SpaceBeforeCtorInitializerColon: true SpaceBeforeInheritanceColon: true SpaceBeforeParens: ControlStatements SpacesInCStyleCastParentheses: false Standard: Latest TabWidth: 4 UseTab: Never
69,537,561
73,571,639
No result in QTSql query
I've created a function to exeute a query to postgresql database. I call the function with the query string, a boolean in order to tell me if the query is ok or not and an error string. If I try with a correct query (tested in postgresql prompt) I dont enter in xQueryResult.next() loop but xQueryResult is not empty. I use c++17, postgresql database and QTSql library (Qt 5.15) #include "SqlDatabase.h" #include <QtSql\QSqlError> #include <QtSql\QSqlQuery> #include <QtSql/QSqlRecord> #include <QJsonObject> #include <QJsonArray> QJsonDocument SqlDatabase::fun(const QString &i_xQuery, bool& bOk, QString& strErrorMessage) { QJsonDocument xJsonDoc; QSqlQuery xQueryResult = m_pxCurrentDatabase->exec(i_xQuery); if (QSqlError::NoError != xQueryResult.lastError().type()) { bOk = false; strErrorMessage = QString("%1: %2").arg(__FUNCTION__).arg(xQueryResult.lastError().text()); return xJsonDoc; } QJsonArray xRecordsArray; int iFieldIndex = 0; int iFieldCount = 0; xQueryResult.first(); while (true == xQueryResult.next()) { const QSqlRecord& xSqlRecord = xQueryResult.record(); QJsonObject xJsonObj; if (iFieldCount == 0) iFieldCount = xSqlRecord.count(); for (iFieldIndex = 0; iFieldIndex < iFieldCount; iFieldIndex++) { QString strKey = xSqlRecord.fieldName(iFieldIndex); xJsonObj[strKey] = QJsonValue::fromVariant(xSqlRecord.value(iFieldIndex)); } xRecordsArray.append(xJsonObj); } QJsonObject xObject; xObject["Records"] = xRecordsArray; xObject["NumRowsAffected"] = xQueryResult.numRowsAffected(); xObject["LastInsertId"] = xQueryResult.lastInsertId().toString(); xJsonDoc.setObject(xObject); bOk = true; strErrorMessage = ""; return xJsonDoc; } i call the function from main with QJsonDocument xResultDoc; std::unique_ptr<Exercise::Comm::SqlDatabase> m_pxDatabase; QString strQuery = "INSERT INTO public.tab1 (id,name_id,descr_id,description,"user") VALUES ( 'test', '$Default', 0, 'test', '' )RETURNING id;" bool bOk; QString strErrorMessage; xResultDoc = m_pxDatabase->exec2(strQuery, bOk, strErrorMessage);
The code is ok. Bug is in qt version. Updating Qt code works properly.
69,538,013
69,545,109
Shared CMake scripts between multiple projects
I'm looking for a way to share CMake scripts between multiple projects. In a repo called somelib I have a cmake folder, and from the other projects I want to include the scripts in it. In the CMakeLists.txt of somelib I include many files from the cmake folder. My projects declare "somelib" as an external dependency like so : include(FetchContent) FetchContent_Declare( somelib GIT_REPOSITORY git@git.somewhere.com:somewhere/somelib.git GIT_TAG origin/master ) FetchContent_MakeAvailable(somelib) I'm not sure this is a good practice so feel free to correct me, but I'm willing to include the CMakeLists.txt of somelib so that my project include all the files that somelib includes. So after the FetchContent_MakeAvailable I did : include(${somelib_SOURCE_DIR}/CMakeLists.txt) This include by itself works just fine, but the issue lies in the CMakeLists.txt of somelib. Indeed, the includes it does are not relative to its location resulting in errors like : CMake Error at _build/_deps/somelib-src/CMakeLists.txt:26 (include): include could not find load file: cmake/Cache.cmake Call Stack (most recent call first): CMakeLists.txt:47 (include) CMake Error at _build/_deps/somelib-src/CMakeLists.txt:29 (include): include could not find load file: cmake/Linker.cmake Call Stack (most recent call first): CMakeLists.txt:47 (include) CMake Error at _build/_deps/somelib-src/CMakeLists.txt:33 (include): include could not find load file: cmake/CompilerWarnings.cmake Call Stack (most recent call first): CMakeLists.txt:47 (include) I do realize that instead of including the CMakeLists.txt I could simply do : include(${somelib_SOURCE_DIR}/cmake/Cache.cmake) include(${somelib_SOURCE_DIR}/cmake/Linker.cmake) include(${somelib_SOURCE_DIR}/cmake/CompilerWarnings.cmake) But this will become quite big as the time goes by (plus it will be duplicated between all my projects), so I would like to have a single entry point, a single thing I can include to have everything at hand in my CMakeLists. Is it possible ?
Don't do include(${somelib_SOURCE_DIR}/CMakeLists.txt) since FetchContent_MakeAvailable(somelib) already calls add_subdirectory on that same file. If you want access to its scripts, then just run: list(APPEND CMAKE_MODULE_PATH "${somelib_SOURCE_DIR}/cmake") include(Cache) include(Linker) include(CompilerWarnings) But this will become quite big as the time goes by (plus it will be duplicated between all my projects), so I would like to have a single entry point, a single thing I can include to have everything at hand in my CMakeLists. Is it possible? You could also move these helpers to their own repository and have every project FetchContent that. Then its CMakeLists.txt would just have this: list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") set(CMAKE_MODULE_PATH "${CMAKE_MODULE_PATH}" PARENT_SCOPE) And you would run: FetchContent_MakeAvailable(my_helpers) include(MyHelpers) where MyHelpers.cmake simply include()s all the other helpers.
69,538,035
69,538,226
Implementing the assignment operator in an abstract base class using the curiously recurring template pattern (CRTP)
I am writing an abstract CRTP-based abstract base class for static/dynamic arrays. I intend to put as many methods as possible in the base class so that there is no code duplication in the derived classes. I have got the indexing operator working but I'm struggling with the assignment (=) operator. /** Array base class. */ template <class t_derived_class, class data_type> class ArrayBase { private: t_derived_class& Derived; public: /** Default constructor. */ ArrayBase() : Derived(static_cast<t_derived_class&>(*this)) {} /** Pure virtual desctructor. */ virtual ~ArrayBase() {}; /** Index operator overloads. */ data_type& operator[](const std::size_t _index) { return *(Derived.begin() + _index); } const data_type& operator[](const std::size_t _index) const { return *(Derived.begin() + _index); } /** Assignment operator overloads. */ t_derived_class& operator=(const t_derived_class& _other_derived) { for(std::size_t i = 0; i < Derived.size(); ++i) Derived[i] = _other_derived[i]; return Derived; } }; /** Static array class. */ template <class data_type, int array_size> class StaticArray : public std::array<data_type, array_size>, public ArrayBase<StaticArray<data_type, array_size>, data_type> { using Base = ArrayBase<StaticArray<data_type, array_size>, data_type>; friend Base; public: /** Default constructor. */ StaticArray() : std::array<data_type, array_size>() {} /** Default destructor. */ ~StaticArray() = default; using Base::operator[]; using Base::operator=; }; /** Dynamic array class. */ template <class data_type> class DynamicArray : public std::vector<data_type>, public ArrayBase<DynamicArray<data_type>, data_type> { // ... }; int main() { StaticArray<double, 3> array1; array1[0] = 1.0; array1[1] = 2.0; array1[2] = 3.0; // This code compiles StaticArray<double, 3> array2 = array1; // This code does not compile array2 = array1; return 0; } My IDE (CLion) gives me the following error when I use the assignment operator as above: Object of type 'StaticArray<Apeiron::Float, 3>' (aka 'StaticArray<double, 3>') cannot be assigned because its copy assignment operator is implicitly deleted The compiler errors are: error: ‘Apeiron::StaticArray<double, 3>& Apeiron::StaticArray<double, 3>::operator=(const Apeiron::StaticArray<double, 3>&)’ cannot be overloaded with ‘t_derived_class& Apeiron::ArrayBase<t_derived_class, data_type>::operator=(const t_derived_class&) [with t_derived_class = Apeiron::StaticArray<double, 3>; data_type = double]’ 90 | class StaticArray : public std::array<data_type, array_size>, public ArrayBase<StaticArray<data_type, array_size>, data_type> | ^~~~~~~~~~~ Array.h:62:20: note: previous declaration ‘t_derived_class& Apeiron::ArrayBase<t_derived_class, data_type>::operator=(const t_derived_class&) [with t_derived_class = Apeiron::StaticArray<double, 3>; data_type = double]’ 62 | t_derived_class& operator=(const t_derived_class& _other_derived) Can anyone advise me on how I can get this to work?
Since the member variables of your ArrayBase are reference, the implicitly-declared ArrayBase::operator= will be automatically deleted. The alternative is to remove the member variables and directly use the help function to get the reference of the derived class: template <class t_derived_class, class data_type> class ArrayBase { private: t_derived_class& Derived() noexcept { return static_cast<t_derived_class&>(*this); }; const t_derived_class& Derived() const noexcept { return static_cast<const t_derived_class&>(*this); }; public: /** Pure virtual desctructor. */ virtual ~ArrayBase() {}; /** Index operator overloads. */ data_type& operator[](const std::size_t _index) { return *(Derived().begin() + _index); } // ... };
69,538,072
69,538,242
Avoid copy construction by std::transform
I'm calling std::transform with a lambda that takes by reference and gives back a reference to the vector element. However, according to my program output, the copy constructor is called and the objects are NOT the same. Code: #include <algorithm> #include <iostream> #include <vector> class Math { private: int val_ = 5; public: Math(const Math& m) { std::cout << "Copy constructor, our address: " << this << ", his address: " << &m << std::endl; } Math(int val) : val_(val) { std::cout << "Object constructed with " << val << std::endl; } }; int main() { std::vector<Math> v_math = { { 5 }, { 10 } }; std::transform( begin(v_math), end(v_math), begin(v_math), [](const Math& m)-> const Math& { return m; }); } Output (Godbolt): Object constructed with 5 Object constructed with 10 Copy constructor, our address: 0x23d7ec0, his address: 0x7fff9dc499a8 Copy constructor, our address: 0x23d7ec4, his address: 0x7fff9dc499ac So three things are unclear to me right now: Why are the objects different? Shouldn't they be the same? Why is one object's address bigger than the other? Is this because the copied-to object remains on the stack which has offset-pointers? How can I avoid copy construction as well (actually I just "misuse" std::transform for a declarative way of invoking a lambda on every std::vector element)?
The copies have nothing to do with your usage of std::transform. They happen when you construct your v_math std::vector, because you're using a std::initializer_list constructor, which forces copies during construction. In your std::transform call, operator=(const Math&) is called, change your code to the following to see this. class Math { private: int val_ = 5; public: Math(const Math& m) { std::cout << "Copy constructor, our address: " << this << ", his address: " << &m << std::endl; } Math(int val) : val_(val) { std::cout << "Object constructed with " << val << std::endl; } Math& operator=(const Math& other) { val_ = other.val_; std::cout << "Operator=(const Math&) called!\n"; return *this; } }; int main() { std::vector<Math> v_math = { { 5 }, { 10 } }; std::cout << "After constructing v_math!\n"; std::transform( begin(v_math), end(v_math), begin(v_math), [](const Math& m)-> const Math& { return m; }); std::cout << "After std::transform call!\n"; }
69,538,474
69,538,595
Need help understanding the sort() c++ function weird behavior
I have a comparator function that compares two strings which represent numbers that have no leading zeros, eg "123" or "5". bool comp(string s1,string s2){ if(s1.size()!=s2.size()) return s1.size()<s2.size(); int i=0; while(i<s1.size() && s1[i]==s2[i]) i++; if(i==s1.size()) return true; return s1[i]<s2[i]; } Along with a vector of strings nums I use the sort() function like this: sort(nums.begin(),nums.end(),comp); And this function will work for this vector: {"5","5","5","5","5","5","5","5","5","5","5","5","5","5","5","5"} But if I add one more "5" to the vector it throws this: terminate called after throwing an instance of 'std::length_error' what(): basic_string::_M_create What is going on here?
Your comparer doesn't respect strict weak ordering, equality checked by if (i == s1.size()) return true; should be if (i == s1.size()) return false; Alternatively, using <tuple> facility ensures strict weak ordering: bool comp(const std::string& s1, const std::string& s2) { return std::forward_as_tuple(s1.size(), s1) < std::forward_as_tuple(s2.size(), s2); }
69,539,246
69,543,604
How do i find empty space in array and fill it with part of code / how do i rand 3 randed arrays into one and shuffle it randomly?
Got a task to do password generator. Right now i have a problem with the output because if i build the code here is the outcome. so my problem is that i need to get something more like this with my own input choice and to mix it into each other so it wouldn't go like the first picture. i hopefully made myself more clear about my problem. i - stands for the number for cycle. la - stands for the lower alphabet for cycle. ha - stands for the higher alphabet for cycle. #include <iostream> #include<ctime> using namespace std; const char num[] = "0123456789"; const char lower_alp[] = "abcdefghijklmnopqrstuvwxyz"; const char higher_alp[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; int sizeofnum = sizeof(num) - 1; int sizeoflower_alp = sizeof(lower_alp) - 1; int sizeofhigher_alp = sizeof(higher_alp) - 1; int main() { int password_length = 0, nums, loweralp, higheralp; cout << "Enter password length: "; cin >> password_length; cout << "How many lower alphabet symbols do you want in the password:"; cin >> loweralp; cout << "How many higher alphabet symbols do you want in the password:"; cin >> higheralp; cout << "How many numbers do you want in the password:"; cin >> nums; srand(time(NULL)); for (int i = 0; i < nums; i++) { cout << num[rand() % sizeofnum]; } for (char la = 0; la < loweralp; la++) { cout << lower_alp[rand() % sizeoflower_alp]; } for (char ha = 0; ha < higheralp; ha++) { cout << higher_alp[rand() % sizeofhigher_alp]; } return 0; }
If I understand you want to combine a random selection of characters from each of the 3 sets in a random order, then a convenient way to ensure you end up with a randomized selection from each set combined in a random order would be to: shuffle each set initially, create a string concatenating the needed number of characters from each shuffled string, and shuffle the concatenated string. You can build in that direction based upon the shuffle_string() answer received to do: void shuffle_from_sets(std::string& str, size_t n1, size_t n2, size_t n3) { std::random_device rd; std::mt19937 g(rd()); std::string s1 {"abcdefghijklmnopqrstuvwxyz"}, s2 {"ABCDEFGHIJKLMNOPQRSTUVWXYZ"}, s3 {"0123456789"}; std::shuffle (s1.begin(), s1.end(), g); /* shuffle sets */ std::shuffle (s2.begin(), s2.end(), g); std::shuffle (s3.begin(), s3.end(), g); /* create string from shuffled sets */ str = s1.substr (0, n1) + s2.substr (0, n2) + s3.substr (0, n3); std::shuffle(str.begin(), str.end(), g); /* shuffle final string */ } (note: you would want to validate that n1, n2, n3 are less than or equal to the length of the set each draws from -- that if left to you) You can also add a set with special characters to strengthen your final password, e.g. std::string s4 {"~!@#$%^&*()_+-={}|[]\\:\";'<>?,./"}; A complete example would be: #include <iostream> #include <string> #include <random> #include <algorithm> void shuffle_from_sets(std::string& str, size_t n1, size_t n2, size_t n3) { std::random_device rd; std::mt19937 g(rd()); std::string s1 {"abcdefghijklmnopqrstuvwxyz"}, s2 {"ABCDEFGHIJKLMNOPQRSTUVWXYZ"}, s3 {"0123456789"}; std::shuffle (s1.begin(), s1.end(), g); /* shuffle sets */ std::shuffle (s2.begin(), s2.end(), g); std::shuffle (s3.begin(), s3.end(), g); /* create string from shuffled sets */ str = s1.substr (0, n1) + s2.substr (0, n2) + s3.substr (0, n3); std::shuffle(str.begin(), str.end(), g); /* shuffle final string */ } int main (void) { std::string s{}; size_t n1, n2, n3; std::cout << "no chars [a-z] : "; if (!(std::cin >> n1)) { return 1; } std::cout << "no chars [A-Z] : "; if (!(std::cin >> n2)) { return 1; } std::cout << "no chars [0-9] : "; if (!(std::cin >> n3)) { return 1; } shuffle_from_sets (s, n1, n2, n3); std::cout << "shuffled string : " << s << '\n'; } Example Use/Output Building your randomized passwords from the sets would look similar to: $ ./bin/string_shuffle_sets no chars [a-z] : 6 no chars [A-Z] : 4 no chars [0-9] : 3 shuffled string : LtW9bu53ksxIC or $ ./bin/string_shuffle_sets no chars [a-z] : 6 no chars [A-Z] : 4 no chars [0-9] : 3 shuffled string : yJKqP5hnbi3Q6 Look things over and let me know if you have further questions.
69,539,401
69,539,667
Finding factors of number in C++ but I want to print number of factors on first line
I am able to find the factors but not getting how to print the count of factors like in Sample output in c++ Question : You are given a number N and find all the distinct factors of N Input: First-line will contain the number N. Output: In the first line print number of distinct factors of N. In the second line print all distinct factors in ascending order separated by space. Constraints 1≤N≤10^6 Sample Input 1: 4 Sample Output 1: 3 //Number of factor 1 2 4 //factors //My code #include<bits/stdc++.h> using namespace std; int main(){ int n; cin>>n; int count =0; for(int i=1;i<=n;i++){ if(n%i == 0){ count++; cout<<count<<endl; cout<<i<<" "; } }
Store the factors in a vector: #include <iostream> #include <vector> int main() { int n; std::cout << "Please enter a number" << std::endl; std::cin >> n; std::vector<int> factors; for(int i = 1; i <= n; ++i) { if(n%i == 0) { factors.push_back(i); } } std::cout << factors.size() << std::endl; for (std::vector<int>::iterator itr = factors.begin(); itr != factors.end(); ++itr) { std::cout << *itr << " "; } }
69,540,071
69,541,011
Coding in Bits. or Structuring a Byte into several different values with respect to corresponding bits. or Bitwise coding or Bit Manipulation
I would like to have single byte with multiple funtions. I would like to split a Byte into 5 parts; that is first half byte or first four bits, with 0-15 different values. Then the last half of the byte or last 4 bits must be separated, each bit (that is 5th, 6th, 7th, or 8th_bit) must have value of 0 or 1. For example: if I pass value something like this "0b 1111 1 1 1 1". It should configure to the funtion which is there in value 15 of first 4 bits(0-15) and the 5th_bit(0-1) must be set(1) or clear(0) to do certain funtion and 6th, 7th, and 8th_bit must also do similar thing like 5th bit Maybe if you look into the image you might get what I am trying to say. Please click the link to see the image. I am not sure about title, I think the title fits my question. I would like to achieve this in C++. How to achieve this? How to do this? any examples?
You need to learn a littel bit about boolean algebra. Most important are AND, OR and NOT operations. You can build anything with these 3 operations. There are other Operations which can also be used to come to any desired outcome, like NAND and NOR, and more. But anyway. C++ has bitwise operators for AND & or OR | or NOT~. Please do not mix up with boolean logical operators &&. || and ! that work on boolean expressions. Let us look like that bitweise operators behave. In the following example we are always talking about one sinegle bit: AND Result Or Result NOT Result a b y a b y a y --------- ---------- ---------- 0 0 0 0 0 0 0 1 0 1 0 0 1 1 1 0 1 0 0 1 0 1 1 1 1 1 1 1 No we need to understand, how we can set a bit and clear a bit. From the above table you can see that Something AND 0 --> is always 0. So, we can clear a bit with AND 0 Something OR 1 --> is always 1. So, we can set a bit with OR 1 Something AND 1 --> is always "Something". So, AND with 1 is a neutral operation Something OR 0 --> is always "Something". So, OR with 0 is a neutral operation OK. Now we know how to set a bit or how to clear a bit. We can also do multiple bit sets or bit clearences. So, if we want to set the uppermost 4 bits in a byte, we can write byte = byte | 0b11110000. That will set the upper most 4 bits and not change the 4 lower most bits. If we want to delete/reset/set-to-0 the bit number 0 and 1, then we can write: byte = byte & 0b11111100. If we want to know the value of several bits, we can "mask" them. We can create a binary value, with bits set on positions that we want to read. Example. We want to read the 3 lower most bits. So, value = byte & 0b00000111. Should be clear now. . . . We have also 2 additional important operations, and that is shifting. Since bits, depending on their position, have a different value, we need often to shift tehm to the correct position. In your example, letS write the value 9 to the 4 upper most bits. What we need to do is: Delete any old stuff that is possibly thaer with masking Create value 9 and shift it to 4 positions to the right Delete the 4 lower bits of the shifted values OR the result over the target value unsigned char value = 9; value = value << 4; value = value & 0b11110000; Target = target | value; Of course you can do all this in one statement. Reading the 4 upper most values will be the reverse approach. value = target & 0b11110000; value = value >> 4; value = value & 0b00001111; by creating bit patterns ( a mask) you can influence all desired bits
69,540,504
69,543,729
Segmentation fault when emplacing to map
I have a map like this, std::unordered_map<size_t, Connection> connections; and I emplace elements into it like this, void onConnectionEvent(size_t peer, std::string message, Local::TCP::Connection socket) { auto [element, inserted] = connections.try_emplace(peer); auto& connection = element->second; // Do Work } I was load testing the sever by making concurrent connections and at the 1000th connection the sever receives segfault and when debugging with GDB, I found that it happens because for some reason that it can't read variable inside the standard library's own emplacing code. Existing answers on Stack Overflow say that this happens because program runs into infinite recursion or that stack size is not large enough, but I can't relate those causes to my problem. I can't reproduce this all the time. It happens randomly. Here is the standard library code where this happens: /usr/include/c++/11/bits/stl_function.h: /// One of the @link comparison_functors comparison functors@endlink. template<typename _Tp> struct equal_to : public binary_function<_Tp, _Tp, bool> { _GLIBCXX14_CONSTEXPR bool operator()(const _Tp& __x, const _Tp& __y) const // This is where this happens { return __x == __y; } };
You must use a lock that surrounds both manipulation and reading of the container. STL containers themselves are not thread-safe by default, even though the way this is formulated is, in my opinion, rather confused. Manipulating the content of the same container instance itself - adding, removing or moving elements - is not thread-safe. By default, the C++ memory model does not define what threads see when other threads manipulate data, unless there is forward progress. Manipulating a map potentially cause a lot of inter-related memory accesses. It is easy to create infinite loops or memory access violations if one thread only sees a partially modified map, or when that memory has been freed (when doing a resize, for example) by another thread. You can enforce forward progress in many ways. In your case, you should protect all access to the list with a lock: anything that gets, adds, moves or removes and element from the list. If your container's iterator does not make a full copy of all elements, which is very likely, this includes iterators. An example solution: class ConnectionManager { std::unordered_map<size_t, Connection> connections; mutable std::mutex m; public: void onConnectionEvent(size_t peer, std::string message, Local::TCP::Connection socket) { std::lock_guard guard(m); auto [element, inserted] = connections.try_emplace(peer); auto& connection = element->second; // Do Work } void handleConnection(std::function<void(std::unordered_map<size_t, Connection>) > handle) const { std::lock_guard guard(m); handle(connections); } }; If you want to make sure multiple reads can happen any time, but modifying the map uses an exclusive lock: class ConnectionManager { std::unordered_map<size_t, Connection> connections; mutable std::shared_mutex m; public: void onConnectionEvent(size_t peer, std::string message, Local::TCP::Connection socket) { std::lock_guard guard(m); auto [element, inserted] = connections.try_emplace(peer); auto& connection = element->second; // Do Work } void handleConnection(std::function<void(std::unordered_map<size_t, Connection>) > handle) const { std::shared_lock guard(m); handle(connections); } };
69,540,628
69,540,897
Data members from variadic typename template and overloading
Similar to question Declare member variables from variadic template parameter, but with an additional question: Let's say I have 2 (or many) structs: struct A { int a; }; struct B { int b; }; And I want to make a class holding dynamic arrays of each, AND be able to have a call doing specific processing to one of those types: struct Manager<A, B> { std::vector<A> as; std::vector<B> bs; template<typename T> process(); }; Where, if I call process<A> it will loop over all "as", and process<B> loops over all "bs". Additionally, I provide A, B or any number of structs (distinct from eachother) as variadic template parameters. In other words, doing Manager<A, B> is the expected use, but doing Manager<A, A, B> is not allowed (because of the 2 'A's). Is this possible (and, if possible, in a way that doesn't create a stupidly high amount of boilerplate code or is unreadeable)?
From what I understand, std::tuple does the job too: template <typename... Ts> struct Manager { std::tuple<std::vector<Ts>...> vectors; template <typename T, typename F> void process(F f) { for (auto& e : std::get<std::vector<T>>(vectors)) { f(e); } } }; Demo
69,540,867
69,541,266
QT: Use stylesheet as external file
I have a project developed in QT 5.9.5, so C++. I have an with a GUI and I want to describe the appereance of the widgets with an external global stylesheet. I'm working with QTCreator. I added a general file named "stylesheet.qss" and QTCreator put it into "Other files" directory. I have not created resources files. Only the qss file inside the "Other files" directory. To call the file, I write in the mainwindow.cpp (mainwindow is the user interface, mainwindow.ui) the following code: QFile file(":/stylesheet.qss"); file.open(QIODevice::ReadWrite); QTextStream in(&file); QString text; text = in.readAll(); file.close(); setStylesheet(text); When I run the app, the application output give me the following problem: QIODevice::read (QFile, ":/stylesheets.qss"): device not open Instead, if I write: QFile file("stylesheet.qss"); And also if I write: file.open(QIODevice::ReadOnly); the problem doesn't occur. However, in all the cases, the variable text is empty and I can't use stylesheet. Checking the file.errorString(), it gives: "Unknown error" and checking the file.error(), it gives: 0 Someone can suggest me a solution or another way to add a stylesheet to my app? Thank you, Marco
add your .qss File in Resource(.qrc) put this code that you want to add your qss in your program in main.cpp : #include "mainwindow.h" #include <QApplication> #include <QFile> int main(int argc, char *argv[]) { QApplication a(argc, argv); /** * Load the application style */ QFile styleFile(":/Style.qss"); styleFile.open(QFile::ReadOnly); /** * Apply the loaded stylesheet */ QString style(styleFile.readAll()); a.setStyleSheet(style); MainWindow w; w.show(); return a.exec(); }
69,541,092
69,541,147
Is there a reason to use std::distance() over iterator::operator-()?
I am unsure why there is both std::distance(iterator const&, iterator const&) and a iterator::operator-(iterator const&) (as well as adaptors operator-(iterator const&, iterator const&)), where iterator is a placeholder for any iterator. Should one be used over the other, and if so, what circumstances?
operator - is not a member of most iterator types, so it is an error to use it generically unless your algorithm only supports random access. std::distance on the other hand knows about iterator categories and will use operator - if it is available and if not, it will use N calls to operator -- to do the subtraction.
69,541,247
69,542,061
Save a char* parameter intro a string
Please help me with this question.. I'm beginner with gtest. I have a mocked function DoSomething(const char* par0, const char* par2) I want to save its second argument into std::string `savedPar_`; EXPECT_CALL(mockd_, DoSomething(_, _,)) .WillOnce(DoAll(SaveArg<1>(savedPar_), (Return(Ok)))); And got this error: error: no match for ‘operator*’ (operand type is ‘const std::__cxx11::basic_string<char>’) *pointer = ::testing::get<k>(args); Than you so much in advance!
According to the doc SaveArg<N>(pointer) Save the N-th (0-based) argument to *pointer. It should be: std::string savedPar_; EXPECT_CALL(mockd_, DoSomething(_, _,)) .WillOnce(DoAll(SaveArg<1>(&savedPar_), (Return(Ok)))); // ^
69,541,591
69,550,275
Is there a reason why make_reverse_iterator(make_reverse_iterator(it)) results in a different type?
I would think that: static_assert(is_same_v< decltype(make_reverse_iterator(make_reverse_iterator(it))) , decltype(it)>); would compile, but it doesn't. Is there some reason why this is? I can see this as potentially resulting in larger generated code when writing templates. This isn't that difficult to implement: template <typename T> T make_reverse_iterator(reverse_iterator<T> it) { return it.base(); } and would result in a smaller binary if double or more reversals are done when calling a template function, especially if that function were to say call itself recursively using a reverse_iterator of what it was called with without complicating the code with other specializations.
There's a simple question whose answer explains this: Is the return value of make_reverse_iterator a reverse_iterator? See, a reverse iterator is not just an iterator that runs backwards. It's a type. Or rather, it's a template which generates a family of types. And that template is expected to provide certain behavior; that behavior is what makes it a reverse iterator. And this is behavior that is not required to be provided by a non-reverse_iterator type. A reverse_iterator<reverse_iterator<I>> is not the same thing as I. You can't get the base of I, for example. If a user calls make_reverse_iterator, it is their right to expect that they will get a reverse_iterator, with all the powers and privileges provided by that template. To return anything else would be tantamount to lying to the user. What you seem to want is make_iterator_go_backwards: a function that returns some iterator type that goes backwards through the sequence. And that's a valid thing to want. But that thing is not spelled make_reverse_iterator. If you have a function called, make_some_type, it should return some_type.
69,541,820
69,649,867
Qt5 Ignoring Native Touch Events
A couple years ago, I had to implement touch features in an application, but my company was still using Scientific Linux 6.4, which did not natively support touch, not to mention multi-touch. Fortunately, I was able to upgrade the kernel to 2.6.32-754, which gave me access to multi-touch events, and while they were not natively handled, I was able to write my own "driver" in the application that would read the /dev/input/event file and use the input_event class in the kernel to capture touch events and translate them to application behavior. Now, two years later, we're finally moving on to RedHat 8, and obviously there's now native touch support. Pretty much all my code is still required as it's highly specific to this application, and I don't see much point in re-writing anything. However, because touch events are now natively recognized, I'm seeing some issues where touch press events will be registered twice -- once from the OS, and once from my driver. The touch press events from my driver are required because they're being tracked and handled by my driver. Is there a way I can update my driver to ignore the OS native touch events that are interfering with my driver without affecting my driver's operation? This is especially prevalent with the on-screen keyboard which is causing it to type the same character twice when the button is pressed.
The simple answer to this problem seemed to be to use xinput to disable the touchscreen device input, which gave me the behavior I wanted. The reason I don't want to re-write the code handling it is because it would be a lot of effort and time for no difference in behavior or performance. I can't just use the native touch because the UI doesn't just use single touch actions, it uses custom gestures that are interpreted by my driver.
69,541,986
69,542,891
Cannot instantiate class inside other class. Member Map::value is not a type name
сlass Chunk { private: size_t value; public: Chunk(size_t value) { this->value; } }; class Snake { private: size_t value; std::vector<Chunk> snake_body; public: Snake(size_t value) { Chunk head_chunk(value); snake_body.push_back(head_chunk); } }; class Map { private: size_t value; // Not able to find "snake" definiton Snake snake(value); // member Map::value is not a type name Snake snake { value; } // Why it works? } I'm newbie in OOP, trying to learn it by creating a game console-snake. Here's a problem i met. Structure of the game should be that class Map holds one snake. But when i am trying to instantiate it, i get a problem. Spent so many time on SOF, but nothing have found yet. And why it works with {} Please help ;/
Snake snake(value) is not valid syntax for initialization, and Snake snake{ value } is valid syntax(but probably initializes to an unitialized value since value is not initialized). Some more comments in code below : class Map { public: // this is best if you want the main program to initialize snake with a user provided value explicit Map(size_t value) : snake{ value } // aggregate initialization https://en.cppreference.com/w/cpp/language/aggregate_initialization { } private: size_t value; // if you use Snake{value} then also initialize value here, size_t value{0}; (or size_t value = 0;) // Not able to find "snake" definiton Snake snake(value); // <== this tries to make a call to the constuctor of Snake which can't be done here Snake snake{ value; } // <== this is a valid initialization syntax, but uses unitialized value (so result can be any number) }
69,542,293
69,542,294
How to link with ntdll.lib using CMake?
I am using ntdll.lib functions in my code to set the system timer to a higher resolution. But when I build my project I get this error: ... .../bin/ld.exe: ... undefined reference to `__imp_NtSetTimerResolution' collect2.exe: error: ld returned 1 exit status ... How do I tell the linker to link with ntdll.lib in my CMake?
This worked for me: if (WIN32) target_link_libraries(executable ntdll) endif()
69,542,355
69,542,560
When is it better to populate an array with fixed index macros vs by incrementing an index?
When would it be better to proceed this way #define PREFIX_IDX 0 #define SUFFIX_IDX 1 #define ARRAY_DATA_SIZE 2 int data[ARRAY_DATA_SIZE ] = 0; int main() { data[PREFIX_IDX] = 6; data[SUFFIX_IDX] = 19; return 0; } compared with #define ARRAY_DATA_SIZE 2 int data[ARRAY_DATA_SIZE ] = 0; int main() { uint8_t currIdx = 0; data[currIdx++] = 6; data[currIdx++] = 19; return 0; } I was told with small arrays it was better to use fixed macros, but I feel like it does not scale very well. What would be the general advice for this?
You should avoid macros whenever possible, and it's possible in this case. If you are using at least C++11 (and you should be), you can use constexpr to declare your magic constants at compile time: static inline constexpr auto PREFIX_IDX = 0u; static inline constexpr auto SUFFIX_IDX = 1u; static inline constexpr auto ARRAY_DATA_SIZE = 2u; That said, you need to match your code to the semantics of what you're doing. This makes your code more readable. The size of the array doesn't matter. What matters is if you've attached different meanings to different elements of the array. You've attached a sematic tag of "prefix" to data[0] and one of "suffix" to data[1]. Since elements of the array have magic roles, you should index them with your magic constants. int data[ARRAY_DATA_SIZE]; int main() { data[PREFIX_IDX] = 6; data[SUFFIX_IDX] = 19; return 0; } Depending on how complex your actual code is, it might be better to forego the array entirely and use separate variables. However, I've had code where you have to treat things as the same type of thing in one place and as different types in another, so an array is definitely OK.
69,542,566
69,542,708
Full pyramid from 5 digit int
i'm having trouble with my C++ homework.. I need an algorithm that can turn an 5 (x4, x3, x2, x1, x0) digit number, into a pyramid like that: x2 x3x2x1 x4x3x2x1x0 Ex. => 12345 3 234 12345 How can I do that? Do I have to take each number individually and display them in order? Edit* I did it, and the code looks like (for anyone that might have the same problem): int num; string str; cout << "Type a 5-digit number: "; cin >> num; stringstream ss; ss << num; ss >> str; char x0 = str[4]; char x1 = str[3]; char x2 = str[2]; char x3 = str[1]; char x4 = str[0]; cout << " " << x2 << endl; cout << " " << x3 << x2 << x1 << endl; cout << x4 << x3 << x2 << x1 << x0;
Yes, you’d have to process the digits individually. Generally I’d expect students to try and tackle it in following ways: Convert the number to a string, then index individual characters on that string and display them. There are multiple ways of doing the integer-to-string conversion. The simplest may be to use an std::ostringstream, say (std::ostringstream() << 1234).str(). Use arithmetic to extract each digit of the string, and convert the digit to a character as it’s passed to a print function. By converting a digit to a character I mean 5 -> '5'. Incidentally, this conversion is as simple as adding '0' to the digit. So, 5+'0' == '5'. The '0' is a number, since in the C family of languages, characters are just small numbers. There may be many approaches to formatting the pyramid, but since the assignment doesn’t require any flexibility, the simplest way would be the best: add necessary spaces by hand.
69,542,764
69,542,910
Searching a vector for a string, and then find the position of the string in c++
I am trying to erase a string from a text file. To do this, I want to read the file into a vector, then I want to search for the position of this string, so I can use vector::erase to remove it. After the string has been erased from the vector, I can write the vector into a new file. So far, I have made all of that, but finding the position of the string. I've found all sorts of solutions using < algorithm > 's std::find, but those answers were trying to check if this string exists, not its position. Here is an example of how the text file is set up. With a string, followed by an integer, followed by .txt without spaces. Each string is on a newline. file123.txt Bob56.txt' Foo8854.txt In this case, the vector would be "file123.txt", "bob56.txt", "Foo8854.txt". This is the code I have made already: std::vector<std::string> FileInVector; std::string str; int StringPosition; std::fstream FileNames; FileNames.open("FileName Permanent Storage.txt"); while (std::getline(FileNames, str)) { if(str.size() > 0) { FileInVector.push_back(str); // Reads file, and this puts values into the vector } } //This is where it would find the position of the string: "bob56.txt" as an example FileInVector.erase(StringPosition); // Removes the string from the vector remove("FileName Permanent Storage.txt"); // Deletes old file std::ofstream outFile("FileName Permanent Storage.txt"); // Creates new file for (const auto &e : FileInVector) outFile << e << "\n"; // Writes vector without string into the new file
Below is the working example. There is no need to store the string into a vector or search for the position of the string inside the vector because we can directly check if the read line is equal to the string to be searched for, as shown. main.cpp #include <iostream> #include <fstream> int main() { std::string line, stringtobeSearched = "Foo8854.txt"; std::ifstream inFile("input.txt"); std::ofstream outFile("output.txt"); if(inFile) { while(getline(inFile, line, '\n')) { std::cout<<line<<std::endl; //if the line read is not same as string searched for then write it into the output.txt file if(line != stringtobeSearched) { outFile << line << "\n"; } //if the line read is same as string searched for then don't write it into the output.txt file else { std::cout<<"string found "<<std::endl;//just printing it on screen } } } else { std::cout<<"file could not be read"<<std::endl; } inFile.close(); outFile.close(); return 0; } input.txt file123.txt Bob56.txt' Foo8854.txt file113.txt Bob56.txt' Foo8854.txt file223.txt Bob96.txt' Foo8814.txt output.txt file123.txt Bob56.txt' file113.txt Bob56.txt' file223.txt Bob96.txt' Foo8814.txt
69,542,803
69,546,285
getting runtime version information of Qt5 library
Is there inside the Qt5 libraries (for Linux) a C++ function or an API to retrieve at runtime the precise version information of the Qt shared library? The GNU glibc has gnu_get_libc_version. The libcurl has curl_version. I want the equivalent for Qt5 (for the RefPerSys project, if that matters). It uses a Qt5 X11 GUI interface.
Use qVersion or QT_VERSION (alternative). To check a specific version: QT_VERSION_CHECK(6, 0, 0).
69,542,820
69,544,763
CMake Include paths - library that depend on external library
Take for example this project structure project CMakeLists.txt main.cpp libA src.cpp CMakeLists.txt libB foo.h foo.cpp CMakeLists.txt src.cpp and main.cpp: #include "foo.h" . . . I need both src.cpp and main.cpp to have libB in their include path, what I've tried to do is: libB/CMakeLists.txt: add_library(libB SHARED src.cpp) libA/CMakeLists.txt: add_library(libA SHARED foo.cpp) target_link_libraries(libA libB) project/CMakeLists.txt: add_subdirectory(libA) add_subdirectory(libB) add_executable(App main.cpp) target_include_directories(App PUBLIC libB) target_link_libraries(App libA libB) And yet I get an error that src.cpp: fatal error: foo.h: No such file or directory
In the top-level: cmake_minimum_required(VERSION 3.21) project(project) option(BUILD_SHARED_LIBS "Build shared libs instead of static" ON) add_subdirectory(libA) add_subdirectory(libB) add_executable(App main.cpp) target_link_libraries(App PRIVATE libA libB) In libA: add_library(libA src.cpp) # Use PUBLIC below if libA exposes libB's types in its API. target_link_libraries(libA PRIVATE libB) In libB: add_library(libB foo.cpp) target_include_directories( libB PUBLIC "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>" ) PUBLIC and INTERFACE properties on targets propagate to their linkees. Thus, when we set up the include directories on libB, any target linking to it will get its source directory added it its include path. We guard the include directory with $<BUILD_INTERFACE:...> so that if you ever install() the library somewhere it might be re-used in another CMake build, it won't remember details of your specific file system.
69,542,893
69,543,307
How to print to file?
I'm need to print some info on a file ".txt". I wrote on the program the link of the file I want to copy the info. The ".txt" file is empty. Eclipse tells me that the code is without error. This is the part of code of the print on file: void stampaVendute(string& vendute,int& n,Opere f[],char p[],int a){ cout<<"\nInserisci il file sul quale vuoi visualizzare le opere vendute: "<<endl; getline(cin,vendute); ofstream ofs; ofs.open(vendute.c_str()); if(!ofs.good()){ cout<<"C'è qualche problema nell'apertura del file"<<endl; return; } for(int i=0;i<n;i++){ if((!stricmp(p,f[i].N_C)) and a<=f[i].anno){ ofs<<"\nOPERA "<<(i+1)<<endl; ofs<<"Codice: "<<f[i].codice<<";"<<endl; ofs<<"Titolo: "<<f[i].titolo<<";"<<endl; ofs<<"Autore: "<<f[i].N_C<<";"<<endl; ofs<<"Anno: "<<f[i].anno<<";"<<endl; ofs<<"Valore: "<<f[i].prezzo<<";"<<endl; } ofs.close(); } cout<<"\nI DATI SONO STATI COPIATI CORRETTAMENTE SUL FILE!"<<endl; }
If if((!stricmp(p,f[i].N_C)) and a<=f[i].anno){ fails the test then nothing is printed to the file. Add a line that unconditionally prints to the file after opening, to see if it works. Print the file name to the user when the file is opened successfully. If you are using Windows, you can use process monitor from SysInternals (now owned by Microsoft) to see what file is actually being opened. ofs.open(vendute.c_str()); why are you using c_str here? You know that open takes a std::string normally! You are getting a pointer to the raw characters just to construct a new different string object, and forcing the compiler to re-count the number of characters (calling strlen() again). You should write it as one line anyway. Initialize the variable when you define it: ofstream ofs {vendute}; ⧺SL.io.50 Don't use endl. for(int i=0;i<n;i++){ ... many uses of `f[i]` follows You should be using a range-based for loop rather than subscripts, but the way you are passing the data (separate pointer to the first element and length) instead of simply passing a collection prevents that. This is not a good way to do things! See Standard Guidelines ⧺I.13 etc. If you did need to go over the collection via subscripts, don't keep subscripting it over and over and over. Make a reference variable pointing to that spot: for(int i=0;i<n;i++){ const auto& x = f[i]; ... now use x over and over, not f[i] here's your problem Look where ofs.close(); is being called. The indentation of the code in the post is all messed up... it looks like this should be after the loop, before the final cout line. But what's that extra } coming from? You are closing the file after the first iteration through the loop. If that case (i==0) did not print results, nothing will ever be shown.
69,543,157
69,543,231
mulit netsting `mutable` in Google proto
I have proto file, saying that, message RecommendInfo{ repeated RecommendItem vec_item = 1; } message Response{ RecommendInfo recomInfo = 1; } I want to produce type Response response. So I use following code, Response response; *(recommendResponse.recominfo().mutable_vec_item()) = {items.begin(), items.end()}; LOG_INFO << response.DebugString(); But there gets empty vecitem. I thought there existed Response object on stack. Response object includes RecommendInfo object on the stack. Because I want to change items inside RecommendInfo object. So I use mutable_vec_item() to set items. I try *(recom_response.mutable_recominfo()->mutable_vecitem()) = {items.begin(), items.end()}; The code works and print complete RecommendInfo object including vec_item. I can't explain it clearly. When I try to change recom_response.recominfo(), it seems to be wrong. However,isn't RecommendInfo an object on stack? And I just want to modify vec_item.
Modifying vecitem modifies the RecommendInfo it belongs to. So in order to modify the content of vecitem, you have to be operating on a modifiable (aka mutable) RecommendInfo. That's why you have to use mutable_recominfo() instead of recominfo().
69,544,262
69,544,603
How to add elements to a vector of pairs every 3rd line?
I'm trying to make a vector of pairs from a text that looks something like that: line1 line2 line3 And the vector would contain a pair of line1 and line2. And another vector would contain line1 and line3 Normally I would add lines to a vector like this vector<string> vector_of_text; string line_of_text; ifstream test_file("test.txt"); if(test_file.is_open()){ while(getline(test_file, line_of_text)){ vector_of_text.push_back(line_of_text) } test_file.close(); } but I don't know if it is possible to access the next line of text with the getline command. For example, in an array, I would do i+1 or i+2 for the next or 3rd element. I was wondering if there was a way to do that with getline.
If I understand the question correctly, you want two vector<pair<string, string>>. This could be one way: // an array of two vectors of pairs of strings std::array<std::vector<std::pair<std::string, std::string>>, 2> tw; unsigned idx = 0; std::string one, two, three; // read three lines while(std::getline(file, one) && std::getline(file, two) && std::getline(file, three)) { // put them in the vector pointed out by `idx` tw[idx].emplace_back(one, two); tw[idx].emplace_back(one, three); // idx will go 0, 1, 0, 1, 0, 1 ... until you can't read three lines anymore idx = (idx + 1) % 2; } Demo
69,544,423
69,545,387
Need help creating a program to factorize numbers
The task is to create a program that can do the maximum factorial possible by the machine using "for" cycle. I understood i have to use bigger data types (the biggest one is "long long", correct me if i'm wrong), and i also understood the concept of the factorial. Otherwise, i really do not know how to apply what i know in c++. these is the idea at the base of what i wrote down as of now: #include <cstdlib> #include <iostream> #include <math.h> include namespace std; int main(int argc, char *argv[]) { long long i, factorial; cin<<factorial; { for(long long i=1; i=factorial; i++) { factorial=factorial*i } } system("PAUSE"); return EXIT_SUCCESS; } Problems are: I don't know if the code it's wrote correctly by doing "factorial=factorial*i", the "i=factorial" in the "for" cycle doesn't make sense, since it will stop the program before it has to. This being said, I would like to point out that i am in high school, my programming knowledge is really poor, and for this reason every kind of advice and information is very well accepted :). Thanks in advance
Maybe you want to compute the maximum factorial that will fit in an unsigned long long data type. But let us look at the horrible program. I add comments with the problems. #include <cstdlib> // Not to be used in C++ #include <iostream> #include <math.h> // Not needed include namespace std; // Completely wrong statement. But even if you would have done it syntactically correct, it should never be used int main(int argc, char *argv[]) // Neither args nor argv is used { long long i, factorial; // i will be redefine later. factorial is not initialized cin<<factorial; // You want to stream somethin into std::cin? { for(long long i=1; i=factorial; i++) // Thats heavy stuff. i=factorial? Nobody know, what will happen { factorial=factorial*i // Semicolon missing } } system("PAUSE"); // Do not use in C++ return EXIT_SUCCESS; // EXIT_SUCCESS is not defined } Maybe the below could give you an idea #include <iostream> int main() { unsigned long long number{}; unsigned long long factorial{1}; std::cin >> number; for (unsigned long long i{ 1 }; i <= number; ++i) factorial = factorial * i; std::cout << factorial; }
69,544,426
69,544,528
C++ reverse a string but printing numbers first
I was given a project in class and almost have it finished, I am required to take a string of numbers and letters and return that string with the numbers printed first followed by the letters in reverse order (ex. abc123 should return 123cba). As of now my code returns a string with the numbers first and the original order of the letters (ex. abc123 returns 123abc). I would be able to do this with two loops however the assignment asks that my code only iterates though the initial string one time. Here is the code I have so far... #include <iostream> #include <string> #include "QueType.h" #include "StackType.h" using namespace std; int main () { QueType<char> myQueue; StackType<char> myStack; string myString="hello there123"; char curchar; string numbers, letters; for (int i = 0; i < myString.length(); i++) { if (isdigit(myString.at(i))) { myQueue.Enqueue(myString.at(i)); myQueue.Dequeue(curchar); numbers += curchar; //cout<<numbers<<endl; } else if (islower(myString.at(i))) { myStack.Push(myString.at(i)); curchar = myStack.Peek(); myStack.Pop(); letters += curchar; //cout<<curchar<<endl; } } cout<<(myString = numbers + letters)<<endl; } In my code, I have two .h files that set up a stack and a queue. With the given string, the code loops through the string looking to see if it sees a letter or number. With a number the spot in the string is then saved to a queue, and with a letter it is saved to the stack. The only other way i can think of reversing the order of the letters is in the if else statement instead of having char = myStack.Peek() every loop, change it to char += myStack.Peek() however I get weird lettering when that happens.
since you already got the string with letters you can basically reverse it and that's it. //emplace version: void reverse_str(std::string& in) { std::reverse(in.begin(), in.end()); } //copy version std::string reverse_str(std::string in) { std::reverse(in.begin(), in.end()); return in; } in your case the emplace version would be the best match. in other cases (e.g. when you want to preserve the original string) the copy version is preferred. adding an example to make it as clean as possible. int main() { std::string inputstr = "123abc"; std::string numbers{}; std::string letters{}; for(auto c : inputstr) { if(isdigit(c)) numbers += c; else letters += c; } reverse_str(letters); //using the emplace version std::cout << numbers + letters; }
69,545,029
69,550,001
C++: How to correct to set up reference of the class function into the non-class reference variable
I have been use the MQTT-library by Goel Gaehwiller(ver. 2.5.0) ad got a little problem with the implementation of the MQTTClient into my own class. The library used a non-class function as a call-back. I tried to use many C++ macroses, but all break the compilation: void CMQTT::local_mqtt_callback(MQTTClient* client, char* topic, char* payload, int payload_length) { //if ( call_back != NULL ) // call_back( client, topic, payload, payload_length ); } void CMQTT::doMQTTSetting() { mqtt_client->begin(host.c_str(), port, *wifiClient); //mqtt_client->onMessageAdvanced( std::bind2nd(std::mem_fun(&CMQTT::local_mqtt_callback),1) ); //no matching function for call to 'mem_fun(void (CMQTT::*)(MQTTClient*, char*, char*, int))' //mqtt_client->onMessageAdvanced( std::bind2nd(&CMQTT::local_mqtt_callback,1) ); //no matching function for call to 'MQTTClient::onMessageAdvanced(std::binder2nd<void (CMQTT::*)(MQTTClient*, char*, char*, int)>)' //mqtt_client->onMessageAdvanced( std::mem_fun(&CMQTT::local_mqtt_callback) );//no matching function for call to 'mem_fun(void (CMQTT::*)(MQTTClient*, char*, char*, int))' //mqtt_client->onMessageAdvanced( std::bind(&CMQTT::local_mqtt_callback),this) );//no matching function for call to 'MQTTClient::onMessageAdvanced(std::_Bind_helper<false, void (CMQTT::*)(MQTTClient*, char*, char*, int)>::type, CMQTT*)' mqtt_client->onMessageAdvanced(CMQTT::local_mqtt_callback); mqtt_client->subscribe(subTopic); } What is incorrect in my code? I know, that declaration of function local_mqtt_callback as static would be decission, but I can understand what is wrong in my code.
I guess the callback is a std::function type, You can use the below, using namespace std::placeholders; mqtt_client->onMessageAdvanced(std::bind(&CMQTT::local_mqtt_callback,this,_1,_2,_3,_4));
69,545,341
69,545,469
getline seems to not be working as I'm expecting (C++)
Beginner programmer here, I'm working on an assignment where we have to create a structure that accepts user input, and I'm running into an issue where the output of the program is skipping a piece of the user input. Essentially I have a piece of code that says: MovieData movie1; MovieData movie2; //Get title cout << "Enter the title of movie 1: "; getline(cin, movie1.title); //Get director cout << "Enter the name of the director 1: "; getline(cin, movie1.director); //Get year released cout << "Enter the year movie 1 was released: "; cin >> movie1.yearReleased; //Get running time cout << "Enter the duration of movie 1 in minutes: "; cin >> movie1.runningTime; //Get title 2 cout << "Enter the title of movie 2: "; getline(cin, movie2.title); //Get director 2 cout << "Enter the name of the director 2: "; getline(cin, movie2.director); //Get year released 2 cout << "Enter the year movie 2 was released: "; cin >> movie2.yearReleased; //Get running time 2 cout << "Enter the duration of movie 2 in minutes: "; cin >> movie2.runningTime; This works fine up until the program asks for the second movie title/director. As soon as I enter the duration of the first movie the program outputs asking for both the title and director for the second movie, so it's skipping over asking for the title and going straight to the director. Here's an example of the output with user input in bold: Enter the title of movie 1: Test mov Enter the name of the director 1: Test dir Enter the year movie 1 was released: 1999 Enter the duration of movie 1 in minutes: 129 Enter the title of movie 2: Enter the name of the director 2: As you can see I never entered anything for the title of the second movie but it skips that part and asks for the director. I originally had all this code inside a function and was running into the same issue so I rewrote it to the code above, but now I'm running into the same issue but only when asking for the second movie title so now I'm a bit lost since it's all working up until asking for the second structures info If needed here's the code for the structure as well: struct MovieData { string title, director; int yearReleased, runningTime; };
The solution is that, after the transition from formatted to unformatted input, so, something like first: std::cin >> variable; and then std::getline(std::cin, variable); , you need to consume the unread White Space. And for that you can use std::ws. Please see here So, after you have used >> add std::ws in your getline, so: getline(cin >> ws, movie2.title); And this for all related places.
69,545,396
69,545,566
Visibility of private field of a template class from a template function
I have a template class template<class T> class MyClass { public: MyClass() { privateField = 0; }; T getPrivateField() { return privateField; } private: T privateField; }; and a template function which takes an instance of MyClass as a parameter template<class T> T foo(MyClass<T> mc) { return mc.privateField; } I was confused by the fact that I can see a private field of MyClass in template function, but can't actually use it. Here is an example of field visibility(screenshot) Question: Why can I see a private field of MyClass exactly in a template function and how can I disable it in my code(if it's possible)? Or it's just like a feature from Visual Studio?
private does not mean that it is completely hidden from the outside, or that nobody outside of the class should be aware that it exists. Consider this example: #include <iostream> struct foo { int x = 0; }; struct bar : foo { private: int x = 0; }; int main() { bar b; b.x = 0; } Now suppose, main was written by a user who only knows about the public parts of the involved classes. They would have no way to understand why they get the error message: <source>: In function 'int main()': <source>:15:7: error: 'int bar::x' is private within this context 15 | b.x = 0; | ^ <source>:10:13: note: declared private here 10 | int x = 0; | ^ Admittetly this is a made up example, and bar can be considered broken. The point is just that your IDE would not necessarily do you a favor if it would not show any private members. Their presence or absence can change the meaning of code that is written only against the public interface.
69,545,451
69,546,208
Can't cross compile C++ files in MinGW properly
I'm trying to compile my C++ app for Windows, using my Linux machine. My issue occurs when I'm executing the compiled exe. Here's a quick example of my issue. helloworld.cpp: #include <iostream> int main() { std::cout << "Hello, World!" << std::endl; return 0; } This code compiles and runs perfectly using g++ on Linux. But when I try compiling it with mingw: i686-w64-mingw32-g++ helloworld.cpp -o helloworld.exeit compiles, but when I try running Windows tells me libgcc_s_dw2-1.ddl is missing. I resolved this problem using the -static-libgcc -static-libstdc++ compiler flags to static link all the needed libraries, but Windows still gives me an error: libwinpthread-1.dll is missing. I haven't found anything useful yet, to answer my question, so does anyone know how do I correctly compile this code to Win32 using MinGW-w64? Thanks!
To build a fully static file you should not only use -static-libgcc and/or -static-libstdc++, but also -static to tell the linker to include static versions of any other libraries. Or you can just build the shared library, but then you will need to distribute any DLL the EXE depends on it with the EXE and put the DLL in the same path as the EXE (or anywhere in a location listed in the PATH environment variable). I wrote a tool called copypedeps as part of https://github.com/brechtsanders/pedeps to copy just those dependencies.
69,546,067
69,546,193
Output is nan while it shouldn't be
I need to calculate the following: S= 1- x^2 / 2! + x^4 / 4! - x^6 / 6! + ... + (-1)^n * x^2n / (2n)! Where n is between 1 and 100, and x is a double. I have the following code: unsigned int factorial (unsigned int n) { if (n == 0) return 1; return n * factorial(n - 1); } double exFive(int n, double x) { double s = 1; for (int i = 1; i <= n; ++i) { int j = 2 * i; s = s + pow(-1, i) * pow(x, 2*i) / factorial(j); //problem is here I guess } return s; } void fiveIO() { int n = 1; double x; cout << "Input n: "; cin >> n; while ((n < 1) || (n > 100)) { cout << "Wrong number, input again: "; cin >> n; } cout << "Input: "; cin >> x; cout << "Result is " << fixed << setprecision(2) << exFive(n, x); } It works however the result is nan where n is above ~15.. but I don't know why. I would presume it’s the FiveX function. So, for instance, n = 3, x = 5 outputs -7.16 (which is correct), but n = 50, x = 5 outputs "nan".. is it because the output is too large of a number? But then how am I supposed to do it?
Avoid int overflow (undefined behavior (UB)) in factorial(j) Typical 32-bit int can only hold result of factorial(12). Improve loop computation by calculating the term based on its prior value. //for (int i = 1; i <= n; ++i) { // int j = 2 * i; // s = s + pow(-1, i) * pow(x, 2*i) / factorial(j); //problem is here I guess //} // Something like double xx = x*x; double term = 1.0; for (int i = 1; i <= n; ++i) { int j = 2 * i; term *= -xx / ((j-1)*j); s += term; } A more advanced approach would calculate the sum in reverse to minimize computation errors, yet a lot depends on the allowable range of x, something not constrained by OP.
69,546,421
69,634,715
Undeclared Idenfitier - Templates C++
The goal of the program is to use templates to create generic lists. My DoublyLinkedList.cpp file takes in a generic type and later stores elements in a linked-list fashion. Anyways, I'm having trouble getting my main function to initialize the list. Some of my code can be found below. int main(int argv, char* argv[]) { cout << "Enter list type (i = int, f = float, s = std:string)"; char listType; cin >> listType; if (listType == 'i') { DoublyLinkedList<int>* list = new DoublyLinkedList<int>(); } else if (listType == 'f') { DoublyLinkedList<float>* list = new DoublyLinkedList<float>(); } else { DoublyLinkedList<string>* list = new DoublyLinkedList<string>(); } (*list).print(); }
Since this site is useless and unhelpful I just figured it out myself. The best way I found to accomplish this was to create a function in main.cpp that takes in a template and implements all functions using the object there. void testList(DoublyLinkedList<T>* list) { (*list).print(); } int main(int argv, char* argv[]) { cout << "Enter list type (i = int, f = float, s = std:string)"; char listType; cin >> listType; if (listType == 'i') { DoublyLinkedList<int>* list = new DoublyLinkedList<int>(); testList(list); } else if (listType == 'f') { DoublyLinkedList<float>* list = new DoublyLinkedList<float>(); testList(list); } else { DoublyLinkedList<string>* list = new DoublyLinkedList<string>(); testList(list); } }
69,546,443
69,548,062
Vscode Run with debugger error "Launch program *file/path* does not exist
I'm trying to figure out what's wrong with my complier or launch.json file. I get an error whenever i try to run a simple program in vs code. The error says, "Launch program file_path does not exist. I tried downloading different compliers and adding different paths to my system environment variables. I'm losing faith at this point.
I think I know which one is your issue, let me show you a quick example: I have a folder called Test, having only Test.cpp file: Then the Test.cpp is only having this simple code: #include <iostream> using namespace std; int main(){ cout<<"Hello World!"<<endl; return 0; } To compile the code and execute it I am using this documentation , checking your launch.json file I saw that you are using the same, but your problem is in your launch.json specifically in the variable called program: VS Code is trying to execute your program with just the workspace folder and that's causing an error, you should use this value on the variable to run and debug the program without issues: "program": "${fileDirname}\\${fileBasenameNoExtension}.exe" ${fileDirname} - the current opened file's dirname ${fileBasenameNoExtension} - the current opened file's basename with no file extension In that way VS Code can run and debug the executable that was generated after compiling the code, in my example I opened the file called test.cpp to do the run because the executable was generated from that one. Here is the order of the folders at the end: I recommend you to read this article with the variables for the JSON files on VS Code and this one.
69,546,491
69,546,522
Converting and printing hex values using sprintf(keeping the leading zeroes)
I have the following C code which takes two long integer values and convert them to two hex strings using the sprintf function: void reverse_and_encode(FILE *fpt, long *src, long *dst) { char reversed_src[5], reversed_dst[5]; sprintf(reversed_src, "%x", *dst); sprintf(reversed_dst, "%x", *src); printf("Reversed Source: %s\n", reversed_src); printf("Reversed Destination: %s\n", reversed_dst); } But when I print the hex value strings, I can't get the leading zero in the output. Eg. Reversed Source: f168 // for integer 61800 Reversed Destination: 1bb // This output should be "01bb" for integer 443
Use sprintf(reversed_src, "%04x", ( unsigned int )*dst); Pay attention to that in general if the the expression 2 * sizeof( long ) (the number of hex digits) can be equal to 8 or 16.for an object of the type long. So you need to declare the arrays like char reversed_src[2 * sizeof( long ) + 1], reversed_dst[2 * sizeof( long ) + 2]; and then write for example sprintf(reversed_src, "%0*lx", ( int )( 2 * sizeof( long ) ), ( unsigned long )*dst); Here is a demonstrative program. #include <stdio.h> int main(void) { enum { N = 2 * sizeof( long ) }; char reversed_src [N + 1]; long x = 0xABCDEF; sprintf( reversed_src, "%0*lX", N, ( unsigned long )x ); puts( reversed_src ); return 0; } The program output is 0000000000ABCDEF