question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
72,076,574
72,086,141
Error handling exponent ("e") preceding digit
I'd like to create a function that checks whether a number input with an exponent such as 1.32e2, 1e3, +1.32e+2 indeed has the e in the correct position, after a number, not before it (such as e1 or .e4) I'm a beginner so it's just trial and error at this point. This is what I have so far: bool validate_alpha_e(string op) { if (count_alpha(op) <= 1) { if (count_es(op) == 1) { //return true; int length = op.length(); for (int i = 0; i < length; i++) { char ch = op[i-1]; if (ch == 'e' || ch == 'E') { if (i-1 != isdigit(i)) { return false; } } } return true; }
Worked it out. Thanks for the comments but I wasn't able to figure it out. So I had to create 3 separate functions (see below) First function validates for correct input before the e. Second function validates for correct input after the e. Third function validates that the first character is not an e. Put all these together in a bool if statement and if it returns false then the input is not correct. bool validate_e_after(string op) { int length = op.length(); for (int i = 1; i < length; i++) { char ch = op[i-1]; if (ch == 'e' || ch == 'E') { char ch2 = op[i]; if (isdigit(ch2) || ch2 == '+' || ch2 == '-') { return true; } else { return false; } } } } bool validate_e_before(string op) { int length = op.length(); for (int i = 1; i < length; i++) { char ch = op[i+1]; if (ch == 'e' || ch == 'E' && i != 0) { char ch2 = op[i]; if (isdigit(ch2) || ch2 == '+' || ch2 == '-') { return true; } else { return false; } } } } bool validate_ezero(string op) { int length = op.length(); for (int i = 0; i < length; i++) { char ch = op[i]; if (ch == 'e' or ch == 'E') { if (i == 0) { return false; } } } return true;
72,076,590
72,076,744
C++ subtuple from tuple given variadic index sequence
Assume I have a std::tuple, I'd like to write a function which receives a tuple and a variadic sequence outputting a subtuple containing the columns corresponding to those indexes. Example usecase: std::tuple<int, char, float, std::string> t{1, 'd', 3.14, "aaa"}; auto subtuple = extract_subtuple(t, 0, 2); // returns std::tuple<int, float>(1, 3.14) Is this possible ? I had a look at this other question but in the end I didn't find what I was looking for.
You can't do it directly because tuple indices should be constant expressions and function parameters are never constant expressions even if corresponding arguments are. You have two main options. Firstly, you could make indices template parameters: template<std::size_t... Is, class... Ts> auto extract_subtuple(const std::tuple<Ts...>& tuple) { return std::make_tuple(std::get<Is>(tuple)...); } auto subtuple = extract_subtuple<0, 1>(t); Secondly, if you want to make indices function parameters, you could wrap them into types: template<class... Ts, class... Indices> auto extract_subtuple(const std::tuple<Ts...>& tuple, Indices...) { return std::make_tuple(std::get<Indices::value>(tuple)...); } template<std::size_t I> using Idx = std::integral_constant<std::size_t, I>; auto subtuple = extract_subtuple(t, Idx<0>{}, Idx<1>{});
72,076,844
72,076,907
My programs doesn't return 0 when deleting array pointer
When I try to delete array pointer which declared like short *width = NULL; width = new short[lenght]; delete[] width; the programs stop at delete part and returns a random number. here is my all program int main(){ short **junction = NULL, *width = NULL, length = 0; ifstream input; input.open("sample_input.txt"); if(!input) cout << "No such a file named \"sample_input.txt\"" << endl; else if(input >> length){ junction = new short*[length]; width = new short[length]; string str; for(int i = 0; i - 1 < length && getline(input, str); i++){ istringstream ss(str); width[i - 1] = (str.size() + 1) / 2; //numbers can be two char, so in this case, here we allocate more than necessary memory junction[i - 1] = new short[width[i - 1]]; for(int j = 0; j < width[i - 1]; j++){ if(ss.eof()){ junction[i - 1][j] = -1; // -1 is the key value of emtpy spaces continue; } ss >> junction[i - 1][j]; } } } input.close(); /* for(int i = 0; i < length; i++) delete[] junction[i]; delete[] junction; delete[] width; */ return 0; } the comment part makes problem, I tried those delete statements seperately just for part is runing but not as I expected here is my sample input:
Your code should be actually fine. Please show us the whole program. florian@florian-desktop:~$ cat -n test2.cpp 1 #include <iostream> 2 int main() 3 { 4 const int length = 4; 5 short *width = NULL; 6 width = new short[length]; 7 delete[] width; 8 } florian@florian-desktop:~$ valgrind ./a.out ==22630== Memcheck, a memory error detector ==22630== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al. ==22630== Using Valgrind-3.18.1 and LibVEX; rerun with -h for copyright info ==22630== Command: ./a.out ==22630== ==22630== ==22630== HEAP SUMMARY: ==22630== in use at exit: 0 bytes in 0 blocks ==22630== total heap usage: 2 allocs, 2 frees, 72,712 bytes allocated ==22630== ==22630== All heap blocks were freed -- no leaks are possible ==22630== ==22630== For lists of detected and suppressed errors, rerun with: -s ==22630== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0) Valgrind shows that all reserved memory is correctly released. -- Updated: I corrected your full code: #include <iostream> #include <sstream> #include <fstream> using namespace std; int main() { short **junction = NULL, *width = NULL, length = 12; ifstream input; input.open("sample_input.txt"); if(!input) cout << "No such a file named \"sample_input.txt\"" << endl; else if(input >> length){ junction = new short*[length]; width = new short[length]; string str; for(int i = 0; i < length && getline(input, str); i++){ istringstream ss(str); width[i] = (str.size() + 1) / 2; //numbers can be two char, so in this case, here we allocate more than necessary memory junction[i] = new short[width[i]]; for(int j = 0; j < width[i]; j++){ if(ss.eof()){ junction[i][j] = -1; // -1 is the key value of emtpy spaces continue; } ss >> junction[i][j]; } } } input.close(); for(int i = 0; i < length; i++) delete[] junction[i]; delete[] junction; delete[] width; return 0; }
72,076,963
72,077,400
Fastest way to count words of string
How could I make this algorithm faster and shorten this code which counts word of given string? int number_of_words(std::string &s) { int count = 0; for (int i = 0; i < s.length(); i++) { // skip spaces while (s[i] == ' ' && i < s.length()) i++; if (i == s.length()) break; // word found count++; // inside word while (s[i] != ' ' && i < s.length()) i++; } return count; }
Your code is quite alright, speed-wise. But if you want to make your code shorter, you may use find_first_not_of() and find_first_of standard functions, like I did in following code that solves your task. I made an assumption that all your words are separated by only spaces. If other separators are needed you may pass something like " \r\n\t" instead of ' ' in both lines of my code. One small optimization that can be made in your code is when you notice that after first while-loop we're located on non-space character, so we can add ++i; line for free before second loop. Similarly after second while-loop we're located on space character so we may add one more ++i; line after second while loop. This will give a tiny bit of speed gain to avoid extra two checks inside while loop. Try it online #include <iostream> #include <string> int number_of_words(std::string const & s) { ptrdiff_t cnt = 0, pos = -1; while (true) { if ((pos = s.find_first_not_of(' ', pos + 1)) == s.npos) break; ++cnt; if ((pos = s.find_first_of(' ', pos + 1)) == s.npos) break; } return cnt; } int main() { std::cout << number_of_words(" abc def ghi ") << std::endl; } Output: 3
72,077,314
72,077,358
Segmentation fault in C++ adding item to a vector
Lately I have set myself to learn C++, and while working on a bigger project, I have tried to use 'vectors'. But every-time I try passing it a value, it exits with a segmentation fault. Here is my terminal output: #include <iostream> #include <vector> using namespace std; int main(){ vector<int> test; cout << "hello world" << endl; test[0] = 0; return 0; } me@my-MacBook-Pro Desktop % g++ test.cpp -o o && ./o hello world zsh: segmentation fault ./o #include <iostream> #include <vector> using namespace std; int main(){ vector<int> test; cout << "hello world" << endl; //test[0] = 0; return 0; } me@my-MacBook-Pro Desktop % g++ test.cpp -o o && ./o hello world me@my-MacBook-Pro Desktop %
Size it vector<int> test = {0,1,2,3,4}; or vector<int> test(5) But you might want to use push_back in this situation #include <iostream> #include <vector> using namespace std; int main(){ vector<int> test; cout << "hello world" << endl; test.push_back(0); cout << test[0]; return 0; } Basically adds an item at the end. Can also use maps with the keys be ints if you want to be able to just [] it or leave in spaces (which from what i saw is what your trying to do) #include <iostream> #include <unordered_map> using namespace std; int main(){ unordered_map<int, int> test; cout << "hello world" << endl; test[0] = 0; cout << test[0]; return 0; }
72,077,483
72,077,524
Include instructions from other file in CMakeLists.txt
I want to create a second file, for example Instructions.txt, and be able to include it's CMake instructions to the main CMakeLists.txt, for example: // Instructions.txt set(MY_VARIABLE value) set(MY_SECOND_VARIABLE 1234) // CMakeLists.txt <HERE INCLUDE INSTRUCTIONS.TXT> // And be able to use those variables, for example project(MY_VARIABLE)
You usually do that simply by using another cmake. Contrary to what you might believe, the file extension is different for other file than build files. Let's call this file instructions.cmake: set(MY_VARIABLE value) set(MY_SECOND_VARIABLE 1234) Then you can include it like this inside your CMakeLists.txt: include(instructions.cmake) If the file is in the module path, you can include it like that: include(instructions) There are some other filename that are important for CMake though. For example, any file that start with Find then ends with .cmake like FindXYZ.cmake, the XYZ part is assumed to be a package name and in that case you should use find_package(XYZ REQUIRED).
72,077,841
72,077,985
why return type of operation overloading is sample
why sample as return type in operation overloading can anyone explain how this code works. why the return type is class itself whats the use of .x here #include<iostream> class sample { private: int x; public: sample(); void display(); friend sample operator+(sample ob3,sample ob4) }; sample::sample() { x=1; } void sample::display() { cout<<x; } sample sample::operator+(sample ob3,sample ob4) { sample ob5; ob5.x=ob3.x+ob4.x; return(ob4); } int main() { sample ob1,ob2,ob3; ob3=ob1+ob2; ob3.display(); }
why sample as return type in operation overloading The return type is sample because the author that wrote the operator overload chose to use sample as the return type. It is quite typical for binary operator+ overloads to have the same return type as the type of the operands. Part of why it is typical is that it follows the example of all corresponding built-in operators which is a good convention to adhere to. When both operands of a built-in operator+ have the same type (after conversion), the type of the expression is also the same. For example the operands of 1+1 are int and the type of the expression is int also. In cases where operands have different type (e.g. pointer arithmetic), the resulting type is one of the operand types. whats the use of .x here . is an operator to access the member of an object. x is a data member of and instance of the class sample.
72,078,767
72,078,805
How to Add 0 infront of an int without external library c++
What i Hope to accomplish So i have a class with date and time and i am using a struct in which year, month, date are integers I want when the user enters a number for example 3 it must output 03 but must be in an int format without using the IOMANIP library or fmt library as when i use these library i get 'error time does not have a type' Please Help How can i get a 0 infront of months and days to be stored in a variable whilst still being an int; I have tried the setw But does not work as mentioned above So what i have tried was to store it in a pointer and vector I have a class called vehicle with struct date and time struct time { int hh; int mm; int ss; char col1; char col2; }; struct date { int day; int month; int year; char sym1; char sym2; }; class vehicle { string pltno; int type; date dt; time arrive; time departure; Code I have vector<vehicle> vehleft(100); int static totalvehicle=0,totalcar=0,totalbike=0,totalamt=0,i=0,z=0; fstream file; void vehicle::addVehicle() { vehicle *v = new vehicle; cin.ignore(); cout<<"Enter vehicle number : "; std::getline(cin, v->pltno); cout<<"Enter arrival time in hours minutes and seconds : "; cin>>v->arrive.hh>>v->arrive.col1>>v->arrive.mm>>v->arrive.col2>>v->arrive.ss; cout<<"Enter date in day month and year: "; cin>>v->dt.day>>v->dt.sym1>>v->dt.month>>v->dt.sym2>>v->dt.year; What i tried to do was use the setw and setfill to add a 0 infront but when i do so i get an error that 'time is not a type' this happens whenever i include the ctime library or Iomanip library. Basically I want v->dt.day and v->dt.month to assign the user input as of this moment if the number is 3 it will stay as 3 and not 03 which is the format i want Update When I input 10 for example in month when it is outputed it says 0 instead of 10?
setw works in conjunction with setfill so something like std::cout << std::setw(2) << std::setfill('0') << day; might work for you. See also https://en.cppreference.com/w/cpp/io/manip/setfill
72,079,021
72,079,267
Example of use of std::forward_iterator
I have a compute function that looks like this: template <typename PayloadType, complex ValueType> static void comupte_everything( const typename std::vector<DataPointWithAverage<PayloadType, ValueType>>::iterator begin, const typename std::vector<DataPointWithAverage<PayloadType, ValueType>>::iterator end) I want to extend that function so it can accept any iterators instead of just vectors, and I'm trying to do it with std::forward_iterator: template <typename PayloadType, complex ValueType, std::forward_iterator<DataPointWithAverage<PayloadType, ValueType>> Iterator> static void comupte_everything( const Iterator begin, const Iterator end) Now, the compiler complains that I give forward_iterator too many arguments. How do I use this correctly?
std::forward_iterator is a concept, not a template, so you can't use it like a template, if you want to constrain the value_type of iterator, then you can template<typename T> constexpr bool is_DataPointWithAverage = false; template<typename PayloadType, complex ValueType> constexpr bool is_DataPointWithAverage< DataPointWithAverage<PayloadType, ValueType>> = true; template <std::forward_iterator I> requires is_DataPointWithAverage<std::iter_value_t<I>> static void comupte_everything(I begin, I end); which will constrain I must model forward_iterator, and its value_type must be a specialization of DataPointWithAverage. Note that begin() and end() of a range in C++20 can return different types, so a more generic declaration should be template <std::forward_iterator I, std::sentinel_for<I> S> requires is_DataPointWithAverage<std::iter_value_t<I>> static void comupte_everything(I begin, S end);
72,079,217
72,079,434
When declaring a function that has an argument pointer to function, is there such a way to restrict the argument func such that it belongs to a class
Let's say that I have the function doSomething(char* (*getterOne)()) { //do something here } although I've named the parameter of doSomething "getterOne", I have no way of verifying that the function is going to be a getter ( I think? ). So I wonder, is there a way to explicitly specify the kind of function that can be passed as an argument? For example, if I have the class "Cat", is there a way to say that the function doSomething accepts as parameter function, that belongs to the class Cat, and if so, how can I use it like this: doSomething(char* (*getterOne)()) { Cat cat; cat.getterOne(); // where getterOne will be the getter that I pass as a parameter and do something with it } Also if anyone asks why I use char* instead of string, it is for a school project and we are not allowed to use string.
A function pointer and a pointer-to-member-function are two different things. If you make a function that accepts a pointer-to-member-function you have no choice but to specify which class it belongs to. Here is an example. #include <iostream> struct Cat { char* myGetter() { std::cout << "myGetter\n"; return nullptr; } }; void doSomething(char* (Cat::*getterOne)()) { Cat cat; (cat.*getterOne)(); } int main() { doSomething(&Cat::myGetter); } The syntax for using a pointer-to-member is .* or ->* and the extra brackets are needed.
72,079,305
72,762,162
Windows Sharing file over network NetShareAdd Error 53
I tried to compile this example from microsoft docs for sharing a folder over network however the executable gives an error. Full Code : #include "stdafx.h" #ifndef UNICODE #define UNICODE #endif #include <windows.h> #include <stdio.h> #include <lm.h> #pragma comment(lib, "Netapi32.lib") void wmain(int argc, TCHAR *argv[]) { NET_API_STATUS res; SHARE_INFO_2 p; DWORD parm_err = 0; if (argc<2) printf("Usage: NetShareAdd server\n"); else { // // Fill in the SHARE_INFO_2 structure. // p.shi2_netname = TEXT("TESTSHARE"); p.shi2_type = STYPE_DISKTREE; // disk drive p.shi2_remark = TEXT("TESTSHARE to test NetShareAdd"); p.shi2_permissions = 0; p.shi2_max_uses = 4; p.shi2_current_uses = 0; p.shi2_path = TEXT("F:\\abc"); p.shi2_passwd = NULL; // no password // // Call the NetShareAdd function, // specifying level 2. // res = NetShareAdd(argv[1], 2, (LPBYTE)&p, &parm_err); // // If the call succeeds, inform the user. // if (res == 0) printf("Share created.\n"); // Otherwise, print an error, // and identify the parameter in error. // else printf("Error: %u\tparmerr=%u\n", res, parm_err); } return; } Exe command : ConsoleApplication1.exe myShare Error Shown : Error: 53 parmerr=0 However the follwing from cmd works fine : net share abc=F:\abc I am unable to figure out what actually the error is and how to resolve that. can anybody help? I am on windows 11 and code is compiled on VS 2015 Community.
With admin privileges, servername ConsoleApplication1.exe localhost and ConsoleApplication1.exe 127.0.0.1 worked fine.
72,079,440
72,079,503
winapi handling multiple keys
I need the program to be able to handle multiple keys at the same time. For this I wrote this code: case WM_KEYDOWN:{ int debug=pix.getMsg().lParam; if(debug>=16 && debug<=23){ char lpKeyState[256]; ZeroMemory(lpKeyState,256); char input[2]; int symNum=ToAsciiEx(pix.getMsg().wParam,pix.getMsg().lParam,(BYTE*)lpKeyState,(WORD*)input,0,GetKeyboardLayout(0)); if(symNum==1) keyboardInput.push_back(input[0]); } break; } ToAsciiEx accepts the second parameter of the hardware key scanning code, it says on msdn that WM_KEYDOWN should supposedly pass it through lparam, but something wrong comes to lparam. Where can I get the hardware key scan code or are there other ways to implement this?
As stated in the documentation of WM_KEYDOWN, bits 16 to 23 of lParam contain the scan code. To extract the scan code from lParam, you can use the following line: DWORD dwScanCode = ( lParam >> 16 ) & 0xFF;
72,079,446
72,080,399
How do I reset the GLFW Fragment / Load a different shader during runtime?
I'm writing a shadertoy-like tool for the desktop. It uses GLFW (OpenGL), Glad, and ImGui to render out images. I've gotten to a point now where I fixed all my previous issues, but I'm now stuck on one particular problem that's been plaguing me the past few days. I want to be able to hot-reload shaders. Right now it takes a simple mandelbulb raymarcher GLSL fragment, draws it, and also draws a little ImGui panel with a "reload shader" button. Ive been trying to figure out how to unlink the current shaderprogram, and load it again with a new shader, but Ive come up with nothing. The code doesnt have any errors, but it definitely doesnt work. When I click the button the OpenGL Viewport just goes black. I've tried looking online but there were essentially no solid solutions for this, most of the questions I already saw were never actually answered. This is my current code for resetting the shader (and grabbing it from the files again) if (ImGui::Button("Reload Shader", ImVec2(0, 0))) { glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glDeleteProgram(shaderProgram); gladLoadGL(); glViewport(0, 0, width, height); vertexShader = glCreateShader(GL_VERTEX_SHADER); fragmentShader = loadShaderFromFile("assets\\round.glsl", GL_FRAGMENT_SHADER); shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); glDeleteShader(vertexShader); glDeleteShader(fragmentShader); GLuint VAO, VBO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); glUseProgram(shaderProgram); GLint resUniform = glGetUniformLocation(shaderProgram, "iResolution"); glUniform3f(resUniform, width, height, width / height); double mxpos, mypos; glfwGetCursorPos(window, &mxpos, &mypos); GLint mouseUniform = glGetUniformLocation(shaderProgram, "iMouse"); glUniform4f(mouseUniform, mxpos, mypos, mxpos, mypos); GLint timeUniform = glGetUniformLocation(shaderProgram, "iTime"); glUniform1f(timeUniform, currentTime); glBindVertexArray(VAO); glDrawArrays(GL_TRIANGLES, 0, 3); glfwSwapBuffers(window); glfwPollEvents(); } This is the current github commit with all the code / the entire program, incase its needed: https://github.com/ArctanStudios/OpenGL-Sandbox/tree/e7ba32310b898d1a60eae89f8969179600f5d391 The actual Main.cpp file with the rest of my GLFW code: https://github.com/ArctanStudios/OpenGL-Sandbox/blob/e7ba32310b898d1a60eae89f8969179600f5d391/Main.cpp
So after fiddling around a while, I actually figured it out. Turns out I was doing way more than was required. All I needed to do was detach the fragment at the start, then delete everything, then re-attach a new fragment, link the program again, then detach and delete it again. Now I can reload my shaders during runtime. Code I used during initialization: GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexShaderSource, NULL); glCompileShader(vertexShader); GLuint fragmentShader = loadShaderFromFile("assets\\round.glsl", GL_FRAGMENT_SHADER); GLuint shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); glDetachShader(shaderProgram, fragmentShader); glDeleteShader(vertexShader); glDeleteShader(fragmentShader); What this does is just grab the frag + vert, attach them both, cache / link the program to the renderer, then detach the frag, delete the vertex + frag to save memory, and its ready to be overwritten at any time. This is the code I used inside of my reload button: if (ImGui::Button("Reload Shader", ImVec2(0, 0))) { glDetachShader(shaderProgram, fragmentShader); fragmentShader = loadShaderFromFile("assets\\round.glsl", GL_FRAGMENT_SHADER); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); glDetachShader(shaderProgram, fragmentShader); glDeleteShader(fragmentShader); } What this does is grab the current shader program, with no fragment, and the already existing vertex still cached on it. Then it attaches the new fragment, links / caches the program to the renderer again, then repeats the process from the initial one. it detaches the fragment, deletes it to save memory, then its ready to be overwritten again. You can also use this with the vertex shader, just detach and delete it, same as the fragment. I decided not to since the aim of my program is to render 2D shaders onto a plane, similarly to shadertoy
72,079,593
72,079,638
Cast raw bytes to any datatype
I'm worried if my implementation is unsafe or could be improved. Suppose I have an array of bytes (more specifically, std::byte); is casting an element's address to a void pointer and then to any datatype safe? template <typename To> constexpr To *byte_cast(std::byte &From) { return static_cast<To *>(static_cast<void *>(&From)); } // or rather template <typename To> constexpr To *byte_cast(std::byte *From) { return static_cast<To *>(static_cast<void *>(From)); } I'm avoiding reinterpret_cast due to its unreliability. Do note that I want to the T * to keep same address of the byte it was cast from. I do have in mind that the array might not fit the datatype, or maybe endianness might cause a problem, but both will be fixed after my question's answered.
Your paired static_casts are exactly equivalent to a reinterpret_cast. Both cause UB due to strict aliasing violations (except when the target type is char, unsigned char, or std::byte). The solution is std::bitcast<T>(source). It has the interface similar to what you attempted, except that it returns by value. It's not possible to have a "safe reinterpret_cast" that would return a pointer/reference. A less modern alternative is std::memcpy.
72,079,627
72,079,798
Do while loop keeps looping c++
So, I want this program to keep prompting when the number of digits isn't 16, that part worked, but whenever I try to input 16 digits it loops without letting me type anything in again. This is what I wrote: do{ cout<<"insert number pls: "; cin>>number; //counting digits number_count = 0; while(number != 0){ number = number/10; number_count++; } }while(number_count != 16); cout<<"done"<<endl; I tried to do it with (number_count != 1) until (number_count != 10) and they worked, it only started not working from 11, why is that?
The value limit of int which you're using to store your number is 2147483647, which corresponds to 10 digits. That's why it stopped working at 11 digits. An easy workaround is to use long long int instead. The maximum value in this case is 2^63 which equals 9223372036854775807 (19 digits). You can check the max value on a specific system programmatically with: #include <iostream> #include <limits> int main() { std::cout << std::numeric_limits<long long int>::max(); } Output: 9223372036854775807 However I advise that you use an array of chars to store your number instead, as that's the optimal way to handle big numbers.
72,080,085
72,080,159
why can't I declare the size for the array inside a class?
So I am working on a project and it compiles with no errors but I can't run when I declare the size of the array inside the class but when I declare it inside the class it works. This is what I get when I declare it inside the class. c:\Users\david\OneDrive\Desktop\account>cd "c:\Users\david\OneDrive\Desktop\account" && g++ account.cpp -o account && "c:\Users\david\OneDrive\Desktop\account"account C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\david\AppData\Local\Temp\ccakK21Q.o:account.cpp:(.rdata$.refptr._ZN7Account1nE[.refptr._ZN7Account1nE]+0x0): undefined reference to `Account::n' collect2.exe: error: ld returned 1 exit status I am still a newbie when it comes to coding so I have no idea what exactly this means. But this is the code can someone please help. Thank you very much. //const unsigned n{5}; THIS IS OUT SIDE THE CLASS class Account { const string accNum; const string name; int balance{0'00}; static const unsigned n{5}; // THIS IS INSIDE THE CLASS int count = 0; unsigned e{0}; unsigned z{0}; unsigned tranNo{1}; std::array<int,n> buffer; public: Account(string n, string a) : name{n}, accNum{a} {} int deposite(int x){ return balance += x; } int withdraw (int x){ return balance += x; } const int getBal() const{ //out << "BALANCE: " << balance << endl; return balance; } string getAccNUm() const{ //out << "ACCOUNT NUMBER: " << accNum << endl; return accNum; } string getName() const{ //out << "NAME: " << name << endl; return name; } string getTime() const{ const auto opened = chrono::system_clock::to_time_t(chrono::system_clock::now()); // FOR EXTRA CREDI ASSAIGNMENT #1 //cout << ctime(&opened) << endl; string time = ctime(&opened); return time; } /* const void GetDetails();{ getName(); getAccNUm(); getBal(); cout << "ACCOUNT OPENED: "; getTime(); } */ void Append(int x){ buffer [e] = x; e++; e %= n; ++z; } void print(){ const auto opened = chrono::system_clock::to_time_t(chrono::system_clock::now()); // FOR EXTRA CREDI ASSAIGNMENT #2 unsigned length{min (z,n)}; unsigned i{z <= n ? 0: (z-length) % n}; for (unsigned j{0}; j<length; j++){ cout << "Transtion no." << tranNo << " was = "<< buffer.at(i++%n) << " at "; cout << ctime(&opened) << endl; tranNo++; } } int converter (string m){ int a = stoi(m); return a; } }; void simulation(){ string name; getline(cin,name); string AccountNum; getline(cin,AccountNum); Account x(name, AccountNum); assert(x.getName() == name); assert(x.getAccNUm() == AccountNum); string money; while(getline(cin,money)){ int mon = x.converter(money); if (mon > 0){ x.deposite(mon); x.Append(mon); } else { x.withdraw(mon); x.Append(mon); } } cout << "Name: " << x.getName() << endl; cout << "Account Number: " << x.getAccNUm() << endl; cout << "Balance: " << x.getBal() << endl; cout << "ACCOUNT OPENED: " << x.getTime() << endl; x.print(); } int main(){ simulation(); }
Non-inline static member variables must be defined outside of the class in exactly one translation unit. Like this: const unsigned Account::n{5}; However, this will make it a non-constant expression prior to this initialisation, so you wouldn't be able to use it as the size of the array. A solution is to use an inline variable instead: class Account { static inline const unsigned n{5}; Alternatively, you can declare it constexpr which makes it implicitly inline: class Account { static constexpr unsigned n{5};
72,080,211
72,080,388
Using type trait to ensure a type cannot be derived from itself
I would like to statically check if a class is derived from a base class but not from itself. Below is an example of what I try to achieve. The code compiles unfortunately (never thought I would say this). I was hoping for the second static assertion to kick in and see that I tried to derive a class from itself. I would appreciate if you guys could help me in understanding better what I am doing wrong. I tried to search online without success. #include <type_traits> struct Base {}; template <typename T> struct Derived : T { static_assert(std::is_base_of<Base, T>::value, "Type must derive from Base"); static_assert(!(std::is_base_of<Derived, T>::value), "Type must not derive from Derived"); }; int main(int argc, char** argv) { Derived<Base> d__base; // should be OK Derived<Derived<Base>> d_d_base; // should be KO return 0; }
Type must not derive from Derived Derived is not a type in itself, it's a template which in std::is_base_of<Derived, T>::value gets resolved to the current specialization in the context it's in and it can never be T. If you have Derived<Derived<Base>> then T is Derived<Base> and the Derived without specified template parameters is Derived<Derived<Base>>, so, not the same as T. You could add a type trait to check if T is Derived<something>: template <template<class...> class F, class T> struct is_from_template { static std::false_type test(...); template <class... U> static std::true_type test(const F<U...>&); static constexpr bool value = decltype(test(std::declval<T>()))::value; }; Now, using that would prevent the type Derived<Derived<Base>>: struct Base {}; template <typename T> struct Derived : T { static_assert(std::is_base_of<Base, T>::value, "Type must derive from Base"); static_assert(!is_from_template<Derived, T>::value, "Type must not derive from Derived<>"); }; int main() { Derived<Base> d_base; // OK // Derived<Derived<Base>> d_d_base; // error }
72,080,305
72,081,415
Copy without duplicates using generic function
I'm trying to make a generic function which will copy elements without duplicates from one block to another. Function accepts three pointers/iterators and must work for all types of iterators. Function should return a pointer/iterator that points exactly one place behind the destination block. p1 and p2 are from the same type. However, p3 doesn't have to be the same type as p1 and p2. #include <iostream> #include <algorithm> #include <vector> template<typename iter_type1, typename iter_type2> auto CopyWithoutDuplicate(iter_type1 p1, iter_type1 p2, iter_type2 p3){ int n=std::distance(p1,p2); std::unique_copy(p1,p2,p3); p3+=n; return p3; } int main() { std::string s="abc defabcd ghidef",str; std::vector<int>a{1,1,2,2,3,4,3,5},b; auto it1=CopyWithoutDuplicate(s.begin(),s.end(),str.begin()); while(it1!=str.begin()) { std::cout<<*it1; it1--; } std::cout<<endl; auto it2=CopyWithoutDuplicate(a.begin(),a.end(),b.begin()); while(it2!=b.begin()) { std::cout<<*it2<<" "; it2--; } return 0; } Correct output would be: abc defghi 1 2 3 4 5 I tried to use std::unique_copy for this, but I don't know where I made mistaked in my code. This doesn't print anything on screen.
CopyWithoutDuplicate can be simplified. auto CopyWithoutDuplicate(iter_type1 p1, iter_type1 p2, iter_type2 p3){ return std::unique_copy(p1,p2,p3); } The working example: #include <iostream> #include <iterator> #include <algorithm> #include <vector> #include <unordered_set> template<typename iter_type1, typename iter_type2> iter_type2 CopyWithoutDuplicate(iter_type1 p1, iter_type1 p2, iter_type2 p3){ std::unordered_set<typename std::iterator_traits<iter_type1>::value_type> m; for (; p1 != p2; ++p1) { if (m.count(*p1) != 0) continue; *p3++ = *p1; m.insert(*p1); } return p3; } int main() { std::string s="abc defabcd ghidef",str; std::vector<int>a{1,1,2,2,3,4,3,5},b; CopyWithoutDuplicate(s.begin(),s.end(),std::back_inserter(str)); for(char c : str) std::cout<<c; std::cout<<std::endl; CopyWithoutDuplicate(a.begin(),a.end(),std::back_inserter(b)); for(int n : b) std::cout<<n<<" "; return 0; } Output abc defghi 1 2 3 4 5
72,080,506
72,080,521
Making a pointer point to an element of char array?
Let v be an array of chars, with values "Hello". If I run the following: char v[]="Hello"; char* p_char= v; char* p_char_2 = &v[1]; cout<<"p_char: "<<p_char<<"\n"; cout<<"p_char_2: "<<p_char_2<<"\n"; cout<<"p_char_2 value: "<<*p_char_2<<"\n"; it returns p_char: Hello p_char_2: ello p_char value: e I'm not sure why, when I add p_char_2 to output stream, I get something like "ello" instead of a memory address...
p_char_2 has type char *, which is the type traditionally used to pass around pointers to strings in C and C++. So the designers of the C++ language decided that when you pass a char * to std::cout << , it prints it as a null-terminated string. That's just how the language was designed, and it makes it easy to output strings to the standard output.
72,080,986
72,080,997
One Definition Rule and static member initialization
I've read the one definition rule yet could not find the answer to what I'm trying to achieve. I'm implementing a class in which I need to count every occurrence created of this class, let's name it "Item" Such that when the header and CPP files are complicated, the static member is defined and with every call to the class' constructor, said static member grows by one and applied to current object that is created. (That is how I presume things are happening 'back stage') Thanks for any help!
I was using Item::idCounter all along, while I needed to use int Item::idCounter; Weirdly, no flags were raised about this.
72,080,987
72,081,041
C++ Array of random numbers
I have a bit of a problem with this. I've tried to create a function to return a random number and pass it to the array, but for some reason, all the numbers generated are "0". #include <iostream> #include <ctime> #include <iomanip> using namespace std; int generLosNum(int); int main() { srand(time(NULL)); int LosNum; const int rozmiar = 10; int tablica[rozmiar]; for(int i=0; i<rozmiar; i++) { tablica[i] = generLosNum(LosNum); cout << tablica[i] <<" "; } return 0; } int generLosNum(int LosNum) { int LosowyNum; LosowyNum = (rand() % 10); return (LosNum); }
So the return for your int generLosNum(int LosNum) was printing 0 because you had it returning LosNum which was initialized equaling to zero. I changed your code so it works and will print out the 10 random numbers. #include <iostream> #include <ctime> #include <iomanip> using namespace std; int generLosNum(); int main() { srand(time(NULL)); int LosNum = 0; const int rozmiar = 10; int tablica[rozmiar]; for (int i = 0; i < rozmiar; i++) { tablica[i] = generLosNum(); cout << tablica[i] << " "; } return 0; } int generLosNum() { int LosowyNum; LosowyNum = (rand() % 10); return LosowyNum; }
72,081,124
72,081,179
Why it is a segmentation fault with this code fragment?
Here is my code about Matrix (I decided to practise OOP writing own Matrix class) Matrix.hpp #ifndef MATRIX_HEADER #define MATRIX_HEADER typedef unsigned int u_int; class Matrix { double **mtrx; u_int x, y; public: Matrix(u_int a, u_int b); Matrix(const Matrix &); ~Matrix(); double det(); Matrix operator+(const Matrix &) const; Matrix operator-(const Matrix &) const; Matrix operator*(const Matrix &) const; friend Matrix operator*(const Matrix &, const double &); Matrix operator/(const Matrix &) const; double *operator[](const u_int idx) const { return mtrx[idx]; } bool IsEqual(const Matrix &) const; u_int GetX() const { return x; } u_int GetY() const { return y; } }; #endif Matrix.cpp #include "Matrix.hpp" Matrix::Matrix(u_int a, u_int b) : x(a), y(b) { mtrx = new double *[x]; for (u_int i = 0; i < x; i++) mtrx[i] = new double[y]; } Matrix::Matrix(const Matrix &ref) { if (mtrx) { for (u_int i = 0; i < x; i++) delete[] mtrx[i]; delete[] mtrx; } x = ref.x; y = ref.y; *mtrx = new double[x]; for (u_int i = 0; i < x; i++) mtrx[i] = new double[y]; } Matrix::~Matrix() { if (mtrx) { for (u_int i = 0; i < x; i++) delete[] mtrx[i]; delete[] mtrx; } } bool Matrix::IsEqual(const Matrix &a) const // If sizes of matrixes are equal { // matrixes are equal return (a.GetX() == x) && (a.GetY() == y); } Matrix Matrix::operator+(const Matrix &a) const { if (!IsEqual(a)) // Check on equality matrixes return Matrix(1,1); // I have not any idea yet what Matrix matrix(x, y); // should it give is sizes for (u_int i = 0; i < x; i++) // of Matrix are not equal for (u_int j = 0; j < y; j++) matrix[i][j] = a.mtrx[i][j] + mtrx[i][j]; return matrix; } main.cpp #include <stdio.h> #include "Matrix.hpp" int main() { Matrix a(2, 5); Matrix b(2, 5); for (u_int i = 0; i < a.GetX(); i++) { for (u_int j = 0; j < a.GetY(); j++) { a[i][j] = i + j; } } for (u_int i = 0; i < b.GetX(); i++) { for (u_int j = 0; j < b.GetY(); j++) { b[i][j] = i + j; } } Matrix c = a + b; return 0; } When I turn on my program, it throws me a segmentation fault after adding two matrixes. The more interesting thing for me in that situation is first 2 lines in Matrix.cpp, Matrix Matrix::operation+.... When I delete these 2 lines (check on equality 2 matrixes), when I turn on my program, it doesn't throw me a segmentation fault, but when I add these 2 lines, the program throws me a s.f. Can you tell me why does it work like that?
You might consider using a 1D double[x*y] array instead of a 2D double*[x] of double[y] arrays. It will make memory management a bit easier, since you will have only 1 array to deal with, instead of multiple arrays. In any case, your Matrix(const Matrix &) copy constructor should not be delete[]'ing anything in mtrx yet, because mtrx has not been initialized yet (it is pointing at random memory). And the rest of that constructor is not allocating the arrays correctly, either. You allocate the arrays correctly in the Matrix(u_int, u_int) constructor, so just copy that logic into the copy constructor. And then finish off the copy constructor by, you know, actually copying the double values from the Matrix being copied from. As for operator+, if you don't know what you should return for different sized matrices, then I would suggest throw'ing an exception instead. Also, even though your current code doesn't use this yet, you should add a copy assignment operator= to finish off the Rule of 3 (you already have a copy constructor and a destructor). Try this: #ifndef MATRIX_HEADER #define MATRIX_HEADER typedef unsigned int u_int; class Matrix { double **mtrx; //or: double *mtrx; u_int x, y; public: Matrix(u_int a, u_int b); Matrix(const Matrix &); ~Matrix(); double det(); Matrix& operator=(const Matrix &); Matrix operator+(const Matrix &) const; Matrix operator-(const Matrix &) const; Matrix operator*(const Matrix &) const; friend Matrix operator*(const Matrix &, const double &); Matrix operator/(const Matrix &) const; double* operator[](const u_int idx) const { return mtrx[idx]; //or: return &mtrx[idx*x]; } bool IsEqualSize(const Matrix &) const; u_int GetX() const { return x; } u_int GetY() const { return y; } }; #endif #include "Matrix.hpp" #include <utility> #include <stdexcept> Matrix::Matrix(u_int a, u_int b) : x(a), y(b) { mtrx = new double*[x]; for (u_int i = 0; i < x; ++i) { mtrx[i] = new double[y]; } // or: mtrx = new double[x*y]; } Matrix::Matrix(const Matrix &ref) : x(ref.x), y(ref.y) { mtrx = new double*[x]; for (u_int i = 0; i < x; ++i) { mtrx[i] = new double[y]; for (u_int j = 0; j < y; ++j) { mtrx[i][j] = ref.mtrx[i][j]; } } /* or: u_int size = x*y; mtrx = new double[size]; for (u_int i = 0; i < size; ++i) { mtrx[i] = ref.mtrx[i]; } */ } Matrix::~Matrix() { // this loop is not needed for a 1D array... for (u_int i = 0; i < x; ++i) { delete[] mtrx[i]; } delete[] mtrx; } bool Matrix::IsEqualSize(const Matrix &a) const { return (a.GetX() == x) && (a.GetY() == y); } Matrix& Matrix::operator=(const Matrix &a) { if (&a != this) { Matrix tmp(a); std::swap(mtrx, tmp.mtrx); } return *this; } Matrix Matrix::operator+(const Matrix &a) const { if (!IsEqualSize(a)) throw std::logic_error("Cannot add matrices of different sizes"); Matrix matrix(x, y); for (u_int i = 0; i < x; ++i) { for (u_int j = 0; j < y; ++j) matrix.mtrx[i][j] = mtrx[i][j] + a.mtrx[i][j]; } /* or: u_int size = x*y; for (u_int i = 0; i < size; ++i) { matrix.mtrx[i] = mtrx[i] + a.mtrx[i]; } */ return matrix; } ... #include <stdio.h> #include "Matrix.hpp" int main() { Matrix a(2, 5); Matrix b(2, 5); for (u_int i = 0; i < a.GetX(); ++i) { for (u_int j = 0; j < a.GetY(); ++j) { a[i][j] = i + j; } } for (u_int i = 0; i < b.GetX(); ++i) { for (u_int j = 0; j < b.GetY(); ++j) { b[i][j] = i + j; } } Matrix c = a + b; return 0; }
72,081,271
72,081,294
I am getting a "base operand of ‘->’ has non-pointer type" when calling my function
In this program, I am supposed to call animal.at(0)->makeSound() in main() and have it return "Woof" from the public member function makeSound() for Dog. However, when I compile the code as written, it gives me an error: base operand of '->' has non-pointer type While I know there are other ways around this, I am not allowed to modify any of this code except for the vector type and the element list of the vector, as this is a practice problem from an old homework I got wrong. If somebody could tell me how to set up the array properly (vector <MISSING_TYPE> animal {MISSING VECTOR ELEMENT};) so that it will compile, you will be saving me for finals. What I have now is currently incorrect. #include <iostream> #include <vector> using namespace std; class Animal { public: virtual void makeSound() { cout << "Animal!" << endl; } }; class Dog : public Animal { public: void makeSound() { cout << "Woof" << endl; } }; int main() { Dog dog; vector<Animal> animal {dog}; animal.at(0)->makeSound(); return 0; }
The compiler error is because the vector is holding Animal objects, not Animal* pointers to objects, so you would have to use the . operator instead of the -> operator to access the makeSound() member, eg: animal.at(0).makeSound(); // or, since you KNOW there is 1 object in the vector, the // bounds checking of at() is redundant, use operator[] instead: // // animal[0].makeSound(); Online Demo However, although that will fix the compiler error, calling makeSound() at runtime will print "Animal!" instead of "Woof", because you are not actually storing a Dog object in the vector, you are storing an Animal object due to object slicing. To fix that, you would need to instead store an Animal* pointer to the Dog object, eg: int main() { Dog dog; vector<Animal*> animal {&dog}; animal.at(0)->makeSound(); // or: animal[0]->makeSound(); return 0; } Online Demo
72,081,278
72,081,350
Is it possible to union variable conversion function?
For example, there are three variable conversion functions. //Int int toInt(std::string input) { int ret = strtol(input.c_str(), 0, 10); return ret; } //Double double toDouble(std::string input) { double ret = strtod(input.c_str(), 0); return ret; } //Const char* const char* toChar(std::string input) { return input.c_str(); } I want to combine these functions like below: ~~ toConvert(std::string input) { if ( Variable type is Int ) return strtol(~~~) else if ( Varibale type is Double ) return strtod(~~~) ... // Using int i = toConvert<int>(input); double d = toConvert<double>(input); const char* c = toConvert<const char*>(input); Is it possible? Please help for implemet above function.
Your "using" code is passing a template argument to toConvert(), so make sure toConvert() is actually a template, and then you can specialize it for each type you want, eg: template<typename T> T toConvert(std::string &input) { return T{}; /* or, throw an exception... */ } template<> int toConvert<int>(std::string &input) { return strtol(input.c_str(), 0, 10); } template<> double toConvert<double>(std::string &input) { return strtod(input.c_str(), 0); } template<> const char* toConvert<const char*>(std::string &input) { return input.c_str(); } Or, if you are using C++17 or later, you can instead use if constexpr in a single template: #include <type_traits> template<typename T> T toConvert(std::string &input) { if constexpr (std::is_same_v<T, int>) return strtol(input.c_str(), 0, 10); else if constexpr (std::is_same_v<T, double>) return strtod(input.c_str(), 0); else if constexpr (std::is_same_v<T, const char*>) return input.c_str(); else return T{}; // or, throw an exception, or static_assert a compiler error... } Notice in either case that I changed the input parameter to std::string&. Your original code was taking in the std::string by value, which means it takes in a copy of the caller's string, and so the const char* conversion would return a dangling pointer to invalid memory when the copied std::string is freed upon return. By taking a reference instead, you avoid that copy. You might be tempted to take in a const std::string& reference instead, but that would allow calls like toConvert<const char*>("string") to compile but still return a dangling pointer, since the compiler would have to create a temporary std::string to bind to the const reference. But a string literal can't bind to a non-const reference.
72,081,406
72,081,533
Convert an integer to an array of digits C++
I'm working on the "Plus One" LeetCode problem, which has you write a function that takes a number (represented by an array of digits), adds one and returns the result as an array of digits. Here is the problem statement: You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's. Here is my code, I have the var numB and I want to add each element to the vector<int> res. How would I do such a thing? #include <string> #include <sstream> class Solution { public: vector<int> plusOne(vector<int>& digits) { vector<int> res; stringstream ss; for (int i : digits) ss << i; int numB; ss >> numB; numB++; } };
If what you really want is just to get the resulting vector, you can do this with math instead of converting things to strings std::vector<int> plusOne(const std::vector<int>& digits) { std::vector<int> res = digits; res[res.size()-1] += 1; // carry the 1 if any digit is > 9 int p = res.size()-1; while (res[p] > 9) { res[p] = res[p] % 10; if (p > 0) { res[p - 1] += 1; --p; } else { res.insert(res.begin(), 1); } } return res; } You can try it out and see that it works, make sure to test with a number where the result has more digits than the input. void print(const std::string& name, const std::vector<int>& v) { std::cout << name << " = "; for (auto&& vi : v) std::cout << vi << " "; std::cout << std::endl; } int main() { std::vector<int> in = { 1,2,9 }; auto out = plusOne(in); print("in",in); print("out",out); in = {9,9 }; out = plusOne(in); print("in",in); print("out",out); return 0; } Produces this result: in = 1 2 9 out = 1 3 0 in = 9 9 out = 1 0 0 If you really want to do it with strings for some reason, this will accomplish the same thing, but keep in mind that this will fail for large numbers of digits (for numbers greater than INT_MAX numB will overflow) std::vector<int> plusOne(const std::vector<int>& digits) { std::vector<int> res; std::stringstream ss; for (int i : digits) { ss << i; } int numB; ss >> numB; numB++; std::string numstr = std::to_string(numB); for (int i = 0; i < numstr.size(); ++i) { std::string c = numstr.substr(i, 1); res.push_back(std::atoi(c.c_str())); } return res; }
72,081,621
72,081,639
Automatic constructor inheritance in C++20
I just have this code, and I wonder why this code compiles in C++20 and later, but it doesn't compile in C++17 and earlier. struct B { B(int){}; }; struct D : B { }; int main() { D d = D(10); } I know that inheriting constructors is a C++11 feature. But class D doesn't inherit the B::B(int) constructor, even though this line D d = D(10); compiles. My question is, why does it compile only in C++20 and not in C++17? Is there a quote to the C++ standard that applies here? I am using g++11.2.0.
C++20 added the ability to initialize aggregates using parentheses; see P0960. Previously, you could have initialized d using D d{10};; now you can do the same thing with parentheses instead of braces. The class D does not implicitly inherit constructors from B.
72,081,724
72,082,040
Why does exporting a type alias such as std::vector<std::string> in a module allow use of both std::vector and std::string in some internal partition?
I am currently using Visual Studio 2022 Update 17.1.6, and I found something interesting with exporting type alias. For reasons I don't understand, when I export a type alias for some data type such as std::vector<std::string> in a module interface file, I can use both std::vector<> and std::string in the file that imported it. For example: modInterface.ixx export module words; import <iostream> import <vector>; import <string>; ... export using Words = std::vector<std::string>; ... In an internal partition: modInternalPartition.cpp module words:wordsIP; import words; //This compiles as expected Words wordStorage; //Why does my compiler sees below as correct, and compiles it without error? std::vector<int> numStorage = { 1, 2, 3, 4 }; //Why does my compiler also sees below as correct, and compiles it without error? std::string text = "This dish is tasty"; //This would produce an error, which is expected since I did not export import <iostream> in modInterface.ixx std::cout << text; ... My first thought was that since Words is a type alias, exporting it would mean exporting std::vector<> and std::string, but since std::vector<> is a template, why is it not the case that only the instantiation of it (std::vector<std::string>) is exported?
Here's a funny thing about modules: export declarations only matter for code outside of a module. If you import a module unit that is part of the same module as yourself, you have access to all of the declarations in that module unit. This allows you to have "private" declarations which are not exported to the module's interface, but are still accessible to other code within the module. This includes module imports: Additionally, when a module-import-declaration in a module unit of some module M imports another module unit U of M, it also imports all translation units imported by non-exported module-import-declarations in the module unit purview of U. Header units are not special in this regard. You imported those header units, so they are imported by your primary module interface. Therefore, any module implementations for that module that import your primary module interface will see them.
72,082,143
72,082,166
error: anachronistic old-style base class initializer while using cmake
I am trying to run the code in repository Link. Here, is the Google Colab link which installs all the libraries as required to run the repository. - Link In the link, there are two ways I have built the project. One is using qmake and the other is using cmake. Both of them give me the same errors. I searched for the error in question but gave me some answers that were 7 years old. Considering the code in the repository is built in 2020, I doubt there is a problem in the code. I think the problem may be with the version of gcc/g++. Version: GCC/G++ : 7.5. The code that throws the error: #define len(p) (std::sqrt(p.x * p.x + p.y * p.y)) The above code is present in src/geomutils.h line 31. Does this code follow some specific C++ version like C++-11, C++-14, etc.?
You defined a proprocessor macro named len(). We can tell from the GCC error message that the file /usr/include/mlpack/core/data/serialization_shim.hpp contains the code len(len) inside it, which is presumably intended to initialize the len member of a class. But the preprocessor is inserting your code there and causing syntax errors. Rename len to something less likely to be used in other code, or make sure you only define it after including all third-party header files.
72,082,414
72,088,538
Does std::ranges::to allow converting to a std::map?
In the std::ranges::to paper wg21.link/p1206 ths overview section has the following //Supports converting associative container to sequence containers auto f = ranges::to<vector>(m); However I can't find where the detail of converting to a std::map is descibed in the rest of the paper. I tried range-v3 and Sy Brand's implementation of ranges::to in https://github.com/TartanLlama/ranges and neither of them compiles code converting a range to a std::map. So is this just missing from those libraries or is converting to a std::map not really intended to be allowed?
Does std::ranges::to allow converting to a std::map? Yes. I tried range-v3 and Sy Brand's implementation of ranges::to in https://github.com/TartanLlama/ranges and neither of them compiles code converting a range to a std::map I haven't tried Sy's implementation, and it looks like range-v3's implementation is weirdly broken: #include <map> #include <vector> #include <range/v3/range/conversion.hpp> int main() { std::vector<std::pair<int, int>> v = {{1, 2}, {3, 4}}; // this works (explicit) // m1 is a std::map<int, int> auto m1 = ranges::to<std::map<int, int>>(v); // this works (deduced with a pipe) // m2 is a std::map<int, int> auto m2 = v | ranges::to<std::map>(); // but this does not (deduced, direct call) auto m3 = ranges::to<std::map>(v); } The issue is that the class template direct call version in range-v3 for some reason specifically tries to instantiate C<range_value_t<R>> (which would be std::map<std::pair<int, int>> in this case, clearly wrong) even though there is a metafunction here already that does the right thing and would deduce std::map<int, int> (used by the pipe version). The ranges::to in the standard library specifies these two to do the same (correct) thing, so this will work in C++23. This is just an easy bug fix in range-v3.
72,084,241
72,084,352
How to store a specific object's member function of known signature in a variable in C++?
What is the recommended way to store a reference to a non-static member function of a specific signature on some object instance? In a way where the calling code needs not to know of the object's class (i.e. no casting), just that the function is the correct signature. For example, if there are two different classes with functions of the same void(int) signature, like class Foo { public: int myInt; void multMyInt(int multiplier) { myInt *= multiplier; } }; class Bar { public: bool isBig; void setMySize(int size) { isBig = size > 100; } }; What should this code look like? int main() { Foo* myFoo = new Foo(); Bar* myBar = new Bar(); int x = 10; callIntFunc(x, /* myFoo->multMyInt() */); callIntFunc(x, /* myBar->setMySize() */); } // Calls any function which matches void(int). void callIntFunc(int inInt, /* function stored in some way */) { // call given function with inInt as the parameter } What is the recommended approach to doing this using standard library only? p.s. Apologies if this is a repeat question. I have searched in any terms that came to mind, and couldn't find it.
As you have to store not only the pointer to the member function but also the object which the function should access, you need a way to store both in a single kind of object. As C++ has lambda functions you simply can take them and use them like in the following example modified from your code. class Foo { public: int myInt; void multMyInt(int multiplier) { std::cout << "Calls multMyInt" << std::endl; myInt *= multiplier; } }; class Bar { public: bool isBig; void setMySize(int size) { std::cout << "Calls setMySize" << std::endl; isBig = size > 100; } }; // Calls any function which matches void(int). void callIntFunc(int inInt, auto& func ) { func(inInt); } int main() { Foo* myFoo = new Foo(); Bar* myBar = new Bar(); auto multMyInt = [myFoo](int parm){ myFoo->multMyInt(parm);}; auto setMySize = [myBar](int parm){ myBar->setMySize(parm);}; int x = 10; callIntFunc(x, multMyInt); callIntFunc(x, setMySize); } In times before C++11 you have to use std::bind but that is really not longer needed. Instead of using auto in connection with lambda, you can also go with std::function which results in: // Calls any function which matches void(int). void callIntFunc(int inInt, std::function<void(int)>& func ) { func(inInt); } int main() { Foo* myFoo = new Foo(); Bar* myBar = new Bar(); std::function<void(int)> multMyInt = [myFoo](int parm){ myFoo->multMyInt(parm);}; std::function<void(int)> setMySize = [myBar](int parm){ myBar->setMySize(parm);}; int x = 10; callIntFunc(x, multMyInt); callIntFunc(x, setMySize); } The templated version which uses auto needs some more program memory as it generates for each function type a new instance, but it is fast. The std::function version needs less program space but results in a bit runtime overhead. It depends on your needs what you prefer! Update from comments: There is nothing special regarding the scope in case of using lambdas as in every other situation where you use pointers or references. But you have to take care: if you capture by reference, the referenced object must be alive if you call the function / lambda. if you capture a copy of the object, you get a new independent copy. As this, it is valid as long the lambda is alive, but you reference to a copy and not the original object. What is the type of auto: Every lambda results in a new type. The type itself is always hidden and generated by the implementation. That is why you have to use auto.
72,084,796
72,084,871
Is there a best way to deal with undefined behavior in bitwise conversion between floats and integers in C++14, C++17, C++20 and different compilers?
Which way in below tests is the most preferred in terms of dealing with undefined behavior, auto-vectorization (for struct of arrays) and portability (clang,gcc,msvc,icc)? Is there another way of doing same operation? #include <iostream> #include <cstring> union trick1 { float fvar; int ivar; }; struct trick2 { float fvar; int ivar() { int result; std::memcpy(&result,&fvar,sizeof(float)); return result; } }; struct trick3 { float fvar; int ivar() { int result=0; asm ("mov %0,%0" : "=r" (result) : "0" (fvar)); return result; } }; struct trick4 { float fvar; int ivar() { int result; result = *reinterpret_cast<int*>(&fvar); return result; } }; int main() { trick1 test1; test1.fvar = 3.14f; // 1078523331 std::cout<<test1.ivar<<std::endl; trick2 test2; test2.fvar = 3.14f; // 1078523331 std::cout<<test2.ivar()<<std::endl; trick3 test3; test3.fvar = 3.14f; // 1078523331 std::cout<<test3.ivar()<<std::endl; trick4 test4; test4.fvar = 3.14f; // 1078523331 std::cout<<test4.ivar()<<std::endl; return 0; } For example, is memcpy ok for converting array of floats to array of integers bitwise?
trick1 (union): Undefined behaviour in ISO C++, unlike ISO C99. The C++ compilers you mentioned support it as an extension in C++. trick2 (std::memcpy) is your best choice before C++20: Well defined with the precondition that sizeof(int) == sizeof(float), but not as simple as std::bit_cast. Mainstream compilers handle it efficiently, not actually doing an extra copy of anything (effectively optimizing it away), as long as the copy size is a single primitive type and writes all the bytes of the destination object. trick3 (inline asm): Non-standard; not portable (neither CPU arch nor compiler). Seriously hinders optimisation, including auto-vectorization. trick4 (deref a reinterpret_cast pointer): Undefined behaviour in ISO C++, and in practice on many real compilers (notably GCC and Clang), unless you compile with gcc -fno-strict-aliasing. I recommend C++20 std::bit_cast when applicable. It's as efficient as memcpy, and cleaner syntax: return std::bit_cast<int>(fvar);
72,085,417
72,085,971
How to extract all tuple elements of given type(s) into new tuple
The existing tuple overloads of std::get are limited to return exactly 1 element by index, or type. Imagine having a tuple with multiple elements of the same type and you want to extract all of them into a new tuple. How to achieve a version of std::get<T> that returns a std::tuple of all occurrences of given type(s) like this? template<typename... Ts_out> constexpr std::tuple<Ts_out...> extract_from_tuple(auto& tuple) { // fails in case of multiple occurences of a type in tuple return std::tuple<Ts_out...> {std::get<Ts_out>(tuple)...}; } auto tuple = std::make_tuple(1, 2, 3, 'a', 'b', 'c', 1.2, 2.3, 4.5f); auto extract = extract_from_tuple <float, double>(tuple); // expecting extract == std::tuple<float, double, double>{4.5f, 1.2, 2.3} Not sure if std::make_index_sequence for accessing each element by std::get<index> and std::is_same_v per element could work.
Only C++17 is needed here. std::tuple_cat is one of my favorite tools. Use a std::index_sequence to chew through the tuple Use a specialization to pick up either a std::tuple<> or a std::tuple<T> out of the original tuple, for each indexed element. Use std::tuple_cat to glue everything together. The only tricky part is checking if each tuple element is wanted. To do that, put all the wanted types into its own std::tuple, and use a helper class for that part, too. #include <utility> #include <tuple> #include <iostream> // Answer one simple question: here's a type, and a tuple. Tell me // if the type is one of the tuples types. If so, I want it. template<typename wanted_type, typename T> struct is_wanted_type; template<typename wanted_type, typename ...Types> struct is_wanted_type<wanted_type, std::tuple<Types...>> { static constexpr bool wanted=(std::is_same_v<wanted_type, Types> || ...); }; // Ok, the ith index in the tuple, here's its std::tuple_element type. // And wanted_element_t is a tuple of all types we want to extract. // // Based on which way the wind blows we'll produce either a std::tuple<> // or a std::tuple<tuple_element_t>. template<size_t i, typename tuple_element_t, typename wanted_element_t, bool wanted=is_wanted_type<tuple_element_t, wanted_element_t>::wanted> struct extract_type { template<typename tuple_type> static auto do_extract_type(const tuple_type &t) { return std::tuple<>{}; } }; template<size_t i, typename tuple_element_t, typename wanted_element_t> struct extract_type<i, tuple_element_t, wanted_element_t, true> { template<typename tuple_type> static auto do_extract_type(const tuple_type &t) { return std::tuple<tuple_element_t>{std::get<i>(t)}; } }; // And now, a simple fold expression to pull out all wanted types // and tuple-cat them together. template<typename wanted_element_t, typename tuple_type, size_t ...i> auto get_type_t(const tuple_type &t, std::index_sequence<i...>) { return std::tuple_cat( extract_type<i, typename std::tuple_element<i, tuple_type>::type, wanted_element_t>::do_extract_type(t)... ); } template<typename ...wanted_element_t, typename ...types> auto get_type(const std::tuple<types...> &t) { return get_type_t<std::tuple<wanted_element_t...>>( t, std::make_index_sequence<sizeof...(types)>()); } int main() { std::tuple<int, const char *, double> t{1, "alpha", 2.5}; std::tuple<double, int> u=get_type<int, double>(t); std::cout << std::get<0>(u) << " " << std::get<1>(u) << std::endl; std::tuple<int, int, int, char, char, char, double, double, float> tt; auto uu=get_type<float, double>(tt); static_assert(std::is_same_v<decltype(uu), std::tuple<double, double, float>>); return 0; }
72,086,309
72,088,506
How to create c++ lib with specific architecture?
I am using gradle to build c++ library C++ library gradle reference 1. Configure library target machines library { targetMachines = [ machines.linux.x86_64, machines.windows.x86, machines.windows.x86_64, machines.macOS.x86_64 ] } 2. Configure library linkages library { linkage = [Linkage.STATIC, Linkage.SHARED] } I can't understant the above targetmachines and linkage code. I want to create c++ library with specific architecture. Can any one explain what is the purpose of those code ?
The reference you've provided gives a very good documentation of what is needed. There are 2 types of libraries, static and shared, that you can create. For the linkage config, you will have to specify the type of library that you would like to create. The targetMachines specifies the configuration of the system where your library is expected to be used. one example here could be library{ targetMachines= [machines.windows.x86, machines.windows.x86_64] linkage = [Linkage.STATIC] }
72,086,552
72,086,585
Why doesn't accessing this nullpointer cause an exception?
#include <iostream> class TestClass { public: TestClass() { std::cout << "TestClass instantiated\n"; } ~TestClass() { std::cout << "TestClass destructed\n"; } void PrintSomething() { std::cout << "TestClass is printing something\n"; } }; int main() { TestClass* tClass = new TestClass(); delete tClass; tClass = nullptr; tClass->PrintSomething(); std::cout << "Exiting...\n"; return 0; } Result: TestClass instantiated TestClass destructed TestClass is printing something Exiting... I thought that trying to print something after the tClass pointer had been set to nullptr would cause a nullpointer exception error, but it prints just fine.
Why doesn't accessing this nullpointer cause an exception? Because it's not specified to cause an exception. Accessing through a null poitner results in undefined behaviour. Don't do it.
72,086,820
72,087,404
How to make qlineedit only for some string?
I'm newer for qt. I want to make a lineedit only sell signals for some string,like apple,banana,melon. How can I get it with regex or other method?
Just use QComboBox and check it's editable flag
72,086,996
72,087,324
xarray multiplication via operator * and raw loop give different results
I'm a beginner at xtensor and in the following code, I thought the variables result and sum should be equal but aren't. In this example result == 1000 and sum == 55000. The two variables also hold different results if I compare operations like xt::transpose(x)*A*x and its raw loop implementation (where A has compatible shape with x). How should I use xtensor operations in order to get the same results of raw loops? #include <stdio> #include <cmath> #include <xtensor/xarray.hpp> #include <xtensor/xbuilder.hpp> #include <xtensor/xstrided_view.hpp> int main(int argc, char* argv[]){ xt::xarray<double> x = xt::ones<double>({10ul,1ul}); xt::xarray<double> b = xt::zeros<double>({10ul,1ul}); for(int i = 1; i <= 10; ++i){ b(i-1,0) = 1000*i; } double result = (xt::transpose(b)*x)(0); double sum = 0; for(int i = 0; i < 10; ++i){ sum += b(i,0)*x(i,0); } std::cout << result << " " << sum << "\n"; return 0; } Live example: https://godbolt.org/z/GMEeEzn8r (thanks to Daniel Langr in the comments)
There is a small issue in the following line: double result = (xt::transpose(b)*x)(0); Very understandably, you may assume that the multiplication of the vectors gives the sum over the pointwise product, because this is what mathematical expressions would do. However this is not what xtensor does. Fo xtensor, the expression is just the pointwise product of the two vectors, not including summation. To get the correct result, change the line to double result = xt::sum(xt::transpose(b)*x)();
72,087,238
72,094,479
The module "%VSINSTALLDIR%\DIA SDK\bin\msdia140.dll" failed to load, while trying to install llvm on windows 10
I am trying to get started with compiler development using llvm, I follow official setup page on the 10th step and am getting the following error The module "%VSINSTALLDIR%\DIA SDK\bin\msdia140.dll" failed to load make sure the binary is stored at specified path or debug it to check for problems with binary or dependent .DLL files. The specified module could not be found. Visual Studio 2022 information : Microsoft Visual Studio Community 2022 Version 17.1.6 VisualStudio.17.Release/17.1.6+32421.90 Microsoft .NET Framework Version 4.8.04084 Installed Version: Community Visual C++ 2022 00482-90000-00000-AA606 Microsoft Visual C++ 2022 ASP.NET and Web Tools 2019 17.1.363.30963 ASP.NET and Web Tools 2019 Azure App Service Tools v3.0.0 17.1.363.30963 Azure App Service Tools v3.0.0 C# Tools 4.1.0-5.22165.10+e555772db77ca828b02b4bd547c318387f11d01f C# components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used. Microsoft JVM Debugger 1.0 Provides support for connecting the Visual Studio debugger to JDWP compatible Java Virtual Machines Microsoft MI-Based Debugger 1.0 Provides support for connecting Visual Studio to MI compatible debuggers Microsoft Visual C++ Wizards 1.0 Microsoft Visual C++ Wizards Microsoft Visual Studio VC Package 1.0 Microsoft Visual Studio VC Package NuGet Package Manager 6.1.0 NuGet Package Manager in Visual Studio. For more information about NuGet, visit https://docs.nuget.org/ Test Adapter for Boost.Test 1.0 Enables Visual Studio's testing tools with unit tests written for Boost.Test. The use terms and Third Party Notices are available in the extension installation directory. Test Adapter for Google Test 1.0 Enables Visual Studio's testing tools with unit tests written for Google Test. The use terms and Third Party Notices are available in the extension installation directory. TypeScript Tools 17.0.1229.2001 TypeScript Tools for Microsoft Visual Studio Visual Basic Tools 4.1.0-5.22165.10+e555772db77ca828b02b4bd547c318387f11d01f Visual Basic components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used. Visual Studio Code Debug Adapter Host Package 1.0 Interop layer for hosting Visual Studio Code debug adapters in Visual Studio Visual Studio IntelliCode 2.2 AI-assisted development for Visual Studio. Visual Studio Tools for CMake 1.0 Visual Studio Tools for CMake I am trying to get llvm up and running, The .dll files are available at the given location, please help. $ ls amd64/ arm/ arm64/ msdia140.dll*
I had the same problem as you at first, please read my solution carefully: You need to use the cd command to enter the folder where you want to install LLVM. Regarding the cd command, I suggest you search for usage methods on Google, I believe it will be easier to understand than what I described. The documentation mentions that You may install the llvm sources in other location than c:\llvm but do not install into a path containing spaces (e.g. c:\Documents and Settings...) as it will fail. Run the Developer Command Prompt for VS 2019 as an administrator. Enter regsvr32 "%VSINSTALLDIR%\DIA SDK\bin\msdia140.dll" to get the following result. Please look carefully at Figure 1.
72,088,421
72,090,259
Why template class assignment operator can use "templated copy constructor" to assign different type
I have a template<class T> class Container {}. While doing some code experiments, I realised that when I call the assigment operator (operator=()) with a different type (i.e. passing a different template parameter to my Container template class), it compiles. It turns out that this is possible because I also have a "templated copy constructor" (I'm not sure what would be the proper name for this) which is called whenever I call the operator=() with a different argument type. #include <iostream> template<typename T> class Container { public: Container() : data() { } Container(const Container &c) : data(c.data) { std::cout << "COPY CONSTRUCTOR" << std::endl; } // This is what I call a "templated copy constructor". // If I remove this, the operator=() does not compile with a different type template<class U> Container(const Container<U> &c) : data(c.getData()) { std::cout << "TEMPLATE COPY CONSTRUCTOR??" << std::endl; } Container &operator=(const Container &c) { std::cout << "assignment operator" << std::endl; if (this == &c) return *this; this->data = c.getData(); return *this; } const T &getData() const { return this->data; } private: T data; }; int main() { Container<int> c1; Container<float> c2; c2 = c1; // Assigning a Container<int> to a Container<float> return 0; } The code above compiles without any errors. If I remove the "templated copy constructor" the compiler gives me this error: test.cpp:41:5: error: no viable overloaded '=' c3 = c1; ~~ ^ ~~ test.cpp:18:14: note: candidate function not viable: no known conversion from 'Container<int>' to 'const Container<float>' for 1st argument Container &operator=(const Container &c) { Can someone explain why this happens and what exactly does the "templated copy constructor" do? Thanks in advance! :)
Just like @Jarod42 said in the comments. I used cppinsights.io and realised that the compiler is seeing c2 = c1 as c2.operator=(Container<float>(c1));, so I suppose it is simply looking for a conversion constructor (what we called a "templated copy constructor" earlier), to see if there is any known way to cast one type to the other.
72,088,667
72,088,732
Should I move the value out of an optional or move the whole optional?
Is there an effective difference between std::move(*optional) and *std::move(optional)? Which one is preferable? Full example: #include <optional> #include <vector> void foo() { std::optional<std::vector<int>> ov = std::vector<int>{}; std::vector<int> v; v = std::move(*ov); } void bar() { std::optional<std::vector<int>> ov = std::vector<int>{}; std::vector<int> v; v = *std::move(ov); }
They do the same thing. In v = std::move(*ov);, *ov is a std::vector<int>& so std::move(*ov) gives you a std::vector<int>&& that you are trying to assign to v. In v = *std::move(ov); ov is a std::optional<std::vector<int>> so std::move(ov) gives you a std::optional<std::vector<int>>&& and calling * on that calls constexpr T&& operator*() && noexcept; so you again have a std::vector<int>&& that you are trying to assign to v Personally I prefer v = std::move(*ov); as v = *std::move(ov); makes me go: "Hmm, I am dereferencing, do I have an lvalue like most dereferences give or do I really have an rvalue?" and I would rather not have to ask myself that.
72,088,896
72,088,994
C++: For two different functions with do-while loops, why does x+=y give the same result as x=x+y in one function but not the other?
For function A below, I get a different result when I use est += XXX as compared to using est = est + XXX. The former gives a result of 1.33227e-15 while the latter gives a result of 8.88178e-16. On the other hand, for function B below, I get the same result regardless of whether I use est += XXX or est = est + XXX. Would anyone be able to explain why x+=y is equivalent to x=x+y in function B but not in A? function A double A(int nTerm){ const double PI = 3.141592653589793238463; double est = 0; double counter = 0; do { est += ( 16 * pow(-1,counter) )/ (2*counter+1) * pow((double)1/5, 2*counter+1) - ( 4 * pow(-1,counter) )/ (2*counter+1) * pow((double)1/239, 2*counter+1); counter++; } while (counter<=nTerm); return est-PI; } function B double B(int nTerm){ double est = 0; double counter = 0; do { est += counter; counter++; } while (counter<=nTerm); return est; }
x += y - z is the equivalent to x = x + ( y - z ). You likely wrote x = x + y - z. You need to enforce precedence. See here that with the brackets, the return values are the same. In your case, you want: est = est + ( ( 16 * pow(-1,counter) )/ (2*counter+1) * pow((double)1/5, 2*counter+1) - ( 4 * pow(-1,counter) )/ (2*counter+1) * pow((double)1/239, 2*counter+1) ); Note: when dealing with double values, A + B - C can be very different than A + ( B - C ) even though they should be the same. See Is floating point math broken?
72,089,029
72,092,221
Difference between a destructor in Python vs C++
How do the contracts of a C++ destructor and a Python destructor differ, especially relating to object lifecycle and when resources are reclaimed? I haven't found a comprehensive side-by-side comparison. What I think a C++ destructor does is that it entirely frees the memory held by the object. And Python deregisters the object but it still remains in the cache memory (calling it garbage collection), and then frees the memory entirely after the program is complete.
Liftime of a C++ object begins with its construction, and ends with its destruction. C++ assumes a system with limited amount of resources; Resource Aquisition Is Initialization. That just means every aquired resource is bound to an object and must be freed before the objects lifetime ends: the destructor is supposed to pay the debt of constructor. Otherwise a resource leak happens. Thus C++ defines 4 storage classes: External objects trancende others they are created at beginning of the program(before main) and destroyed upon exit. Static objects are much like external objects, but they can be a bit lazyier in construction and generally get destryed prior to external objects(things are more complicated) Do not ever forget forget the initialization order fiasco. Automatic objects( function local objects or none static class data members) die when they go out of scope. Scope for function local variables is the closing curly brace } corresponding the nearest opening curly brace { that embrace the object. None-static data members are killed by their parents. General rule for distructoin is that since new-commers build upon pioneers' work, each object may rely on the existance and validity of objects previously constructed: so automatic objects are destructed in the reverse order of construction(declaration). Dynamic objects are the most dangerous ones. Compiler does not automatically put a bound on their lifetime; but the progrmmer must do. General rule is to delete every instance created by new. But that is easier said than done. So good practice is to avoid using naked new/delete pair and stick to smart pointer and generic container libraries that cautiously take care of the tricky parts. But that is not all. In order to correctly implement RAII per class, one must be familiar with famous idioms. C++ Programmer must be able to utilize the rule of 0/3/5 and he must be familiar with copy/swap idiom for not so time-critcal cases. Nothing is a must, but those 2 idioms can be good start points for general cases; specific cases need specific treatment (eg. Copy/swap does not do good with vector).
72,089,764
72,089,841
How to proper set up a destructor in C++ with Xcode?
there is something that has been bugging me for a while. I cannot create a destructor using Xcode (with other IDEs like VS2021 that is no issue). I get the error: 1. Constructor cannot be redeclared 2. Missing return type for function '˜Pointer'; did you mean the constructor name 'Pointer'? If I try to declare outside of the class and uncomment the lines in *.cpp and *.hpp the errors get even crazier. My Pointers.hpp is the following: #ifndef Pointers_hpp #define Pointers_hpp #include <iostream> class Pointer{ public: Pointer(void); ˜Pointer(void){}; //˜Pointer(void); }; #endif /* Pointers_hpp */ and my Pointers.cpp is this one: #include "Pointers.hpp" Pointer::Pointer(void){}; //Pointer::˜Pointer(void){}; After several research in the internet, I could not find a solution to that, could any one give me a light on this? Many thanks in advance, Raphael
Solved thanks to user4581301: For those having the same problem I did. The issue here was the similarity between ˜ and ~ The correct one should be ~ If you are using MacBook Pro the short-key is Option-N.
72,090,121
72,090,482
How does Hoare partitioning work in QuickSort?
Here is the pseudocode straight from the book (CORMEN): Partition(A,p,r) x=A[p] i=p-1 j=r+1 while(TRUE) repeat j=j-1 until A[j]<=x repeat i=i+1 until A[i]>=x if i<j SWAP A[i] <=> A[j] else return j Here is code in C++: #include<bits/stdc++.h> using namespace std; int partition(int a[], int low, int high) { int pivot = a[low]; int i = low - 1; int j = high + 1; while (1) { do { i++; } while (a[i] < pivot); do { j--; } while (a[j] > pivot); if (i >= j) { cout<<j<<endl; return j; } swap(a[i], a[j]); } } /* The main function that implements QuickSort arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ void quickSort(int arr[], int low, int high) { if (low < high) { /* pi is partitioning index, arr[p] is now at right place*/ int pi = partition(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } } /* Function to print an array */ void printArray(int arr[], int size) { int i; for (i=0; i < size; i++) printf("%d ", arr[i]); printf("\n"); } // Driver program to test above functions int main() { int arr[] = {7,3,2,6,4,1,3,5}; int n = sizeof(arr)/sizeof(arr[0]); cout<<"partition:\n"; partition(arr,0,7); printArray(arr, n); quickSort(arr, 0, n-1); printf("Sorted array: \n"); printArray(arr, n); return 0; } If I use this array in input: [5,3,2,6,4,1,3,7] everything works logically well because the array returned by the partitioning will be: [3,3,2,1,4,6,5,7] Termination i=5 and j=4 so my pivot is 4. And all elements to the left of 4 are minor and all to the right are major Now if I use this array in input: [7,3,2,6,4,1,3,5] I will have this situation at the end of the partition [5,3,2,6,4,1,3,7] which will return to me as pivot j = 6 that is 3. Now the elements on the left of 3 are not all minor and on the right are major. But how is it possible that this works? Shouldn't I have the elements to the left of the pivot minor and to the right major?
With Hoare partition the pivot and values equal to the pivot can end up anywhere. The returned index is not an index to the pivot, but just a separator. For the code above, when partition is done, then elements <= pivot will be at or to the left of j, and elements >= pivot will be to the right of j. After doing a partition step, the C++ code should be: quickSort(arr, low, pi); // not pi - 1 quickSort(arr, pi + 1, high); example code that includes testing of quicksort: uint32_t Rnd32() { static uint32_t r = 0; r = r*1664525 + 1013904223; return r; } int Partition(int ar[], int lo, int hi) { int pv = ar[lo+(hi-lo)/2]; int i = lo - 1; int j = hi + 1; while(1){ while(ar[++i] < pv); while(ar[--j] > pv); if(i >= j) return j; std::swap(ar[i], ar[j]); } } void QuickSort(int ar[], int lo, int hi) { while (lo < hi){ int pi = Partition(ar, lo, hi); if((pi - lo) < (pi - hi)){ QuickSort(ar, lo, pi); lo = pi + 1; } else { QuickSort(ar, pi + 1, hi); hi = pi; } } } #define COUNT (16*1024*1024) int main(int argc, char**argv) { size_t i; int * ar = new int [COUNT]; for(i = 0; i < COUNT; i++){ ar[i] = Rnd32(); } QuickSort(ar, 0, COUNT-1); for(i = 1; i < COUNT; i++) if(ar[i-1] > ar[i]) break; if(i == COUNT) std::cout << "passed" << std::endl; else std::cout << "failed" << std::endl; delete[] ar; return(0); }
72,090,297
72,090,874
Maximum sum subarray, C++, DSA
I had tried to write a program to find the maximum sum subarray, I am able to take the output correctly in a certain scenario but if I want to change it the output is not as desired. So anyone can help me? #include<iostream> using namespace std; int main(){ int minValue,n; int a[n]={4,-2,-3,4,-1,-2,1,5,-3}; int max_so_far = minValue; int max_ending_here=0; int start=0, end=0, s=0; for(int i=0; i<n;i++){ max_ending_here = max_ending_here+a[i]; if(max_so_far < max_ending_here){ max_so_far = max_ending_here; start=s; end = i; } if(max_ending_here<0){ max_ending_here=0; s = i+1; } start=s; } cout<<"maximum sum subarray is: "<<max_so_far; cout<<"\nstart "<<start; //cout<<"\nend "<<end; return 0; } The output of this code is: maximum sum subarray is: 7 start 3 But if I try to print the value of end as well as shown in the following program: #include<iostream> using namespace std; int main() { int minValue,n; int a[n]={4,-2,-3,4,-1,-2,1,5,-3}; int max_so_far = minValue; int max_ending_here=0; int start=0, end=0, s=0; for(int i=0; i<n;i++) { max_ending_here = max_ending_here+a[i]; if(max_so_far < max_ending_here){ max_so_far = max_ending_here; start=s; end = i; } if(max_ending_here<0){ max_ending_here=0; s = i+1; } start=s; } cout<<"maximum sum subarray is: "<<max_so_far; cout<<"\nstart "<<start; cout<<"\nend "<<end; return 0; } The output becomes as: maximum sum subarray is: 32760 start 3 end 0 Can anybody point out the actual error for me?
Here I made 2 changes: Used INT_MIN Used vector instead of array definition. #include<iostream> using namespace std; int main() { vector<int> a ={4,-2,-3,4,-1,-2,1,5,-3}; // <------------ here int minValue=INT_MIN, n= a.size(); // <--------- here int max_so_far = minValue; int max_ending_here=0; int start=0, end=0, s=0; for(int i=0; i<n;i++) { max_ending_here = max_ending_here+a[i]; if(max_so_far < max_ending_here){ max_so_far = max_ending_here; start=s; end = i; } if(max_ending_here<0){ max_ending_here=0; s = i+1; } start=s; } cout<<"maximum sum subarray is: "<<max_so_far; cout<<"\nstart "<<start; cout<<"\nend "<<end; return 0; } OUTPUT: maximum sum subarray is: 7 start 3 end 7
72,090,569
72,094,168
Adding ACE+TAO with numerous compile errors
I am adding ACE TAO to my existing project, and I have compile errors after adding the projects. Most of the errors were "No such file or directory", and these errors can simply be fixed by changing the patch of the #include, but there are thousands of them, and I am thinking I must have done something wrong on my end. For example, in ace/Assert.h, it has #include ace/pre.h #include ace/ACE_export.h #include ace/config-all.h but Assert.h is also in the ace directory. These type of errors are every where in the ACE TAO project, am I doing something wrong? or do I just need to fix the #include paths manually?
For "No such file or directory" you should add the file path: Open the project's Property Pages dialog box. Select the Configuration Properties > C/C++ > General property page. Modify the Additional Include Directories property. Since you have other errors, I guess you may not have installed the Windows SDK for the corresponding operating system, you could install it in the visual studio installer. If the program has other errors, please upload the relevant details.
72,090,624
72,091,050
How to properly cleanup after google mock objects when calling exit(0)?
According to https://learn.microsoft.com/en-us/cpp/cpp/program-termination?view=msvc-170#exit-function, "Issuing a return statement from the main function is equivalent to calling the exit function with the return value as its argument.". Yet this proves to be wrong as the following example demonstrates: main.cpp #include "gtest/gtest.h" #include "gmock/gmock.h" #include "MyClass.h" // defines a class named `MyClass` #include "mock_test.h" using ::testing::_; using ::testing::Return; int main(int argc, char **argv) { Mock_MyClass mock_; EXPECT_CALL(mock_, foo(_)) .WillRepeatedly(Return(0)); exit(0); } mock_test.h class Mock_MyClass : public MyClass { public: MOCK_METHOD(int, foo, (string& _), (override)); }; Assume that MyClass defines a virtual destructor and a method virtual int foo(string &) (yet the full content of MyClass is not relevant). Upon running the program resulting from the preceding source code, I systematically get the following error: ERROR: this mock object should be deleted but never is. Its address is @0000000001100EF0. ERROR: 1 leaked mock object found at program exit. However, if exit(0) is replaced with return 0, I no longer get this error. Hence it seems that calling exit(0) bypasses some cleanup process that happens when return 0 is used. How can one, using exit(0), have the program cleanup after google mock objects in the same way that using return 0 would? That would enable one to terminate the program execution from a subfunction by calling exit(0) while ensuring to not get the above-mentioned error. (I compiled for Linux, armv7, with -std=c++17)
That seems like an information specific to MSVC compiler only. cppreference on std::exit says: Stack is not unwound: destructors of variables with automatic storage duration are not called. For comparison, a moment later returning from main is mentioned: Returning from the main function, either by a return statement or by reaching the end of the function performs the normal function termination (calls the destructors of the variables with automatic storage durations) and then executes std::exit, passing the argument of the return statement (or ​0​ if implicit return was used) as exit_code. That is consistent with C++ standard support.start.term [...] (Objects with automatic storage duration are not destroyed as a result of calling exit().) So the only standard way to call those destructors is to change object storage duration to static one (thread_local may work, I'm not sure) or to use return instead of std::exit or ensure destruction before std::exit call (e.g. by introducing another scope for the mock objects).
72,092,205
72,092,427
googletest - mocking abstract class
I am learning mocking and using googletest I created MockServer class that should mock the abstract class IServer: class IServer { virtual void writeData(QString buffer) = 0; virtual QByteArray readData() = 0; protected: virtual ~IServer() = default; }; class MockServer: public:: testing:: Test, public IServer { MOCK_METHOD(void, writeData, (QString buffer), (override)); MOCK_METHOD(QByteArray, readData, (), (override)); }; And now want to test the other class that uses it, however, I cannot initialize MockServer because it is an abstract class. How to solve this? TEST_F(Serv_test, start) { ?? MockServer mockServer; // <- how to declare it? EXPECT_CALL(mockServer, writeData(testing::_)).Times(1); EXPECT_CALL(mockServer, readData()).Return("testing"); Car car (nullptr, mockServer); }
You are confusing a few things: You are using a test fixture, but a test fixture needs to be a standalone class. You are mixing it with your mock class. You need to create a separate class for it. The Car class should take a parameter of type mock class (not the test fixture). .Return should be used inside WillOnce or WillRepeatedly among other places. You can't use it directly on EXPECT_CALL. I rewrote your code as follows: class IServer { public: virtual void writeData(QString buffer) = 0; virtual QByteArray readData() = 0; protected: virtual ~IServer() = default; }; // Test fixture class Serv_test : public ::testing::Test { }; // Mock class class MockServer: public IServer { public: MOCK_METHOD(void, writeData, (QString buffer), (override)); MOCK_METHOD(QByteArray, readData, (), (override)); }; class Car{ public: Car(int*, IServer* server):_server(server){ _server->writeData("testing"); _server->readData(); } IServer* _server; }; TEST_F(Serv_test, start) { MockServer mockServer; // <- how to declare it? EXPECT_CALL(mockServer, writeData(testing::_)).Times(1); EXPECT_CALL(mockServer, readData()) .WillOnce(testing::Return("testing")); Car car (nullptr, &mockServer); } Working example here: https://godbolt.org/z/avsKdh37r
72,093,848
72,234,350
Is there a direct way to get clear details on gcc acceptable option values (e.g. for -std) without grep-ing through irrelevant material?
The gcc (or g++) compiler has a -std option to specify the language standard to use for compiling C or C++. At the top level one can see that this option exists. gcc --help -std=<standard> Assume that the input sources are for <standard> However, different versions of the gcc compilers will have a different set of supported standards. Is there a simple and direct way to ask for detailed help on just that option so that one gets the details about accepted standards, etc. for just that option? I have done kludges in the past where I dumped exhaustive help about all manner of options and then tried to filter out just the lines I wanted by piping it through grep (see footnote). I'm not asking for that. I'm asking for a way to get the details for just the option one wants (such as -std) directly without any such ugly kludge. (Besides being awkward, the ugly kludges become problematic regarding getting all the relevant detail lines, including those lines concerning the option that don't happen to include whatever search term one is using to filter without knowing the extent of surrounding help text.) It's hard to believe there is no direct way to do this. Surely other people must want to be able to get detailed information about some option without getting mounds of unrelated other stuff besides. I'm hoping someone can tell me the simple method I'm missing. It's not this... gcc --help=std cc1: warning: unrecognized argument to --help= option: ‘std’ *Sedenion was kind enough to provide the following example of the grep approach, which some readers of this question may find helpful. gcc -Q --help=c++ | grep "\-std=" If someone only wants lines containing a known string, something like this could serve, if one remembers all the arguments and syntax details. If one wants other lines in the same entry for some gcc option, that becomes trickier since one doesn't necessarily know in advance what lines to capture. (Remember that -std is the example of the more general need for a better help option.)
Sadly, it seems that no one knows of a feature in gcc itself that would provide what I was seeking, i.e. a direct way to use gcc --help to get the detailed information about a particular option for that version of gcc. I appreciate the comments by RetiredNinja that fall back on the web documentation. Even though that is a tacit indication that the gcc command itself is not (yet?) up to the task, for now that does seem to be the next best general purpose alternative. A general procedure could follow steps like these. Get the relevant gcc --version Use the version to find and click on the most relevant GCC Manual at https://gcc.gnu.org/onlinedocs/ Find and then click on any of the links (toward the bottom) for either "Option Index" or "[Index]" (but NOT on the "Option Index" for the "Short Table of Contents"). On the Option Index page, click on the link to "Jump to:" the section for the relevant starting character. If there are multiple choices for the same option word (e.g. 4 entries for "std:"), one can try what seems the most appropriate (and then try another if that doesn't have what you were looking for). But wouldn't it be much more handy (and not even dependent on the internet) if one could just enter that option name in a single command, perhaps something more or less like the following? gcc --help=optionName
72,094,435
72,095,485
Find the Longest Common starting substring of S2 in S1
I was solving a problem. i solved the Longest Common starting substring of S2 in S1 part but the time complexity was very high. In the below Code I have to find the Longest Common starting substring of str3 in s[i]. In the below code instead of find function i have also use KMP algorithm but i faced high time complexity again. string str3=abstring1(c,1,2,3); while(1) { size_t found = s[i].find(str3); if(str3.length()==0) break; if (found != string::npos) { str1=str1+str3; break; } else { str3.pop_back(); } } Example : S1=balling S2=baller ans=ball S1=balling S2=uolling ans= We have to find common starting substring of S2 in S1 Can you help in c++ I find Similar Post but i was not able to do my self in c++.
Here is a solution that emits the faint aroma of a hack. Suppose s1 = 'snowballing' s2 = 'baller' Then form the string s = s2 + '|' + s1 #=> 'baller|snowballing' where the pipe ('|') can be any character that is not in either string. (If in doubt, one could use, say, "\x00".) We may then match s against the regular expression ^(.*)(?=.*\|.*\1) This will match the longest starting string in s2 that is present in s1, which in this example is 'ball'. Demo The regular expression can be broken down as follows. ^ # match beginning of string ( # begin capture group 1 .* # match zero or more characters, as many as possible ) # end capture group 1 (?= # begin a positive lookahead .* # match zero or more characters, as many as possible \| # match '|' .* # match zero or more characters, as many as possible \1 # match the contents of capture group 1 ) # end positive lookahead
72,094,764
72,094,944
Most performant way to verify an element exists in a given set in C++
I've been trying to write a code that finds all the numbers which summed to its inverted counterpart would result in an odd number, as for "12 + 21 = 33", "605839 + 938506 = 1544345", and so on and so forth... I've reached the problem of accessing the values of a given unordered_set and checking if a value is within it or not. The problem is the performance of the said "check", as for some reason that I can't identify, this verification is absurdly slow the way I did it, it seems the time grows exponentially the bigger the number of elements in the given set is. I would like to create a set, or a list of elements that doesn't repeat its values, which can access and insert elements in the most performatic way, disregarding the order of the elements, as the order doesn't really matter for this implementation. This is the code a came up with #include <iostream> #include <bits/stdc++.h> #include <string> using namespace std; string invertSequence(string sequence); int main() { unordered_set <int> control; for(int i = 0; i < 1000000; i++) { string number = std::to_string(i); string invertedSequence = invertSequence(number); int invertedNumber = stoi(invertedSequence); int sumValue = i + invertedNumber; if (!control.count(invertedNumber) && number.at(number.length() - 1) != '0') { control.insert(i); if (sumValue % 2 != 0) { cout << i << " + " << invertedNumber << " = " << i + invertedNumber << endl; } } } return 0; } string invertSequence(string sequence) { char inverted[sequence.length()]; const char* charSequence = sequence.c_str(); for (int i = 0; i < sequence.length(); i++) { inverted[sequence.length() -i - 1] = charSequence[i]; } return inverted; } I made the same code in Java, and it runs pretty good, it calculates all the ocurrences between 0 and 1 million in around 3800 milliseconds, whereas in my C++ code I never really let it run until the end, because its too slow and would take an eternity. Java has the HashSet class which does this job pretty well. Here is my java code Impl. I've searched the internet and read that unordered_set in C++ is similar to HashSet in Java, but maybe I'm missing out on something, cause the performance of both is way too different the way I'm doing it. I'd appreciate any help in this matter!
As @JaMiT recognized, it's not the set that's the problem; it's the potentially unterminated C string. If you invert into another std::string, which knows its length, you won't run into that problem: string invertSequence(string sequence) { string inverted(' ', sequence.size()); for (int i = 0; i < sequence.length(); i++) { inverted[sequence.length() - i - 1] = sequence[i]; } return inverted; } and at least on my computer, it runs in about 0.6 seconds. Finally, of course, std::reverse is shorter, safer, and even a little faster: string invertSequence(string sequence) { reverse(sequence.begin(), sequence.end()); return sequence; }
72,095,007
72,095,093
Undefined behaviour of delete operator
I am relatively new to C++ and I'm learning about pointers. I was trying to dynamically allocate some memory for an array and found this issue. Here is my code, #include <iostream> int main(){ int n = 5; int *arr = new int(n*(sizeof(int))); for(int i=0; i<n; i++) *(arr+i) = i+1; delete[] arr; for(int i=0; i<n; i++) std::cout << *(arr+i) << " "; } and the expected output is some garbage value since I'm freeing the memory with delete operator, however, this is my output instead: First run: 755597344 47626 2043 4 5 Second run: -1437908960 62859 2043 4 5 Third run: -902037472 965 2043 4 5 I've tried several runs, but only first 3 values change, and the others seem as the array was still there, what could be the explanation for this?
In the small piece of code there are multiple errors and problems: The expression new int(n*(sizeof(int))) allocates a single int value and initializes it to the value n*(sizeof(int)). If you want to allocate space for an array of int values you need to use new[], as in new int[n] Because of the above problem, you will go out of bounds of the allocated memory, leading to undefined behavior. Once you fix issue number 1, you need to pair new[] with the delete[] operator. Mismatching operators also leads to undefined behavior. And lastly, once you have deleted memory you can no longer access it, and any attempt of dereferencing the pointer will again lead to undefined behavior. All in all the program should look something like this: #include <iostream> #include <cstdlib> int main() { constexpr std::size_t n = 5; // Allocate memory int* arr = new[n]; // Initialize the memory for (std::size_t i = 0; i < n; ++i) { arr[i] = i + 1; } // Display the memory for (std::size_t i = 0; i < n; ++i) { std::cout << "arr[" << i << "] = " << arr[i] << '\n'; } // Free the memory delete[] arr; } With all of the above said and done, there are better ways to create arrays of either fixed or dynamic size. If you have a fixed-size array, whose size is known at compile-time and whose size will never change during run-time, use std::array instead: // Create and initialize array std::array<int, 5> arr = {{ 1, 2, 3, 4, 5 }}; // Display array for (int value : arr) { std::cout << value << '\n'; } If the size is not known at compile-time, or the size will need to change during run-time, use std::vector instead: // Create a vector with five "zero-initialized" elements std::vector<int> arr(5);
72,095,192
72,095,234
use std::for_each with bind a member function on a std::set , the code can't be compile
I can compile normal,when I use vector: TEST(function_obj,bindMemeber1){ std::vector<Person> v {234,234,1241,1241,213,124,152,421}; std::for_each(v.begin(),v.end(), std::bind(&Person::print,std::placeholders::_1) ); } but when I use set,something wrong: TEST(function_obj,bindMemeber1){ std::set<Person,PersonCriterion> v{234,234,1241,1241,213,124,152,421}; std::for_each(v.begin(),v.end(), std::bind(&Person::print,std::placeholders::_1) ); } clion's tips The IDE tell me that something wrong.when I force IDE to compile, it also can't compile successfully . Below is the code of Person; class Person{ private: size_t no; std::string name; public: Person():no(0){}; Person(size_t n): no(n){}; Person(const Person& p):no(p.no),name(p.name){}; friend class PersonCriterion; size_t getNo() const; void print(){ std::cout<<no<<' '; } const std::string &getName() const; }; class PersonCriterion{ public: bool operator()(const Person& p1,const Person& p2){ return p1.no<=p2.no; } }; size_t Person::getNo() const { return no; } const std::string &Person::getName() const { return name; }
Elements got from std::set are const-qualified; they're supposed to be non-modifiable. You should mark Person::print as const then it could be called on a const object. class Person { ... void print() const { // ^^^^^ std::cout<<no<<' '; } ... }; BTW: Better to mark operator() in PersonCriterion as const too. class PersonCriterion { public: bool operator()(const Person& p1, const Person& p2) const { return p1.no<=p2.no; } };
72,095,232
72,097,188
Cannot find source file: /home/tensorflow/core/util/stats_calculator.cc
I'm new to CMake and ROS. I've been following the tutorial on setting up tensorflow on ubuntu 20.0.4 (server) and rpi4, as well as building tensorflow lite with CMake for my turtlebot3 project. I added the following code to my CMakeLists.txt and modified my tensorflow source directory from "${TENSORFLOW_SOURCE_DIR}/tensorflow/lite" to "${TENSORFLOW_SOURCE_DIR}/ubuntu/tensorflow/tensorflow/lite" set(TENSORFLOW_SOURCE_DIR "" CACHE PATH "Directory that contains the TensorFlow project" ) if(NOT TENSORFLOW_SOURCE_DIR) get_filename_component(TENSORFLOW_SOURCE_DIR "${CMAKE_CURRENT_LIST_DIR}/../../../../" ABSOLUTE) endif() add_subdirectory( "${TENSORFLOW_SOURCE_DIR}/ubuntu/tensorflow/tensorflow/lite" "${CMAKE_CURRENT_BINARY_DIR}/tensorflow-lite" EXCLUDE_FROM_ALL) add_executable(MobileNetV1 src/scripts/MobileNetV1.cpp) target_link_libraries(MobileNetV1 ${catkin_LIBRARIES} ${OpenCV_INCLUDE_DIRS} tensorflow-lite) After building I experience the error below. CMake Error at /home/ubuntu/tensorflow/tensorflow/lite/CMakeLists.txt:449 (add_executable): Cannot find source file: /home/tensorflow/core/util/stats_calculator.cc Tried extensions .c .C .c++ .cc .cpp .cxx .cu .m .M .mm .h .hh .h++ .hm .hpp .hxx .in .txx CMake Error at /home/ubuntu/tensorflow/tensorflow/lite/CMakeLists.txt:449 (add_executable): No SOURCES given to target: benchmark_model The files exist under /home/ubuntu/tensorflow/tensorflow/core/util/stats_calculator.cc. I don't know why its not being detected. I don't know what to do next can some help me and explain why its giving me this error please. Code example that I want to compile and run come from this github if you want to replicate. And if you have links on easy to follow tutorials on how to setup tensorflow-lite on c++ that would be awesome!
As stated in your code, directory TENSORFLOW_SOURCE_DIR contains the TensorFlow project. In other words, content of this directory should look like that: https://github.com/tensorflow/tensorflow. And path to the tensorflow-lite should be exactly as written in the tutorial: ${TENSORFLOW_SOURCE_DIR}/tensorflow/lite If expression "${CMAKE_CURRENT_LIST_DIR}/../../../../" doesn't denote root of TensorFlow project on your machine, then modify that expression but remain meaning of TENSORFLOW_SOURCE_DIR variable. You may print value of variable TENSORFLOW_SOURCE_DIR after your computations and check that it actually refers to the root of Tensorflow project on your machine. Actually, the variable TENSORFLOW_SOURCE_DIR is used in the TensorFlow project itself. And exactly that usage causes problems when your setting of TENSORFLOW_SOURCE_DIR doesn't corresponds to expectations of its meaning in Tensorflow project. I wonder why the tutorial suggests to set TENSORFLOW_SOURCE_DIR variable but does not note about the variable's usage in the TensorFlow project. Instead of TENSORFLOW_SOURCE_DIR variable your code could use any other variable which isn't used by Tensorflow. You could even hardcode the path to TensorFlow lite in your code: # Do not define and do not use `TENSORFLOW_SOURCE_DIR` variable at all add_subdirectory( "/home/ubuntu/tensorflow/tensorflow/lite" "${CMAKE_CURRENT_BINARY_DIR}/tensorflow-lite" EXCLUDE_FROM_ALL) When find variable TENSORFLOW_SOURCE_DIR being not set, the script tensorflow/lite/CMakeLists.txt will correctly set it automatically: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/CMakeLists.txt#L42
72,095,414
72,095,558
Supersede c++ library printed lines
I have a c++ application, where I link my main.cpp with some pre-built libraries (.a files, I dont know their internal details). The main program looks something like this: int main() { printf("..this is my part of the code.\n"); // other code here } Then when I run my application, it produces the following output, where the first line comes from the linked library: Welcome to product XYZ, version 1.2 ..this is my part of the code. As an experiment, I added an "exit(0)" as the first line in my main.cpp: int main() { exit(0); printf("..this is my part of the code.\n"); // other code here } And I got this as the output: Welcome to product XYZ, version 1.2 My question is, how does the linked library start printing even before the first line of my code gets executed? What would be the code in the library (an example), which would make that behavior? And secondly, if I want my line to be printed before the library line, how would I go about doing it? (Note: the subject line for this question may not match the exact question that I am asking, I was not sure how to frame the subject line to summarize my question. Apologies for that in advance.)
As everyone has said in the comments, initializer code for statics and globals is executed before main(), and if this code prints a message, you cannot have something in main() supersede it. Suppose your main program is in main.cc, as you have it, and the library has a single file, thing.cc, like this: #include <iostream> class Thing { public: Thing() { std::cout << "Welcome to the Thing." << std::endl; } }; static Thing _thing; Now, compile this way: c++ thing.cc -o thing.o c++ main.cc thing.o -o main ./main and you'll see the message from Thing appear before you can even exit. When there is more than one, the order of these initializers is implementation-dependent, but they are all guaranteed to happen before main() is called.
72,095,907
72,096,055
Is it possible to replace member function to a noop function?
I write c++ with c++11 and have a question as title. Ex. class Hi { public: Hi(){}; test() {cout << "test" << endl;}; } void noop(){ ; // noop }; int main(){ Hi hi(); hi.test = noop; // just example, not real case return 0; } Is that possible to replace test() of class Hi to a noop function in runtime!? Thanks.
You can't replace any function at runtime, whether class member or not. However, you can achieve the desired effect by using a variable. (This is yet another example of the "add a level of indirection" method of solving problems.) Example: class Hi { public: Hi(): test([this]() { do_test(); }) {} std::function<void()> test; void do_test() { cout << "test" << endl; } }; void noop(){} int main(){ Hi hi; hi.test(); // Outputs 'test' hi.test = noop; hi.test(); // Does nothing }
72,096,254
72,096,910
returning an array in C++ with templates
I have the following code, where the kronecker product of 2 arrays is computed. In this code I want to return the array C which is the kronecker product of the two arrays back to the main function. I have tried pointers instead of void but I am not able to do it. Also I want tje function to compute the kroecker product of the arrays of any sizes so I have used templates here. How can I return the array C (Kronecker product) back to the main. #include <iostream> using namespace std; #include <any> #include <vector> template <size_t size_x1, size_t size_y1, size_t size_x2, size_t size_y2> void Kroneckerproduct(int (&A)[size_x1][size_y1],int (&B)[size_x2][size_y2]) { int rowa=size_x1; int cola=size_y1; int rowb=size_x2; int colb=size_y2; int C[rowa * rowb][cola * colb]; // i loops till rowa for (int i = 0; i < rowa; i++) { //for (int i = 0; i < size_x1; i++) { // k loops till rowb for (int k = 0; k < rowb; k++) { // for (int k = 0; k < size_x2; k++) { // j loops till cola for (int j = 0; j < cola; j++) { //for (int j = 0; j < size_y1; j++) { // l loops till colb for (int l = 0; l < colb; l++) { // for (int l = 0; l < size_y2; l++) { // Each element of matrix A is // multiplied by whole Matrix B // resp and stored as Matrix C C[i + l + 1][j + k + 1] = A[i][j] * B[k][l]; cout << C[i + l + 1][j + k + 1] << " "; } } cout << endl; } } } int main() { int A[3][2] = { { 1, 2 }, { 3, 4 }, { 1, 0 } }, B[2][3] = { { 0, 5, 2 }, { 6, 7, 3 } }; Kroneckerproduct(A, B); return 0; }
To return an array from a function, you must dynamically allocate it first. This is necessary as the array declared in the function statically is cleared after the function finishes its execution. To create an array of dimension m x n you can do something like this: int** c = new int*[m]; for (int i = 0; i < m; i++) { c[i] = new int[n]; } Now, you can simply return it using return c; Also, you need to delete this array manually as it was dynamically created. You can do so by using: for(int i = 0; i < m; i++) // To delete the inner arrays delete [] c[i]; delete [] c;
72,096,295
72,130,330
C++ google test, mocks not called on inherited classes
As said in the title, I try to test my code using google test, but I get some issue on inheritance of mocks. I will further present the structure of my code: file1.hpp struct A: virtual public testing::Test { //function with MocksA }; file2.hpp struct B: virtual public testing::Test { //function with MockB }; file3.hpp include file1 & file2 class C: public B, public A { //call MockB -> fails here }; If I only use the inheritance on "public B" or would put "public B" on 2nd position, the code works. However, I need both A & B to be tested in my class C and would get the same error for A (or B, depending the position). How can I include both files and use their mocks? P.S: both A&B have different names for MOCKS and would not influence one another. P.S 2: If situation is as above, I get: unknown file: Failure C++ exception with description " The mock function has no default action set, and its return type has no default value set." thrown in the test body. Actual function call count doesn't match EXPECT_CALL(...,.. )... Expected: to be called once Actual: never called - unsatisfied and active
The solution was to add EXPECT_CALLS in the 3rd file, not using the ones from file1 & file2
72,096,386
72,096,524
c++ precompiled headers vs. modules
I'm confused on the difference between precompiled headers and modules. What advantage does one have over the other? I've read the Microsoft documentation on both of them but it hasn't helped me much. Precompiled headers Modules
An advantage of modules is that they are a standard feature. All C++20 compilers must implement them as described in the language. Precompiled headers are not a standard feature. Not all compilers necessarily have that feature, and each compiler that has, implements them in their own way that isn't necessarily compatible with other compilers. An advantage of modules over headers is that they encapsulate macros. A (rarely useful) advantage of headers is that they can "export" macros. An advantage of modules over headers is that you have explicit control over what names you export, which allows encapsulating implementation details. At the moment of writing, a disadvantage of modules is that only MSVC has fully implemented them so far.
72,096,817
72,376,393
Sending and receiving integers array by Linux socket
I am trying to pass an array of integers (file descriptors) via linux socket using C++. I used cmgs(3) and seccomp_unotify(2) to write the following send and receive functions: send: static bool send_fds(int socket) // send array of fds by socket { int myfds[] = {568, 519, 562, 572, 569 ,566}; //static values for testing struct msghdr msg = { 0 }; struct cmsghdr *cmsg; char iobuf[1]; struct iovec io = { .iov_base = iobuf, .iov_len = sizeof(iobuf) }; union { char buf[CMSG_SPACE(sizeof(myfds))]; struct cmsghdr align; } u; msg.msg_iov = &io; msg.msg_iovlen = 1; msg.msg_control = u.buf; msg.msg_controllen = sizeof(u.buf); cmsg = CMSG_FIRSTHDR(&msg); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SCM_RIGHTS; cmsg->cmsg_len = CMSG_LEN(sizeof(myfds)); memcpy(CMSG_DATA(cmsg), &myfds, sizeof(myfds)); if (sendmsg (socket, &msg, 0) < 0) { return false; } return true; } receive: static int * read_fds(int sockfd) { struct msghdr msgh; struct iovec iov; int data[6], fd[6]; ssize_t nr; union { char buf[CMSG_SPACE(sizeof(fd))]; struct cmsghdr align; } controlMsg; struct cmsghdr *cmsgp; msgh.msg_name = NULL; msgh.msg_namelen = 0; msgh.msg_iov = &iov; msgh.msg_iovlen = 1; iov.iov_base = &data; iov.iov_len = sizeof(fd); msgh.msg_control = controlMsg.buf; msgh.msg_controllen = sizeof(controlMsg.buf); recvmsg(sockfd, &msgh, 0); cmsgp = CMSG_FIRSTHDR(&msgh); memcpy(&fd, CMSG_DATA(cmsgp), sizeof(int)*6); return fd; } No matter what I send, the array in the receive function is filled with [8,9,10,11,12,13]. What am I doing wrong?
From Cloudflare blog: Technically you do not send “file descriptors”. The “file descriptors” you handle in the code are simply indices into the processes' local file descriptor table, which in turn points into the OS' open file table, that finally points to the vnode representing the file. Thus the “file descriptor” observed by the other process will most likely have a different numeric value, despite pointing to the same file.
72,096,849
72,100,148
How to create a portable C/C++ program on linux using additional libraries?
I need to create a portable linux program that uses a lot of additional libraries defined from yum (CentOS). It is forbidden to install new packages on portable machines. There are no necessary libraries there. How to assemble my program and all packages into a single folder through the gcc compiler? When I move this folder to another machine, my program should start and run successfully. My program is ONLY allowed to use dynamic libraries. Static libraries are STRICTLY prohibited. When trying to replace rpath with /usr/lib64/ with my libraries that are stored in my directory, after transferring to another machine, additional libraries give an error (glibc version conflict).
This sounds like a doomed project, for anything non-trivial. Static libraries are not the issue though. Since they're just collections of .o files, you can unpack them. You can then state that you have just linked object files. Stupid rules give stupid results. I am ignoring software licensing here, though, but that seems implied by the question. You don't need a license for libraries installed via yum, since YOU aren't shipping them. But you absolutely need licenses when you are shipping these libraries in one form or another as part of your product. And given the stupid rules, (L)GPL is likely out of the question, so you will need to obtain commercial licenses for all 7 libraries.
72,096,878
72,097,727
How can i call the parameterized constructor for all objects in my dynamic array of objects on allocation in c++?
When i define dynamic array of objects, i want to choose one parameterized constructor for all objects in my array. without having to write for each object the chosen constructor like this #include <iostream> using namespace std; class foo { public: foo () { cout << "default constructor" << endl; } foo (int x) { cout << "parameterized constructor " << endl; } ~foo () { cout << "destructor" << endl; } }; int main (void) { int size = 3, parameter = 10; foo *array; array = new foo [size] { foo(parameter), foo(parameter), foo(parameter) }; cout << endl; delete [] array; return 0; } output parameterized constructor parameterized constructor parameterized constructor destructor destructor destructor So, as you can see from the above code, I can choose parameterized constructor for each object in my array array = new foo [size] { foo(parameter), foo(parameter), foo(parameter) };. However, if user inputs the size. same trick won't work When I searched for solution, I found that I can do it with copy constructor like this #include <iostream> using namespace std; class foo { public: foo () { cout << "default constructor" << endl; } foo (int x) { cout << "parameterized constructor " << endl; } ~foo () { cout << "destructor" << endl; } }; int main (void) { int size = 3, parameter = 10; foo *array; array = new foo [size]; cout << endl; for (int i = 0; i < size; i++) array[i] = foo(parameter); cout << endl; delete [] array; return 0; } output default constructor default constructor default constructor parameterized constructor destructor parameterized constructor destructor parameterized constructor destructor destructor destructor destructor However, destructors are called for each object, and i don't want this i just want to do it while allocating for the first time Thanks in advance, and I hope that there's a solution.
The simplest solution to this problem would be to use std::vector which handles all those problems internally, e.g.: #include <vector> // skipping class declaration for brevity int main (void) { int size = 3, parameter = 10; std::vector<foo> array; array.reserve(size); cout << endl; for (int i = 0; i < size; i++) array.emplace_back(parameter); cout << endl; return 0; } However, if for some reason you want/need to do this by hand then you should be allocating a "raw buffer" and construct objects inside that buffer with placement new - this will however also require you to manually call the destructors One possible example, doing everything "manually" could look like this int main (void) { int size = 3, parameter = 10; foo *array = reinterpret_cast<foo*>(new char[size * sizeof(foo)]); cout << endl; for (int i = 0; i < size; i++) new (&array[i]) foo(parameter); cout << endl; for (int i = 0; i < size; i++) array[i].~foo(); delete[] reinterpret_cast<char*>(array); return 0; } An arguably cleaner solution is to use std::allocator and std::allocator_traits - this would look like this #include <memory> // skipping class declaration int main (void) { std::allocator<foo> alloc; using alloc_t = std::allocator_traits<decltype(alloc)>; int size = 3, parameter = 10; foo *array; array = alloc_t::allocate(alloc, size); cout << endl; for (int i = 0; i < size; i++) alloc_t::construct(alloc, &array[i], parameter); cout << endl; for (int i = 0; i < size; i++) alloc_t::destroy(alloc, &array[i]); alloc_t::deallocate(alloc, array, size); return 0; }
72,096,928
72,097,166
Is int byte size fixed or it occupy it accordingly in C/C++?
I have seen some program that use int instead of other type like int16_t or uint8_t even though there is no need to use int let me give an example, when you assign 9 to an int, i know that 9 takes only 1 byte to store, so is other 3 bytes free to use or are they occupied? all i'm saying is, does int always takes 4-bytes in memory or it takes byte accordingly and 4-bytes is the max-size i hope you understand what im saying.
The size of all types is constant. The value that you store in an integer has no effect on the size of the type. If you store a positive value smaller than maximum value representable by a single byte, then the more significant bytes (if any) will contain a zero value. The size of int is not necessarily 4 bytes. The byte size of integer types is implementation defined.
72,096,954
72,098,408
Does Eigen have arange function like numpy.arange() in Python
Do you know if Eigen has its own arange function, and if not, why? For now, I have written my own arange function using Eigen::VectorXd::LinSpaced() /* * Return evenly spaced values within a given interval. * Values are generated within the half-open interval [start, stop) * (in other words, the interval including start but excluding stop). */ template <typename Scalar> Eigen::VectorXd arange(const Scalar start, const Scalar stop, const Scalar step) { if(step == 0) throw std::domain_error("Arange's step cannot be 0"); Scalar delta = stop - start; size_t size = ceil(delta / step); return Eigen::VectorXd::LinSpaced(size, start, start+(size-1)*step); }
There is indeed LinSpaced currently available for such an operation, but apparently no direct equivalent of arange in Eigen. There are working notes related to this (eg. range and iota) but so far nothing appear to be included in the code for that. In the new Eigen 3.4 with a recent C++ version, you can use std::iota since Eigen now support STL iterators. Thus, there is no real need for a feature like arange to be added in Eigen (in fact LinSpaced is often good enough for most users).
72,097,177
72,106,908
Getting an unsupported media type error while having a json object posted and content-type set to application/json
I'm doing a small test projet, the goal is to log throught Keycloak API and get my access token. The problem i'm facing is that i got a 415 error "unsupported media type" as the following : HTTP error I've tried content type header as text/plain application/x-www-form-urlencoded application/json Here is my code : void MainWindow::on_realmButton_clicked() { QNetworkRequest req{QUrl(QString("http://localhost:8080/realms/demo/protocol/openid-connect/token"))}; req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); QJsonObject body; body["client_id"] = "demo-client"; body["grant_type"] = "password"; body["client_secret"] = "CLIENT_SECRET"; body["scope"] = "openid"; body["username"] = "user"; body["password"] = "password"; QJsonDocument document(body); QByteArray bytes = document.toJson(); qDebug() << "JSON Object :" << bytes.toStdString().c_str(); netReply = netManager->post(req, bytes); connect(netReply, &QNetworkReply::readyRead, this, &MainWindow::readData); connect(netReply, &QNetworkReply::finished, this, &MainWindow::finishReading); }
Try something like. Edit: add this note for clarity. "The protocol/openid-connect/token endpoint expects form encoded body, not a JSON body." req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); QUrl body; body.addQueryItem("client_id","demo-client"); . . . networkManager->post(req, body.toString(QUrl::FullyEncoded).toUtf8());
72,097,439
72,097,476
c++ converting const char* to char* for long buffer
I have an old function which I can't change the API void TraceMsg(const char* fmt, ...) { if (!m_MessageFunctions[TraceLevel]) return; char msgBuffer[MAX_LOG_MSG]; va_list argList; va_start(argList, fmt); vsnprintf(msgBuffer, MAX_LOG_MSG, fmt, argList); va_end(argList); m_MessageFunctions[TraceLevel](msgBuffer); } MAX_LOG_MSG = 2048 I got into a phase where I would like to allocate more space for the messages for the logger in a dynamic way I have read this article: https://code-examples.net/en/q/4904e5 and changed my code into: void TraceMsg(const char* fmt, ...) { if (!m_MessageFunctions[TraceLevel]) return; va_list argList; va_start(argList, fmt); size_t size = vsnprintf(NULL, 0,fmt, argList); char* msgBuffer = new char[size]; vsnprintf(msgBuffer, size, fmt, argList); va_end(argList); m_MessageFunctions[TraceLevel](msgBuffer); delete[] msgBuffer; } how ever I get wierd characters like 2022-05-03 12:13:20,939 INFO Make graph edge Bayer@LSC_1_2 ->Input@DeMux_LSC§§§§н 2022-05-03 12:13:20,939 INFO Make graph edge Bayer@RGB_IR_2_0 ->0@Mux_X2B_BP§§§§нннннњйн‚€нннннннннннннннннннннннннннннннннннн Can you please help?
The return value of vsnprintf is The number of characters that would have been written if n had been sufficiently large, not counting the terminating null character. So you need to add 1 to this to make room for the null terminator.
72,097,526
72,100,357
How to calculate a polynomial using matrix calculation with Eigen
I want to calculate a polynomial using matrix calculation and not for loops. Theory The equation of a polynomial of degree k: a: Coeficients of the polynomial t: X value v: Y value to calculate We can calutate all Y values for n X values with this matrix calculation: Question I have all coeficients. I have a vector with X values using Eigen::VectorXd::LinSpaced(size, start, stop); How to generate the T matrix with Eigen? Current solution For now, I'm using two for loops: std::vector<double> yVector; Eigen::VectorXd xVector = Eigen::VectorXd::LinSpaced(40, -20, 20); for(const double x : xVector) { double y= 0; for(size_t i = 0; i < coeff.size(); i++) { y+= coeff[i] * pow(x, i); } yVector.push_back(y); }
The usual approach to evaluate polynomials would be Horner's method. This avoids any complex functions (such as pow) , is fast and numerically stable. A version in Eigen could look something like this: /** Coefficients ordered from highest to lowest */ Eigen::VectorXd evaluate_poly( const Eigen::Ref<const Eigen::VectorXd>& xvals, const Eigen::Ref<const Eigen::VectorXd>& coeffs) { auto coeff = std::begin(coeffs); const auto last_coeff = std::end(coeffs); assert(coeff != last_coeff && "Empty set of polynomial coefficients"); Eigen::VectorXd yvals = Eigen::VectorXd::Constant(xvals.size(), *coeff); for(++coeff; coeff != last_coeff; ++coeff) yvals = yvals.array() * xvals.array() + *coeff; return yvals; } Eigen's unsupported Polynomial module implements a "stabilized" version. I wasn't able to find a reference for this. In any case, if we adapt that code to your input pattern, we get this: #include <cmath> // using std::abs, std::pow #include <iterator> // using std::make_reverse_iterator Eigen::VectorXd evaluate_poly( const Eigen::Ref<const Eigen::VectorXd>& xvals, const Eigen::Ref<const Eigen::VectorXd>& coeffs) { assert(coeffs.size() && "Empty set of polynomial coefficients"); return xvals.unaryExpr([&coeffs](double x) noexcept -> double { auto coeff = std::begin(coeffs); const auto last_coeff = std::end(coeffs); double y; if(! (std::abs(x) > 1.) /*NaN or range [-1, 1] */) { // normal Horner method for(y = *(coeff++); coeff != last_coeff; ++coeff) y = y * x + *coeff; return y; } const double inv_x = 1. / x; auto reverse_coeff = std::make_reverse_iterator(last_coeff); const auto last_reverse = std::make_reverse_iterator(coeff); for(y = *(reverse_coeff++); reverse_coeff != last_reverse; ++reverse_coeff) y = y * inv_x + *reverse_coeff; return std::pow(x, coeffs.size() - 1) * y; }); } Wikipedia lists several other methods to evaluate polynomials.
72,098,003
72,098,106
Does operator of `[]` of std::map always put the new item into the first place of iterator?
Hi I've met a problem relating to iterator order of inserted values in std::map by operator []. The code is a github program in line 265: many_async_rules[rstval].insert(sync_level); The definition of the map is std::map<RTLIL::SigSpec, std::set<RTLIL::SyncRule*>> many_async_rules; By testing cases and guessing its meaning, this line should insert the rstval into the first iterator slot of many_async_rules. However, in my machine it actually put the rstval into the last of it. Thus I would like to ask if this is normal in std::map?? The following is some system info of my computer: [shore@shore-82b6 yosys]$ gcc --version gcc (GCC) 11.2.0 Copyright © 2021 Free Software Foundation, Inc. [shore@shore-82b6 yosys]$ cat /etc/lsb-release DISTRIB_ID=ManjaroLinux DISTRIB_RELEASE=21.2.6 DISTRIB_CODENAME=Qonos DISTRIB_DESCRIPTION="Manjaro Linux" Any extra info needed, please leave comment.
Elements of std::map are stored in order of the key established by the Compare predicate that was provided to the map (by default, std::less). If rstval is the least key according to the predicate, then it will be the first element. If rstval is the greatest key according to the predicate, then it will be the last element. Which means that if the key is a pointer, then the order is not sure?? If the key is a pointer, and the predicate is std::less, and if the pointers are to elements of an array, then the order is the same as the order of the pointed elements in that array. But if the pointers are not to elements of an array, then their relative order is unspecified.
72,098,313
72,098,358
Why am I getting an error on the makefile.win? (dev c++ 6.3)
I am using C++, I'm quite new to programming and wanted to try out some things. I have been smooth sailing until I reached multifile programming.. I tried putting all the contents of the 3 files into a single cpp file and it works: #include <iostream> using namespace std; const int numOf_people = 4; struct person { std::string name; } individual[4]; // 4 identities void input_movieName (person individual[], int numOf_people) { for (int i = 0; i < numOf_people; i++) { cout << "Enter individual " << i+1 << " name : "; cin >> individual[i].name; } } int main() { input_movieName (individual, numOf_people); for (int i = 0; i < numOf_people; i++) { cout << "Name of person " << i+1 << " : " << individual[i].name << endl; } } but these would just not work: head.h #ifndef MAIN #define MAIN const int numOf_people = 4; struct person { std::string name; } individual[4]; // 4 identities void input_movieName (person*, int); #endif main.cpp #include <iostream> #include "head.h" using namespace std; int main() { input_movieName (individual, numOf_people); for (int i = 0; i < numOf_people; i++) { cout << "Name of person " << i+1 << " : " << individual[i].name << endl; } } func.cpp #include <iostream> #include "head.h" using namespace std; void input_movieName (person individual[], int numOf_people) { for (int i = 0; i < numOf_people; i++) { cout << "Enter individual " << i+1 << " name : "; cin >> individual[i].name; } } I keep getting an error in the makefile.win pointing this error out: $(BIN): $(OBJ) $(CPP) $(LINKOBJ) -o $(BIN) $(LIBS) the error says "head.h:9: multiple definition of `individual'; head.h:9: first defined here" >I removed the directories but I think you guys get the point
The error is that you define the variable individual in the header file: struct person { std::string name; } individual[4]; That means the variable will defined in each translation unit where the header file was included, and C++ only allows variables (and functions) to be defined once. I suggest you split these into the separate structure definition, and a separate variable declaration: struct person { std::string name; }; extern struct individual[4]; Then in a single source file you define the variable: struct individual[4];
72,098,319
72,098,470
CMake string replace removes semi-colon
I have a template cpp file that will contain several placeholders. Excerpt: // WARNING! this file is autogenerated, do not edit manually QString appName() { return "APP_NAME_VALUE"; } Cmake will read this file in, fill in the placeholders and write it back out to the shadow build directory for compilation set(APP_NAME "real application name") file(READ ${CMAKE_SOURCE_DIR}/templates/app-info.cpp APP_INFO) string(REPLACE "APP_NAME_VALUE" ${APP_NAME} APP_INFO ${APP_INFO}) # other tag replacements file(WRITE "${CMAKE_BINARY_DIR}/src/app-info.cpp" ${APP_INFO}) But every time I run cmake, it seems to strip the semi-colon from the file contents. // WARNING! this file is autogenerated, do not edit manually QString appName() { return "real application name" } Is this expected behaviour? What can I do to counter this?
From https://discourse.cmake.org/t/what-is-the-best-way-to-search-and-replace-strings-in-a-file/1879 In my CMake script, I need to modify other source files by searching and replacing specified strings. In my case, the configure_file 2 command is not a solution because I have no control over the input file. Previously I used the file and string commands in the following way - file(READ header.h FILE_CONTENTS) string(REPLACE "old text" "new text" FILE_CONTENTS ${FILE_CONTENTS}) file(WRITE header.h ${FILE_CONTENTS}) However this technique appears to strip out semi-colons from the input file. Answer: put quotes around ${FILE_CONTENTS} in both commands Explanation: It comes from a CMake’s list syntax, which is ;-separated, the fact that arguments passed to CMake commands are basically mashed together into a list, and that those commands take unbounded number of inputs. So you end up with one longer list. Quoting prevents the semicolons in the expansion from being treated as list-element-separators. Consider: WRITE;header.h;x;y;z vs WRITE;header.h;"x;y;z" So in your case, it will appear as such: set(APP_NAME "real application name") file(READ ${CMAKE_SOURCE_DIR}/templates/app-info.cpp APP_INFO) string(REPLACE "APP_NAME_VALUE" ${APP_NAME} APP_INFO "${APP_INFO}") # other tag replacements file(WRITE "${CMAKE_BINARY_DIR}/src/app-info.cpp" "${APP_INFO}")
72,098,438
72,098,910
How can a reference be present in a signature of a function callable from C code?
I'm a bit confused: I have a C++ API which is supposed to be called from C code and uses __cdecl in the function declarations. There's a vtable with function pointers like this: void (__cdecl *funptr) (const MyStruct& obj); references are a C++ construct, are they not? How can there be a __cdecl with references? And finally: is __cdecl equivalent to wrapping everything in an extern "C" statement? What about references in that case? I'm a bit confused..
These are apples and oranges. __cdecl is a non-standard keyword used to describe one of the more common x86 ABI calling conventions (together with __stdcall) which specifies how variables are passed/stacked between caller and callee. It has nothing to do with C specifically - some historic Microsoft C compiler just used this calling convention, hence the name. Many programming languages can use this calling convention and similarly, C code doesn't have to use it. extern "C" just means that the code should be compiled "like C" by the C++ compiler, disabling various name mangling etc used internally by the C++ compiler. It's not necessarily related to compliant C, but could as well be used when sharing code between two different C++ compilers that may use different name mangling. Neither has anything to do with how references work. In C they will not compile, in C++ they will compile. The code you posted is C++.
72,098,489
72,098,566
Preprocessor directives in C++
I have read several articles about how Preprocessor directives work in C++. It's clear to me that Preprocessor directives are managed by the pre-processor before compilation phase. Let's consider this code: #include <iostream> #ifndef N #define N 10 #endif int main(){ int v[N]; return 0; } The Pre-processor will elaborate the source code by performing text replacement, so this code during compilation phase would be equivalent to: int main(){ int v[10]; return 0; } Now my question is: Can I define a Macro by setting its value equal to a function? It looks a bit weird to me but the answer is yes. #include<iostream> #include <limits> #ifndef INT_MIN #define INT_MIN std::numeric_limits<int>::min() #endif int get_max(){ return 5; } #ifndef INT_MAX #define INT_MAX get_max() #endif int main() { std::cout << INT_MIN << " " << INT_MAX; return 0; } Conceptually I'm not understanding why this code works, the pre-processor have to replace text before compilation phase, so how could a function be invoked (In this case get_max() function) ? Functions invoking is a task managed by compiler? isn't it? How could Pre-processor get access to std::numeric_limits::min()? This value is present inside the "limits" library, but if I understand correctly the libraries's inclusion is done by compiler.
For the sake of illustration I removed the includes from your code: #ifndef INT_MIN #define INT_MIN 0 #endif int get_max(){ return 5; } #ifndef INT_MAX #define INT_MAX get_max() #endif int main() { return INT_MIN + INT_MAX; } Then I invoked gcc with -E to see the output after preprocessing: int get_max(){ return 5; } int main() { return 0 + get_max(); } This is the code that will get compiled. The preprocessor does not call the funciton. It merely replaces INT_MAX with get_max(). Live Demo Can I define a Macro by setting its value equal to a function? Thats not what you do. #define INT_MAX get_max() just tells the preprocessor to replace INT_MAX with get_max(). The preprocessor doen't know nor care if get_max() is a function call or something else.
72,098,883
72,099,197
Can't deserialise from Json using nlohman json using custom class with private members
Really struggling to do this; it should be really simple, but I can't work out how. I've got it working for struct, but not for a class with private members. Following instructions from (https://github.com/nlohmann/json). I'm building this on Visual Studio 2019 and obtained the library from nuget, version 3.10.4. The error is on the get line in main.cpp, where it says "no matching overloaded function call found.". There are two other errors listed; Error (active) E0304 no instance of overloaded function "nlohmann::basic_json<ObjectType, ArrayType, StringType, BooleanType, NumberIntegerType, NumberUnsignedType, NumberFloatType, AllocatorType, JSONSerializer, BinaryType>::get [with ObjectType=std::map, ArrayType=std::vector, StringType=std::string, BooleanType=bool, NumberIntegerType=int64_t, NumberUnsignedType=uint64_t, NumberFloatType=double, AllocatorType=std::allocator, JSONSerializer=nlohmann::adl_serializer, BinaryType=std::vector<uint8_t, std::allocator<uint8_t>>]" matches the argument list Assignment4 C:\Users\allsoppj\source\repos\Assignment4\Assignment4\main.cpp 120 object type is: json Error C2672 'nlohmann::basic_jsonstd::map,std::vector,std::string,bool,int64_t,uint64_t,double,std::allocator,nlohmann::adl_serializer,std::vector<uint8_t,std::allocator<uint8_t>>::get': no matching overloaded function found Assignment4 C:\Users\allsoppj\source\repos\Assignment4\Assignment4\main.cpp 120 Error C2893 Failed to specialize function template 'unknown-type nlohmann::basic_jsonstd::map,std::vector,std::string,bool,int64_t,uint64_t,double,std::allocator,nlohmann::adl_serializer,std::vector<uint8_t,std::allocator<uint8_t>>::get(void) noexcept() const' Assignment4 C:\Users\allsoppj\source\repos\Assignment4\Assignment4\main.cpp 120 Here's my address1.h #include <nlohmann/json.hpp> #include <string> using json = nlohmann::json; class address1 { private: std::string street; int housenumber; int postcode; public: address1(std::string street, int housenumber, int postcode); NLOHMANN_DEFINE_TYPE_INTRUSIVE(address1, street, housenumber, postcode); }; address1.cpp #include "address1.h" address1::address1(std::string street, int housenumber, int postcode) :street(street), housenumber(housenumber), postcode(postcode) {} main.cpp int main(int argc, const char** argv) { address1 p1 = { "home",2,3 }; json j = p1; auto p3 = j.get<address1>(); std::cout << std::setw(2) << j << std::endl; }
The problem is that your address1 type does not have a default constructor. From https://nlohmann.github.io/json/features/arbitrary_types/#basic-usage : When using get<your_type>(), your_type MUST be DefaultConstructible. (There is a way to bypass this requirement described later.) If I add address1() = default; to your example, then it compiles no problem. Ps. The "bypass described later" can be found here: https://nlohmann.github.io/json/features/arbitrary_types/#how-can-i-use-get-for-non-default-constructiblenon-copyable-types
72,099,169
72,099,249
What is lower_bound(B,B+N,goal) - B in C++
When I see some code I found lower_bound function which execute binary search. it is used like following. int pos1 = lower_bound(B, B + N, goal) - B; I understand that lower_bound returns iterators , but what is the role of -B in this sample. I totally confused about this, if someone has opinion will you please let me know Thanks
As mentioned in a comment, it calculates the difference between the iterator returned from lower_bound and B. pos can then be used as index to B: B[pos]. A cleaner way to get the distance between two iterators is using std::distance: auto it = std::lower_bound(....); auto offset = std::distance(B,it); However, there is no reason to switch back and forth between iterators and indices, unless you really need the index. For accessing elements in the container one can simply use the returned iterator: *it == B[pos].
72,099,896
72,099,993
Use of deleted function when using fstream
I'm receiving the message "Use of deleted function" when I combine the use of an ofstream (which I later want to use to record information) and the placement of one class inside another. Here is my minimal example: #include <iostream> #include <unistd.h> #include <fstream> class Tracker { private: std::ofstream tracker_file; public: Tracker(const std::string filename) { tracker_file.open("tracker_file.csv", std::ios_base::app); } }; class Penguin { private: Tracker p_tracker; public: Penguin( Tracker p_tracker ) : p_tracker(p_tracker) {} }; int main() { Tracker penguin_tracker = Tracker("output"); Penguin gentoo(penguin_tracker); return 1; } I don't understand how these are related, but if I remove the intermediate class then it works, and if I remove the ofstream it works.
In this line in the ctor of Penguin: ) : p_tracker(p_tracker) {} You attempt to initalize the Tracker p_tracker data member. Since you pass it an existing Tracker instance, it attempts to use the copy constuctor. But class Tracker does not have a copy constructor. This is the "deleted function" mentioned in the error you got. As @NathanPierson wrote in the comment below, this is because of the deleted copy constructor of the std::ofstream member variable tracker_file (and not because of the converting constructor you defined, as I originally wrote). You could have theoretically solved it by adding a copy ctor to Tracker, something like: Tracker(Tracker const & other) { // ... } However - as mentioned above class Tracker has a std::ofstream member which is non copyable. So the question is what did you mean should happen in this case ? On a side note: using the same name: p_tracker for both the class data member and the parameter passed to the constructor is a bit confusing and not recomended. UPDATE: To answer the question of the OP in the comment below: If class Penguin only needs to keep a refernce to a Tracker instance, you can do the following (added "m_" prefix to members to diffrentiate them from other variables): #include <iostream> #include <fstream> // No change in Tracker: class Tracker { private: std::ofstream m_tracker_file; public: Tracker(const std::string filename) { m_tracker_file.open("tracker_file.csv", std::ios_base::app); } }; // Penguin now holds a reference to Tracker: class Penguin { private: Tracker & m_tracker; public: Penguin( Tracker & tracker ) : m_tracker(tracker) {} }; int main() { Tracker penguin_tracker("output"); Penguin gentoo(penguin_tracker); return 0; } However - this solution requires you to ensure the Tracker penguin_tracker is alive as long as Tracker penguin_tracker is alive (otherwise you will have a dangling reference). In your example it is OK, just mentioned in for the general case. Another side note: main should return 0 if all went well (not 1). See: What should main() return in C and C++?.
72,100,006
72,100,050
why non-movable Object still a copy
Consider the following code, Entity object is non-movable. I know that std::move(Obj) just cast the Obj to a rvalue reference Obj. And I also know that rvalue reference variable is still a lvalue object. But I still confusing why statement auto temp = std::move(a) can call copy constructor, statement a = std::move(b); can call copy assignment operator. Since, std::move(a) is a rvalue reference, why it can still call lvalue constructor. #include <iostream> template<typename T> void my_swap(T& a, T& b) { auto temp = std::move(a); a = std::move(b); b = std::move(temp); } class Entity{ int _id; public: Entity(int id) :_id(id) {std::cout << "construtor\n" << std::endl;} Entity(const Entity& other) { _id = other._id; std::cout << "copy constructor\n" << std::endl; } Entity& operator= (const Entity& other) { if (&other == this) return *this; this->_id = other._id; std::cout << "copy assignment operator\n"; return *this; } }; int main() { Entity e1 = Entity(10); Entity e2 = Entity(20); my_swap(e1,e2); return 0; }
Entity object is non-movable No. Even it doesn't have move constructor/assignment-operator, it has copy constructor/assignment-operator taking lvalue-reference to const. std::move(a) and std::move(b) are rvalue (xvalue) expressions and they could be bound to lvalue-reference to const. You might also check std::is_move_constructible: Types without a move constructor, but with a copy constructor that accepts const T& arguments, satisfy std::is_move_constructible.
72,100,278
72,100,505
Boost Asio J1939 / Can-bus Multithreading
I am implementing a J1939 socket handler on top of Boost::ASIO and canary. My previous application had a socket to listen for devices and the each device discovered would also have a socket. Each socket would use the same interface (In this case can0). From my understanding of SocketCan and J1939 this is the correct approach. As each socket can have filters applied to only get messages from the device its listening for. In my current application I have tested async_read on two sockets with two threads executing io_context.run(). From the logs this seems to be perfectly fine. I am guessing that this is because the kernel checks against the filters on each socket before passing the data on. However with async_write I am a lot more uncertain about thread safety. Given that all the sockets have the same interface (can0) would the sockets need to share a strand? Or is a strand in each socket handler enough? Or is there is there some synchronization in the kernel that means writing to the CAN-bus is thread safe.
Yes there is synchronization in the kernel. The same happens for example with TCP sockets. They also share a single network interface (like eth0). The linux network subsystem makes sure, that different sockets (used by different threads or even processes) can share one interface without colliding. You only need synchronization if you access one socket from several threads simultaneously.
72,100,304
72,100,448
I want to get an LED to blink using the millis() function but my LED stays constantly on, what's wrong with my code?
I know there are other ways but I'd like to know what's wrong with my code and why it doesn't work. Pin 2 seems to constantly stay 'HIGH' despite the 'else if' statement. const int led = 2; int ledState = digitalRead(led); const unsigned long interval = 1000; unsigned long previousTime = 0; void setup() { Serial.begin(9600); pinMode(led,OUTPUT); } void loop() { unsigned long current = millis(); if((current - previousTime >= interval) && (ledState == LOW)) { digitalWrite(led,HIGH); previousTime = current; } else if((current - previousTime >= interval) && (ledState == HIGH)) { digitalWrite(led,LOW); previousTime = current; } }
The first comment said you did not update ledState. This is the problem. I believe a better solution to that is the following: const int led = 2; const unsigned long interval = 1000; unsigned long previousTime = 0; void setup() { Serial.begin(9600); pinMode(led,OUTPUT); } void loop() { unsigned long current = millis(); if(current - previousTime >= interval) { digitalWrite(led,!digitalRead(led)); previousTime = current; } } This reads the current led state and inverts it with !digitalRead(led) without the need of an if () else {}
72,100,341
72,100,607
Is it valid to call operator-- for an iterator when it points to std::begin()
Is it valid to call operator-- on an iterator that already points to the first element of the collection? Does the answer change for different collections (e.g. list vs vector vs set). E.g. see below #include <algorithm> #include <iostream> #include <numeric> #include <string> #include <vector> int main() { std::vector<int> v {1, 2, 4, 8, 16}; auto i=v.begin(); auto j=i; --i; // not sure what's the effect of this v.erase(j); ++i; // also not sure if this is not std::begin() anymore, what's the effect of ++ v.erase(i); // Print vector. std::for_each(v.begin(), v.end(), [](const int n) { std::cout << n << ' '; }); } I suspect it's undefined behaviour but not quite sure. Furthermore, what about removing elements from a std::list like below std::list<int> v = { 1, 2, 3, 4, 5, 6 }; for (auto it = v.begin(); it != v.end(); it++) { v.erase(it--); }
Let's take std::list as an example, because essentially the same reasoning will apply to the other containers. Looking at the member types of std::list, we see that std::list::iterator is a LegacyBidirectionalIterator. Checking the description there, we see the following precondition listed for operator-- to be valid: Preconditions: a is decrementable (there exists such b that a == ++b) This is not the case for an iterator to the first element in a container, and indeed cppreference explicitly calls this out: The begin iterator is not decrementable and the behavior is undefined if --container.begin() is evaluated. Other containers like std::vector use more expansive notions like LegacyRandomAccessIterator, but there's nothing there that changes the behavior of decrementing a begin iterator.
72,100,483
72,193,004
Matrix multiplication of an Eigen Matrix for a subset of columns
What is the fastest method for matrix multiplication of an Eigen::Matrix over a random set of column indices? Eigen::MatrixXd mat = Eigen::MatrixXd::Random(100, 1000); // vector of random indices (linspaced here for brevity) Eigen::VectorXi idx = VectorXi::LinSpaced(8,1000,9); I'm using RcppEigen and R, which is still on a 3.x version of Eigen (no support for () with index arrays), and regardless, my understanding is that the () operator still performs a deep copy. Right now I'm doing a deep copy and generating a new matrix with data only for columns in idx: template <typename T> inline Eigen::Matrix<T, -1, -1> subset_cols(const Eigen::Matrix<T, -1, -1>& x, const std::vector<size_t>& cols) { Eigen::Matrix<T, -1, -1> y(x.rows(), cols.size()); for (size_t i = 0; i < cols.size(); ++i) y.col(i) = x.col(cols[i]); return y; } and then doing matrix multiplication: Eigen::MatrixXd sub_mat = subset_cols(mat, idx); Eigen::MatrixXd a = sub_mat * sub_mat.transpose(); a is what I want. There must be some way to avoid a deep copy and instead use Eigen::Map? Edit 5/9/22: In reply to @Markus, who proposed an approach using raw data access and Eigen::Map. The proposed solution is a bit slower than matrix multiplication of a deep copy. Benchmarking here is done with Rcpp code and R: //[[Rcpp::depends(RcppClock)]] #include <RcppClock.h> //[[Rcpp::export]] void bench(Eigen::MatrixXd mat, Eigen::VectorXi idx){ Rcpp::Clock clock; size_t reps = 100; while(reps-- > 0){ clock.tick("copy"); Eigen::MatrixXd sub_mat = subset_cols(mat, idx); Eigen::MatrixXd a = sub_mat * sub_mat.transpose(); clock.tock("copy"); clock.tick("map"); double *b_raw = new double[mat.rows() * mat.rows()]; Eigen::Map<Eigen::MatrixXd> b(b_raw, mat.rows(), mat.rows()); subset_AAt(b_raw, mat, idx); clock.tock("map"); } clock.stop("clock"); } Here are three runs of a 100,000-column matrix with 100 rows. We are doing matrix multiplication on (1) a subset of 10 columns, (2) a subset of 1000 columns, and (3) a subset of 10000 columns. R: bench( matrix(runif(100000 * 100), 100, 100000), sample(100000, 10) - 1) # Unit: microseconds # ticker mean sd min max neval # copy 31.65 4.376 30.15 69.46 100 # map 113.46 21.355 68.54 166.29 100 bench( matrix(runif(100000 * 100), 100, 100000), sample(100000, 1000) - 1) # Unit: milliseconds # ticker mean sd min max neval # copy 2.361 0.5789 1.972 4.86 100 # map 9.495 2.4201 7.962 19.90 100 bench( matrix(runif(100000 * 100), 100, 100000), sample(100000, 10000) - 1) # Unit: milliseconds # ticker mean sd min max neval # copy 23.04 2.774 20.95 42.4 100 # map 378.14 19.424 351.56 492.0 100 I benchmarked on a few machines with similar results. Above results are from a good HPC node. Edit: 5/10/2022 Here is a code snippet that performs matrix multiplication for a subset of columns as quickly as any code not directly using the Eigen BLAS: template <typename T> Eigen::Matrix<T, -1, -1> subset_AAt(const Eigen::Matrix<T, -1, -1>& A, const Eigen::VectorXi& cols) { const size_t n = A.rows(); Eigen::Matrix<T, -1, -1> AAt(n, n); for (size_t k = 0; k < cols.size(); ++k) { const T* A_data = A.data() + cols(k) * n; for (size_t i = 0; i < n; ++i) { T tmp_i = A_data[i]; for (size_t j = 0; j <= i; ++j) { AAt(i * n + j) += tmp_i * A_data[j]; } } } return AAt; }
Exploiting symmetry You can exploit that the resulting matrix will be symmetric like so: Mat sub_mat = subset_cols(mat, idx); // From your original post Mat a = Mat::Zero(numRows, numRows); a.selfadjointView<Eigen::Lower>().rankUpdate(sub_mat); // (1) a.triangularView<Eigen::Upper>() = a.transpose(); // (2) Line (1) will compute a += sub_mat * sub_mat.transpose() for the lower part only. (2) will then write the lower part to the upper part. Also see the documentation (here and here). Of course, if you can live with only the lower part, step (2) can be omitted. For a 100x100000 matrix mat, I get a speed up of a factor of roughly ~1.1x when taking 10 columns, ~1.5x when taking 100 columns, ~1.7x when taking 1000 columns both on Windows using MSVC and on Linux using clang with full optimizations and AVX. Enabling parallelization Another way to speed up the computation is to enable parallelization by compiling with OpenMP. Eigen takes care of the rest. The code above that exploits the symmetry does not benefit from it, however. But the original code Eigen::MatrixXd sub_mat = subset_cols(mat, idx); Eigen::MatrixXd a = sub_mat * sub_mat.transpose(); does. For a 100x100000 matrix mat, using clang on Linux, running with 4 threads (on 4 real cores) and comparing to a single thread, I get a speed up of a factor of roughly ~1.0x when taking 10 columns, i.e. no speed up at all ~1.8x when taking 100 columns ~2.0x when taking 1000 columns In other words, 4 cores or more outperform the symmetric method shown above except for a very small number of columns. Using only 2 cores was always slower. Note that using SMT hurt the performance in my tests, sometimes notably. Other notes I already wrote this in the comment, but for the sake of completeness: Eigen::Map will not work because the strides are non-equidistant. Using slicing gives me ~10% better performance than your copying method on Linux with clang and gcc, but somewhat worse on MSVC. Also, as you noted, it is not available on the 3.3 branch of Eigen. There is a custom way to mimic it, but it performed always worse in my tests. Also, in my tests, it did not save any memory compared to the copying method. I think it is hard to beat the copying method itself regarding performance because the Eigen matrices are column major by default, meaning that copying a few columns is rather cheap. Moreover, without really knowing details, I suspect that Eigen can then throw the full might of its optimization on the full matrix to compute the product and transpose without having to deal with views or anything like this. This might give Eigen more chances for vectorization or cache locality. Apart from this, not only optimizations should be turned on but also the highest possible instruction set should be used. Turning on AVX in my tests improved the performance by ~1.5x. Unfortunately, I cannot test AVX512.
72,100,838
72,100,984
Is there any standard functionality for creating a flattened view of a map with a container as the mapped_type?
Is there any standard functionality to create a range/view over all pairs? The following code illustrates the view I am looking to create: std::unordered_map<std::string, std::vector<int>> m{{"Foo", {1,2}}, {"Hello", {4,5}}}; auto view = ???; std::vector<std::pair<std::string, int>> v{view.begin(), view.end()}; std::vector<std::pair<std::string, int>> out1{{"Foo", 1}, {"Foo", 2}, {"Hello", 4}, {"Hello", 5}}; std::vector<std::pair<std::string, int>> out2{{"Hello", 4}, {"Hello", 5}, {"Foo", 1}, {"Foo", 2}}; assert(v == out1 || v == out2); Note: It is trivial to write a nested for loop to iterate over this structure.
Yes, combine std::ranges::views::join with std::ranges::views::transform and some lambdas. using namespace std::ranges::views; auto to_pairs = [](auto & pair){ auto to_pair = [&key=pair.first](auto & value){ return std::pair{ key, value }; }; return pair.second | transform(to_pair); }; auto view = m | transform(to_pairs) | join | common;
72,101,010
72,101,725
replacing macro with a function causes "signed/unsigned mismatch" warning
For this snippet const std::vector<int> v; if (v.size() != 1) {} // could call operator!=() the code complies cleanly even at high warnings levels (all warnings enabled in Visual Studio 2022). However, if I pass the arguments to a function const auto f = [](auto&& lhs, auto&& rhs) { if (lhs != rhs) {}}; f(v.size(), 1); the compiler generates a '!=': signed/unsigned mismatch warning. How can I make the function behave the same way as the "inline" code, i.e., no warning? Keep in mind that the "real code" is something like #define f(lhs, rhs) if (lhs != rhs) {} I'd like to "do the 'right thing'" and replace the macro with a function temmplate<typename TLhs, typename TRhs> inline void f(TLhs&& lhs, TRhs&& rhs) { if (lhs != rhs) {} }
Move the problem out of your code by calling std::cmp_not_equal const auto f = [](auto&& lhs, auto&& rhs) { if (std::cmp_not_equal(lhs, rhs)) { blah blah } }; This family of functions, added in C++20, is defined in a way that properly compares integer arguments even in the presence of a signed/unsigned mismatch. Now the Standard library author is responsible for writing "all that template gunk" and all you need to do extra is #include <utility> For the specific case of assertions, you need a macro anyway to capture information. #define ASSERT_EQ(actual, expected) do { \ if (lhs == rhs) break; \ log_assertion_failure(__FILE__, __LINE__, #actual, actual, expected); \ } while(0)
72,101,735
72,101,864
Array of different data types
I need to store an array of newspapers and booklets And then in a loop, print out how much paper it takes to print each product, but when I call the price calculation function, the function is called from the main class and not from the child ones, how can I call the function from the child classes in an array with different objects? #include <iostream> using namespace std; class PrintedProduct { public: string name; int pages; int paperCost() { return 1; } PrintedProduct() {} PrintedProduct(string name, int pages) { this->name = name; this->pages = pages; } }; class NewsPaper : public PrintedProduct { public: int pageSize; int quantity; int period; NewsPaper(string name, int pages, int pageSize, int quantity, int period) : PrintedProduct(name, pages) { this->pageSize = pageSize; this->quantity = quantity; this->period = period; } int paperCost() { return pages * pageSize * quantity * period; } }; class Booklet : public PrintedProduct { public: int pageSize; int quantity; Booklet(string name, int pages, int pageSize, int quantity) : PrintedProduct(name, pages) { this->pageSize = pageSize; this->quantity = quantity; } int paperCost() { return pages * pageSize * quantity; } }; void print(PrintedProduct a) { cout << a.paperCost() << endl; }; int main() { // Write C++ code here size_t size; cout << "Please, enter a size of the array: " << endl; cin >> size; PrintedProduct *array = new PrintedProduct[size]; cout << "Please, enter " << size << " Printed products: "; for (size_t i = 0; i < size; i++) { cout << "Please enter: 1. Newspaper or 2. Booklet"; int type; cin >> type; if (type == 1) { cout << "Enter name:" << endl; string name; cin >> name; cout << "Enter page count" << endl; int pages; cin >> pages; cout << "Enter page size " << endl; int pageSize; cin >> pageSize; cout << "Enter quantity" << endl; int quantity; cin >> quantity; cout << "Enter period" << endl; int period; cin >> period; array[i] = NewsPaper(name, pages, pageSize, quantity, period); } else { cout << "Enter name:"; string name; cin >> name; cout << "Enter page count"; int pages; cin >> pages; cout << "Enter page size"; int pageSize; cin >> pageSize; cout << "Enter quantity"; int quantity; cin >> quantity; array[i] = Booklet(name, pages, pageSize, quantity); } } for (size_t j = 0; j < size; j++) { print(array[j]); } delete[] array; std::system("PAUSE"); return EXIT_SUCCESS; }
I need to store an array of newspapers and booklets This isn't possible. Arrays can only contain objects of one type. In case of new PrintedProduct[size] that array contains objects of type PrintedProduct. The elements of the array are not instances of classes derived from PrintedProduct. The solution to this is to use indirection. You can create an array of pointers to PrintedProduct. Those pointers may point to base sub object of derived classes. In following example, I will be using std::vector and std::unique_ptr in order to avoid owning bare pointers: std::vector<std::unique_ptr<PrintedProduct>> array(size); ... array[i] = std::make_unique<NewsPaper>( name, pages, pageSize, quantity, period); how can I call the function from the child classes You can call a member function from a derived class by overriding a virtual function. Example: class PrintedProduct { public: virtual int paperCost() = 0; // ... class NewsPaper : public PrintedProduct { public: int paperCost() override { return pages * pageSize * quantity * period; } // ... a.paperCost(); // virtual dispatch
72,101,801
72,102,272
'Clang-Tidy: Do not implicitly decay an array into a pointer' when using std::forward and const char*
I do not understand why Clang-Tidy produces the error Clang-Tidy: Do not implicitly decay an array into a pointer in the following example: struct Foo { explicit Foo(std::string _identifier) : identifier(std::move(_identifier)) {} std::string identifier; }; struct Bar { template<typename... Ts> explicit Bar(Ts &&...args) : foo(std::forward<Ts>(args)...) {} // <-- Error Foo foo; }; Bar bar("hello world"); From the error I understand that "hello world" being an array of type const char[11] (or similar) is decayed to type const char* somewhere during std::forward. But why and how can I fix this error? std::make_shared<Foo>("hello world") is very similar regarding usage of std::forward and does work.
This looks like a bogus diagnostic. I would disable it globally, since this usecase is so common.
72,101,936
72,104,249
QImage 16 bit grayscale with QQuickPaintedItem
I have unsigned 16 bit image data that I displayed by subclassing QQuickPaintedItem in Qt 5.12.3. I used QImage with Format_RGB32 and scaled the data from [0, 16383] to [0, 255] and set that as the color value for all three R,G,B. Now, I am using Qt 5.15.2 which has a QImage FORMAT_GrayScale16 that I'd like to use but for some reason the image is displayed incorrectly. The code I used to convert my unsigned 16 bit image data to QImage for both formats is shown below. The QQuickPaintedItem is a basic subclassing with drawImage(window(), my_qimage); that I pass the QImage as returned from the code below. Why is the new format not displaying correctly? Format_RGB32 method QImage image(image_dim, QImage::Format_RGB32); unsigned int pixel = 0; for (uint16_t row = 0; row < nrow; row++) { uint *scanLine = reinterpret_cast<uint *>(image.scanLine(row)); for (uint16_t col = 0; col < ncols; col++) { uint16_t value = xray_image.data()[pixel++]; // Get each pixel unsigned short color_value = uint16_t((float(value) / 16383) * 255.0f); // scale [0, 255] *scanLine++ = qRgb(int(color_value), int(color_value), int(color_value)); } } return image; Format_Grayscale16 method QImage image(image_dim, QImage::Format_Grayscale16); unsigned int pixel = 0; for (uint16_t row = 0; row < nrow; row++) { // **EDIT WRONG:** uint *scanLine = reinterpret_cast<uint *>(image.scanLine(row)); uint16_t *scanLine = reinterpret_cast<uint16_t *>(image.scanLine(row)); for (uint16_t col = 0; col < ncols; col++) { *scanLine++ = xray_image.data()[pixel++]; // Get each pixel } } return image;
This worked for me (below is just fragments): class Widget : public QWidget { private: QImage m_image; QImage m_newImage; QGraphicsScene *m_scene; QPixmap m_pixmap; }; ... m_image.load("your/file/path/here"); m_newImage = m_image.convertToFormat(QImage::Format_Grayscale8); m_pixmap.convertFromImage(m_newImage); m_scene = new QGraphicsScene(this); m_scene->addPixmap(m_pixmap); m_scene->setSceneRect(m_pixmap.rect()); ui->graphicsView->setScene(m_scene); Based on your OP, you probably want to render it differently. graphicsView is just a QGraphicsView defined in design mode.
72,101,951
72,103,495
Win32 Get unscaled Virtual Desktop size in C++
Working on a C++ application, trying to map the mouse from the coordinates to the full screen windows. Getting the mouse coordinates with GetPhysicalCursorPos(&mouse_point); which returns the coordinates relative to the origin 0,0. This is causing issues because the mouse is going "out of bounds" of the monitors because windows is scaling them down in size. E.g. it returns {3839, 1079} when it's at the bottom right corner, but Windows computes the total desktop size as 3200x1080. (this example two 1080p monitors, side by side, left has 100% scaling, right has 150% scaling) Retrieving the virtual desktop size with: unsigned int vScreenWidth = GetSystemMetrics(SM_CXVIRTUALSCREEN); unsigned int vScreenHeight = GetSystemMetrics(SM_CYVIRTUALSCREEN); But this is returning a desktop where the monitors with a higher DPI are smaller so for a dual 1080p monitor config of 3840x1080, it returns 3200x1080 (configuration above). I've tried using GetSystemMetricsForDpi with 96 DPI (100%) but it returns the same as above: unsigned int vScreenWidth = GetSystemMetricsForDpi(SM_CXVIRTUALSCREEN, 96 /* 100% scaling*/); unsigned int vScreenHeight = GetSystemMetricsForDpi(SM_CYVIRTUALSCREEN, 96 /* 100% scaling*/); The above also returns 3200x1080 in my mixed scaling example above, despite explicitly telling it to force use 100% scaling. Is there any other way to get the un-scaled virtual desktop size? Note the application is NOT DPI aware.
Thanks to @RaymondChen I was able to fix it by calling SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); prior to GetSystemMetricsForDpi. It now returns the full virtual desktop size.
72,101,958
72,102,091
Relationships between VS ans MSVC version
I can't make up a puzzle. I meet names like Visual C++15 (here for example: https://www.sfml-dev.org/download/sfml/2.5.1/). But other sources say that the last version to the moment is 14.31 (wikipedia stays with them: https://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B). It's also gets challenging for me at the moment to check out the version myself. So there are three questions: What is Visual C++15 (is it compiler version or something like language dialectic specification) and if it's not a compiler version, so what is it? Is there any relationship between VS version and version (or a model) of it's built-in C++ compiler? Which version of VS should I use to successfully use SFML? Thanks!
The Visual C++15, that you mention here, is in fact Visual Studio version 15(aka Visual Studio 2017). It isn't a compiler version but in fact a version of the IDE. There is no relation with VS versions directly with C++ standards. But it's more like, some versions of C++ can only be supported on the latest VS versions. for e.g.. C++20 is only supported on Visual studio 2022. C++11/C++14/C++17 is supported in Visual studio 2019 and higher. For SMFL, it just says any C++ compiler but I would honestly suggest Visual Studio 2017 or higher.
72,102,506
72,103,317
Dynamically allocate ragged matrix
I'm trying to make a generic function which will dynamically allocate 2D structure. Number of elements in every row doesn't have to be same for all rows. Structure is represented as a container type, whose elements are again of a container type (for example a set of lists). The type of elements of that inner container can also be arbitrary. Containers only support the begin, end, and size functions. Iterator operations must be supported for all iterator types. The function should first dynamically allocate the space for storing the 2D structure by the continuous allocation procedure, and then rewrite the elements of the structure it has accepted into the dynamic structure. The function returns a double pointer through which the elements of this structure can be accessed. #include <iostream> #include <set> #include <list> #include <vector> template < typename tip > auto Make2DStructure(tip mat) { using tip_objekta = typename std::decay < decltype(mat[0][0]) > ::type; tip_objekta ** dynamic_mat = nullptr; int rows = 0, total = 0; for (auto i: mat) { rows++; for (auto j: i) total++; } int columns[rows]; int k = 0; for (auto i: mat) { int num_of_colums = 0; for (auto j: i) num_of_colums++; columns[k] = num_of_colums; k++; } try { dynamic_mat = new tip_objekta * [rows]; dynamic_mat[0] = new tip_objekta[total]; for (int i = 1; i < rows; i++) dynamic_mat[i] = dynamic_mat[i - 1] + columns[i]; for (int i = 0; i < rows; i++) for (int j = 0; j < columns[i]; j++) dynamic_mat[i][j] = mat[i][j]; } catch (...) { delete[] dynamic_mat[0]; delete[] dynamic_mat; throw std::bad_alloc(); } return dynamic_mat; } int main() { std::vector<std::vector<int>>mat{ {1,2}, {3,4,5,6}, {7,8,9} }; int columns[3]={2,4,3}; try { int ** dynamic_mat = Make2DStructure(mat); for (int i = 0; i < 3; i++) { for (int j = 0; j < columns[i]; j++) std::cout << dynamic_mat[i][j] << " "; std::cout << std::endl; } delete[] dynamic_mat[0]; delete[] dynamic_mat; } catch (...) { std::cout << "Problems with memory"; } return 0; } How could I modify this to work without indexing inside Make2DStrucure()? Also, if I used std::set<std::list<int>> instead of std::vector<std::vector<int>> in main function I would have deduction problems. How could I modify this to work for different outside and inside container?
Here's one way to accomplish what you want: #include <iterator> #include <type_traits> template <typename tip> auto Make2DStructure(tip&& mat) { // create an alias for the value type: using value_type = std::decay_t<decltype(*std::begin(*std::begin(mat)))>; // allocate memory for the return value, the pointer-pointer: value_type** rv = new value_type*[mat.size()]; // C++17: std::size(mat) // Calculate the number of values we need to allocate space for: size_t values = 0; for(auto& inner: mat) values += inner.size(); // C++17: std::size(inner) // allocate the space for the values: value_type* data = new value_type[values]; // loop over the outer and inner container and keep the index running: size_t idx = 0; for(auto& inner : mat) { // assign the outer pointer into the flat data block: rv[idx++] = data; for(auto& val : inner) { // assign values in the data block: *data++ = val; } } return rv; } With the use of std::size where indicated, this would work with plain arrays too, not only the container classes.
72,102,530
72,102,597
Can the compiler generates a default copy constructor that takes reference to different class type?
I have this example struct B { B(); }; struct D : B { }; D d{ B() }; // what happens here? or why it's well-formed This is an aggregate initialization, but I can't understand how d is constructed? Does the compiler generates implicitly a copy constructor with this signature D::D(const D&) or D::D(const B&) or what? It's clear that the compiler does not generate D::D(const D&) because const D& = B() is ill-formed. So this means it generates a copy constructor D::D(const B&)? Now what would happen if I inherits constructors from B: struct B { B(); }; struct D : B { using B::B; }; D d{ B() }; // why it's ill-formed? One said to me that the default copy constructor of B which is B::B(const B&) is inherited into D but it's excluded from the set of candidates, that's why it's ill-formed. Is that true?
Can the compiler generates a default copy constructor that takes reference to different class type? By definition, no. A constructor that accepts an object of another type is not a copy constructor. It would be a converting constructor. No such converting constructor is implicitly generated. This is an aggregate initialization, but I can't understand how d is constructed? No constructor of the enclosing class is called in aggregate initialisation. The sub objects are initialised directly. D is an aggregate with a base class of type B. Aggregate initialisation is used to initialise this base sub object. It's clear that the compiler does not generate D::D(const D&) because const D& = B() is ill-formed. Former cannot be deduced from the latter. In fact, there is a (trivial) D::D(const D&) which you can prove by attempting copy initialisation: D d1{}; D d2(d1); // works That said, a trivial constructor is a concept for the abstract machine, and the compiler doesn't have to generate anything in practice. Now what would happen if I inherits constructors from B struct D : B { using B::B; }; D d{ B() }; // why it's ill-formed? Having inherited constructors disqualifies the class from being an aggregate and hence aggregate initialisation does not apply. List initialisation will attempt to call a constructor, but no converting constructor exists.
72,103,012
72,103,152
Is it safe to pass a uint64_t containing a 32-bit value to an external function whose parameter is actually a uint32_t?
I'm working on a cross-platform program that calls a function from a dynamic library with C linkage. I need to support multiple versions of this dynamic library, but between two of the versions I need to support, there is a function parameter that has changed from uint32_t to uint64_t. If I pass this function a uint64_t that contains value which is still representable as a uint32_t, is that safe to do even when the function's parameter is actually a uint32_t? Put more specifically: If the source of the function as compiled into the dynamic library is: extern "C" void foo(uint32_t param) { ... } Is it safe for me to use the function like so: extern "C" void foo(uint64_t); uint32_t value32 = 10; // Ensure value can be represented by uint32_t uint64_t value64 = value32; foo(value64); If yes, is it safe to do this across different platforms? This program of mine supports 32-bit and 64-bit Windows (compiled as x86 for both), x86_64 macOS, arm64 macOS, x86 Linux, and x86_64 Linux.
No, this is illegal. C++20 [basic.link] p11: After all adjustments of types (during which typedefs (9.2.3) are replaced by their definitions), the types specified by all declarations referring to a given variable or function shall be identical. Moreover, it will actually fail on 32-bit x86 systems using the usual stack-based calling conventions. The function defined with uint32_t will be looking for one dword on the stack, but two will have been pushed. Any arguments above it will then be in the wrong place. It's even worse with the stdcall convention, in which the called function pops its own arguments; it will pop the wrong amount, unbalance the stack, and cause all sorts of mayhem after returning.
72,103,570
72,105,010
SIMD - how to add corresponding values from 2 vectors of different element widths (char or uint8_t adding to int)
Please tell me how can add values from a SIMD vector of the same type, but the values themselves, which are occupied by a different number of bytes in these SIMD vectors. Here's an example: int main() { //-------------------------------------------------------------- int my_int_sequence[16] = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 }; __m128i my_int_sequence_m128i_1 = _mm_loadu_si128((__m128i*) & my_int_sequence[0]); __m128i my_int_sequence_m128i_2 = _mm_loadu_si128((__m128i*) & my_int_sequence[4]); __m128i my_int_sequence_m128i_3 = _mm_loadu_si128((__m128i*) & my_int_sequence[8]); __m128i my_int_sequence_m128i_4 = _mm_loadu_si128((__m128i*) & my_int_sequence[12]); //-------------------------------------------------------------- //----------------------------------------------------------------------- char my_char_mask[16] = { 1,0,1,1,0,1,0,1,1,1,0,1,0,1,0,1 }; __m128i my_char_mask_m128i = _mm_loadu_si128((__m128i*) &my_char_mask[0]); //----------------------------------------------------------------------- } That is, I have an array of int values ​​in the my_int_sequence array - and since all 16 int values ​​will not fit in one __m128i vector, I load these values ​​4 values ​​into the 4th __m128i vectors. I also have an array of 16 bytes, which I also loaded into the my_char_mask_my_m128i vector. And now I want to add to each 4 byte value of the my_int_sequence_m128i_x vectors, as if the corresponding one-byte value from the my_char_mask_my_m128i vector. The problem is obvious that I need to add up, as it were, different dimensions. Is it possible? Perhaps I need each byte of the vector my_char_mask_my_m128i - how to transform it into 4 bytes?
Perhaps I need each byte of the vector my_char_mask_my_m128i - how to transform it into 4 bytes? You're looking for the SSE4.1 intrinsic _mm_cvtepi8_epi32(), which takes the first 4 (signed) 8-bit integers in the SSE vector and sign-extends them into 32-bit integers. Combine that with some shifting to move the next 4 into place for the next extension, and you get something like: #include <iostream> #include <cstdint> #include <emmintrin.h> #include <smmintrin.h> void print_int4(__m128i vec) { alignas(16) std::int32_t ints[4]; _mm_store_si128(reinterpret_cast<__m128i*>(ints), vec); std::cout << '[' << ints[0] << ", " << ints[1] << ", " << ints[2] << ", " << ints[3] << ']'; } int main(void) { alignas(16) std::int32_t my_int_sequence[16] = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 }; alignas(16) std::int8_t my_char_mask[16] = { 1,0,1,1,0,1,0,1,1,1,0,1,0,1,0,1 }; __m128i char_mask = _mm_load_si128(reinterpret_cast<__m128i*>(my_char_mask)); // Loop through the 32-bit int array 4 at a time for (int n = 0; n < 16; n += 4) { // Load the next 4 ints __m128i vec = _mm_load_si128(reinterpret_cast<__m128i*>(my_int_sequence + n)); // Convert the next 4 chars to ints __m128i chars_to_add = _mm_cvtepi8_epi32(char_mask); // Shift out those 4 chars char_mask = _mm_srli_si128(char_mask, 4); // And add together __m128i sum = _mm_add_epi32(vec, chars_to_add); print_int4(vec); std::cout << " + "; print_int4(chars_to_add); std::cout << " = "; print_int4(sum); std::cout << '\n'; } } Example (Note that you usually have to tell your compiler to generate SSE 4.1 instructions - with g++ and clang++ use the appropriate -march=XXXX option or -msse4.1): $ g++ -O -Wall -Wextra -std=gnu++11 -msse4.1 demo.cc $ ./a.out [0, 1, 2, 3] + [1, 0, 1, 1] = [1, 1, 3, 4] [4, 5, 6, 7] + [0, 1, 0, 1] = [4, 6, 6, 8] [8, 9, 10, 11] + [1, 1, 0, 1] = [9, 10, 10, 12] [12, 13, 14, 15] + [0, 1, 0, 1] = [12, 14, 14, 16] Alternative version suggested by Peter Cordes if your compiler is new enough to have _mm_loadu_si32(): // Loop through the 32-bit int array 4 at a time for (int n = 0; n < 16; n += 4) { // Load the next 4 ints __m128i vec = _mm_load_si128(reinterpret_cast<__m128i*>(my_int_sequence + n)); // Load the next 4 chars __m128i char_mask = _mm_loadu_si32(my_char_mask + n); // Convert them to ints __m128i chars_to_add = _mm_cvtepi8_epi32(char_mask); // And add together __m128i sum = _mm_add_epi32(vec, chars_to_add); // Do more stuff }
72,103,700
72,103,827
enable_if for class template specialization with argument other than void
I know that a C++ compiler picks a template specialization in preference to the primary template: template<class T, class Enable = void> class A {}; // primary template template<class T> class A<T, std::enable_if_t<std::is_floating_point_v<T>, void>> { }; // specialization for floating point types However, I don't understand why the selection fails when a type other than void is used as argument to enable_if: template<class T> class A<T, std::enable_if_t<std::is_floating_point_v<T>, int>> { }; // specialization for floating point types The compiler would surely "see" class A<T, int>. So it certainly can't be SFINAE, nevertheless the primary template is preferred to the specialization. This question arises from a context where a custom type detection machinery could be used instead of enable_if, e.g. an SFINAE friendly type extractor like common_type.
Specializations are irrelevant until the compiler knows which types it is going to use for the primary template. When you write A<double>, then the compiler looks only at the primary template and sees that you actually mean A<double,void>. And only then it is looking for specializations. Now, when your specialization is for A<double,int>, then it is not suitable because you asked for A<double,void>.
72,103,800
72,108,937
Lifetime of std::initializer_list when used recursively
I am trying to use std::initializer_list in order to define and output recursive data-structures. In the example below I am dealing with a list where each element can either be an integer or another instance of this same type of list. I do this with an intermediate variant type which can either be an initializer list or an integer. What is unclear to me is whether the lifetime of the std::initializer_list will be long enough to support this use-case or if I will be experiencing the possibility of inconsistent memory access. The code runs fine, but I worry that this is not guaranteed. My hope is that the std::initializer_list and any intermediate, temporary std::initializer_list objects used to create the top-most list are only cleaned up after the top-level expression is complete. struct wrapped { bool has_list; int n = 0; std::initializer_list<wrapped> lst; wrapped(int n_) : has_list(false), n(n_) {} wrapped(std::initializer_list<wrapped> lst_) : has_list(true), lst(lst_) {} void output() const { if (!has_list) { std::cout << n << ' '; } else { std::cout << "[ "; for (auto&& x : lst) x.output(); std::cout << "] "; } } }; void call_it(wrapped w) { w.output(); std::cout << std::endl; } void call_it() { call_it({1}); // [ 1 ] call_it({1,2, {3,4}, 5}); // [ 1 2 [ 3 4 ] 5 ] call_it({1,{{{{2}}}}}); // [ 1 [ [ [ [ 2 ] ] ] ] ] } Is this safe, or undefined behavior?
As far as I can tell the program has undefined behavior. The member declaration std::initializer_list<wrapped> lst; requires the type to be complete and hence will implicitly instantiate std::initializer_list<wrapped>. At this point wrapped is an incomplete type. According to [res.on.functions]/2.5, if no specific exception is stated, instantiating a standard library template with an incomplete type as template argument is undefined. I don't see any such exception in [support.initlist]. See also active LWG issue 2493.
72,104,337
72,104,542
signal SIGSEGV, Segmentation fault. __strlen_avx2 () at ../sysdeps/x86_64/multiarch/strlen-avx2.S:65
I have converted my old code: #define MAX_LOG_MSG 2048 in the *.h file typedef void (*LogMessageFunction)(char *); in the *.cpp file static LogMessageFunction m_MessageFunctions[LastLogCount] = {NULL}; void DebugMsg(const char* fmt, ...) { if (!m_MessageFunctions[DebugLevel]) return; char msgBuffer[MAX_LOG_MSG]; va_list argList; va_start(argList, fmt); vsnprintf(msgBuffer, MAX_LOG_MSG, fmt, argList); va_end(argList); m_MessageFunctions[DebugLevel](msgBuffer); } into a dynamic allocated char* void DebugMsg(const char* fmt, ...) { if (!m_MessageFunctions[DebugLevel]) return; va_list argList; va_start(argList, fmt); size_t size = vsnprintf(NULL, 0, fmt, argList) + 1; va_end(argList); char* msgBuffer = new char[size]; va_start(argList, fmt); vsnprintf(msgBuffer, size, fmt, argList); va_end(argList); m_MessageFunctions[DebugLevel](msgBuffer); delete[] msgBuffer; } on windows everything works great now. Thread 1 "ATETests" received signal SIGSEGV, Segmentation fault. __strlen_avx2 () at ../sysdeps/x86_64/multiarch/strlen-avx2.S:65 65 ../sysdeps/x86_64/multiarch/strlen-avx2.S: No such file or directory. as far as I can see this has something to do with the size of the buffer or the string? Can you help?
I'd make a variadic template out of it instead and use a std::unique_ptr<char[]> for the memory allocation: #include <memory> template<class... Args> void DebugMsg(const char* fmt, Args&&... args) { if (!m_MessageFunctions[DebugLevel]) return; int size = std::snprintf(nullptr, 0, fmt, args...) + 1; if (size < 1) return; // check for error auto msgBuffer = std::make_unique<char[]>(size); size = std::snprintf(msgBuffer.get(), size, fmt, args...); if (size < 0) return; // probably unnecessary m_MessageFunctions[DebugLevel](msgBuffer.get()); }
72,104,603
72,104,710
Assigning function to function pointer with template parameter
So I have these two functions: bool intComp(int a, int b) { return a > b; } bool stringComp(std::string a, std::string b) { return strcmp(a.c_str(), b.c_str()) > 0; } And in my sort function I want to assign either the stringComp or intComp function: template<typename T> void sort(std::vector<T>& vector) { bool (*compare)(T a, T b); if (typeid(T) == typeid(int)) { compare = &intComp; } else if (typeid(T) == typeid(std::string)) { compare = &stringComp; } ... } The assignment and sorting works fine when I remove the else if block with compare = &stringComp. But as soon as I try to assign functions with types other than int (for instance string) I get the following compiler error: '=': cannot convert from 'bool (__cdecl *)(std::string,std::string)' to 'bool (__cdecl *)(T,T)' What am I doing wrong? And why does the code work with int but not with other types? Do templates maybe work with integers under the hood similar to enums and that's why I can assign the intComp function without issues?
The problem is that all branches of a normal if need to be valid at compile time, but only one of the branches in yours is. If T is int, then compare = &stringComp is invalid. If T is std::string, then compare = &intComp is invalid. Instead, you need if constexpr, which was introduced in C++17 and does its comparison at compile time. It discards branches that it doesn't take as long as it's dependent on a template parameter, so it doesn't matter if they don't make sense for that type. For example: template <typename T> void sort(std::vector<T>& vector) { bool (*compare)(T a, T b); if constexpr (std::is_same_v<T, int>) { compare = &intComp; } else if constexpr (std::is_same_v<T, std::string>) { compare = &stringComp; } else { // Error } // ... }
72,104,705
72,104,751
I can't use accents with string in C++
I can set the accents with SetConsoleOutputCP(1252) or locale::global(locale"FR-fr"), but I can't use it with strings. Seems like it's one or the other. I can output text with accents, or I can output the string with accents, not both. Any ideas? The code below can be used to reproduce the problem. Simply add locale::global(locale"FR-fr") or SetConsoleOutputCP(1252): #include <iostream> #include <string> #include <windows.h> using namespace std; int main() { string mot; cout << "Inscrivez un mot avec des accents (é ou è): "; cin >> mot; cout << mot; }
I suggest that you set both the input and output code pages: SetConsoleCP(1252); // input SetConsoleOutputCP(1252); // output
72,104,836
72,105,217
Can WebView2 Navigate to an html resource embedded in the application?
I've been converting our application from using CHtmlView over to WebView2. Our application has a web-based start page that generally gets all its information from our servers, but we have local resources setup in the event of our servers being down or the client having internet trouble. Using CHtmlView we were able to navigate to an html page in the embedded resources like so: HINSTANCE hInstance = AfxGetResourceHandle(); ASSERT(hInstance != NULL); TCHAR lpszModule[_MAX_PATH]; if (GetModuleFileName(hInstance, lpszModule, _MAX_PATH)) { CString strResourceURL; strResourceURL.Format(_T("res://%s/%d"), lpszModule, IDR_STARTPAGE); Navigate2(strResourceURL, NULL,NULL); } This would load the page and the images that where also embedded as resources. WebView2 Navigate doesn't seem to support this same method since passing the same string only gives a blank page. I was able to load the page into a CString via LoadResource and then pass that on to NavigateToString. That loads the page fine, but none of the images show up. Is there any way to get to the embedded images with WebView2?
WebView2 does not support the res URI scheme. For serving app content that is not on the disk, you can use: NavigateToString: You can provide app created HTML to render, however there is no way to additionally reference subresources that are dynamically app created. WebResourceRequested: You can use the CoreWebView2.WebResourceRequested event to intercept any resource requests that you want after setting the filter via AddWebResourceRequestedFilter. In this event you can intercept any resource request and decide to supply your own response stream rather than allowing the request to actually go to the network. You could use these both together, using NavigateToString to supply the initial HTML to render, refer to subresources on a particular domain like app.example in that HTML, and then in WebResourceRequested intercept all requests to app.example and provide your own stream.
72,105,092
72,105,136
Virtual methods and overriding
What am I doing? I'm trying to do some basic inheritance for the game I'm working on. The idea is to have a base Entity class that the Player will inherit from. The Entity class has a virtual update or think method that each child will override to fit it's needs. This is how the engine handles the update loop: void Engine::update() { for (Entity entity : entities) { entity.update(deltaTime); } } The code: Entity.hpp #pragma once #include "Position.hpp" #include "AssetManager.hpp" #include "Logger.hpp" #define SPATIAL 1 #define VISUAL 1 << 1 class Entity { public: Entity(Position *position, const char *visualPath); int flags; const char *visualPath; Position position; virtual void update(float deltaTime); }; Entity.cpp #include "Entity.hpp" Entity::Entity(Position *position, const char *visualPath) { flags = 0; if (position) { flags |= SPATIAL; this->position = *position; } if (visualPath) { flags |= VISUAL; this->visualPath = visualPath; } } void Entity::update(float deltaTime){ Logger::log("No update method"); }; Player.hpp #pragma once #include "../Entity.hpp" #include "../Logger.hpp" class Player : public Entity { public: Player(); void update(float deltaTime) override; }; Player.cpp #include "Player.hpp" Player::Player() : Entity(new Position(0, 0), "assets/player.png") {} void Player::update(float deltaTime) { this->position.x += 10; Logger::log("Player says hi"); } What's the issue? Even tho I have overridden the update method on the Entity within Player, Player still prints "No update method". It seems the override didn't do anything.
Change this: void Engine::update() { for (Entity entity : entities) { entity.update(deltaTime); } } To this: void Engine::update() { for (Entity& entity : entities) { entity.update(deltaTime); } } In the original implementation, your for loop makes a copy of the item in entities. You probably didn't want that, but more importantly, entity is just a copy of the base class, so the derived class information is lost. Pass by reference to avoid this issue and other bugs.
72,105,162
72,105,271
C++ Copy Map to Vector Templated
I have the following: template<typename MapT> std::vector<int> mapToVec(const MapT &_map) { std::vector<int> values; for(const auto &entry : _map) { values.push_back(entry.second); } return values; } Obviously this only works if the value type of the map is an int. How do I template this further to convert a map to a vector of it's value type? So essentially it should return a vector of the values (or second elements of the key-value pairs) of any std::map passed in.
You can use typename MapT::mapped_type as the std::vector::value_type, eg: template<typename MapT> std::vector<typename MapT::mapped_type> mapToVec(const MapT &_map) { std::vector<typename MapT::mapped_type> values; values.reserve(_map.size()); for(const auto &entry : _map) { values.push_back(entry.second); } return values; } Online Demo Alternatively, you can share a template argument for both the std::vector::value_type and the std::map::mapped_type, eg: template<typename KeyT, typename ValueT> std::vector<ValueT> mapToVec(const std::map<KeyT, ValueT> &_map) { std::vector<ValueT> values; values.reserve(_map.size()); for(const auto &entry : _map) { values.push_back(entry.second); } return values; } Online Demo
72,105,527
72,132,277
Linking C++ code to a DYLIB library in macOS
I was able to setup BlockSci on macOS v10.13 (High Sierra) 10.13.6. The setup installed header files in /usr/local/include and a libblocksci.dylib in /usr/local/lib. The C++ code I am trying to compile is: #include "blocksci.hpp" #include <iostream> #include <string> int main(int argc, const char * argv[]) { blocksci::Blockchain chain{"path/config.json"}; return 0; }; The compile command I am using for hello.cpp is: g++ -std=c++17 -L/usr/local/lib -I/usr/local/include/blocksci -I/usr/local/include/blocksci/external -o hello hello.cpp However, the symbols for the BlockSci library are not found: Undefined symbols for architecture x86_64: "blocksci::Blockchain::Blockchain(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)", referenced from: _main in hello-942a60.o "blocksci::Blockchain::~Blockchain()", referenced from: _main in hello-942a60.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) What am I doing wrong when I try to compile this?
I found this and this that were helpful. It finally compiled with: g++ hello.cpp -std=c++17 -I/usr/local/include/blocksci/external -o hello -L/usr/local/lib -lblocksci -Wl,-rpath,/usr/local/lib However, now I get a runtime error: libc++abi.dylib: terminating with uncaught exception of type std::runtime_error Abort trap: 6 Back to the drawing board, but it compiled for now.
72,105,682
72,108,027
How do you tell C++ to use a specific file from a folder when you don't always know the exact path?
Note: I only know C in depth at the moment, but I am enrolled in a summer course starting soon on modern C++, so methods for C++20 would be extremely helpful as well. If this is a dumb question or was already asked (I didn't find anything from googling), then links would be helpful as well. Question: Okay, so say I am designing a program. I want the program to fopen a file, and I can either tell it the exact path, or have it in my working directory. Let's make up two paths below for the sake of example: (my computer path)/project/partone/mainfiles/main.c (my computer path)/project/parttwo/mainfiles/data.csv Now this isn't normally a problem, because I can just give main.c the full path to data.csv. But what if I want to publish the program? Then whoever downloads it will have a different path on their computer, automatically making the code fail. Is there any way to do this in C++20 (preferred answer) and/or C99 (if you know it for C99, that at least gives me some keywords to google for C++20, and I heard C code for the most part is usable in C++). I was thinking maybe there is like some package in C++20 that could act sort of like the "cd" command in the Linux Terminal where it can change directories starting at the one I am in? Like tell C++ to (from project/partone/mainfiles): //pseudocode cd .. cd .. cd parttwo cd mainfiles fopen data.csv
Here’s a little helper module to get a path to a creatable/writable directory for saving your program data. appdata_path.hpp #ifndef APPDATA_PATH_HPP #define APPDATA_PATH_HPP #include <filesystem> #include <string> std::filesystem::path get_appdata_path( const std::string & application_name ); #endif appdata_path.cpp #include "appdata_path.hpp" #ifdef _WIN32 #include <windows.h> #include <shlobj.h> #include <objbase.h> #pragma comment(lib,"Shell32") #pragma comment(lib,"Ole32") std::filesystem::path get_known_folder_path( REFKNOWNFOLDERID rfid ) { wchar_t * p; if (S_OK != SHGetKnownFolderPath( rfid, 0, NULL, &p )) return ""; std::filesystem::path result = p; CoTaskMemFree( p ); return result; } std::filesystem::path get_appdata_path( const std::string & application_name ) { auto path = get_known_folder_path( FOLDERID_LocalAppData ); // or FOLDERID_RoamingAppData if (!path.empty()) path /= application_name; return path; } #else #include <stdlib.h> #include <pwd.h> #include <sys/types.h> #include <unistd.h> std::filesystem::path get_appdata_path( const std::string & application_name ) { const char * p = getenv( "HOME" ); if (p) return p + ("/" + application_name); struct passwd * pw = getpwuid( getuid() ); if (pw) return pw->pw_dir + ("/" + application_name); return ""; } #endif example.cpp #include <iostream> #include "appdata_path.hpp" int main() { auto path = get_appdata_path( "Example Application" ); if (path.empty()) std::cout << "Wut?\n"; else std::cout << path << "\n"; } Notes: Notice that the Windows code has a choice between Local and Roaming. Unless you plan for your app to work across multiple computers, use Local. Certain characters are not valid in filenames (on Windows). In general you should avoid weird characters when naming files anyway, so use a simplified, filesystem-friendly name for your application. As you see in the example, spaces are OK, but whether you use them or not is up to you. Notice that the code does nothing but return a valid path. It does not create or verify the existence of the path. You must do that yourself. For example, to save data you might use something like: void save_data() { auto save_directory = get_appdata_path( "Quuxer" ); auto save_filename = save_directory / "data.csv"; if (save_directory.empty()) std::filesystem::create_directory( save_directory ); std::ofstream f( save_filename ); f << my_data; } This module compiles on Windows with MSVC as-is. If you use a different compiler (GCC or LLVM/Clang) you will need to explicitly link with Shell32.lib and Ole32.lib. It compiles on Linux (and Mac too!) as-is. Requires C++17, I think.