question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
69,978,467
69,978,525
Converting calculation contained in string to integer - C++
I was wondering if it would be possible to store caluclations contained in a string to integer. For example: #include <iostream> #include <string> using namespace std; int main() { string variable = "-123+432"; cout << stoi(variable) << endl; } This returns -123, would it be possible to make it return 309? Also what if there would be more calculations inside the string (eg. "-123+432*2"), and the person writing program would not know how many calculations will there be in a string (eg. string would be entered by user when the programm is runing). Thanks for all answers
It's possible for sure, but it's quite complicated to parse arbitrary strings, work out if they contain a valid mathematical expression and then work out the result. Unless you are wanting to implement the solution yourself for fun, I would suggest looking up and using a 3rd party library that evaluates string expressions, for example https://github.com/cparse/cparse This would allow you to do something like (probably not exactly correct, just for rough example): int main() { string variable = "-123+432"; std::cout << calculator::calculate(variable, &vars) << std::endl; } If you are wanting to do this yourself for fun, I suggest you look up "Expression evaluation" and start from there. It's quite a large and complicated topic but a lot of fun to write your own evaluator imo.
69,979,117
69,979,139
How can I randomly generate integers in interval <-99,99> in c++?
I tried something like this but this generate only in interval (-99,0) void input(int array [row][col]){ for (int i = 0; i < row; i++){ for (int j = 0; j < col; j++){ array[i][j] = rand() % 99 + (-99); } } }
You can use std::uniform_int_distribution for example something like std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> distrib(-99, 99);
69,979,373
69,979,585
Adding functions to string class in c++
I am using the up to date compiler for gcc. Therefore my code can execute to_String() and stoi() but unfortunately the platform that I am trying to compile my code in has a much previous one and I want to add these two functions into the string class therefore I can use them in my code without any problem.This is one of each example of the errors I get. Cabinet.cpp:93:25: error: 'to_string' was not declared in this scope cout << to_string(id) << " not found"<<endl; LabOrganizer.cpp: In member function 'void LabOrganizer::findClosest(int, int, int)': LabOrganizer.cpp:294:38: error: 'stoi' was not declared in this scope cc = stoi(arr1[i].substr(1,1))-1;
These two functions aren't part of the "string class". All you need is to use alternatives that existed in 1998: The to_string function isn't even needed in this context. You can simply change it to: cout << id << " not found" << endl; You can replace stoi with atoi. It doesn't throw exceptions if the conversion fails, but since it's a school assignment -- you most probably don't care about that: cc = atoi(arr1[i].substr(1,1).c_str())-1; If you have many instances whose replacement is too cumbersome, you can, of course, define those functions in some common header file: template<class T> std::string to_string(const T &x) { std::ostringstream s; s << x; return s.str(); } inline int stoi(const std::string &s) { // ... ignores error handling ... return atoi(s.c_str()); } Hopefully this compiles with that 1998 GCC.
69,979,450
69,979,599
Round-off error when computing value inside range
For finite values v0, v1 and value r in [0, 1] range, will the value v, computed as below, always belong to [v0, v1] range, or can it be (slightly) outside due to round off errors? double v0; // Finite double v1; // Finite double r; // In [0, 1] double v = v0 * r + v1 * (1.0 - r); if (v0 <= v1) assert(v0 <= v && v <= v1); else assert(v1 <= v && v <= v0);
Yes, it can be. Here's an example: #include <assert.h> int main() { double v0 = 2.670088631008241e-307; double v1 = 2.6700889402193536e-307; double r = 0.9999999999232185; double v = v0 * r + v1 * (1.0 - r); if (v0 <= v1) assert(v0 <= v && v <= v1); else assert(v1 <= v && v <= v0); return 0; } This produces: Assertion failed: (v0 <= v && v <= v1), function main, file b.cpp, line 12. The value of v computed in this case is: 2.67009e-307
69,980,168
69,980,233
Recursive parameter pack functions without parameters C++
I'm trying to create a recursive parameter pack function as follows: template <class T, class ... Ts> void myFunction() { execute<T>(); myFunction<Ts...>(); } This doesn't compile with the error: error C2672: 'Test::myFunction': no matching overloaded function found. Does anyone know how to do what I'm trying to achieve? Thanks
If you can use C++17 or newer, you can skip the recursion and use a fold expression like template<class... Ts> void myFunction() { (execute<Ts>(), ...); }
69,980,578
69,983,371
Using fork() and exec() to execute Python code from C++
I am trying to use exec() to run Python from C++, and use pipes to communicate between the processes. I found that the C++ process keep waiting at the exec() command after the Python process terminates, which makes it unable to execute the codes below that line. Please check my code below (I have minimized the problem so the acutal communication part is removed) C++ file: int main() { int pipe_cpp_to_py[2]; int pipe_py_to_cpp[2]; if (pipe(pipe_cpp_to_py) || pipe(pipe_py_to_cpp)) { std::cout << "Couldn't open pipes" << std::endl; exit(1); } pid_t pid = fork(); if (pid == 0) { std::cout<<"child started"<<std::endl; char *intrepreter="python3"; char *pythonPath="./Pipetest.py"; char *pythonArgs[]={intrepreter,pythonPath,NULL}; std::cout<<"child before exec"<<std::endl; execvp(intrepreter,pythonArgs); std::cout<<"child after exec"<<std::endl; close(pipe_py_to_cpp[0]); close(pipe_cpp_to_py[1]); close(pipe_py_to_cpp[1]); close(pipe_cpp_to_py[0]); std::cout<<"child terminated"<<std::endl; } else if (pid < 0) { std::cout << "Fork failed." << std::endl; exit(1); } else { std::cout<<"parent started"<<std::endl; std::cout<<"parent terminated"<<std::endl; exit(0); } std::cout<<"cpp terminated"<<std::endl; return 0; } Python file: import os import time import struct if __name__ == "__main__": print("in python") exit() Output: ece:~/cpp> ./Pipetest parent started parent terminated child started child before exec ece:~/cpp> in python (blinking cursor here) For the C++ file, if I remove the fork command and simply call exec() in the main function to execute the Python program, it will behave as expected and terminate successfully. Could anyone tell me what is going on? Update: Thanks for all the answers! Now I see that codes after exec() will not be executed. However, the output still confuses me because the new command prompt does not show up (in my case, it's ece:~/cpp>). In fact, it shows up only after I enter something. This happens even when I replace exec() with system(). Why is this happening?
You aren’t waiting on the child process, so the parent exits during (or, as in your example output, before) the (relatively long) startup time for Python and the shell prints its next prompt before the child prints anything. You can see this in that if you type anything on the “(blinking cursor here)” line, it gets executed as the next shell command.
69,981,189
69,981,359
How to find element in map where key is a shared_ptr?
I have a map of std::shared_ptr's for both key and value and I'm trying to find the right element. Below is what I have, though, it still has a problem and won't compile. std::map<std::shared_ptr<MyObjA>, std::shared_ptr<ValObj>> aobjs; std::map<std::shared_ptr<MyObjB>, std::shared_ptr<ValObj>> bobjs; template <typename T> int findit(T& t) { T myobj = t; typename std::map<std::shared_ptr<T>, std::shared_ptr<ValObj>>::iterator it; if constexpr(std::is_same<T, net::MyObjB>::value) { net::MyObjB objB; // failing here ... auto it = std::find_if(bobjs.begin(), bobjs.end(), [&](std::shared_ptr<MyObjB> const& p) { return *p == objB; }); if (it != bobjs.end()) { // found it return 0; } } return -1; } I think the problem is with the first and last of the find_if returning the std::shared_ptr, but unsure. I got a ton of output that I've had trouble parsing ... /usr/lib/gcc/x86_64-pc-linux-gnu/10.3.0/include/g++-v10/bits/predefined_ops.h: In instantiation of ‘constexpr bool __gnu_cxx::__ops::_Iter_pred<_Predicate>::operator()(_Iterator) [with _Iterator = std::_Rb_tree_iterator<std::pair<const std::shared_ptr<MyObjB>, std::shared_ptr<ValObj> > >; _Predicate = findit<MyObjB>::<lambda(const std::shared_ptr<MyObjB>&)>]’: /usr/lib/gcc/x86_64-pc-linux-gnu/10.3.0/include/g++-v10/bits/stl_algobase.h:1912:42: required from ‘constexpr _InputIterator std::__find_if(_InputIterator, _InputIterator, _Predicate, std::input_iterator_tag) [with _InputIterator = std::_Rb_tree_iterator<std::pair<const std::shared_ptr<MyObjB>, std::shared_ptr<ValObj> > >; _Predicate = __gnu_cxx::__ops::_Iter_pred<findit<MyObjB>::<lambda(const std::shared_ptr<MyObj>&)> >]’ /usr/lib/gcc/x86_64-pc-linux-gnu/10.3.0/include/g++-v10/bits/stl_algobase.h:1974:23: required from ‘constexpr _Iterator std::__find_if(_Iterator, _Iterator, _Predicate) [with _Iterator = std::_Rb_tree_iterator<std::pair<const std::shared_ptr<MyObjB>, std::shared_ptr<ValObj> > >; _Predicate = __gnu_cxx::__ops::_Iter_pred<findit<MyObjB>::<lambda(const std::shared_ptr<ValObj>&)> >]’ /usr/lib/gcc/x86_64-pc-linux-gnu/10.3.0/include/g++-v10/bits/stl_algo.h:3934:28: required from ‘constexpr _IIter std::find_if(_IIter, _IIter, _Predicate) [with _IIter = std::_Rb_tree_iterator<std::pair<const std::shared_ptr<MyObjB>, std::shared_ptr<ValObj> > >; _Predicate = findit<MyObjB>::<lambda(const std::shared_ptr<MyObjB>&)>]’ Thoughts?
I have a map of std::shared_ptr's for both key and value ... thoughts? A few things come to mind: 1. It is likely not a good idea to hold a map like that - especially with respect to the keys. It doesn't make sense to have "heavy" keys, that require resource allocation, and which you are likely avoiding holding many copies of. It is likely that MyObjA's have some kind of cheap numeric identifier you can use; and if they don't - consider adding such a field, and constructing MyObjA with such a unique identifier. Then, instead of a map from MyObjA's to MyObjB's, you could map from ObjAKey to MyObjB's, or even from ObjAKey to std::pair's of a MyObjA and MyObjB. 2. I suspect that even for the map values, a std::shared_ptr may not be necessary, but you haven't given us enough context. 3. Do you really need an ordered map? Would std::unordered_map not work for you? Also, if the number of elements in your map is not big enough, you can probably just use a vector of MyObjA, MyObjB pairs and it'll be good enough. It's not as though the standard library maps are fast.
69,981,591
69,981,715
Copying memory of adresses with memcpy
Base function: template <typename T> T** shifting (T* in, int size, int dist, int pos) { auto out = new T* [size]; int k = (pos-1) * size/dist; for (int i{0}; i < size; ++i) { if (i+k >= size) { out[i] = &in[k+i-size]; } else { out[i] = &in[k+i] } } return out; } This function is creating an array of pointers out to elements of array in in a specific order, I wondered if there would be a faster approach with memory manipulation, so I tried something different. New function: template <typename T> T** stuff(T* in, int size, int dist, int pos) { int helper = size/dist; auto out = new T* [size]; for (int i{0}; i < dist; i++) { if (pos + i < size) { memcpy(out + i - pos + dist, in+i*helper, helper * sizeof(T*)); } else { memcpy(out + i - pos, in+i*helper, helper * sizeof(T*)); } } return out; } However this is not giving an array of adresses, but rather converts the values behind the addresses to pointers so I get the value of the element as a pointer. On closer inspection this behaviour should not be otherwise, but I can't think of a way to get it to work. Thanks for any help.
Your new loop body (before your edit, but my analysis remains basically the same) is: memcpy(out + i - pos + (pos + i < size ? dist: 0), in+i*helper, helper * sizeof(T*)); Expanding that for readability (which will not hurt performance, so you should do it too): T** dest = out + i - pos + (pos + i < size ? dist: 0); T* src = in + i * helper; memcpy(dest, src, helper * sizeof(T*)); By writing it out with types, now you can see that the types are not compatible (T** and T*). What you're trying to do is copy addresses to particular locations of in, but you can't do that in chunks like this because those addresses don't exist as numbers in memory yet, you need to create them! Your best bet is to stick with your original code, which is clearer. If there is a performance problem, tell us what level of optimization you're compiling with, what are the input sizes you're using, what is the time taken by this function, and how much is your time budget?
69,981,676
69,988,903
RC4 encryption cpp algorithm
I am writing a program that can encrypt files using the cipher RC4, In my file "test.txt" is a word "Plaintext", the program should encrypt and save it also in a file (for test I was using "cout") I thing there is a problem with the last part of the code while ( plik.read(&x,1) ) { i = ( i + 1 ) % 256; j = ( j + S [ i ] ) % 256; swap( S [ i ], S [ j ] ); temp = S [ ( S [ i ] + S [ j ] ) % 256 ] ^ x; cout << temp; } There is no errors and no warnings, What should I change? #include <algorithm> #include <fstream> #include <iostream> #include <string> using namespace std; int main() { unsigned char S[256]; int i = 0; for ( i = 0; i < 256; i++ ) S [ i ] = i; string Key; cout << "Enter the key: "; cin >> Key; int j = 0; for ( i = 0; i < 256; i++ ) { j = ( j + S [ i ] + Key.at( i % Key.length() ) ) % 256; swap( S [ i ], S [ j ] ); } ifstream plik; string path = "tekst.txt"; plik.open( path ); char tekst; plik >> tekst; string printFile = "Encryption_" + path; ofstream outfile( printFile ); char x; j = 0; i = 0; string temp; while ( plik.read(&x,1) ) { i = ( i + 1 ) % 256; j = ( j + S [ i ] ) % 256; swap( S [ i ], S [ j ] ); temp = S [ ( S [ i ] + S [ j ] ) % 256 ] ^ x; cout << temp; } plik.close(); outfile.close(); return 0; } My key is: "key" and the result should be Good Result
Your algorithm is mathematically totally correct, I just did few small corrections to other parts of your code and your code made correct output. For testing purposes lets take test examples here from Wiki, first example. Input key will be Key, input file will be Plaintext, resulting file should be BB F3 16 E8 D9 40 AF 0A D3 in hex. Following modified code passes this test. In code below you input a key from console, then input file is taken from tekst.txt and output file is written to Encryption_tekst.txt. It is better not to print result to console as ASCII chars but to view resulting file in hex viewer, because console will mess up with character encodings, better to view in hex. I added printing to console of resulting hex characters. Also notice that in following code very first block writes Plaintext to tekst.txt, I did this for the purpose of example, so that code can be just copy pasted and run without any extra dependencies. You have to delete very first block that writes to teks.txt, because you have your own input tekst.txt and it will be overwritten. When you run following example enter Key in console prompt. Try it online! #include <algorithm> #include <fstream> #include <iostream> #include <iomanip> #include <string> #include <cstdint> using namespace std; int main() { { ofstream out("tekst.txt"); out << "Plaintext"; } unsigned char S[256]; int i = 0; for (i = 0; i < 256; i++) S[i] = i; string Key; cout << "Enter the key: "; cin >> Key; int j = 0; for (i = 0; i < 256; i++) { j = (j + S[i] + Key.at(i % Key.length())) % 256; swap(S[i], S[j]); } ifstream plik; string path = "tekst.txt"; plik.open(path); string printFile = "Encryption_" + path; ofstream outfile(printFile); char x; j = 0; i = 0; char temp = 0; while (plik.read(&x, 1)) { i = (i + 1) % 256; j = (j + S[i]) % 256; swap(S[i], S[j]); temp = S[(S[i] + S[j]) % 256] ^ x; outfile << temp; cout << std::hex << std::setw(2) << std::setfill('0') << uint32_t(uint8_t(temp)) << " "; } plik.close(); outfile.close(); return 0; } Input key (from console): Key Input file tekst.txt: Plaintext Console output: Enter the key: Key bb f3 16 e8 d9 40 af 0a d3 Output Encryption_tekst.txt viewed in hex viewer with code page CP1252:
69,982,459
69,982,575
Using compare_exchange_strong on atomic booleans (C++)
I'm new to concurrent programming and I'm trying to compile the following code: private: std::atomic<bool> resizing_; void Resize() { if (resizing_.compare_exchange_strong(false, true)... } This throws error: no matching member function for call to 'compare_exchange_strong' and I'm not sure how I can fix this. I've tried using a bool* for the first argument but that didn't seem to help. I've tried to read the documentation on atomic<>s but it hasn't helped. Any information on what I'm doing wrong would be really helpful!
The first parameter of the compare_exchange_strong method is a reference to the type. This method exchanges two values, but only if the comparison of the contained value and the expected value is true. Otherwise it replaces the expected with the contained value. The idiom is like this: std::atomic<int> value; int expected = value; do { int new_value = get_updated_value(expected); } while(!value.compare_exchange_strong(expected, new_value)); Note that the expected is automatically updated whenever the comparison is false, and another new_value is evaluated each iteration.
69,982,473
69,994,284
ESP8266WiFi.h: No such file or directory
How can I make the WifiManager library work on a ESP32 board? I'm using PlatformIO to develop my code. Here are my imports: #include "esp_camera.h" #include <Arduino.h> #include <WiFiClientSecure.h> #include <PubSubClient.h> #include <ArduinoJson.h> #include <EEPROM.h> #include <WiFiManager.h> WiFiClient espClient; PubSubClient client(espClient); WiFiManager wifiManager; platformio.ini [env:esp32cam] platform = espressif32 board = esp32cam framework = arduino monitor_speed = 115200 build_flags = -DMQTT_MAX_PACKET_SIZE=36000 lib_deps = espressif/esp32-camera@^1.0.0 knolleary/PubSubClient@^2.8 bblanchon/ArduinoJson@^6.18.5 tzapu/WiFiManager@^0.16.0 But when I run the code, I get this following error: .pio\libdeps\esp32cam\WiFiManager/WiFiManager.h:16:25: fatal error: ESP8266WiFi.h: No such file or directory After further research, I see that WiFiManager uses ESP8266WiFi.h and now I'm wondering how I can make this library work on my ESP32 or is there an alternative library? The project's readme does say it works on ESP32.
The latest release of WiFiManager library (0.16) is almost a year old and doesn't support ESP32. You will need to install the library from Github to get ESP32 support. In your platformio.ini replace tzapu/WiFiManager@^0.16.0 with https://github.com/tzapu/WiFiManager.git@^2.0.5-beta
69,982,811
69,983,026
Read .csv into `map<vector<uint>>`
I am trying to read a .csv file into a map<vector<uint>>. The .csv file represents a modbus register map, in the form name,register,register,register.... eg. address,1 position,10,11 status,20,21,22 I have tried this (based on https://stackoverflow.com/a/24930415/15655948), and get a segmentation fault. register_map is declared as a class attribute in the header file. int SomeClass::readCSV(std::string fileName) { const uint MAX_LINE_LENGTH = 1024; const char* DELIMS = ","; std::fstream fin(fileName); if (!fin.is_open()) { spdlog::get("runtime_log")->error("Could not open file {0}.", fileName); return -1; } char buffer[MAX_LINE_LENGTH] = {}; char* pch; std::vector<uint> values; while (fin.getline(buffer, MAX_LINE_LENGTH)){ const char* row = strtok(buffer, DELIMS); pch = strtok(NULL, DELIMS); values.push_back(strtoul(pch,NULL,10)); while (pch != NULL){ pch = strtok(NULL, DELIMS); values.push_back(strtoul(pch,NULL,10)); } register_map[std::string(row)] = values; values.clear(); } return 1; } Why am I getting the segmentation fault above?
Among other assumptions, the critical one is this: while (pch != NULL) { pch = strtok(NULL, DELIMS); //<-- pch can be NULL values.push_back(strtoul(pch, NULL, 10)); //<-- BOOM! } Here, you're calling strtok, which might return NULL. But you still go ahead and convert the string anyway. This guarantees undefined behavior. To fix it, you should reverse the logic so that you only convert pointers that you have already NULL-tested. const char* row = strtok(buffer, DELIMS); pch = strtok(NULL, DELIMS); while (pch != NULL) { values.push_back(strtoul(pch, NULL, 10)); pch = strtok(NULL, DELIMS); } This type of error can easily be detected by running your program in a debugger and stepping through execution one line of code at a time. The debugger is also likely to break execution on an error like this, and show you the call stack at the point of crash. So you'd take one look and think "oh, it crashed here because pch is NULL". I recommend Right Now (TM) as a good time to learn how debug small programs. Most IDEs come with an integrated debugger, which makes it even easier.
69,983,044
69,983,231
Unexpected output when using fork() and system() in C++
I am trying to use fork() and system() to execute another C++ program in a child process but got some unexpected outputs. Please check my code below: main: int main(void) { pid_t pid = fork(); if (pid == 0) { std::cout<<"child started"<<std::endl; system("./helloworld"); std::cout<<"child terminated"<<std::endl; } else if (pid < 0) { std::cout << "Fork failed." << std::endl; exit(1); } else { std::cout<<"parent started"<<std::endl; std::cout<<"parent terminated"<<std::endl; } return 0; } helloworld.cpp: int main(void) { std::cout<<"hello world!"<<std::endl; return 0; } main program output: ece:~/cpp> ./Pipetest parent started parent terminated child started ece:~/cpp> hello world! child terminated (blinking cursor here) helloworld program output: ece:~/cpp> ./helloworld hello world! ece:~/cpp> (blinking cursor here) As is shown above, when the main program is executed, the next command-prompt (in my case, it's ece:~/cpp>) does not show up, and the program seems to be waiting for my input at the blinking cursor. In fact, the next prompt shows up only after I enter something. I wish the main program could terminate quitely with the next command-prompt showing up, just as the helloworld program does. How could I do that?
The shell is going to print the prompt as soon as the parent exits. If you don't want the child to print things after that, then you need to make sure the parent doesn't exit before the child does. You can do that by putting #include <sys/wait.h> at the beginning of your source file and wait(NULL); right before std::cout<<"parent terminated"<<std::endl;.
69,983,484
69,983,548
What does repeat n times mean in gdb debugger?
For example: bool plugin::checkQuality(string &text) { string temp = normalizeContent(text, 1); map<string, int> mapWords; matchWords(temp.c_str(), mapWords); ... } Once gdb enter this function, I can see the value as: plugin::checkQuality (this=0x7fffffffd9c0, text="This is a test", ' ' <repeats 20 times>, "c,,,,") at /mod/filter/plugin.cpp:59 What does the 2nd argument <repeats 20 times> means? And what's the 3rd argument "c,,,,"? Isn't the function only have one argument?
This is just the default behavior of how GDB prints more than 10 consecutive identical elements in an array. From the docs When the number of consecutive identical elements of an array exceeds the threshold, GDB prints the string "<repeats n times>", where n is the number of identical repetitions, instead of displaying the identical elements themselves. So in your example, the value of the parameter text appears to be "This is a test c,,,," You can set the threshold for how many characters need to be repeated before this is printed with set print repeats <number-of-repeats>
69,983,525
70,104,420
ATTiny85 Interrupts in Arduino IDE
I have an ATTiny85 which I program using a sparkfun programmer (https://www.sparkfun.com/products/11801) and the ATTiny Board Manager I am using is: https://raw.githubusercontent.com/damellis/attiny/ide-1.6.x-boards-manager/package_damellis_attiny_index.json Below is my code, I am having trouble getting the interrupt to work when I ground Pin 2. I have tested the LED does work outside of the interrupt (inside the loop). Any suggestions are welcome. #include "Arduino.h" #define interruptPin 2 const int led = 3; bool lastState = 0; void setup() { pinMode(interruptPin, INPUT_PULLUP); attachInterrupt(interruptPin, pulseIsr, CHANGE); pinMode(led, OUTPUT); } void loop() { } void pulseIsr() { if (!lastState) { digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level) lastState = 1; } else { digitalWrite(led, LOW); // turn the LED off by making the voltage LOW lastState = 0; } }
I was way off. Here is how to set up an interrupt on the ATTiny85 using the Arduino IDE (this example uses digital pin 4 (pin 3 on the chip): #include "Arduino.h" const byte interruptPin = 4; const byte led = 3; bool lastState = false; ISR (PCINT0_vect) // this is the Interrupt Service Routine { if (!lastState) { digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level) lastState = true; } else { digitalWrite(led, LOW); // turn the LED off by making the voltage LOW lastState = false; } } void setup() { pinMode(interruptPin, INPUT_PULLUP); // set to input with an internal pullup resistor (HIGH when switch is open) pinMode(led, OUTPUT); // interrupts PCMSK |= bit (PCINT4); // want pin D4 / pin 3 GIFR |= bit (PCIF); // clear any outstanding interrupts GIMSK |= bit (PCIE); // enable pin change interrupts } void loop() { }
69,983,554
69,983,853
std::getline() does not ignore white space
I am new to C++ and I have some trouble preventing getline to read the new line character at the end of my text file. I tried truncating it using a newline character and then passing to a delimiter with ',' but it just doesnt work. Can you please help me understand what is going on and why I am not able to achieve what i intended to do? I have edited this post to correct the mistake of getline() more than what is available. However I dont know how to transfer this getline() string to prevent taking the'\n' character #include <iostream> #include <fstream> #include <string> #include <sstream> static int Ncol = 5; int main() { int ctr=0,Nrow; std::string line,line1; std::ifstream myFile1; Nrow = 4; std::cout.precision(15); std::fixed; double* input = new double[Nrow*Ncol]; double* ftrue = new double[Nrow]; myFile1.open("./Data_codelink_test/test.txt"); while(ctr<Nrow) { std::getline(myFile1,line1,','); // This gives me line1 with the new line character std::cout<<"Read "<<line1<<std::endl; input[ctr] = std::stold(line1); std::cout<<"Stored "<<input[ctr]<<std::endl; ctr++; } myFile1.close(); My test.txt looks like this 1,2,3,4,5 1,2,3,4,5 1,2,3,4,5 1,2,3,4,5 I would like to have a vector of size 20 to have values stored in this manner 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
std::getline only accepts a single character as delimiter: Can I use 2 or more delimiters in C++ function getline? It's more clear to use two loops to read data as below: #include <iostream> #include <fstream> #include <string> #include <sstream> static int Ncol = 5; int main() { int column=0,Nrow; std::string line,field; std::ifstream myFile1; Nrow = 5; std::cout.precision(15); std::fixed; double* input = new double[Nrow*Ncol]; double* ftrue = new double[Nrow]; myFile1.open("./Data_codelink_test/test.txt"); int row = 0; while (std::getline(myFile1, line)) { std::stringstream stream(line); int column = 0; while(column < Ncol) { std::getline(stream,field,','); // This gives me line1 with the new line character std::cout<<"Read "<<field<<std::endl; input[row * Ncol + column] = std::stold(field); std::cout<<"Stored "<<input[row * Ncol + column]<<std::endl; column++; } row++; } myFile1.close(); } The result is:
69,983,996
69,984,829
Why does 'extern template class' technique not work as expected?
The original question has been refined. Given a source code file named main.cpp as follows: #include <string> extern template class std::basic_string<char>; template<typename T> struct A { T n = {}; T get() const { return n; } }; extern template struct A<int>; int main() { auto a = A<int>{}.get(); // undefined reference to `A<int>::get() const' auto b = static_cast<int>(std::string{}.size()); // ok return a + b; } What I expected: Note that the source code has extern template class std::basic_string<char> but no template class std::basic_string<char>. So, the compiler would not instantiate class std::basic_string<char>, then g++ main.cpp would cause link errors on line std::string{}.size() as on line A<int>{}.get(). What I observed: It is ok to g++ main.cpp on line std::string{}.size(). Online demo Why does extern template class technique not work as expected?
There are at least two reasons why it doesn't work. One There is no prohibition against library class and function template instantiations being declared as extern template by the implementation. gcc and libstdc++ do just that. $ g++ -E main.cpp | grep 'extern.*string' extern template class basic_string<char>; // <-- from the library extern template class basic_string<wchar_t>; // <-- from the library extern template class std::basic_string<char>; // <-- your line The standard library implementation contains the explicit instantiation definitions (you can dig the source). Two An entity that is the subject of an explicit instantiation declaration and that is also used in a way that would otherwise cause an implicit instantiation in the translation unit shall be the subject of an explicit instantiation definition somewhere in the program; otherwise the program is ill-formed, no diagnostic required [temp.explicit]. A possible rationale for the NDR is that extern template should not prevent inlining and other uses that do not involve linking. Indeed, with -O2 A::get is inlined, and the program builds just fine. There is no established technology that would force this program to be rejected no matter what. It can be rejected because of linker errors, but there is no requirement for linker errors to appear.
69,984,034
69,984,310
stack corruption detected when use memset in c++ from JNI Android
I am developing an Android application using C++ native code. I have C++ code (XTTEA Algorithm in C++ native) which perfectly runs online with C++ compiler and I can get the output, but when I try to use that class method using JNI cpp class, it give me the error below: A/libc: stack corruption detected (-fstack-protector) A/libc: Fatal signal 6 (SIGABRT), code -1 (SI_QUEUE) in tid 13328 (example.ndkdemo), pid 13328 (example.ndkdemo) Below is the JNI cpp code where I pass the data as input. extern "C" JNIEXPORT jint JNICALLJava_com_example_ndkdemo_MainActivity_encryptDataInt(JNIEnv *env, jobject thiz /* this */){ // return add(5,3); int len; unsigned char input[8] = { 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11 }; sg_xxtea_encrypt (input, 8); return 1; } Below is the method that I call from above JNI code. I debug the code and find out that the error occurs in the memset() function inside the first if conditon. int sg_xxtea_encrypt (unsigned char *data, int data_size) { int i = 0; int block_size = ((data_size + 2) / 4 + 1) * 4; memset (sg_data_buff, 0, ENCRYPT_INT_BUFF * 4); if (block_size > data_size) { memset (&data[data_size], 0, block_size - data_size); // We get error in this line } for (i = data_size + 1; i >= 2; i--) { data[i] = data[i - 2]; } data[0] = (data_size >> 8) & 0xff; data[1] = (data_size >> 0) & 0xff; for (i = 0; i < block_size / 4; i++) { sg_data_buff[i] = bytesTOint (&data[i * 4]); } TEA_EncryptCore (block_size, sg_data_buff, sg_key_buff); for (i = 0; i < block_size / 4; i++) { intTobyte (sg_data_buff[i], &data[i * 4]); } return block_size; } Can anyone please suggest what could be the issue.
Your input array is 8 bytes. The data parameter is a pointer to input, and the data_size parameter is 8, so theblock_size variable is calculated as 12. Your memset() is writing 4 0x00 bytes to &data[data_size], aka &input[8], which is out of bounds of the input array. So, you have a buffer overflow that is corrupting stack memory surrounding the input array. The subsequent for loop after the memset() is also accessing the input array's elements out of bounds, too. input is a fixed sized array. Accessing elements outside of its bounds does not make it grow larger.
69,984,321
69,984,349
Why can't I assign lambdas to function parameters as a default value?
Take the following function: template<typename T> decltype(auto) find_median(T begin, T end, bool sorted = false, auto comparison = [](auto a, auto b){return a < b;}){ assert(begin != nullptr); assert(end != nullptr); return sorted ? find_median_sorted(begin, end) : find_median_unsorted(begin, end, comparison); } Note that I set the comparison param to a default value [](auto a, auto b){return a < b;}. So if I call this function like the following: find_median(std::addressof(arr), std::addressof(arr[9])) where arr is an std::array, this should work. But it doesn't work, does can someone tell me why?
You can provide a default value for a known type, but you can't provide a default value for a deduced type like this. It's just not something the language supports. You have to provide a default for the type and the value: template<typename T, typename Cmp = std::less<>> decltype(auto) find_median(T begin, T end, bool sorted = false, Cmp comparison = {}) { // ... }
69,984,598
69,985,539
Using count_if() to find the same string value
I tried using a lambda expression and count_if() to find the same string value in a vector, but it didn't work. The error message is: variable 'str' cannot be implicitly captured in a lambda with no capture-default specified std::vector<std::string> hello{"Mon","Tue", "Wes", "perfect","Sun"}; for (unsigned int i = 0; i < hello.size(); i++) { int n=0; std::string str=hello[i]; n=std::count_if(hello.begin(),hello.end(),[](std::string s){return s==str;}); std::cout<<n; }
@Steven The brackets [] of lambda functions, are called a capture list. They define the scope of variables that the lambda function uses. See this reference. When you use this formatting [&], it means you can see all the variables (by reference) of the current scope in your lambda function. So the type of variables doesn't matter. For your example, when you write: s == str The lambda function only knows about the variable s, which is passed as an argument. To see the str, you can use either of these: [&], pass everything by reference [&str], pass only the variable str as reference Note, there are also ways to pass by value.
69,984,704
69,984,714
How can I specialize std::common_type<A,B> so that it's naturally commutative?
std::common_type<T1, ..., TN> is a helper template in C++ which can find the common type which all of T1 ... TN are implicitly convertible to. According the C++ spec, a user may specialize std::common_type<T1,T2> if certain conditions apply, and: std::common_type<T1, T2>::type and std::common_type<T2, T1>::type must denote the same type. However, common_type<T1, T2> might be a very complicated specialization for user types T1 and T2: namespace std { template <typename T1, complicated_constraint_of<T1> T2, ...> struct common_type<complicated_expression_of<T1, ...>, complicated_expression_of<T2, ...>> { using type = complicated_type_expression_of<T1,T2>; }; } In general, the constraint expressions are not necessarily symmetrical (for example, we might specify that T2 is a base of T1). This means that to preserve symmetry, we'd need to rewrite the entire specialization with T1 and T2 reversed, but doing that without making any mistake is extremely difficult and fragile. How can I robustly define a commutative specialization of common_type<T1,T2> for my own types?
Here is the C++20 solution I came up with: // define concept of `common_type<A,B>` existing template <typename A, typename B> concept has_in_common_ordered = requires { common_type<A,B>::type; }; namespace std { // define common_type<A,B> if common_type<B,A>::type exists: template <typename A, has_in_common_ordered<A> B> struct common_type<A,B> : public common_type<B,A> {}; } Now, with the above, the following should compile: struct X {}; struct Y {}; namespace std { template<> struct common_type<X,Y> { using type = X; // or whatever }; } int main() { // even though we only specialized for one ordering, // both orderings now exist: std::common_type<X,Y>::type a; std::common_type<Y,X>::type b; } I think one of two things is possible: This is a natural technique that should really just be part of the standard definition of std::common_type. This is extremely evil and you should never do it, for subtle reasons. I await someone to tell me which one it is in the comments. ;)
69,985,321
69,986,674
Inter process communication from python to cpp program
Suppose there are 3 files: f1.cpp, f2.py, f3.cpp. I am running the command on linux terminal as follows: $./f1.out | python3 f2.py | ./f3.out The output of f1 goes perfectly into the input of f2. Also, f2's output goes perfectly into f3. I am displaying the output in f3. f1 generates input for f2 after a particular interval. In this interval, I need to enter a user input in f3 file so that it can give an output accordingly during that pause. I tried debugging my code and I found that although my final output without user input is generated by f3, my user input is not being read. Somebody help!!
Since you have already declared from your command that f3 should take input from f2's output and f2 should take input from f1's output, there is no straightforward way to give console input to f3 now. The best way here would be (assuming you are only the author of f1 and f2 also) you can just read that user input in f1 only and immediately print it cin >> input; cout << input; so that it will be passed to f2's input. You can do a similar thing in f2 also inp = str(input) print(inp) hence passing that to f3 as you wanted. But if you don't want to do it this way or if you are not the author of f1 and f2, I would suggest you launch f3 in a separate terminal window and use a named pipe(FIFO) for communication between f2 and f3. Since the communication would be happening through a FIFO, the stdin would still be pointing to the keyboard and you can type input to f3. Edit Another way you can do it is(although, I'm not sure how healthy this is), you can spawn a new thread before sleeping. Take input in new thread and terminate that new thread once input is taken. The new thread will be running as long as input is not given. In the main thread sleep for 5 seconds and when main thread wakes up, forcefully terminate the new thread using something like pthread_kill.
69,986,173
69,986,340
Is there a way to conditionally initialize a global static variable?
So my current code looks like the following: static Item fields[] = { {GROUP1, TEXT1}, {GROUP2, 0}, } Now I need to make change in such a way that I initialize GROUP2 only if certain condition is met else need to initialize with GROUP3. So I tried the following: static Item fields[] = (flagSet)? { {GROUP1, TEXT1}, {GROUP2, 0}, } : { {GROUP1, TEXT1}, {GROUP3, 0}, } But this didn't work. I know that one way is to use #ifdef macros but this flagSet happens at runtime and based on that I need to initialize the static array. Also since the static initialization happens before anything else is it possible to do this at all?
Is there a way to conditionally initialize a global static variable? Yes. The ways are pretty much the same as conditionally initialising a non-global non-static variable. You cannot however conditionally initialise an array. You could use a bit of indirection: static Item fields_true[] { {GROUP1, TEXT1}, {GROUP2, 0}, }; static Item fields_false[] = { {GROUP1, TEXT1}, {GROUP3, 0}, }; static auto& fields = flagSet ? fields_true : fields_false; Or, you could initialise the array elements conditionally. Since only one element has a difference, there isn't even any repetition in this case: static Item fields[] = { {GROUP1, TEXT1}, {flagSet ? GROUP2 : GROUP3, 0}, }; but this flagSet happens at runtime Using runtime input is not an option to initialise static objects. You will have to modify the array after initiliasation using assignment operation.
69,986,484
69,987,960
Cuda compile error when "cuMemGetAddressRange" exists
Here comes the sample codes: #include <cuda.h> #include <cuda_runtime.h> #include <stdio.h> int main() { unsigned char* cu_test; cudaMalloc((void**)&cu_test, 3200); CUdeviceptr pbase; size_t psize; CUresult res = cuMemGetAddressRange(&pbase, &psize, (CUdeviceptr)cu_test); printf("cu_img_yuv size: %ld", psize); return 0; } While it throws error when compiling whatever the cuda version is(tested from 11.3 to 11.5): $ nvcc main.cu -o main /tmp/tmpxft_0000e288_00000000-11_main.o: In function `main': tmpxft_0000e288_00000000-6_main.cudafe1.cpp:(.text+0x54): undefined reference to `cuMemGetAddressRange_v2' collect2: error: ld returned 1 exit status Can someone help pointing out what the problem is plz?
The message: error: ld returned 1 exit status denotes that it is a linking error ( see ld ). To see this is the case, you can run nvcc -c main.cu -o main.o and you will not get any error. This is the source-code compilation step! Solution: You need to explicitly specify linkage with the CUDA driver stub library: nvcc main.cu -o main -lcuda That is because cuMemGetAddressRange() is part of the CUDA Driver API, not the CUDA runtime API. NOTE: you did not cudaFree() the allocated memory, you might want to fix this! Edit: (credit to @talonmies comment) You do not have to explicitly link against the CUDA runtime library (-lcudart), because nvcc will automatically link against it.
69,986,491
69,986,716
how do I swap the values at index 2 and index 3 in a vector of type integer in C++?
Problem: You have to swap the values between the 2nd and 3rd index of an array. The array is a vector array consisting of 10 elements. assuming it is; std::vector<int> arr1 = { 33,12,11,13,54,65,23,67,22,10 }; Final result: before swapping: 33 12 11 13 54 65 23 67 22 10 after swapping: 33 12 13 11 54 65 23 67 22 10 Additional info: Any concept of logic around the solution is allowed. Apart from integer type the array should be able to take other datatypes.
Version 1: Using std::swap #include <iostream> #include <algorithm> #include <vector> int main() { std::vector<int> vec= { 33,12,11,13,54,65,23,67,22,10}; std::swap(vec[2], vec[3]); for(const int &elem: vec) { std::cout<<elem<<std::endl; } return 0; } Version 2: Manually using a temp variable #include <iostream> #include <vector> //define a function template that takes the first argument as a vector of arbitrary type and second argument as first index to swap and the third argument as the second index to swap template<typename T> void mySwap(std::vector<T>&vec, std::size_t indexOne, std::size_t indexTwo ) { T temp = vec.at(indexOne); vec.at(indexOne) = vec.at(indexTwo); vec.at(indexTwo) = temp; } int main() { std::vector<int> vec= { 33,12,11,13,54,65,23,67,22,10}; mySwap(vec, 2,3); for(const int &elem: vec) { std::cout<<elem<<std::endl; } return 0; } The second version is given just to illustrate how you can achieve the same effect as std::swap.
69,986,510
69,986,742
How can I initialize this pointer correctly to avoid a segmentation fault?
This is my class structure class A { public: void doSomething { bInstance -> bMethod(); } ... private: std::shared_ptr<B> bInstance } class B { public: void bMethod(); } A::A(std::shared_ptr<B> bInstance) : bInstance(bInstance){} Then using GTest, this is my test fixture // Test Fixture class ATest: public ::testing::Test { protected: ATest() : bInstancePointer(std::make_shared(...)), aInstance(bInstancePointer) {} A aInstance; std::shared_pt bInstancePointer; }; In my test I have aInstance.doSomething() This results in a segmentation fault. Does anyone know why this syntax is incorrect or have any suggestions on how I can restructure the initialization of my pointers to avoid this segmentaion error?
Just fix the order of members' declaration: // Test Fixture class ATest: public ::testing::Test { protected: ATest() : bInstancePointer(std::make_shared(...)), aInstance(bInstancePointer) {} std::shared_pt bInstancePointer; A aInstance; };
69,986,883
69,988,323
Adding value to variables in array
I am creating a menu program in which user chooses a drink like tea or coffee. The essence of the program is that the user can choose drinks in the menu through the corresponding buttons (numbers 0, 1, 2, 3). The user can choose as much as he wants until he enters the number -1, which stops the program and gives the result where it should be highlighted: 1) How many drinks did he choose in total (quantity) 2) The amount of each drink selected by him ( that is, if he chose tea 2 times, then Tea should be allocated: 2 ) The problem is that I can't output the amount of each drink that user has selected. What I have tried: I initiated a string array called beverage and included the names of 4 drinks. After I created a while loop and used a sentinel of -1. Then I used an integer variable beverageCount[size] to store the overall amount of a precise drink/beverage relating them with mutual index choice, however it does not calculate the amount and shows me the wrong amount of each drink. I will attach my code: #include <iostream> #include <iomanip> using namespace std; int main() { const int size = 5; string beverage[size] = { "Coffee", "Tea", "Coke", "Orange Juice" }; int beverageCount[size]; int choice=0; int i = 0; int coffee = 0; int tea = 0; int coke = 0; int juice = 0; //cin>>choice; //cout<<beverage[choice]; while (choice != -1) { cout << "Please input the favorite beverage of person #1: Choose 0, 1, 2, or 3 from the\n"; cout << "above menu or -1 to exit the program \n"; cin >> choice; while (choice > 3 && choice != -1) { cout << "Invalid, only 1,2,3,4 or -1. Try again\n"; cin >> choice; } beverageCount[choice]=0; beverageCount[choice]++; ++i; if (choice == -1) { cout << "Number of beverages:" << i-1 << endl; cout << "Number of each beverage: " << beverage[0] << "\t" << beverageCount[0] << endl; for (i=0; i<4; i++) { cout<< beverage[i] << "\t" << beverageCount[i] << endl; } } } }
Here is my full solution with lots of refactoring and cleanup: #include <iostream> #include <iomanip> void processOrder( ) { const std::string beverage[] = { "Coffee", "Tea", "Coke", "Orange Juice" }; constexpr size_t numOfBeverageTypes { sizeof( beverage ) / sizeof( std::string ) }; int beverageCount[numOfBeverageTypes] { }; int choice { }; int totalBeverageCount { }; do { std::cout << "Please input the favorite beverage of person #1: Choose 0, 1, 2, or 3 from the " << "above menu or -1 to exit the program\n"; std::cin >> choice; while ( choice > 3 || choice < -1 ) { std::cout << "Invalid, only 0,1,2,3 or -1. Try again\n"; std::cin >> choice; } if ( choice == -1 ) { std::cout << "Number of beverages ordered: " << totalBeverageCount << '\n' << "Number of each beverage: \n"; for ( size_t idx = 0; idx < ( numOfBeverageTypes ); ++idx ) { std::cout << beverage[idx] << "\t" << beverageCount[idx] << std::endl; } } else { ++beverageCount[choice]; ++totalBeverageCount; } } while ( choice != -1 ); } int main() { processOrder( ); return 0; } Notice that I moved the code from main() to a function named processOrder(). Also, the do-while loop will do a better job compared to a while loop in this case.
69,987,018
69,987,225
error: conversion from 'double' to non-scalar type '' requested" struct in c++?
I want to change one of attribute in my simple struct. I can't change anything in main function. But the compiler giving me error about scalar type - what does it exactly mean and what do i wrong? #include <iostream> using namespace std; struct Number{ int a; double b; }; double zmiana(Number *number,double scale){ number->a*=scale; return number->a; } int main() { Number number1={2,3.14}; Number number2=zmiana(&number1,2.); cout<<&number2; return 0; } Expected output: 4 3.14
Here is the potential fix: #include <iostream> struct Number { int a; double b; }; double zmiana( Number* number, double scale ) { number->a *= scale; return number->a; } int main() { Number number1 = { 2, 3.14 }; Number number2; number2.b = zmiana( &number1, 2. ); std::cout << &number2; // Notice that what you do here is printing a pointer's value return 0; }
69,988,150
69,999,847
seekg after reading to the end of the file
I'm trying to use the code below on the ifstream twice - before I read anything from the file, and after I read to the end of it (using readline()). m_hexFile->m_ifsteam->seekg(0, m_hexFile->m_ifsteam->ios_base::end); test1 = m_hexFile->m_ifsteam->tellg(); m_hexFile->m_ifsteam->clear(); m_hexFile->m_ifsteam->seekg(m_hexFile->m_startPosition); test1 = m_hexFile->m_ifsteam->tellg(); (m_startPosition is some poisition in the middle of the file. It is not important for this issue.) On the first run, the code works as expected. Then when I run it the second time, the value of the variable test1 is -1, even after using clear(). I looked through the similar questions, and all of the solutions said to use function clear() (which I already do).
Solution was to check elsewhere. I had closed the stream somewhere else in the program. Using the code above on a closed stream ofcourse wont work.
69,988,354
69,988,534
Binary Search Tree using std::unique ptr
I'm trying to implement a Binary Search Tree using smart pointers and I've read that the recommended way to implement it is by using unique_ptr since a parent owns the child and there are no multiple owners in a binary search tree. Take this tree for example, 10 4 20 2 5 11 30 3 here 4 is left child of 10 and 2 is left child of 4 and 3 is right child of 2 and so on. Now the struct looks like, template<typename T> struct TreeNode { T data; std::unique_ptr<TreeNode<T>> left, right; }; there's a unique_ptr<TreeNode<T>> root pointing to the root. Now if I'm understanding it correctly unique_ptr's can't be copied or assigned and they have unique ownership of the object. So if I want to traverse the tree I can't do something like initialize a std::unique_ptr<TreeNode<T>> temp to the root and traverse every node from there since it'll throw an error once I try to set the root which is a unique_ptr to the temp. So do I need to use a raw pointer of type TreeNode* to traverse the tree and perform operations? is it good or safe to do so? For all my operations on this tree then will I have to use raw pointers? Another problem is with deleting a node. If I say want to delete node with the value 3. If I initialize a raw pointer of type TreeNode* temp and arrive at Treenode 3. Then if I call delete(temp) what will happen? A unique_ptr from TreeNode 2 is pointing at TreeNode 3. What will happen to this pointer?
Then if I call delete(temp) what will happen? The TreeNode will be destroyed. Note that delete doesn't need parentheses A unique_ptr from TreeNode 2 is pointing at TreeNode 3. What will happen to this pointer? The pointer becomes invalid, and it is undefined behaviour for the unique_ptr object to be destroyed, as it will attempt to delete an invalid pointer. So do I need to use a raw pointer of type TreeNode* to traverse the tree and perform operations? is it good or safe to do so? For all my operations on this tree then will I have to use raw pointers? You can have a reference (or pointer) to a std::unique_ptr, you don't need to copy it. Rather than delete a raw pointer, you can call the reset member function of the unique_ptr to free the pointed-to TreeNode
69,988,586
69,988,818
C++ unable cout salary from method
Entry point is int main() so I try summon pwr.GetSalary to cout outside string "Salary" and double value, however program does not print out anything. So it is base class. class Employee { public: std::string FirstName; std::string LastName; std::string Patronymic; double Salary; Employee() {}; explicit Employee(std::string FirstName, std::string LastName, std::string Patronymic, double Salary) : FirstName(FirstName), LastName(LastName), Patronymic(Patronymic), Salary(Salary) {} bool operator==(Employee other) const { if (this->FirstName == other.FirstName && this->LastName == other.LastName && this->Patronymic == other.Patronymic) return true; else return false; } }; An daughter class that inherits base class... Here is wonderful method that shall count a salary and print it out... class Papersworker : public Employee { private: std::string FirstName; std::string LastName; std::string Patronymic; double Salary; public: Papersworker() {}; using Employee::Employee; const std::string Job = "Papersworker"; std::map<std::string, double> Coefficient = { {"Director", 4.2}, {"Papersworker", 1.2}, {"Guardian", 1.5}, {"Programmer", 2.5} }; void ChangeCoefficient(std::string Job, double NewCoefficient) { Coefficient[Job] = NewCoefficient; } void ChangeNameSalary(std::string FirstName, std::string LastName, std::string Patronymic, double Salary) { this->FirstName = FirstName; this->LastName = LastName; this->Patronymic = Patronymic; this->Salary = Salary; } void PrintPapersworker() { std::cout << "First name\t" << "Lastname\t" << "Patronymic\t" << "Salary\n" << this->FirstName << "\t\t" << this->LastName << "\t" << this->Patronymic << "\t" << this->Salary << "\n" << std::flush; for (const auto& i : this->Coefficient) { std::cout << i.first << " = " << i.second << ";\t" << std::flush; } std::cout << "\n------------------------------------------------------------\n" << std::flush; } double GetSalary(double Salary, std::string Job) { return Salary * this->Coefficient[Job]; } }; Wonderful int main()'s part. int main() { Papersworker pwr; double sr = 0.0; std::cout << "\nEnter director's salary\t" << std::flush; std::cin >> sr; std::cout << "\nSalary\t" << pwr.GetSalary(sr, "Director"); return 0; } If you see a some bad and need optimization don't mind to reply. ._. I do not understand what is going on there in matter of classes building tricks. https://pastebin.com/p7HXaX80 P. S. My homework forces to use private FirstName,LastName,Patronymic,salary... P. S. S. However, I use Visual Studio 2022 Preview with newest C++ nowadays. https://imgur.com/a/N8cDK3n
program does not print out anything Your program(pastebin link you gave) compiles successfully and prints continuously if you change _getch() to getch() as can be seen here. But for some reason it goes on forever. Since the link that you gave have around 500 lines of code i didn't take a look as to why the condition is not breaking(or if the program has any undefined behavior). Maybe you can narrow down the problem and edit your question again.
69,988,841
69,988,918
Getting Python output in real-time from C++/boost::process
From a C++ program (running under Windows 10), I use boost::process to invoke Python in order to interpret a simple Python script. I want to redirect Python script's output in real-time to my C++ program's console. My problem is that I'm getting the whole Python script output at once when the program completed, I'm not getting it in real-time. Here is my MCVE: Python script (script.py): import time from datetime import datetime print( "Started Python script at t=" + str(datetime.now().time()) ) time.sleep(1) print( "Slept 1 sec, t=" + str(datetime.now().time()) ) time.sleep(1) print( "Slept 1 sec, t=" + str(datetime.now().time()) ) print( "Stopped Python script at t=" + str(datetime.now().time()) ) C++ program (main.cpp): #include <boost/process.hpp> #include <ctime> #include <iostream> #include <chrono> namespace bp = boost::process; std::ostream &operator<<(std::ostream &stream, const std::chrono::system_clock::time_point& time_point) { const auto time {std::chrono::system_clock::to_time_t (time_point)}; const auto localtime {*std::localtime (&time)}; const auto time_since_epoch {time_point.time_since_epoch()}; const auto milliseconds_count {std::chrono::duration_cast<std::chrono::milliseconds> (time_since_epoch).count() % 1000}; stream << "[" << std::put_time (&localtime, "%T") << "." << std::setw (3) << std::setfill ('0') << milliseconds_count << "] - "; return stream; } int main( int argc, char* argv[] ) { std::cout << std::chrono::system_clock::now() << "Creating child" << std::endl; bp::ipstream stream; bp::child c("python.exe", "script.py", bp::std_out > stream); std::cout << std::chrono::system_clock::now() << "Created child" << std::endl; std::cout << std::chrono::system_clock::now() << "Invoking getline" << std::endl; std::string line; while (getline(stream, line)) { std::cout << std::chrono::system_clock::now() << "From Python output: " << line << std::endl; } std::cout << std::chrono::system_clock::now() << "getline ended" << std::endl; c.wait(); return 0; } This program outputs: [12:50:34.684] - Creating child [12:50:34.706] - Created child [12:50:34.708] - Invoking getline [12:50:36.743] - From Python output: Started Python script at t=12:50:34.742105 [12:50:36.745] - From Python output: Slept 1 sec, t=12:50:35.743111 [12:50:36.745] - From Python output: Slept 1 sec, t=12:50:36.743328 [12:50:36.746] - From Python output: Stopped Python script at t=12:50:36.743328 [12:50:36.747] - getline ended As you can see, we get the whole 4 outputs after Python process ended (first call to getline freezes for 2 seconds - while Python runs the two time.sleep(1) - and then within 3ms we get the whole 4 lines). I would expect to get something like: [12:50:34.684] - Creating child [12:50:34.706] - Created child [12:50:34.708] - Invoking getline [12:50:34.XXX] - From Python output: Started Python script at t=12:50:34.742105 [12:50:35.XXX] - From Python output: Slept 1 sec, t=12:50:35.743111 [12:50:36.XXX] - From Python output: Slept 1 sec, t=12:50:36.743328 [12:50:36.XXX] - From Python output: Stopped Python script at t=12:50:36.743328 [12:50:36.XXX] - getline ended I suspect the problem comes more from boost::process than from Python, but all the examples I could find for boost::process are reading std::cout the same way. Is there any thing I should change to have the getline loop run in real-time while Python prints output?
Python streams are (like C streams or C++ ones) buffered (for performance reasons). You may want to use some flush method in your Python code. And your question could be operating system specific. For Linux, be also aware of fsync(2) and termios(3) (and pipe(7) and fifo(7)...). For other operating systems, read their documentation.
69,988,956
69,989,001
void(os << args). What does void mean in this context?
I was reading about folding expressions and found an example of what was used before folding expressions: template <class... Ts> void print_all(std::ostream& os, Ts const&... args) { using expander = int[]; (void)expander{0, (void(os << args), 0)... }; } The problem is the void(os << args) bit. What does void mean in this context? I've already tried to search for this, but it is pretty generic. Thanks for your time.
It casts the result of (os << args) to void. That's it. This style is used to prevent the very rare overload of ,(comma) operator since in theory, << can be overloaded for user-defined args argument and return something that has overloaded the comma operator for X, 0 expression. That might break the initialization trick. This way, the code is safe and comma is always used as the ordinary sequencing operator.
69,989,439
69,989,491
Replacing a pair of characters in a string with another
I want to replace a pair of characters with another pair. For example if want to replace "ax" with "57" and the string is "vksax", it will give out "vks57". Tried it this way but get a weird output that is only partially correct: #include <stdio.h> #include <stdlib.h> int main() { char dummy; int i; char string[16]; scanf("%s", string); for(i=0;string[i];i++){ if(string[i] == 'a' && string[i+1] == 'x'){ string[i] = '5' ; string[i+1] = '7'; i=0; } printf("%s", string) ; } exit(0); } I can't figure out why it gives, for example, with an input of 1234ax the output 1234ax1234ax1234ax1234ax123457123457123457123457123457123457
Within the for loop for(i=0;string[i];i++){ if(string[i] == 'a' && string[i+1] == 'x'){ string[i] = '5' ; string[i+1] = '7'; i=0; } this statement i=0; does not make a sense. Remove it. And instead of string[i+1] = '7'; write string[++i] = '7'; And move this call printf("%s", string) ; outside the for loop. Pay attention to that the variable dummy is declared but not used. char dummy; Remove this declaration. And there is no great sense to use exit( 0 ); instead of return 0;. And the call of scanf will be more safer if to write it like scanf("%15s", string);
69,991,400
69,991,735
ReportEvent: Logged messages run all lines together
I'm noticing that when logging a multi-line message using ReportEvent, it drops all line ends and runs the text together. For example, my MC file may have: MessageId= Severity=Informational SymbolicName=MSG_TEST_MSG Language=English Some text Another line of text. Last line of text. . The message in Event Viewer shows all three lines run together. If I put \r\n sequences in the text in insertion strings, those line ends do show up correctly in the logged message. Also, if I use FormatMessageW to generate the text string of the above message, the line ends are correctly included in the text. They seem to be removed only when posting to Event Viewer. I have not seen ANY reference to the fact that line ends are being dropped anywhere. Any idea? Is this just the way it is? Thanks.
You have to use %n to force a "hard line break" inside the message. Source: %n Generates a hard line break when it occurs at the end of a line. This can be used with FormatMessage to ensure that the message fits a certain width. "Why does Format­Message say that %0 terminates the message without a trailing newline? Is it secretly adding newlines?" might also be interesting in this context.
69,991,935
69,992,768
Need help correcting Homework code, C++ input/output
I'm in my first intro to Comp Sci course. The assignment I have is inputting a .txt file and then outputting a revised .txt file. The first problems I had was just with fixing the directories. I did and everything came out fine with the .txt files, except the professor says I have an error in the switch statement. #include <fstream> #include <iostream> using namespace std; int main() { int s = -2, a = 0, b = 0, NumIn; ifstream inFile("NumbersIn.txt"); if (inFile.fail()) { cout << "Unable to open file" << endl; return -1; } ofstream outFile("RevisedNumbers.txt"); while (!inFile.eof()) { inFile >> NumIn; cout << NumIn << endl; if (NumIn < 0) NumIn = -1; else if (NumIn > 0) NumIn = 1; outFile << NumIn << endl; switch (NumIn) { case -1: a += s; break; case 0: s += 1; case 1: b += s; } } outFile.close(); inFile.close(); cout << "A = " << a << endl; cout << "B = " << b << endl; cout << "S = " << s << endl; return 0; } Output: 0 -2 9 14 -22 12 6 -9 12 13 -33 21 9 0 1 2 3 4 1 A = -4 B = -9 S = 0 Program ended with exit code: 0 I'm including the assignment question here, so the reason why I used s, a, and b as integers: You program will require the following files Input file: NumbersIn.txt (attached to this assignment) Output file: RevisedNumbers.txt You program will use the following variables: int s=-2, a = 0, b = 0. NumIn; As long as there is data in the input file, your program will read a number into the variable NumIn, print it on the screen, and then determine the following: If NumIn is negative change it to -1 If NumIn is positive change it to +1 If NumIn is zero, do nothing Write the new value of NumIn to the output file RevisedNumbers After updating NumIN, use a switch statement to based on the current value of NumIn When NumIn is -1 increase the value of A by S When NumIn is 0 increment S by 1 When NumIn is 1 increase the value of B by S When you no longer have data to read in print out the current value of A, B and S. Submit a copy of your program. The screen output The input file. The output file.
Your version: switch (NumIn) { case -1: a += s; break; case 0: s += 1; case 1: b += s; } To fix it, add two break statements: switch (NumIn) { case -1: a += s; break; case 0: s += 1; break; case 1: b += s; break; } Without them, case 0 falls through to case 1. It's actually legal to do that, but considered a common bug, so you should ALWAYS make a comment if your fall-through is intentional. I presume this time it isn't.
69,992,199
69,992,368
Why can't the overload operator<() implement the comparison function?
I was looking at this. The author first defined operator<() in my_data and said "everything is normal". After adding a member variable, he said "operator<() does not really implement a comparison operation". I want to know what is the difference between the two and why the former is wrong? struct my_data { std::string key; std::string value; //first bool operator<(const my_data data)const { return key < data.key; } }; //second struct Compare { bool operator()(const my_data& l, const my_data& r) const { return l.key < r.key; } }; from there
With struct my_data { std::string key; std::string value; //first bool operator<(const my_data data)const { return key < data.key; } }; std::set<my_data> data; You can use the class with a std::set, but your operator < isn't using all of the object, it is just comparing a single field. That is what the author of the video is complaining about. They take issue that it only compares one field of the object, and not the whole state of the object. By switching to struct my_data { std::string key; std::string value; }; struct Compare { bool operator()(const my_data& l, const my_data& r) const { return l.key < r.key; } }; std::set<my_data, Compare> data; There is no longer a "lying" operator <, but instead a custom comparator that compares just what you want.
69,992,395
69,994,428
Error while trying to use the boost::variant - "No matching function for call"
I'm continuously getting errors saying "No matching call for function" while using boost::variant. Below is my code snippet. struct Output { int a; float b; } typedef boost::variant<ClassA<X, Y>, ClassA<>> ClassAGeneric; class Operation: public boost::static_visitor<Output> { public: double d; int a; float b; Output operator()(ClassA<X, Y> obj) const { obj.operate(d, a, b); return (Output) {a, b}; } Output operator()(ClassA<> obj) const { obj.operate(d, a, b); return (Output) {a, b}; } }; I'm getting this error in the obj.operate() call in the first operator() that is defined. I tried the passing the templates as well like mentioned in the other answer, but I still see an error. obj.operate<X,Y>(d,a,b); Could somebody help me with this? I could give the exact scenario as well here : struct Output{ Row<size_t> predictions; mat probabilities; }; typedef boost::variant<RandomForest<GiniGain, RandomDimensionSelect>, RandomForest<>> RandomForestGeneric; class Operation: public boost::static_visitor<Output> { public: mat dataset; Row<size_t> predictions; mat probabilities; Output operator()(RandomForest<GiniGain, RandomDimensionSelect> obj) const { obj.Classify(dataset, predictions, probabilities); return (Output) {predictions, probabilities}; } Output operator()(RandomForest<> obj) const { obj.Classify(dataset, predictions, probabilities); return (Output) {predictions, probabilities}; } };
Here's my imagined self-contained tester: Live On Coliru #include <boost/variant.hpp> #include <iostream> struct X; struct Y; template <typename... T> struct ClassA { void operate(double d, int a, float b) const { std::cout << __PRETTY_FUNCTION__ << "(" << d << "," << a << "," << b << ")\n"; } }; struct Output { int a; float b; }; typedef boost::variant<ClassA<X, Y>, ClassA<>> ClassAGeneric; class Operation // : public boost::static_visitor<Output> { public: double d; int a; float b; Output operator()(ClassA<X, Y> const& obj) const { obj.operate(d, a, b); return Output{a, b}; } Output operator()(ClassA<> const& obj) const { obj.operate(d, a, b); return Output{a, b}; } }; int main() { Operation op {3.14, 42, 9e-2f}; ClassAGeneric v1 = ClassA<X,Y>{}; ClassAGeneric v2 = ClassA<>{}; apply_visitor(op, v1); apply_visitor(op, v2); } Prints void ClassA::operate(double, int, float) const with T = {X, Y} void ClassA::operate(double, int, float) const with T = {} Unsurprisingly that works. Now, one pitfall could be when you failed to make the operate member function const and the arguments are, in fact, const. Also note that you can greatly simplify the visitor (especially assuming C++14): Live On Coliru
69,992,398
69,993,534
How to get complete SID from the SidStart member in a pointer that points to an ACCESS_ALLOWED_ACE structure?
Starting with a string variable containing a Security Descriptor String Format, I convert this string to a security descriptor (using ConvertStringSecurityDescriptorToSecurityDescriptorW function). This function gives me a "pointer" to a Security Descriptor (I put the pointer under quotation mark relative to this blog post). Next, I recover a pointer to the DACL of the pointed Security Descriptor using GetSecurityDescriptorDacl function. From this DACL, I store all the ACEs into a vector of pointers to ACCESS_ALLOWED_ACE structures. Finally in these structures, there is my targeted member (SidStart) that I want to use to get a "translation" of the SID (for example with Well-Known SIDs, I want to translate "S-1-1-0" to a final user readable string like "Everyone"). However, SidStart only gives the first DWORD of a trustee's SID. The remaining bytes of the SID are stored in contiguous memory after the SidStart member (as documentation said). Despite my researches over the Internet, I can't figure it out to get theses remaining bytes. Here is a minimum reproducible example in a C++ Console App: #include <iostream> #include <Windows.h> #include <sddl.h> #include <vector> using namespace std; int main() { LPCWSTR stringSecurityDescriptor = L"D:AI(D;OICI;DCLCDTSD;;;S-1-1-0)"; PSECURITY_DESCRIPTOR pSD; ConvertStringSecurityDescriptorToSecurityDescriptorW(stringSecurityDescriptor, SDDL_REVISION_1, &pSD, nullptr); PACL pDacl; BOOL bDaclPresent = SE_DACL_PRESENT; BOOL bDaclDefaulted = SE_DACL_DEFAULTED; GetSecurityDescriptorDacl(pSD, &bDaclPresent, &pDacl, &bDaclDefaulted); LPVOID pAce; ACCESS_ALLOWED_ACE* pAceBuffer; vector<ACCESS_ALLOWED_ACE*> pDaclAces; if (bDaclPresent) { for (int i = 0; i < pDacl->AceCount; i++) { GetAce(pDacl, i, &pAce); pAceBuffer = (ACCESS_ALLOWED_ACE*)pAce; pDaclAces.push_back(pAceBuffer); } } /* TODO : Get the SID of the ACEs */ } I'm relatively new in C++ programming (and in programming in general), particularly in winapi environment. Moreover, this is my first question on StackOverflow. So, I hope my question is clear, understandable and resolvable. I'm open to critics.
Thanks to @RbMm in the comment section of my question : use (PSID)&SidStart I've added this line to my project (by replacing the TODO section in the minimum reproducible example) in order to test it : PSID pSid = (PSID)&pDaclAces[0]->SidStart And then I converted it into a readable string by reusing and readapting this page with Microsoft documentation to my case, and all of it worked perfectly.
69,992,446
69,992,500
C++: location of localtime_s in GCC
Following the documentation and compiling with gcc-11.2.0 like so g++ -std=c++17 -pthread -O3 -flto -fPIC ... I am not able to use localtime_s in my program: #define __STDC_WANT_LIB_EXT1__ 1 #include <time.h> using SystemClock = std::chrono::system_clock; const auto in_time_t = SystemClock::to_time_t(SystemClock::now()); struct tm buf; localtime_s(&in_time_t, &buf); // error: there are no arguments to ‘localtime_s’ that depend on a template parameter, // so a declaration of ‘localtime_s’ must be available [-fpermissive] struct tm buf; std::localtime_s(&in_time_t, &buf); // error: ‘localtime_s’ is not a member of ‘std’; did you mean ‘localtime’? Am I doing something wrong or localtime_s is not available in GCC? Or it is only available for pure C programs (for example, compiled with gcc -std=c11)? Thank you very much for your help!
Many of the functions specified in the standard ending with _s were originally developed by Microsoft as alternates to functions ending in _r. On Linux systems, localtime_s is not defined but localtime_r is, and has the same parameters/return type, so use that instead.
69,993,346
69,993,648
Does Boost (or another library) offer a way to lift the name of a "constructor-less" class into a function object that uses aggregate initialization?
This is kind of a follow up to this question, where I asked how I could tersely turn a template and/or overloaded function into a function object. The accepted answer was you can't do without macro, which is correct. Then I found that such a macro is offered by Boost, in the form of the BOOST_HOF_LIFT and BOOST_HOF_LIFT_CLASS macros. It turns out, however, that there are other "named things" you can't pass around. I don't know all of them, but one of them is constructors. And Boost.Hof offers a way to lift them to, via boost::hof::construct. The point is that not even boost::hof::construct can deal with a class without a user-declared constructor. For intance, given struct Foo { int foo; }; the call boost::hof::construct<Foo>()(3) simply doesn't work. (Adding the constructor Foo(int) {} in Foo makes it work; that's what boost::hof::construct is for, after all.) Surely, in simple cases like the one above I could just write auto makeFoo = [](int x){ return Foo{x}; }; but if I want to support any type, I have to take care of perfect forwarding and variadic arguments. Is there a library offering this feature already? It doesn't look like Boost.Hof does...
If you want a function object that constructs an object of some type T given some parameters, even if T is an aggregate, that's not difficult to write in C++17: template<typename T> struct lifted_construct { template<typename ...Args> T operator() (Args&& ...args) { if constexpr(std::is_aggregate_v<T>) { return T{std::forward<Args>(args)...}; } else { return T(std::forward<Args>(args)...); } } }; Of course, in C++20, you can use () syntax even for aggregates.
69,993,470
69,993,940
C++ conversion operator for base type in templated wrapper
I'm trying to write a wrapper template class that allows conversion as if the templated type was used. I'm not sure how to write the template code to make this functional. See the code below: class Base { } class Derived : public Base { } template <typename ObjectT> class Wrapper { ... // Implicit conversion to base types template <class T, typename = std::enable_if_t<std::is_base_of<T, ObjectT>::value>> operator Wrapper<T>() const { return Wrapper<T>(data); }; // Explicit conversion required for other types that are convertable template <class T, typename = std::enable_if_t< std::is_convertible<ObjectT, T>::value>> explicit operator Wrapper<T>() const { return Wrapper<T>(data); }; } I would like to use Wrapper like this: Wrapper<Base> wrapper = Wrapper<Derived>(); // Implicit conversion to base Wrapper<float> wrapper = (Wrapper<float>)Wrapper<int>(); // float int requires explicit conversion, but is allowed As of right now, this code gives me a compiler error since std::is_convertible<ObjectT, T> is also true for Base, Derived and thus creates the template function twice creating an ambiguous function member function already defined or declared
Try this: template <typename ObjectT> struct Wrapper { // Implicit conversion to base types template <class T, std::enable_if_t<std::is_base_of_v<T, ObjectT>>* = nullptr> operator Wrapper<T>() const; // Explicit conversion required for other types that are convertable template <class T, std::enable_if_t< !std::is_base_of_v<T, ObjectT> && std::is_convertible_v<ObjectT, T>>* = nullptr> explicit operator Wrapper<T>() const; }; Demo.
69,993,580
69,993,936
Need help to correct my one way selection code
Why when i enter totalprice>50 (42 pens & above), it wont execute the if statement? Can someone help me? This is my code: #include <iostream> using namespace std; int main() { int numbersOfPen; float totalPrice, total; cout<<"Enter numbers of pen:"; cin>>numbersOfPen; totalPrice = 1.20 * numbersOfPen; if (totalPrice > 50) { totalPrice = totalPrice - (totalPrice * (30/100)); } cout<<"Total price is RM"<<totalPrice; return 0; }
Adding a debug statement shows that the if statement is, indeed, executed. However, the 30/100, as @1201ProgramAlarm pointed out, evaluates to 0. In C++, dividing two integers yields another integer, so 30/100 would round down to 0. That means nothing is subtracted so it seems like the if statement never runs. To fix this, rather than typing 30/100, just use a float literal: 0.3f. Putting it all together: totalPrice = totalPrice - (totalPrice * 0.3f); (As a side note, there is a shorthand way of typing the same statement as above using the -= operator) totalPrice -= totalPrice * 0.3f;
69,993,657
69,994,014
Why doesn't gcc emit a format warning?
#include <stdio.h> void a(signed char a) { printf("%u\n", a); } void b(short b) { printf("%u\n", b); } void c(int c) { printf("%u\n", c); } void d(long d) { printf("%u\n", d); } void e(long long e) { printf("%u\n", e); } int main() { a(-1); //no warning b(-1); //no warning c(-1); //no warning d(-1); //warning e(-1); //warning return 0; } Compiled and tested with gcc 11.2.0 using gcc -std=c17 -pedantic -Wall -Wextra test.c and g++ -std=c++17 -pedantic -Wall -Wextra test.cpp. Both don't give any warning to a(), b(), and c(). Is this intended, or a bug?
Short answer: C warnings are a mystery. Use -Wformat-signedness if you want warnings here. Note that -Wformat-signedness requires -Wformat, which is already enabled by -Wall. Apparently, the compiler only checks for sign mismatches when -Wformat-signedness is used. -Wall and -Wextra don't include -Wformat-signedness. I don't know why this is. Someone said it's because it would result in too many warnings, but that tells me it really needs to be used if it's such a common error! So, all that's being checked are size mismatches. The two that warn (d and e) warn because a value of a type that's potentially larger than int is being passed. As for the other two, signed char and short int values are promoted to int values when passed to variadric (...) functions like printf, so a and b are equivalent to c.
69,993,920
69,994,161
Unable to get time form the NTP server in esp8266, arduino
I know I am successfully connected to the network as it's visible in my phone's hotspot. However I am unable to get the time using <Time.h> library through NTP server. Thanks in advance. I will really appreciate your suggestions. platformio.int board_build.f_cpu = 160000000L platform = espressif8266 board = nodemcuv2 framework = arduino lib_deps = paulstoffregen/Time@^1.6 Arduino code #include <Arduino.h> #include <ESP8266WiFi.h> #include <Time.h> #include "WifiCtrl.h" // Wifi setup WifiCtrl WifiControl; void setup() { // Starting serial monitor service // ---------------------------------------------- Serial.begin(9600); // This address the function which is for wifi setup WifiControl.setWifi(); // Load time from the NTP server... time_t now; // Serial.println("Setting time using SNTP"); configTime(5 * 3600, 1800, "pool.ntp.org", "time.nist.gov"); now = time(nullptr); struct tm timeinfo; gmtime_r(&now, &timeinfo); Serial.print("Current time: "); Serial.print(asctime(&timeinfo)); } void loop() {}
You must wait sometime before printing the time data. Hope this work for you #include <Arduino.h> #include <ESP8266WiFi.h> #include <Time.h> void setup() { // Starting serial monitor service // ---------------------------------------------- Serial.begin(9600); // Load time from the NTP server... time_t now; // Serial.println("Setting time using SNTP"); configTime(5 * 3600, 1800, "pool.ntp.org", "time.nist.gov"); now = time(nullptr); // create some delay before printing while (now < 1510592825) { delay(500); Serial.print("."); time(&now); } struct tm *timeCur; timeCur = localtime(&now); // Printing time.. Serial.println(timeCur->tm_hour); Serial.println(timeCur->tm_min); Serial.println(timeCur->tm_sec); } void loop() {}
69,994,082
69,994,133
Find the product of elements located between the maximum and minimum elements of an array
#include <iostream> using namespace std; int main() { int n, a, b,min,max, Prod = 1, Sum = 0; cout << "Initialize an array n: "; cin >> n; do { cout << "Input the start value: "; cin >> a; cout << "Input the end value: "; cin >> b; if (!(a < b)) { cout << "a is bigger than b, please enter new values " << endl; continue; } } while (!(a < b)); int* lpi_arr; lpi_arr = new int[n]; srand(time(NULL)); cout << "Int numbers from " << a << " to " << b << endl; for (int i = 0; i < n; i++) { lpi_arr[i] = rand() % (b - a) + a; cout << lpi_arr[i] << " "; } max = lpi_arr[0]; for (int i = 0; i < n; i++) { if (max < lpi_arr[i]) max = lpi_arr[i]; } min = lpi_arr[0]; for (int i = 0; i < n; i++) { if (min > lpi_arr[i]) min = lpi_arr[i]; } cout << "\nmin element is = " << min << endl; cout << "\nmax element is = " << max << endl; for (int i = max + 1; i < min; i++) Prod *= lpi_arr[i]; for (int i = 0; lpi_arr[i] < 0 && i < n; i++) Sum += lpi_arr[i]; cout << "Summ =" << Sum << endl << "Prod = " << Prod << endl; delete[] lpi_arr; } The main purpose of this code is to calculate the sum of negative numbers of an array, and multiplication of elements located between the maximum and minimum elements of an array. The problem is that the code implements only 1(one) as an answer, and I don't know how to change it. Every other part of the code works well, but if you have any recommendations I'd also like to read it. Waiting for your help.
Your issue is that you're confusing array indexes with array values. Here you're assigning max (and same with min) to an array value. max = lpi_arr[i]; Here you're treating max (and same with min) as an array index. for (int i = max + 1; i < min; i++) Prod *= lpi_arr[i];
69,994,299
69,994,338
terminate called after throwing an instance of 'std::out_of_range' (never seen this error)
I am kinda new to programming and have never seen this kind of error, so if someone can help me it would be appreciated. I tried to use string for numbers to compare digits to one another, but got this error and I guess it doesn't work :D #include <iostream> #include <fstream> #include <string> using namespace std; int main() { int n; fstream f("telef.txt"); f >> n; string numeriai; for (int i=0; i<n; i++) { f >> numeriai; bool nice = false; int length = numeriai.length(); for (int j=0; j<length; j++) { char ch = numeriai.at(j); char chh = numeriai.at(j+1); if (ch > chh) { nice = true; } else { nice = false; break; } } if (nice = true) { cout << numeriai << endl; } for (int k=0; k<length; k++) { char ch = numeriai.at(k); char chh = numeriai.at(k+1); if (ch == chh) { nice = true; } else { nice = false; break; } } if (nice = true) { cout << numeriai << endl; } } }
Let's assume you have a length of 10. That means your loop will loop until j = 9 for (int j=0; j<length; j++) At that point, what happens with the following? char ch = numeriai.at(j); char chh = numeriai.at(j+1); ch gets the value of the last character in the string (at index 9), but chh tries to read one past the last character. This results in your out of range error. You probably want to loop one less time to account for this: for (int j = 0; j < length - 1; j++) Also note that if (ch > chh) { nice = true; } else { nice = false; break; } can be cleaned up to be nice = ch > chh; if(!nice) { break; }
69,994,602
69,995,270
ESP32 not updating the variable when multiple cores are used
My plan is to collect data from ESP32's CORE-1 and use ESP32's CORE-0 for all other tasks. However, I see that the variables are not updated properly when multiple cores are used. Here in this example, I see that the value of getAllData is updated only once. const TickType_t xDelay = 1000 / portTICK_PERIOD_MS; TaskHandle_t collectData; bool volatile getAllData; bool volatile dataReadyToSend; void setup() { Serial.begin(115200); Serial.print("setup() is running on core "); Serial.println(xPortGetCoreID()); xTaskCreatePinnedToCore(collectDataCode,"collectData",10000,NULL,1,&collectData,0); delay(500); } void loop() { if (Serial.available()) { Serial.flush(); getAllData = true; } Serial.print("From loop: "); Serial.println(getAllData); if (dataReadyToSend) { dataReadyToSend = false; } delay(1000); } void collectDataCode(void * params) { while (1) { Serial.print("From collectData: "); Serial.println(getAllData); if (getAllData) { getAllData=0; } vTaskDelay( xDelay ); } } Output of the above code is given below. Where I typed xxx. It is observed that the variable getAllData got updated at this instance, but not changing later. From collectData: 0 From loop: 0 From collectData: 0 From loop: 0 From collectData: 0 From loop: 0 From collectData: 0 From loop: 0 From collectData: 0 xxx From loop: 1 From collectData: 1 From loop: 1 From collectData: 1 From loop: 1 From collectData: 1 From loop: 1 From collectData: 1 UPDATE Upon suggestions, I used atomic with the following code. Still I see no success. #ifdef __cplusplus #include <atomic> using namespace std; #else #include <stdatomic.h> #endif TaskHandle_t collectData; atomic<bool> getAllData; atomic<bool> dataReadyToSend; #include "collectData.h" void setup() { Serial.begin(115200); Serial.print("setup() is running on core "); Serial.println(xPortGetCoreID()); xTaskCreatePinnedToCore(collectDataCode,"collectData",10000,NULL,1,&collectData,0); delay(500); } void loop() { if (Serial.available()) { Serial.flush(); atomic_store (&getAllData, true); } Serial.print("From loop: "); Serial.println(atomic_load(&getAllData)); if (dataReadyToSend) { dataReadyToSend = false; } delay(1000); } void collectDataCode(void * params) { while (1) { Serial.print("From collectData: "); Serial.println(atomic_load(&getAllData)); if (atomic_load(&getAllData)) { atomic_store (&getAllData, false); } vTaskDelay( xDelay ); } }
I found the answer. The problem is not with the variable itself, it is with the Arduino's Serial.flush(). From the version 1.0, arduino is using Serial.flush() to clear the outgoing serial data not the incoming serial data. So, I replaced the Serial.flush() with the following code. while(Serial.available()) { Serial.read(); } With this update, my code is working good. Thanks to the comment of @PeteBecker, I am using atomic. The final code and results are given below. #ifdef __cplusplus #include <atomic> using namespace std; #else #include <stdatomic.h> #endif TaskHandle_t collectData; atomic<bool> getAllData; atomic<bool> dataReadyToSend; #include "collectData.h" void setup() { Serial.begin(115200); Serial.print("setup() is running on core "); Serial.println(xPortGetCoreID()); xTaskCreatePinnedToCore(collectDataCode,"collectData",10000,NULL,1,&collectData,0); delay(500); } void loop() { if (Serial.available()) { while(Serial.available()) { Serial.read(); } getAllData.store(true); Serial.println("Received data request"); } Serial.print("From loop: "); Serial.println(getAllData.load()); if (dataReadyToSend) { dataReadyToSend = false; } delay(1000); } void collectDataCode(void * params) { while (1) { Serial.print("From collectData: "); Serial.println(atomic_load(&getAllData)); if (getAllData.load()) { getAllData.store(false); } vTaskDelay( xDelay ); } } Results From loop: 0 From collectData: 0 From loop: 0 From collectData: 0 From loop: 0 From collectData: 0 . From loop: 0 From collectData: 0 Received data request From loop: 1 From collectData: 1 From loop: 0 From collectData: 0 From loop: 0 From collectData: 0 From loop: 0 From collectData: 0 From loop: 0 From collectData: 0 From loop: 0
69,995,190
69,995,448
How to Embed DirectShow Video Player to SDL Window
I'm trying to play a Video File using DirectShow library in a SDL Window, I use the library provided from Microsoft Docs and works fine when I try build it separately, but the code from main.cpp needs create a apart window in HWND to work and I want to use it in a existent SDL_Window. Code from main.cpp HWND hwnd = CreateWindowEx(0, CLASS_NAME, L"DirectShow Playback", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL); My code SDL_SysWMinfo info; SDL_VERSION(&info.version); SDL_GetWindowWMInfo(g_window, &info); HWND hwnd = GetWindow(info.info.win.window, GWL_WNDPROC); I already have SDL_Window* g_window, SDL_Renderer* g_renderer and SDL_Thread* video_tid but seems not work with HWND hwnd Also, if I got it successfully then I will change ShowWindow(hwnd, nCmdShow);? Here the complete code: TUserFunc(void, PlayVideo, HINSTANCE hInstance, HINSTANCE, PWSTR pCmdLine, int nCmdShow, bool testvideo) { // Register the window class. const wchar_t CLASS_NAME[] = L"Sample Window Class"; WNDCLASS wc = { }; wc.lpfnWndProc = WindowProc; wc.hInstance = hInstance; wc.lpszClassName = CLASS_NAME; RegisterClass(&wc); SDL_SysWMinfo info; SDL_VERSION(&info.version); SDL_GetWindowWMInfo(g_window, &info); HWND hwnd = GetWindow(info.info.win.window, GWL_WNDPROC); if (hwnd == NULL) { NotifyError(NULL, L"CreateWindowEx failed."); } ShowWindow(hwnd, nCmdShow); // Run the message loop. MSG msg = { }; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } } PD: When I use the HWND hwnd of main.cpp the video plays but in a hidden window and the SDL window keeps completely frozen
DirectShow video renderers have support for so called "windowless mode" which you can utilize: Using Windowless Mode Windowless mode avoids these problems by having the VMR draw directly on the application window's client area, using DirectDraw to clip the video rectangle. Old Windows SDK offers related samlpes (e.g. vmr9/windowless).
69,996,050
70,013,300
Why does the "use of local variable with automatic storage from containing function" error message exist?
I have a C++ language/compiler design curiosity question. I'm using gcc 11.2.0, -std=gnu++17 on Cygwin. Why is it an error to directly reference local variables in structures? Lambda functions do this all the time, and they are basically no different from structures containing the operator() method. As an example: static inline void language_complaint( void ) // Grumble, grumble, grumble { printf("\nlanguage_complaint...\n"); // Given that this compiles and runs... int foo= 22; printf("foo: %p->%d\n", &foo, foo); std::function bar= [=](void) { printf("foo: %p->%d\n", &foo, foo); }; bar(); #if true // And so does this... struct named { int const foo; named(int foo) : foo(foo) {} // Use constructor to copy local variable void operator()(void) { printf("foo: %p->%d\n", &foo, foo); } } one(foo); one(); bar= one; // ...And even this, which causes wild stores if improperly used... struct name2 { int& foo; name2(int& foo) : foo(foo) {} // Use constructor to reference local variable void operator()(void) { *foo= 42; printf("foo: %p->%d\n", &foo, foo); } } two(foo); two(); bar= two; printf("foo: %p->%d\n", &foo, foo); #else // Why, then, is this disallowed? struct { int /* const */ bar= foo; // Error: Can't access local variable with auto storage // int const foo= ::foo; // Error: Can't find ::foo. (Probably irrelevant) void operator()(void) { printf("bar: %p->%d\n", &bar, bar); } } one; one(); #endif } This was an attempt to demonstrate a use case as part of the problem description. Instead it obfuscates the question. I'm leaving it, though, so that the critical comments below make sense. The only justification I can think of is this: When copying automatic variables for later use, it is easy to step on your own toes, no matter what method you use. I know, my toes are still sore. But it seems like the language/compiler designers are trying to save you from yourself but only where plain structures are concerned, not for lambda functions or constructor initialized structures. Examples: This compiles because the int a is static: static int a= 'a'; // (Implicitly included in following examples) static inline std::function<void(void)> ok1(void) { struct { int b= a; void operator()(void) { printf("a: %p->%d, b: %p->%d\n", &a, a, &b, b); } } ret; return ret; } This compiles because lambda functions can freely access automatic data: static inline std::function<void(void)> ok2(void) { int b= a; // Copy static "a" into automatic (stack) "b" return [b](void) { (void)b; /* ignore b */ }; } This doesn't compile because it contains an assignment from stack data: static inline std::function<void(void)> ng1(void) { int b= a; struct { int c= b; void operator()(void) { /* ignore c */ }} ret; ^^^^^^^^^ The error-generating statement return ret; } But you can access automatic variables using some extra coding: static inline std::function<void(void)> ok3(void) { int b= a; struct X { int c; X(int p) : c(p) {} // Equivalent to c= b; void operator()(void) { /* ignore c */ } } ret(b); return ret; } Let's test: static inline void test(void) { std::function<void(void)> f= ok1(); f(); // a: 0x100402010->97, b: 0xffffcbb0->97 a= 'b'; f= ok1(); f(); // a: 0x100402010->98, b: 0xffffcbb0->98 a= 'c'; f(); // a: 0x100402010->99, b: 0xffffcbb0->98 } The compiler specifically tests for and disallows automatic variable assignment for no apparent reason. Is there one? What does the user, compiler, or anyone or anything else gain from this restriction?
All of the cases that work specifically involve you passing an expression to a constructor. Even the lambda version requires you to spell out the variables you intend to capture (or to use a default capture). This effectively counts as a way to specify the lambda's constructor (which is why you can't default construct capturing lambdas). In C++, a local class is basically convenience notation. The local class declaration and the definitions within it are scoped as if it were defined just before the containing function's definition. As such, it has no access to any function-local names, including those of local variables.
69,996,512
69,996,647
Error trying to average the elements of a linked list
I want to calculate the average of elements from a linked list: .h class List { public: List() { head = NULL; } void insertNode(int);//inserare nod la sfarsitul unei liste void printList();//afisare lista void deleteNode(int); void medie(float); .cpp void List::medie(float) { int count = 0; int sum = 0; int media = 0; Node* temp3 = head; while (temp3 != NULL) { count++; sum += temp3->val; temp3 = temp3->next; } media = (double)sum / count; return media; } I received this error: return value type doesn't match the function type I don't know how to repair it.
The function is declared with the return type void void medie(float); So it means that it returns nothing. However within the function definition there is a return statement with a non-void expression. return media; So the compiler issues an error message. Also the function parameter is not used within the function. Its declaration does not make a sense. In this statement media = (double)sum / count; there is no great sense to cast the variable sum to the type double because the result is assigned to the variable media having the type int. The function should be declared the following way double medie() const; and defined like double List::medie() const { double sum = 0.0; size_t count = 0; for ( const Node *temp = head; temp != nullptr; temp = temp->next ) { sum += temp->val; ++count; } return count == 0 ? 0.0 : sum / count; }
69,996,737
69,996,777
C++ string returning as "
I am trying to write a function that reverses a string. I've figured out most of the code, and when I print the string to std::cout, it's showing what I need. But, when I test the code, the result is that I got " from the function. Here's my code: #include <iostream> #include <string> using namespace std; string result; string reverseString (string str) { for(int i = str.length(); i >= -1; i--) { result+= str[i]; } cout << result; return result; }
In this for loop, in the very first iteration: for(int i = str.length(); i >= -1; i--) { result+= str[i]; } The terminating zero character '\0' is being written in the first position of the object result, because the expression str[i] is equivalent in this case to the expression str[str.length()]. So, the result string is outputted as an empty string. Also, you are trying to access the source string using the negative index -1, which results in undefined behavior. Instead of this for loop, you could just write: result.assign( str.rbegin(), str.rend() ); If you want to do the task using the for loop, then the loop can look like the following: result.clear(); result.reserve( str.length() ); for ( auto i = str.length(); i != 0; ) { result += str[--i]; } Pay attention to that, it is a bad idea to use the global variable result within the function. The function could look like: std::string reverseString( const std::string &str ) { return { str.rbegin(), str.rend() }; }
69,997,027
69,997,155
How to pass a second parameter in overload to std::visit?
I'm trying to pass a std::shared_ptr<std::jthread> as a parameter in this lambda, but getting an error with this std::visit. It works fine if I leave out the second parameter in the overload. The error can be seen here. https://coliru.stacked-crooked.com/a/95b62272fa49335d #include <iostream> #include <memory> #include <string> #include <thread> #include <variant> template<class... Ts> struct overload : Ts... { using Ts::operator()...; }; template<class... Ts> overload(Ts...) -> overload<Ts...>; class ObjA { int a; }; class ObjB { int b; }; int main() { ObjA a; std::variant<ObjA, ObjB> v; v = a; int rc { 0 };// unused here std::shared_ptr<std::jthread> sp = nullptr; std::visit(overload { [&rc](ObjA& objA, std::shared_ptr<std::jthread> thr) { std::cout << "ObjA!\n"; }, [&rc](ObjB& objB, std::shared_ptr<std::jthread> thr) { std::cout << "ObjB!\n"; } }, v); return 0; }
You've passed a callable to std::visit that accepts two arguments. However, the number of arguments of the callable has to match the number of variants provided to std::visit. That is, std::visit(c, v) will only compile if c takes one argument, and std::visit(c, v1, v2) will only compile if c takes two arguments, and so on. This is because std::visit works by calling c with one argument for each variant, whose type is the type currently contained in the corresponding variant. I'm not sure exactly what you're trying to do in your code, since in your example, most of the variables are unused. Perhaps your problem can be solved by capturing a std::shared_ptr<std::jthread> object in the lambdas, so that only one argument (the ObjA&/ObjB&) needs to be passed to the call operator.
69,997,130
69,997,322
C++: is it possible to make thread_local variable global?
For example, I have a thread_local variable in my code, but there are a set of functions, which access and modify it. For modularity, I took out them to a different translation unit (correct me if I'm wrong on terminology), by creating a header with their declarations and source file with their definitions. // fun.h int fun(); // fun.cpp #include "fun.h" int fun() { // Modify the thread_local variable here } // main.cpp #include "fun.h" thread_local int var = 0; int main() { // Modify the var in the main var = 1; // Modify the var by calling the fun() from fun.h fun(); } What to do? How to access it from fun()? Isn't there a contradiction that global variables are common for all the threads of the process, but thread_local is local?
The variable var is already global. "Global" refers to the scope of the variable: it means it is declared in the outermost namespace, so its use is not restricted to a particular block, class, or sub-namespace. So a variable can be both global and thread-local without any contradiction. All you're asking for is how to allow this global, thread-local variable to be accessed by other translation units. Well, one obvious solution is to declare fun as int fun(int& var), so in main.cpp you would call it as fun(var) instead of just fun(). If you do that, you might not need a global variable, and your code will be easier to reason about. But I'm going to assume you have a good reason why you can't do that. If that's the case, you should provide a declaration of the variable in fun.h: extern thread_local int var; Now every translation unit that includes fun.h is made aware of the existence of a global variable named var, which is of type int and has thread-local storage duration. It is assumed that one translation unit, somewhere in the program, will provide a definition of var, and all other translation units are just referring to that variable. (Since it's a thread-local variable, this single definition creates a set of objects: one per thread.) In your case, that definition, thread_local int var = 0;, is in main.cpp.
69,997,248
70,003,838
Initialising a vector with anoter vector, returned from a function
I'm attempting to create a vector called mems which is declared using the returned vector from my myMembers() function. For some reason when I use the line: vector<string> mems = myMembers(); It returns an error: terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_M_construct null not valid This error doesn't appear at compilation, but instead it appears once the program reaches this line of code. I've been researching for a few hours on what to do to fix it, but I'm really not sure. The code that I've written so far is as follows: vector<string> Person::myMembers(){ fstream file; file.open("myFile.txt"); string myLine; vector<string> mems; while(getline(myFile, myLine)){ vector<string> myLine = split(myLine, ','); mems.push_back(myLine.at(0)); for (int i = 5; i < myLine.size(); i++){ mems.push_back(myLine.at(i)); } } return mems; } The above function will get the name at index 0, and the list of names from index 5 to n. It will then place these names into a vector called mems, and return it. (I should make you aware that split is a function I've written which will simply split a line by a specified delimiter, and then put it into a vector). Then, later in my code, I create a new vector, called mems, and set it equal to the output of myMembers() vector<string> mems = myMembers() I know that it's the above line of code that's causing the error, but I don't know why, or how to fix it. Any help would be greatly appreciated. Thanks for your time :) Edit Upon mention that the error might be a part of the splitString, please find the code for my SplitString function below: vector<string> split(string myString, char delimiter){ string temp = 0; vector<string> splitString; for (int i = 0; i < myString.size(); i++){ if (myString[i] != delimiter){ temp += myString[i]; } else { splitString.push_back(temp); } } return splitString; }
I've discovered the issue for the program. The split() function was causing the error, because temp was initialised as string temp = 0; which meant it was trying to initialise a string with an integer value. The correct code for the split() function is as follows: ector<string> split(string myString, char delimiter){ string temp = ""; vector<string> splitString; for (int i = 0; i < myString.size(); i++){ string temp = ""; if (myString[i] != delimiter){ temp += myString[i]; } else { splitString.push_back(temp); } } return splitString; } This then lets the split() function return a non-null string, and allows the program to run as it should.
69,997,471
69,997,498
Why is this pointer 8 bytes?
I am learning C++, and read that when an array is passed into a function it decays into a pointer. I wanted to play around with this and wrote the following function: void size_print(int a[]){ cout << sizeof(a)/sizeof(a[0]) << endl; cout << "a ->: " << sizeof(a) << endl; cout << "a[0] ->" << sizeof(a[0]) << endl; } I tried inputting an array with three elements, let's say int test_array[3] = {1, 2, 3}; With this input, I was expecting this function to print 1, as I thought a would be an integer pointer (4 bytes) and a[0] would also be 4 bytes. However, to my surprise the result is 2 and sizeof(a) = 8. I cannot figure out why a takes up 8 bytes, but a[0] takes up 4. Shouldn't they be the same?
Shouldn't they be the same? No. a is (meant to be) an array (but because it's a function argument, has been adjusted to a pointer to the 1st element), and as such, has the size of a pointer. Your machine seems to have 64 bit addresses, and thus, each address (and hence, each pointer) is 64 bits (8 bytes) long. a[0], on the other hand, is of the type that an element of that array has (an int), and that type has 32 bits (4 bytes) on your machine.
69,998,343
69,998,365
How to deal when two objects share the same address?
Background: I don't know a lot about memory location neither how zero size objects work, nor how to manipulate them. Since a base class subobject of a standard layout class type with no non-static data member have zero size ( source 1 ), I expect that in the following code struct B has a zero size base-class subobject struct A{}; struct B:A{}; int main(){A a; B b;} Both a and bobjects have a size of 1 byte, but in the draft its said ( source_2 ): The address of a non-bit-field subobject of zero size is the address of an unspecified byte of storage occupied by the complete object of that subobject. So the address of the base-class subobject is the addres of an unspecified byte occupied by b, but it only has 1 byte, so b and its base-class subobject share the same address? If I didn't miss anything and the conclusion is right, how zero size subobjects are handled when "pointered" to?
So the address of the base-class subobject is the addres of an unspecified byte occupied by b, but it only has 1 byte, so b and its base-class subobject share the same address? Yes. If I didn't miss anything and the conclusion is right, how zero size subobjects are handled when "pointered" to? The value of the pointer is the address of the (sub-)object. Same as (sub-)objects of non-zero size.
69,998,406
69,998,521
How to erase reverse_iterator correctly when erase and push_back happens?
I have a list container, which looks like: std::list<int> l = {1,2,3,4,5,6,7,8}; i often erase elements, so i choose std::list. but, i also want to find the elemnt in O(1), so i record the reverse_iterator. For Example: l.push_back(9); auto s = l.rbegin(); // record the iterator of 9, in order to erase it in the future fastly. cout << *s << endl; l.push_back(10); auto s2 = l.rbegin(); but when i erase like this: l.erase(std::next(s).base()); // s the iterator of 9, in my brain i want to erase 9, but actually, it erase 10. I have two questions: why i should use next? actually my *s can get the element, which is different with .end(). how can i make the erase happen in my previous saved iterator?
l.rbegin().base() == l.end(), which is not the position of the last element, but the end of the list. and push_back again won't affect this existing iterator, it is still pointing to the end of the list. Then std::next(l.rbegin()).base() == l.end() - 1, which now is pointing to the last element 10. So if you want to remember the position of the 9, you better use a normal iterator instead of a reverse one, or, use a reverse iteractor whose base pointing to 9, and that should be auto s = std::next(l.rbegin()), and erase it as l.erase(s.base()). the rule is &*r == &*(i-1)
69,998,774
69,998,934
How to check if a variable can be written into a stream
I'm developing a tool class with C++14, which allows developers to print all kinds of objects easily. For the std::map object, I try to develop such a function: template<typename M, typename = std::enable_if_t< std::is_same<M, std::map<typename M::key_type, typename M::mapped_type>>::value || std::is_same<M, std::unordered_map<typename M::key_type, typename M::mapped_type>>::value>> std::string map2String(const M& mp) { std::stringstream res; for (const auto& element : mp) { res << element.first << "," << element.second << "|"; } return res.str(); } It works as expected. (BTW, C++11 is acceptable too, I can use the way of C++11 to replace std::enable_if_t.) However, as you see the std::stringstream has been used, which means that M::key_type and M::mapped_type must be streamed. But I don't know how to check if they are streamed. I need something like this: std::enable_if_t<is_streamable<typename M::key_type>>::value But there is no is_streamable in the Standard Library. If there is no is_streamable, is there any other way to make a compile-time error for those types which can't be written into a stream while invoking my function?
Here's a simple way to make your own type trait in C++14: #include <type_traits> #include <utility> namespace is_streamable_impl { template <typename T, typename Enable = void> struct check : public std::false_type {}; template <typename T> struct check<T, std::enable_if_t<std::is_same< decltype(std::declval<std::ostream&>() << std::declval<T>()), std::ostream&>::value>> : public std::true_type {}; } template <typename T> struct is_streamable : public std::integral_constant<bool, check<T>::value> {}; This trait checks that os << val is a valid lvalue expression of type std::ostream, given an lvalue expression os of type std::ostream and an expression val with type and value category related to T. Other variations on the exact requirements could be written too. The definition of is_streamable_impl::check above might actually be good enough as the trait directly. But it does allow someone to misuse it as check<bad_type, void>::value == true. You could just call that a bad usage and not worry about it; or this pattern here makes sure the extra template parameter is hidden away. For your sample use, I'd actually check is_streamable<const typename M::key_type&>. That will probably will have the same result as just the direct key_type, but it's more precise for strange cases where it could matter.
69,999,004
69,999,052
C++ Simple Menu Program; difficulty finding middle character of user input
this is only my second time posting here so I hope I am doing this correctly. I need to have the user input a string (usrinput) of any length and make a selection 1 - 4. I have completed 2, 3, and 4, but I cannot figure out how to do selection 1. if the user enters a string "This is a Test" and selects option 1, if odd I need to find the middle letter. if even instead of displaying the middle two letters, I need to let the user know that there is no middle. I feel like I have the function close to being correct, but I'm having a hard time understanding what it means. Any help is greatly appreciated, and I can try to elaborate further if necessary. #include <iostream> #include <iomanip> #include <string> using namespace std; int main() { string usrinput, upper, lower, str; int selection, middle, i; bool menu = true; cout << "=============================================================" << endl; cout << "Welcome to my program. Enter a sentence and make a selection: " << endl; cout << "Enter -999 to exit the program. " << endl; cout << "=============================================================" << endl; cout << "1. display middle character. " << endl; //if user selects 1, do "..." cout << "2. display sentence uppercase " << endl; //if user selects 2, do "..." cout << "3. display sentence lowercase" << endl; //if user selects 3, do "..." cout << "4. display sentence backwards" << endl; //if user selects 4, do "..." cout << "Enter a sentence: " << endl; getline(cin, usrinput); //sentence input while (menu == true) { cout << "Make a selection: " << endl; // if selection is 1 - 4 || -999 (good input) anything <1 or >5 (bad input, loop until selection = 1 - 4 cin >> selection; //Step 1. Input Validation while (selection != 1 && selection != 2 && selection != 3 && selection != 4 && selection != -999) //If the selection is not 1 - 4 || -999 loop until selection is valid. { cout << "Invalid Entry. Please make another selection: " << endl; cin >> selection; } if (selection == 1) // if the user enters 1: show middle character if there is one / let the user know there isn't one. { cout << "Middle: " << endl; cout << "=======" << endl; if (((i = usrinput.length() /2 % 2) == 1)) { cout << usrinput[i]; cout << endl; } else if (((i = usrinput.length() / 2) % 2) >= 1) { cout << "There is no middle"; cout << endl; } }
For your selection 1 if statement, all you need to do is check if the string evenly divides by 2 to determine if it is even or odd, no need to divide by 2. You also can just have an else statement right after the if which accounts for even numbers. if (((i = usrinput.length() % 2) == 1)) { i = usrinput.length()/2; cout << usrinput[i]; cout << endl; } else { cout << "There is no middle"; cout << endl; }
69,999,379
69,999,721
What does std::atomic::is_always_lock_free = true really mean?
I have the following code: #include <atomic> int main () { std::atomic<uint32_t> value(0); value.fetch_add(1, std::memory_order::relaxed); static_assert(std::atomic<uint32_t>::is_always_lock_free); return 0; } It compiles and so it means std::atomic<uint32_t>::is_always_lock_free is true. Then, the assembly code looks like this with gcc 10 and -std=c++20 -O3 -mtune=skylake-avx512 -march=skylake-avx512: 0000000000401050 <main>: 401050: c7 44 24 fc 00 00 00 mov DWORD PTR [rsp-0x4],0x0 401057: 00 401058: f0 ff 44 24 fc lock inc DWORD PTR [rsp-0x4] 40105d: 31 c0 xor eax,eax 40105f: c3 ret Many posts point out that read-modify-write operation (fetch_add() here) can't be an atomic operation without a lock. My question is what std::atomic::is_always_lock_free being true really means. This page states Equals true if this atomic type is always lock-free and false if it is never or sometimes lock-free. What does it mean by "this atomic type is always lock-free" then?
"Lock" here is in the sense of "mutex", not specifically in reference to the x86 instruction prefix named lock. A trivial and generic way to implement std::atomic<T> for arbitrary types T would be as a class containing a T member together with a std::mutex, which is locked and unlocked around every operation on the object (load, store, exchange, fetch_add, etc). Those operations can then be done in any old way, and need not use atomic machine instructions, because the lock protects them. This implementation would be not lock free. A downside of such an implementation, besides being slow in general, is that if two threads try to operate on the object at the same time, one of them will have to wait for the lock, which may actually block and cause it to be scheduled out for a while. Or, if a thread gets scheduled out while holding the lock, every other thread that wants to operate on the object will have to wait for the first thread to get scheduled back in and complete its work first. So it is desirable if the machine supports truly atomic operations on T: a single instruction or sequence that other threads cannot interfere with, and which will not block other threads if interrupted (or perhaps cannot be interrupted at all). If for some type T the library has been able to specialize std::atomic<T> with such an implementation, then that is what we mean by saying it is lock free. (It is just confusing on x86 because the atomic instructions used for such implementations are named lock. On other architectures they might be called something else, e.g. ARM64's ldxr/stxr exclusive load/store instructions.) The C++ standard allows for types to be "sometimes lock free": maybe it is not known at compile time whether std::atomic<T> will be lock-free, because it depends on special machine features that will be detected at runtime. It's even possible that some objects of type std::atomic<T> are lock-free and others are not. That's why atomic_is_lock_free is a function and not a constant. It checks whether this particular object is lock-free on this particular day. However, it might be the case for some implementations that certain types can be guaranteed, at compile time, to always be lock free. That's what is_always_lock_free is used to indicate, and note that it's a constexpr bool instead of a function.
69,999,608
69,999,811
Multiple undefined reference errors in hpp file
I am getting multiple undefined reference errors from zmq.hpp such as: `build-client-Desktop_Qt_5_15_2_GCC_64bit-Debug/../client/Headers/zmq.hpp:113: undefined reference to zmq_errno' and the others are zmq_strerror, zmq_msg_init etc. there are like 20 of them. I guess the hpp file can not find the zmq.h ? I added the headers also in .pro file in QT like: SOURCES += \ main.cpp RESOURCES += qml.qrc HEADERS += \ Headers/zmq.h \ Headers/zmq.hpp \ Headers/zmq_utils.h How am I going to link them? OS: Ubuntu 18.04
This is a linker error, you forgot to add library to your .pro file. The line looks like this LIBS +=lib_path/lib_name
70,000,253
70,000,413
Vector Resizing in C++ works only when adding cout statement?
vector<string> solution(vector<string> inputArray) { int n = inputArray.size(); vector<string> outputString(n); int maxSize, curPos = 0; for(auto &i: inputArray) { int currentSize = i.size(); if(currentSize > maxSize) { maxSize = currentSize; curPos = 0; outputString[curPos++] = i; }else if (currentSize == maxSize) { outputString[curPos++] = i; } } cout<<curPos; outputString.resize(curPos); return outputString; } In the original code without the cout line, the outputString resulted in an empty vector. But upon adding the cout line, the problem gets magically solved. What could be the reason behind this?
maxSize is uninitialised so your code has undefined behaviour. UB produces surprising results like printing something changes the behaviour of the program. By using reserve and then adding strings to the vector your code can be a lot simpler: vector<string> solution(const vector<string>& inputArray) { size_t n = inputArray.size(); vector<string> outputString; outputString.reserve(n) for(auto &i: inputArray) { int currentSize = i.size(); if(outputString.empty() || currentSize > outputString.front().size()) { outputString.clear(); outputString.push_back(i); }else if (currentSize == outputString.front().size()) { outputString.push_back(i); } } return outputString; }
70,000,596
70,000,667
Why are there key_type and value_type in std::set
After reading this link: https://en.cppreference.com/w/cpp/container/set, I just found that there were two defined types: key_type and value_type in the class std::set. It seems that they are exactly the same thing. Well, this may be a stupid question but I still want to ask why. Isn't one enough? Why are there two types?
All the stl containers have value_type, and all the associative containers (including std::set, std::map, std::multiset, std::multimap) and unordered associative containers (including std::unordered_set, std::unordered_map, std::unordered_multiset, std::unordered_multimap) have key_type, that means you can perform some general processing (with templates especially) on these containers with the member types.
70,000,687
70,001,246
custom qHash method is not being called
I'm using QPoint as a key in a QHash, and following the documentation, I implemented a global qHash method for QPoint like so: inline uint qHash(QPoint const &key, uint seed) { size_t hash = qHash(QPair<int, int>(key.x(), key.y()), seed); qDebug() << hash; return hash; } I'm using it like this class HashTest { public: QHash<QPoint, QColor> hash; void addPixel(QPoint pt, QColor color) { hash[pt] = color; } } The insert still happens correctly, but it's not using my qHash function. Even if I comment out the qHash function, it still inserts. Considering that QPoint is documented as not having a qHash function, is this expected behavior? EDIT: Minimal Reproducible Example #include <QDebug> #include <QGuiApplication> #include <QHash> #include <QPoint> #include <QQmlApplicationEngine> int main(int argc, char *argv[]) { #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif QHash<QPoint, int> hash; QPoint key = QPoint(0, 0); hash[key] = 3; qDebug() << hash[key]; // 3 }
qHash for QPoint might not be documented but sure is defined: Q_CORE_EXPORT size_t qHash(QPoint key, size_t seed = 0) noexcept;
70,000,828
70,000,962
Cannot call non-static function on a class object in a vector
I'm bulding my own Neural Network with my own Matrix class. I'm trying to use the swishMatrix() function on a Matrix2D class object, before adding it to a vector<Matrix2D> variable. But I get this error and I have no idea why. -> no matching function for call to 'std::vector<Matrix2D>::push_back(int)'| When I use the swishMatrix() on a normal Matrix2D object it works fine. Here's the Matrix2D class class Matrix2D{ public: int rows; int columns; vector<vector<float> > matrix; Matrix2D() = default; Matrix2D(int x, int y){ rows = x; columns = y; for (int i = 0; i < rows; i++) { vector<float> v1; for (int j = 0; j < columns; j++) { v1.push_back(0); } matrix.push_back(v1); } } swishMatrix(){ for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { matrix[i][j] = matrix[i][j] * sigmoid(matrix[i][j]); } } } //Here there's a lot of static functions for matrix operations }; Here's the Neural Network class class NeuralNewtork{ public: //A lot more declaration here but not important Matrix2D first_hidden_weights; Matrix2D input_nodes; vector<Matrix2D> hidden_weights; vector<Matrix2D> hidden_biases; vector<Matrix2D> activated_hidden_nodes; NeuralNewtork(int input_nodes, int hidden_layers, int hidden_nodes, int action_nodes){ first_hidden_weights = Matrix2D(numberof_hidden_nodes, numberof_input_nodes); first_hidden_weights.randomizeMatrix(); hidden_weights.reserve(numberof_hidden_layers-1); for (int i=0; i<numberof_hidden_layers-1; i++){ hidden_weights.push_back(Matrix2D(numberof_hidden_nodes, numberof_hidden_nodes)); hidden_weights.back().randomizeMatrix(); } hidden_biases.reserve(numberof_hidden_layers); for (int i=0; i<numberof_hidden_layers; i++){ hidden_biases.push_back(Matrix2D(numberof_hidden_nodes, 1)); hidden_biases.back().randomizeMatrix(); } //There are more declerations here but they aren't important for this problem } feedForward(Matrix2D input){ input_nodes = input; for(int i = 0; i < numberof_hidden_layers+1; i++){ if(i==0){ activated_hidden_nodes.push_back(Matrix2D::matrixAddition(Matrix2D::matrixMultiplication(first_hidden_weights, input_nodes), hidden_biases[0]).swishMatrix()); //This is the line where I get the error //no matching function for call to 'std::vector<Matrix2D>::push_back(int)'| } if(i!=0 && i!=numberof_hidden_layers){ activated_hidden_nodes.push_back(Matrix2D::matrixAddition(Matrix2D::matrixMultiplication(hidden_weights[i-1], activated_hidden_nodes[i-1]), hidden_biases[i]).swishMatrix()); //This is also a line where I get the error //no matching function for call to 'std::vector<Matrix2D>::push_back(int)'| } if(i==numberof_hidden_layers){ //Not important } } } I might have missed some part of the code, it was hard to keep short, but all the needed variables are correctly assigned.
The trivial fix is to make swishMatrix return the matrix object again: Matrix2D& swishMatrix(){ for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { matrix[i][j] = matrix[i][j] * sigmoid(matrix[i][j]); } } return *this; } Never ever write code again without explicit return types on your methods.
70,001,001
70,001,408
constexpr array vs deque, memory utilization
I need to store a pre-known size of about 30 integers in my code, I have gone for constexpr std::array<size_t, 30> MAPPING{1, 2, 3, ...}; If i am not wrong, the above will be evaluated at compile time, but it would also take up a single sequential block of memory of a size of 30 integers? If it does, is it worth using a std::deque instead const std::deque<int> MAPPING{1, 2, 3, ...}; This way, with a deque, we would not be using a single large sequential memory block and it might use a bunch of fragmented blocks instead and thus it will work fine even if the memory is fragmented? Please let me know if I have missed anything, thanks
It's not worth using std::deque here. It would also take up a single sequential block of memory of a size of 30 integers? Yes, it would take up a single sequential block of memory of a size of 30 integers in the stack This way, with a deque, we would not be using a single large sequential memory block and it might use a bunch of fragmented blocks instead and thus it will work fine even if the memory is fragmented? It's implementation-dependent, for 30 integers they may be split into several small blocks or may not, but it will use heap memory and thus has runtime overhead: As opposed to std::vector, the elements of a deque are not stored contiguously: typical implementations use a sequence of individually allocated fixed-size arrays, with additional bookkeeping, which means indexed access to deque must perform two pointers dereferences, compared to vector's indexed access which performs only one. According to @Homer512's comment, we also need to notice the memory fragmentation when using the heap, there may be memory waste and we can't avoid it.
70,001,881
70,001,997
How we have a return value of pop() function in JavaScript?
While I was recently studying JS coming from a C++ background, I found out that the pop() function of arrays has a return value in JS. Now, in C++ we don't have a return value for pop_back() method because according to a paper by Cargill, it is impossible to design an exception-safe stack pop function as answered here So how are things working in JS or am I missing something?
None of the "Exceptions Thrown by T" cases pop up in JavaScript, because there simply is no assignment or construction operator invoked. JavaScript is a garbage-collected language, so everything is a handle to the actual object. Calling pop just shrinks the array by one and returns the handle that was there without doing anything more. If you want to reason about it in terms of C++, everything is a std::shared_ptr<T>, so pop just move-constructs that to its return value, which is exception-free.
70,002,099
70,002,143
non type template parameter pack expansion
I simply would print out a non type template parameter pack. But I can't find a valid expansion if I want to have spaces in between the elements. Example: template < int ... N > struct X { static void Check() { // this will become std::cout << ( 1 << 2 ) << std::endl; -> prints "4" std::cout << "X" << (N << ...) << std::endl; // this will become: ((std::cout << 1 ) << 2 ) << std::endl; -> prints "12" (std::cout << ... << N) << std::endl; // this becomes: (( std::cout << " " << 1 ) << 2 ) -> prints " 12" (std::cout << " " << ... << N) << std::endl; // the following is not allowed (std::cout << ... << " " << N) << std::endl; // also this one is not compiling (std::cout << ... << N << " ") << std::endl; } }; int main() { X<1,2>::Check(); } Is there any chance to expand the parameter pack to print the elements with space in between without using a helper function?
With the use of a helper variable. std::size_t count{}; ((std::cout << (count++? " " : "") << N), ...);
70,002,208
70,002,670
is there any way to wakeup multiple threads at the same time in c/c++
well, actually, I'm not asking the threads must "line up" to work, but I just want to notify multiple threads. so I'm not looking for barrier. it's kind of like the condition_variable::notify_all(), but I don't want the threads wakeup one-by-one, which may cause starvation(also the potential problem in multiple semaphore post operation). it's kind of like: std::atomic_flag flag{ATOMIC_FLAG_INIT}; void example() { if (!flag.test_and_set()) { // this is the thread to do the job, and notify others do_something(); notify_others(); // this is what I'm looking for flag.clear(); } else { // this is the waiting thread wait_till_notification(); do_some_other_thing(); } } void runner() { std::vector<std::threads>; for (int i=0; i<10; ++i) { threads.emplace_back([]() { while(1) { example(); } }); } // ... } so how can I do this in c/c++ or maybe posix API? sorry, I didn't make this question clear enough, I'd add some more explaination. it's not thunder heard problem I'm talking about, and yes, it's the re-acquire-lock that bothers me, and I tried shared_mutex, there's still some problem. let me split the threads to 2 parts, 1 as leader thread, which do the writing job, the others as worker threads, which do the reading job. but actually they're all equal in programme, the leader thread is the thread that 1st got access to the job( you can take it as the shared buffer is underflowed for this thread). once the job is done, the other workers just need to be notified that them have the access. if the mutex is used here, any thread would block the others. to give an example: the main thread's job do_something() here is a read, and it block the main thread, thus the whole system is blocked. unfortunatly, shared_mutex won't solve this problem: void example() { if (!flag.test_and_set()) { // leader thread: lk.lock(); do_something(); lk.unlock(); flag.clear(); } else { // worker thread lk.shared_lock(); do_some_other_thing(); lk.shared_unlock(); } } // outer loop void looper() { std::vector<std::threads>; for (int i=0; i<10; ++i) { threads.emplace_back([]() { while(1) { example(); } }); } } in this code, if the leader job was done, and not much to do between this unlock and next lock (remember they're in a loop), it may get the lock again, leave the worker jobs not working, which is why I call it starve earlier. and to explain the blocking in do_something(), I don't want this part of job takes all my CPU time, even if the leader's job is not ready (no data arrive for read) and std::call_once may still not be the answer to this. because, as you can see, the workers must wait till the leader's job finished. to summarize, this is actually a one-producer-multi-consumer problem. but I want the consumers can do the job when the product is ready for them. and any can be the producer or consumer. if any but the 1st find the product has run out, the thread should be the producer, thus others are automatically consumer. but unfortunately, I'm not sure if this idea would work or not
it's kind of like the condition_variable::notify_all(), but I don't want the threads wakeup one-by-one, which may cause starvation In principle it's not waking up that is serialized, but re-acquiring the lock. You can avoid that by using std::condition_variable_any with a std::shared_lock - so long as nobody ever gets an exclusive lock on the std::shared_mutex. Alternatively, you can provide your own Lockable type. Note however that this won't magically allow you to concurrently run more threads than you have cores, or force the scheduler to start them all running in parallel. They'll just be marked as runnable and scheduled as normal - this only fixes the avoidable serialization in your own code.
70,003,240
70,003,390
Sorting numbers of an array in descending order
I have an array of 16 numbers that i need to sort in descending order, I tried sorting them this way but can't seem to make it work. Note : I have to program an algorithm so i can't use any special functions :( #include <stdio.h> #include <stdlib.h> int main() { int i, temp1, temp2; int string2[16] = { 0, 4, 2, 5, 1, 5, 6, 2, 6, 89, 21, 32, 31, 5, 32, 12 }; _Bool check = 1; while (check) { temp1 = string2[i]; temp2 = string2[i + 1]; if (temp1 < temp2) { string2[i + 1] = temp1; string2[i] = temp2; i = 0; } else { i++; if (i = 15) { check = !check; } } } return 0; } I realize that this is pretty basic stuff for most of you but any insight is much appreciated!
There're a few problems: _Bool is a strange thing to use in C++ (maybe this question intended for C?) You didn't initialize i. This is called an undefined behavior. This may or may not work, depends on the computer, but it's never good to have something like that in your program. (i=15) is an assignment. Use i==15 for comparison, as == is the comparison operator for "equal to". Reviewed code: #include <stdio.h> #include <stdlib.h> #include <iostream> int main() { int i = 0,temp1,temp2; //i should be initialized int string2[16] = {0,4,2,5,1,5,6,2,6,89,21,32,31,5,32,12}; bool check=1; while(check) { temp1=string2[i]; temp2=string2[i+1]; if(temp1<temp2) { string2[i+1]=temp1; string2[i]=temp2; i=0; } else { i++; if(i==15) { check=!check; } // = -> == } } //if this is intended for C, you can ignore this bit, or use printf for (int i = 0; i < 16; i++) { std::cout << string2[i] << " ";} } Output: 89 32 32 31 21 12 6 6 5 5 5 4 2 2 1 0 A few more aesthetic notes: If you use indentation (tabs and/or space), be consistent. Others may have a hard time understanding your code, although it doesn't matter when the program compile (to anyone questioning, this is before he re-indented the code). string2 is an irregular name of an int array. Again, it could cause confusion. A reading : https://1c-dn.com/library/rules_of_naming_variables/
70,003,416
70,003,561
How to pass a std::array to a function template which can accept std::vector
I'm trying to write a template, which can accept some sequence containers: template <typename S, typename = std::enable_if_t< std::is_same<S, std::array<typename S::value_type>, S::size()>::value || std::is_same<S, std::vector<typename S::value_type>>::value>> std::string arr2String(const S& seqContainer) { std::stringstream res; for (const auto& element : seqContainer) { res << element << "|"; } return res.str(); } However, this can't be compiled because of S::size(). Obviously, there is no such a thing. Is it possible to make such a template function, which can handle std::vector and std::array?
If you want to restrict your template to work for only std::array or std::vector, you can write some helper traits template <typename> struct is_array : std::false_type {} template <typename T, std::size_t N> struct is_array<std::array<T, N>> : std::true_type {} template <typename> struct is_vector : std::false_type {} template <typename... Ts> struct is_vector<std::vector<Ts...>> : std::true_type {} template <typename S, typename = std::enable_if_t< is_array<S>::value || is_vector<S>::value>> std::string arr2String(const S& seqContainer) { std::stringstream res; for (const auto& element : seqContainer) { res << element << "|"; } return res.str(); } Otherwise you can SFINAE on something more general template <typename S, typename = typename S::value_type> std::string arr2String(const S& seqContainer) { std::stringstream res; for (const auto& element : seqContainer) { res << element << "|"; } return res.str(); }
70,003,489
70,005,435
How to split set of vertices with Boost Graph?
I'm writing some algorithm in C++ for parallel graph coloring using Boost Graph and adjacency_list. I'm working with very big graph (the smallest has 32K vertices). What I'm trying to do is to take the whole set of vertices, split them in parts and assign each part to a different thread and work in parallel, but I'm struggling with some passages. The basic idea what this: int step = g.m_vertices.size()/4; int min = 0; for(int i = 0; i < 4; i++){ // call the function } And the function I call inside is something like that for (vp = vertices(g); vp.first != vp.second; ++vp.first) { cout << *vp.first << endl; } So I have two questions: g.m_vertices.size()/4; is the right solutions? If initially I have 10 vertices, then I remove some vertex in the middle (e.g. 4), only 6 vertices left (so this is the new size) but the index of the vertices go from 0 to 5 or from 0 to 9? How can pass only a subset of vertices to vp instead of passing vertices(g)?
g.m_vertices.size()/4; is the right solutions? That depends ONLY on your requirements. If initially I have 10 vertices, then I remove some vertex in the middle (e.g. 4), only 6 vertices left (so this is the new size) but the index of the vertices go from 0 to 5 or from 0 to 9? That depends on your graph model. You don't specify the type of your graph (I know, you do say which template, but not the template parameters). Assuming vecS for the Vertex container selector, then yes, after 4 removals, the vertex descriptors (and index) will be [0,6). How can pass only a subset of vertices to vp instead of passing vertices(g) Many ways. you can std::for_each with a parallel execution policy you can use openmp to create a parallel section from the plain loop you can use filtered_graph adapter to create 4 "views" of the underlying graph and operate on those you can use PBGL which is actually created for dealing with huge graphs. This has the added benefit that it works with threading/interprocess/inter-host communication, can coordinate algorithms across segments etc. you can use sub_graphs; this is mainly (only) interesting if the way your graphs get built have a natural segmentation None of the solutions are trivial. But, here's naive demo using filtered_graph: Live On Compiler Explorer #include <boost/graph/adjacency_list.hpp> #include <boost/graph/filtered_graph.hpp> #include <boost/graph/random.hpp> #include <iostream> #include <random> using G = boost::adjacency_list<>; using V = G::vertex_descriptor; G make_graph() { G g; std::mt19937 prng(std::random_device{}()); generate_random_graph(g, 32 * 1024 - (prng() % 37), 64 * 1024, prng); return g; } template <int NSegments, int Segment> struct SegmentVertices { std::hash<V> _h; bool operator()(V vd) const { return (_h(vd) % NSegments) == Segment; } }; template <int N> using Quart = boost::filtered_graph<G, boost::keep_all, SegmentVertices<4, N>>; template <typename Graph> void the_function(Graph const& g, std::string_view name) { std::cout << name << " " << size(boost::make_iterator_range(vertices(g))) << " vertices\n"; } int main() { G g = make_graph(); the_function(g, "full graph"); Quart<0> f0(g, {}, {}); Quart<1> f1(g, {}, {}); Quart<2> f2(g, {}, {}); Quart<3> f3(g, {}, {}); the_function(f0, "f0"); the_function(f1, "f1"); the_function(f2, "f2"); the_function(f3, "f3"); } Printing e.g. full graph 32766 vertices f0 8192 vertices f1 8192 vertices f2 8191 vertices f3 8191 vertices
70,003,507
70,007,119
Mac Link .h file to .cpp files
I'm a student and have just been introduced to modularity in cpp. I don't understand my mistake though. I have 3 files. One test.cpp /**\ * @file testFile.cpp * @author TomPlanche * @brief test file links \**/ // . Importation Des Bibliothèques Nécessaires. #include <iostream> #include "fraction.h" int main(void) { /**\ * @goal : test file links * @author : : T.Planche * @remarks : non \**/ // ! Déclaration Variables Fraction frac1 = {1, 2}; cout << frac1.denominateur << endl; return 0; } One fraction.cpp /**\ * @file fraction.cpp * @author TomPlanche * @brief Exercice TD2 R1.01/PT2 \**/ // ! Importation Des Bibliothèques Nécessaires. #include "fraction.h" // ! Définition Sous-Programmes int pgcd(int nb1, int nb2) { int min = (nb1 < nb2) ? nb1 : nb2; for (int i = min; i <= min; i--) { if ((nb1 % i == 0) && (nb2 % i == 0)) { return i; } } return 1; } Fraction simplifier(const Fraction fraction) { /**\ * @goal : simplifier une fraction * @author : : T.Planche * @remarks : aucune \**/ Fraction fractionFinale; int pgdcFraction; pgdcFraction = pgcd(fraction.numerateur, fraction.denominateur); fractionFinale.numerateur = fraction.numerateur / pgdcFraction; fractionFinale.denominateur = fraction.denominateur / pgdcFraction; return fractionFinale; } Fraction addition(Fraction frac1, Fraction frac2) { Fraction fractionResultat; if (frac1.denominateur == frac2.denominateur) { fractionResultat.denominateur = frac1.denominateur; fractionResultat.numerateur = frac1.numerateur + frac2.numerateur; } else { fractionResultat.denominateur = frac1.denominateur*frac2.denominateur; fractionResultat.numerateur = frac1.numerateur*frac2.denominateur + frac2.numerateur*frac1.denominateur; } return fractionResultat; } void afficherFraction(const Fraction fraction) { Fraction fractionSimplifiee = simplifier(fraction); cout << fractionSimplifiee.numerateur << "/" << fractionSimplifiee.denominateur << endl; } and one fraction.h #ifndef FRACTION_H #define FRACTION_H #include <iostream> using std::cout; using std::cin; using std::endl; struct Fraction { int numerateur; // Le signe est porté sur ce nombre unsigned int denominateur; // > 0 }; int pgcd(int nb1, int nb2); //! @goal : Retourne Le Pdcg De Deux Entiers Fraction simplifier(Fraction fraction); //! @goal : Simplifier Une Fraction Fraction addition(Fraction frac1, Fraction frac2); //! @goal : Additionner Deux Fractions Fraction soustraction(Fraction frac1, Fraction frac2); //! @goal : Soustraire Deux Fractions Fraction multiplication(Fraction frac1, Fraction frac2); //! @goal : Multiplier Deux Fractions Fraction division(Fraction frac1, Fraction frac2); //! @goal : Diviser Deux Fractions void afficherFraction(const Fraction fraction); //! @goal : Afficher Une Fraction #endif When I try to add just a Fraction frac1 = {1, 2}; it compiles. But when I try to afficherFraction I have cd "/Users/tom_planche_mbpm1/Desktop/BUT/R1.01-IntroDev/PT2/TD2/" && g++ testFile.cpp -o testFile && "/Users/tom_planche_mbpm1/Desktop/BUT/R1.01-IntroDev/PT2/TD2/"testFile Undefined symbols for architecture arm64: "simplifier(Fraction)", referenced from: _main in testFile-8df18c.o ld: symbol(s) not found for architecture arm64 clang: error: linker command failed with exit code 1 (use -v to see invocation) I'm on a MacBook Pro M1 on macOS Monterey (21C5031d) Thanks !
You build your executable with: g++ testFile.cpp -o testFile but you're forgetting the second source file. You can either do everything in one line: g++ testFile.cpp fraction.cpp -o testFile but with an eye on the future, when your program may become much larger, it's a better idea to use separate compilation: g++ -c testFile.cpp g++ -c fraction.cpp g++ testFile.o fraction.o -o testFile When you start using a build system (Make, Cmake) this is the way it will be done: compile only whatever file needs recompiling, and then link them together. Btw, it's a good idea to add a couple of compiler flags, such as -g -O2. The first one makes debugging possible in gdb and such, the second one says "make optimized code".
70,003,533
70,018,151
Multiple definition of variable First defined here error
I have this c++ project with classes' definitions inside .hpp files and methods' declarations inside .cpp files. The project uses a makefile to build and run. The program ran without errors before but LinkedList didn't work as I wanted so I re-wrote it entirely. Now LinkedList.hpp includes both the class definition and its methods' declarations. I adjusted the other classes' methods so that they use LinkedList correctly. Now when debugging the program I get this multiple definition of, first defined here error. find: ‘lib’: No such file or directory g++ -std=c++17 -Wall -Wextra -g -Iinclude -o output/main src/Game.o src/Hero.o src/Title.o src/Level.o src/Menu.o src/Entity.o src/Window.o src/main.o src/Map.o src/Object.o -lncurses /usr/bin/ld: src/Hero.o:/home/user/projects/project-X-githubClone/projectX/include/Object.hpp:2: multiple definition of `TileTypeStr'; src/Game.o:/home/user/projects/project-X-githubClone/projectX/include/Object.hpp:2: first defined here /usr/bin/ld: src/Level.o:/home/user/projects/project-X-githubClone/projectX/include/Object.hpp:2: multiple definition of `TileTypeStr'; src/Game.o:/home/user/projects/project-X-githubClone/projectX/include/Object.hpp:2: first defined here /usr/bin/ld: src/Entity.o:/home/user/projects/project-X-githubClone/projectX/include/Object.hpp:2: multiple definition of `TileTypeStr'; src/Game.o:/home/user/projects/project-X-githubClone/projectX/include/Object.hpp:2: first defined here /usr/bin/ld: src/Map.o:/home/user/projects/project-X-githubClone/projectX/include/Object.hpp:2: multiple definition of `TileTypeStr'; src/Game.o:/home/user/projects/project-X-githubClone/projectX/include/Object.hpp:2: first defined here collect2: error: ld returned 1 exit status make: *** [Makefile:74: main] Error 1 So if I get this correctly, the problem is the multiple definitions of const char* TileTypeStr[]. But why then when I change that array's name to, say, tts the error message still reads "multiple definitions of TileTypeStr"? and why if I comment out the only 2 references (including its declaration and initialisation) of this array inside the whole project the error message is still the same?
TileTypeStr[] was misplaced after all, moved it inside the toString() method I needed it for, then ran make clean to recompile all of the source files and make to build main.cpp. By running make and not recompiling the source files I was stuck running the bugged version of the program.
70,003,639
70,004,411
Using Address Sanitizer or other Undefined Behavior Sanitizers in Production?
In the past there have been concerns about using ASAN in production in certain environments: https://seclists.org/oss-sec/2016/q1/363 . The comment is from 2016 - what is the landscape like today? Is it recommendable to use the sanitizers here in a production system running on a user's device? The application receives untrusted input from other parties and processes these in various ways. Are there security relevant impacts from using them? Do any of the added instrumentations actually make it easier to remotely exploit a bug? The application I'm considering this for is open source, so easing reverse engineering would not be an issue for in this case.
Sanitizers are primarily meant to be used as debug, not hardening tools i.e. for error detection at verification stage but not error prevention in production. Otherwise they may leak sensitive info to the attacker (by printing details about address space and library version to stderr on error) or obtain local root privileges due to uncontrolled use of environment variables. Also sanitizers may add quite a bit of overhead (2x slowdowns are not uncommon for Asan, 1.5x for UBsan). In general sanitizers are sometimes used in production environment for A/B testing, to increase coverage and detect bugs which escaped normal QA. Clang has many options for hardening: fortification (-D_FORTIFY_SOURCE=2), ASLR (-fPIE), stack protection (-fstack-protector, -fsanitize=safe-stack) and control-flow integrity (-fsanitize=cfi) (see Clang Hardening Cheatsheet for details). They have a much smaller overhead and are specifically meant to be used in production. UPDATE (thanks to @cisnjxqu): UBsan supports the -fsanitize-minimal-runtime mode which provides minimalistic, low-overhead runtime library which is supposed to not increase the application attack surface.
70,003,749
70,004,083
Inheritance for class with the same name but different namespace c++
Is it possible to inherit from the class with the same name, but in different namespace and how to achieve it? For example I have the following structure: namespace general { namespace gui { struct GUI { }; }} can I do: namespace proxy { namespace gui { struct GUI : general::gui::GUI { }; }} Or / and there should be another way to doing this (short of actually naming the class / structure differently)? Update based on Pete's Becker comment. The current way it is structured is like that: gui.h #include "world.h" namespace general { namespace gui { struct GUI { }; }} world.h namespace general { namespace world { struct World {}; }} proxy.h namespace proxy { namespace gui { struct GUI : general::gui::GUI { }; }} My understanding is that compiler looks at world.h, doesn't find general::gui and complains with proxy.h(17,30): error C2039: 'gui': is not a member of 'general' world.h(4): message : see declaration of 'general' If I add namespace world { struct World {}; }} to gui.h or other way around, it will most probably work. Just was confused of why do I need to do it. Update2 (with .cpp files): world.cpp #include "world.h" namespace general { namespace world { World{ gui.cpp #include "gui.h" namespace general { namespace gui { proxy.cpp #include "proxy.h" namespace proxy { namespace gui { On the .cpp files side, all of them are just including their corresponding header files. This is the general rule. Plus here is the (relevant) header file chain, which most certainly where the problem is: goal.h includes world.h and proxy.h gui.h includes world.h and goal.h menu.h includes goal.h world.h - includes nothing proxy.h - includes nothing Update3: Fixed now by moving proxy.h into gui.h temporarily and in the process uncovering a dependency error. Will move the files back and just wanted to confirm that the issue was with the interdependencies of the .h files.
Yes, this is possible. If you are getting an error, there is something in your code you have not posted here, such as a using namespace statement. proxy::gui::GUI and general::gui::GUI are two entirely different classes. The fact that both end with GUI says nothing at all. The full/complete name of the class is always the full name including namespaces. That's the point of namespaces. They were invented to prevent name clashes between different libraries. Imagine you have library of vendor "A" which includes a class GUI. Imagine you want to use this library in your own code, where you also have defined a class GUI. Without namespaces these names would clash and you would be forced to rename your own class to use the library. But with namespaces all is good. A::GUI is something different than yourcode::GUI or just plain GUI. So namespace general { namespace gui { class GUI {}; }} namespace proxy { namespace gui { class GUI:public general::gui::GUI {}; }} will / should work. Update (after the .cpp has been posted) proxy.cpp includes proxy.h proxy.h refers to general::gui::GUI but general::gui is not visible to proxy.h. It has not been included. Neither proxy.cpp nor proxy.h "known" anything about a general or a general::gui. That is exactly what the compiler error message is saying. proxy.h(17,30): error C2039: 'gui': is not a member of 'general' The gui thing you are trying to access (in the inheritance) is not a member of a general thing -- at least not to proxy.cpp or proxy.h. These two files know only about a namespace proxy and a namespace gui. Nothing else. Hence the error. It is not enough to declare a namespace general or namespace gui in any header file. Header files don't do anything by themselves. Add a #include "gui.h" to your proxy.h and it should work. But beware of circular references. Read more about includes (and include guards) before continuing.
70,003,917
70,008,097
How to detect a connection failure in Indy TCP Client
I have made a client and a server using Indy TIdTCPClient and TIdTCPServer in C++Builder 11 Alexandria. I can start the server and connect the client to it correctly, but if I set the server MaxConnections to a value N and I try to connect to it with the N+1 client, the connection does not fail, apparently. For example: I set MaxConnections=1 in the server, the first client connects to it and the server OnConnect event is raised, while in the client OnStatus event I get two messages: message 1: Connecting to 10.0.0.16. message 2: Connected. I try to connect the second client: the server OnConnect event is NOT raised (and this is what I expect) but in the client OnStatus event I get the same two messages (and this is not what I expect): message 1: Connecting to 10.0.0.16. message 2: Connected. Then, the first client can exchange data with the server, and the second client can't (this seems right). I don't understand why the second client connection does not fail explicitly, am I doing something wrong?
You are not doing anything wrong. This is normal behavior for TIdTCPServer. There is no cross-platform socket API at the OS level 1 to limit the number of active/accepted connections on a TCP server socket, only to limit the number of pending connections in the server's backlog. That limit is handled by the TIdTCPServer::ListenQueue property, which is 15 by default (but this is more of a suggestion than a hard limit, the underlying socket stack can override this, if it wants to). As such, the TIdTCPServer::MaxConnections property is implemented by simply accepting any client from the backlog that attempts to connect, and then immediately disconnects that client if the MaxConnections limit is exceeded. So, if you try to connect more clients to TIdTCPServer than MaxConnections allows, those extra clients will not see any failure in connecting (unless the backlog fills up), but the server will not fire the OnConnect event for them. From the clients' perspectives, they actually did connect successfully, they were fully accepted by the server's underlying socket stack (the TCP 3way handshake is complete). However, they simply will not process the disconnect until they try to actually communicate with the server, then they will detect the disconnect, usually in the form of an EIdConnClosedGracefully exception (but that is not guaranteed). 1: on Windows only, there is a WSAAccept() function which has a callback that can reject pending connections before they leave the backlog queue. But Indy does not make use of this callback at this time.
70,004,520
70,004,942
Why is this not working? (Trying to convert a text file into a binary file)
#include<iostream> #include<fstream> #include<vector> #include<string> #include<algorithm> #include <sstream> #include<iomanip> using namespace std; const string binaryfile = ".../binaryfile.dat"; void to_binary(const string& filename) { ifstream ist(filename); ofstream ost(binaryfile, ios::binary); char ch; while (ist.get(ch)) { ost.write((char*)&ch, sizeof(char)); } } int main() { cout << "Enter input file name:\n"; string ifile; cin >> ifile; to_binary(ifile); } This seems like it should be working to me but it doesn't? I give input a path to some file on my desktop and then call the function but it's just writing the normal text? The file I'm giving as input contains this: test file idk what to put here but yeah Then I run this and binaryfile.dat gets the exact same text just normal text binaryfile.dat Does anyone know what I'm doing wrong? I open ost in binary mode, then get the address of each character I extract from ist, get 1 byte from it and write it to the binary file what's making this output normal text to it..? Edit : Tried this with an int and it worked I got what I expected: This is what I expected A file that obviously a human can't read why does it work with ints and not chars? This is the code I used: int main() { int a = 5; ofstream out("ItemData.dat", ios::binary); out.write((char*)&a, sizeof(int)); }
What exactly were you expecting to happen? There is no such thing as a binary file. It's just a file. A file is a series of bytes. Nothing more, nothing less. A text file is a file where each byte "means" a character. For example, the byte value 01000001 means the capital letter A. When you open a file in Notepad, Notepad reads the bytes and displays the corresponding letters. If it sees the byte value 01000001 it displays the capital letter A. Notepad has no idea whether the file "is a text file" or not. It just looks at the bytes and displays the letters. You can open any file in Notepad, such as an EXE file or a JPEG file, and whenever it happens to contain the byte value 01000001 it will display the capital letter A. Your code reads bytes from a file in text mode and writes them in binary mode. So it makes a copy of the same file... except for the difference between text mode and binary mode. So what is that difference? Well, the only difference is that text mode tries to "normalize" line endings. Windows has a tradition that the end of a line of text consists of bytes 00001101 and 00001010 in that order. C has a tradition that the end of a line of text is just the byte 00001010. Text mode does that conversion, so that you can read Windows text files in C. If the file has the byte value 00001010 without a 00001101 before it, most text editors still display it as a line ending, but until Windows 10, Notepad didn't display it as a line ending. Now Notepad does that too. So you won't see the difference in a text editor. You can see the difference in a hex editor program, which directly shows you the bytes in a file (in hexadecimal). I recommend HxD if you are using Windows. The main reason for opening binary files in binary mode is because if you open a binary file in text mode, the operating system will add or delete 00001101 bytes which will mess up your binary data. Opening the file in binary mode tells it to please not mess up your binary data.
70,004,605
70,004,722
the output array shows only the last element instead of inserting data at specified location in the array
#include <iostream> using namespace std; #define max 10 int main() { int items[max]; int i,n,ub,location,data; cout<<"Enter the number of items you want to enter: "<<endl; cin>>n; ub=n-1; if(ub>=max-1){ cout<<"Array is full!"<<endl; } else{ cout<<"Enter "<<n<<" elements:"<<endl; for(i=0;i<n;i++){ cin>>items[n]; } cout<<"Enter the location where you want to insert:"<<endl; cin>>location; cout<<"Enter the data you want to insert in location "<<location<<endl; cin>>data; while(ub>=location){ items[ub]=items[ub-1]; ub--; } items[location]=data; cout<<"The array after insertion is as follows: "<<endl; for(i=0;i<n;i++){ cout<<items[n]<<endl; } } } for an input array of n=5 being let's say {1 ,2 ,3 ,4 ,5 },i want to insert data=19 at location 2 of the array such that the output is {1, 19, 3, 4, 5} but the output i get is {5 ,5 ,5 ,5 ,5}. how can i fox this?
You have two issues: cin>>items[n]; must be cin>>items[i]; cout<<items[n]<<endl; must be cout<<items[i]<<endl;
70,005,258
70,026,630
Why does the function ID3D11DeviceContext::Map sometimes produce a mapped subresource with a different resolution to my texture?
When using the Map function on an existing render texture, in certain situations, the output RowPitch and DepthPitch are altered, producing a subtly different resolutions. For example, if the source texture (BGRA 8bit) has the resolution 1559x1080 with a bit depth of 4, the resulting D3D11_MAPPED_SUBRESOURCE has the resolution 1568x1080 (calculated by dividing the output RowPitch ( 6272 ) by BitDepth (4) ). However, if the source texture has the resolution 1568x1080, then the mapped sub-resource will have a RowPitch of 6272 as expected. While I can think of many reasons for this being altered (ie optimising for MipMap levels, fitting existing memory constraints), I would like to understand why and what the exact algorithm is for calculating the output RowPitch so that we can enforce rules for the source texture.
Based on your answer, I'm guessing you're running this on a somewhat modern x86-64 CPU. From some basic math on the values you gave, the algorithm appears to be the following for your PC: RowPitch = AlignUp((BytesPerTexel * TextureWidth), 64); Here, AlignUp rounds the first argument to the smallest value larger than or equal to the first argument cleanly divisible by the second argument. The value 64 is not arbitrary - it is either the size of a cache line on your CPU, or the maximum size of a single PCI transfer from the CPU to your GPU. Since the pointer returned by Map lives on the CPU, my guess is it's a match to the cache line size, in which case it could be different based on the exact CPU you're running on. As for the exact implementation details, you'd have to get a Microsoft engineer to chime in. Overall, however, this would seem to be the most likely explanation. In terms of solving the problem of texture sizes, the best option would actually be to just ignore it for the most part. D3D and the GPU will ignore data that falls outside the texture width, but within the row pitch. Just use the texture width as the write boundary, and the row pitch as an element size. It's worth noting that this happens automatically all the time - if you have a C array of structures, each of which has a size that's not divisible by their alignment, the compiler will insert padding between the structures to keep them all aligned. The same thing is happening here, but the compiler can't hide it from you.
70,005,578
70,005,868
Difference between std::string and const char*?
What's the difference between std::string and const char*? consider following example #include <iostream> #include <string> int main() { const char* myName1{ "Alex" }; std::cout << myName1 << '\n'; std::string myName2{ "Alex" }; std::cout << myName2 << '\n'; return 0; } are they the same?
std::string will give you the ability to use its member functions and most importantly to modify its contents. The initial data will likely1 be copied to a dynamically allocated memory location when the program reaches its constructor. It will also store its size. const char* is only a pointer value that points to a constant that is gonna be baked into the binary. There's no size information stored, and all functions operating on it have to rely on the presence of the '\0' value at the end. 1 It's possible that Small-String Optimization kicks in here.
70,005,580
70,005,726
How to iterate over the size of a parameter pack with a compile-time index parameter
I'm trying to write a variadic template function that includes a loop that iterates over each type in the parameter pack. I'm using this to build up a tuple which I then apply on the callback function which determined the template types. I thought I could do this using sizeof...(Args) as follows: template <typename ...Args> void addCallback(void* handle, std::string address, std::function<void(Args...)> callback) { return addMessageCallback(std::move(address), [callback](const ci::osc::Message& message) { std::tuple<Args...> args; for (size_t i = 0; i < sizeof...(Args); i++) { std::get<i>(args) = message.getArg<std::tuple_element_t<i, decltype(args)>(i); } std::apply(callback, std::move(args)); }); } This doesn't compile because std::get<i>(args) requires i to be a compile time constant. However, all the information is available at compile time. Is there a way to make this work? I've thought about using a fold expression but I'm using C++17.
You can define a helper function to use index_sequence to expand the elements of Tuple and assign values through fold expression. template<class Tuple, class Message, std::size_t... Is> void assign_tuple(Tuple& tuple, const Message& message, std::index_sequence<Is...>) { ((std::get<Is>(tuple) = message.getArg<std::tuple_element_t<Is, Tuple>(Is)), ...); }; template <typename ...Args> auto addCallback(void* handle, std::string address, std::function<void(Args...)> callback) { return addMessageCallback(std::move(address), [callback](const ci::osc::Message& message) { std::tuple<Args...> args; assign_tuple(args, message, std::make_index_sequence<sizeof...(Args)>{}); std::apply(callback, std::move(args)); }); } In C++20 you can just define template lambda inside the function to do this.
70,006,056
70,006,249
Pass a container type as the typename of a template in c++
I'm a beginner at templates in C++ and I would like to know if it's possible to pass a container to the typename of a template function, here is what I'm trying to do: template <typename T> int find_size(const T<int> t) { return (t.size()); } int main(void) { std::array<int, 10> test; for (int i = 0; i < 10; i++) { test[i] = i; } findsize(test); } When I'm compiling I get an error saying that T isn't a template. Is it possible to pass the template of a container to the template of a function?
With minimum changes to make it work, your code could be this: #include <array> template <typename T> int find_size(const T& t) { return (t.size()); } int main(void) { std::array<int, 10> test; for (int i = 0; i < 10; i++) { test[i] = i; } find_size(test); } basically I want my function to be able to take an abritary type of container Thats exactly what the above does. It works for any container type T that has a size(). If you actually want to parametrize find_size on a template rather than a type, then you can use a template template parameter: #include <array> template <template<class,std::size_t> class C> int find_size(const C<int,10>& t) { return (t.size()); } int main(void) { std::array<int, 10> test; for (int i = 0; i < 10; i++) { test[i] = i; } find_size<std::array>(test); } However, using this is either more complicated than illustrated here, or of more limited use than the above: For the function parameter you need a type not just a template, and this find_size will only work with a template C that has 2 parameters, one type and one non-type parameter of type size_t (and I am actually not aware of any other container but std::array with that template parameters). TL;DR: This is not a use case where a template template parameter is needed. Is it possible to pass the template of a container to the template of a function? Yes, but you don't need it here.
70,006,292
70,006,672
Put sin on segment in 3d
i need to put a sin function, or any other function on start of segment in 3d space. Something like that: Example But in 3d space, help me pls, i spent about 4 days for solving it, but did not get result There are 2 points in space at arbitrary positions. I need a sinusoid between these two arbitrary points. 3d segment example An example of the final result
Generate point set in OXY plane and apply affine transformation to make OX axis coincide with desired vector, also you need to define one normal vector to get sin plane unambiguously. Math for affine matrix calculation (here simpler because we can choose unit-length vectors)
70,006,664
70,006,785
C++ thread pool using boost::asio::thread_pool, why can't I reuse my threads?
I am experimenting with boost::asio::thread_pool to create a thread pool in my application. I created the following toy example to see if I understand how it works but clearly not :) #include <boost/asio/post.hpp> #include <boost/asio/thread_pool.hpp> #include <boost/bind.hpp> #include <iostream> boost::asio::thread_pool g_pool(10); void f(int i) { std::cout << i << "\n"; } int main() { for (size_t i = 0; i != 50; ++i) { boost::asio::post(g_pool, boost::bind(f, 10 * i)); g_pool.join(); } } The program outputs 0 I am puzzled by two things: One, if I'm waiting for the threads to finish using g_pool.join(), why can I then not reuse the threads in the next iteration. I.e., I expected to also see the numbers 10,20,30,... printed in subsequent iterations etc. Secondly, I'm creating a thread pool of size 10, why am I not at least seeing 10 outputs then? I cannot wrap my head around this. Please let me know where I am going wrong, thanks in advance!
You join the pool after posting the first task. So, the pool stops before you even accept a second task. That explains why you're not seeing more. This fixes that: for (size_t i = 0; i != 50; ++i) { post(g_pool, boost::bind(f, 10 * i)); } g_pool.join(); Addendum #1 In response to the comments. In case you want to wait for the outcome of a specific task, consider a future: Live On Coliru #include <boost/asio.hpp> #include <boost/bind/bind.hpp> #include <boost/thread.hpp> #include <iostream> #include <future> boost::asio::thread_pool g_pool(10); int f(int i) { std::cout << '(' + std::to_string(i) + ')'; return i * i; } int main() { std::cout << std::unitbuf; std::future<int> answer; for (size_t i = 0; i != 50; ++i) { auto task = boost::bind(f, 10 * i); if (i == 42) { answer = post(g_pool, std::packaged_task<int()>(task)); } else { post(g_pool, task); } } answer.wait(); // optionally make sure it is ready before blocking get() std::cout << "\n[Answer to #42: " + std::to_string(answer.get()) + "]\n"; // wait for remaining tasks g_pool.join(); } With one possible output: (0)(50)(30)(90)(110)(100)(120)(130)(140)(150)(160)(170)(180)(190)(40)(200)(210)(220)(240)(250)(70)(260)(20)(230)(10)(290)(80)(270)(300)(340)(350)(310)(360)(370)(380)(330)(400)(410)(430)(60)(420)(470)(440)(490)(480)(320)(460)(450)(390) [Answer to #42: 176400] (280) Addendum #2: Serializing tasks If you want to serialize specific tasks, you can use a strand. E.g. to serialize all the request based on the remainder of the parameter modulo 3: Live On Coliru #include <boost/asio.hpp> #include <boost/bind/bind.hpp> #include <boost/thread.hpp> #include <iostream> #include <future> boost::asio::thread_pool g_pool(10); int f(int i) { std::cout << '(' + std::to_string(i) + ')'; return i * i; } int main() { std::cout << std::unitbuf; std::array strands{make_strand(g_pool.get_executor()), make_strand(g_pool.get_executor()), make_strand(g_pool.get_executor())}; for (size_t i = 0; i != 50; ++i) { post(strands.at(i % 3), boost::bind(f, i)); } g_pool.join(); } With a possible output: (0)(3)(6)(2)(9)(1)(5)(8)(11)(4)(7)(10)(13)(16)(19)(22)(25)(28)(31)(34)(37)(40)(43)(46)(49)(12)(15)(14)(18)(21)(24)(27)(30)(33)(36)(39)(42)(45)(48)(17)(20)(23)(26)(29)(32)(35)(38)(41)(44)(47) Note that all work is done on any thread, but tasks on a strand happen in the order in which they were posted. So, 0, 3, 6, 9, 12... 1, 4, 7, 10, 13... 2, 5, 8, 11, 14... happen strictly serially, though 4 and 7 don't need to happen on the same physical thread 11 might happen before 4, because they're not on the same strand Even More In case you need more "barrier-like" synchronization, or what's known as fork-join semantics, see Boost asio thread_pool join does not wait for tasks to be finished (where I posted two answers, one after I discovered the fork-join executor example).
70,006,764
70,006,824
Why do I get "0xC0000005: Access violation reading location 0x0000000000000000"
So in one getter method I'm simply trying to get the length of a c-style string (c-style strings give me headaches) and it works everywhere else in the code except on 1 line stated below the code #include <iostream> #include <cstring> #pragma warning(disable : 4996) using namespace std; class MyString { private: char *str; public: int get_length() const { return strlen(str); } char get_string() const { return *str; } void display_obj() const { cout << str << " : " << get_length() << endl; } MyString() :str{nullptr} { str = new char[1]; str = '\0'; } MyString(const char *s) :str{nullptr} { str = new char[strlen(s) + 1]; strcpy(str, s); } MyString(const MyString &source) :str{ nullptr } { str = new char[strlen(source.str) + 1]; strcpy(str, source.str); } MyString(MyString &&source) :str{ source.str } { source.str = nullptr; } MyString &MyString::operator=(const MyString &source) { if (this == &source) return *this; delete[] str; str = new char[strlen(source.str) + 1]; strcpy(str, source.str); return *this; } MyString &MyString::operator=(MyString &&source) { if (this == &source) return *this; delete[] str; str = source.str; source.str = nullptr; return *this; } ~MyString() { delete str; } }; int main() { MyString a{ "hello" }; MyString b; b.display_obj(); b = a; b.display_obj(); b = "Tatarusanu"; b.display_obj(); system("pause"); return 0; } and here int get_length() const { return strlen(str); } I get thrown the exception "Exception thrown at 0x00007FF98602F621 (ucrtbased.dll) in Project1.exe: 0xC0000005: Access violation reading location 0x0000000000000000" and I have no idea why. Any suggestions?
MyString() :str{nullptr} { str = new char[1]; //str = '\0'; // <-- here is your mistake str[0] = '\0'; // do this instead }
70,006,919
70,007,171
Correct way to call user defined conversion operator in templated function with MSVC
I need to call a templated conversion operator inside a class like this : struct S { template<typename T> operator T() const { return T{}; } template<typename T> T test() { return operator T(); } }; int main(){ S s; s.test<int>(); return 0; } This code compiles with clang but not with MSVC(19), gives me a c2352 error. Is the correct syntax? Demo
Syntax is correct, as work around you might be explicit with this->operator T(): template<typename T> T test() { return this->operator T(); } Demo
70,007,229
70,007,437
Why my empty string assignment doesn't clear my string
I have an exercise which looks like that: Problem statement is simple and straight forward . You will be given a non-negative integer P of length N and you need to check whether it's divisible by Q ? Integer P will be given in its decimal representation with P0 as leftmost digit and P1 as second digit from left ! Rest of the digit can be generated from the formula : Pi = ( 4*Pi-1 + Pi-2 ) modulo Q for 2 <= i <= N-1 Input The first line contains one integer T - denoting the number of test cases. T lines follow each containing four integers P0 , P1 , Q and N ! Output For each testcase output YES if the corresponding integer is divisible by Q and NO otherwise. Constraints T <= 100000 0 < P0 , P1 , Q < 10 0 < N <= 1018 Example Input: 4 1 4 2 2 1 4 2 1 4 2 3 2 3 4 7 3 Output: YES NO YES NO Explanation Value of P is 14, 1, 42, 345 in respective cases ! and that's what I came up with #include <iostream> #include <vector> #include <string> using namespace std; int main() { int t, q, n, p_0, p_1, p_temp, p; vector<int> digits; vector<string> answers; string number = ""; cin >> t; for (int i = 0; i < t; i++) { cin >> p_0 >> p_1 >> q >> n; if (n == 1) { digits.push_back(p_0); } else { digits.push_back(p_0); digits.push_back(p_1); for (int i = 2; i <= (n - 1); i++) { p_temp = (4 * digits[i - 1] + digits[i - 2]) % q; digits.push_back(p_temp); } } for (int i = 0; i < digits.size(); i++) { number += to_string(digits[i]); } p = stoi(number); cout << number << endl; if (p % q == 0) { answers.push_back("YES"); } else { answers.push_back("NO"); } number = ""; } for (int i = 0; i < answers.size(); i++) { cout << answers[i] << endl; } } Everything I have done works fine, except for one thing, this part does not clear my number variable number = ""; And honestly I don't know why, could someone correct my mistakes and explain me what did I do wrong. Thanks.
Your problem is with the digits vector. Each loop the number string just gets repopulated with the digits vector which is never cleared. Use digits.clear() to empty the vector like so: #include <iostream> #include <vector> #include <string> using namespace std; int main() { int t, q, n, p_0, p_1, p_temp, p; vector<int> digits; vector<string> answers; string number = ""; cin >> t; for (int i = 0; i < t; i++) { cin >> p_0 >> p_1 >> q >> n; if (n == 1) { digits.push_back(p_0); } else { digits.push_back(p_0); digits.push_back(p_1); for (int i = 2; i <= (n - 1); i++) { p_temp = (4 * digits[i - 1] + digits[i - 2]) % q; digits.push_back(p_temp); } } for (int i = 0; i < digits.size(); i++) { number += to_string(digits[i]); } p = stoi(number); cout << number << endl; if (p % q == 0) { answers.push_back("YES"); } else { answers.push_back("NO"); } digits.clear(); number = ""; } for (int i = 0; i < answers.size(); i++) { cout << answers[i] << endl; } }
70,007,265
70,012,050
Update index variables in threads
I have objects like balls. These objects are dynamically created and stacked into a vector. For each of these balls, a separate stream is created that updates its coordinates. Each of these streams has a reference to a vector with balls and knows the sequence number of its ball. Then, let's say I need to delete several balls and streams associated with them. I did it like this: the sword has a bool killMe variable that becomes true when the ball needs to be removed. The thread that updates the coordinates notices that the ball needs to be removed, removes the ball, and terminates on its own. But when the ball is removed from the vector, the sequence numbers of the subsequent balls change and their streams, trying to refer to them the next time, cause the program to crash. How to organize a timely update of the ball index in their streams?
Rather than each thread having an index into the vector, why not pass a reference to the object being worked on? Note that this may still be problematic if your vector is vector<Ball>, as I'm not sure what happens to references to objects that are moved. That sounds like a problem. But you could store vector<std::shared_ptr<Ball>> and then you're golden. Another choice if you really want to use indexes is still to use a vector of shared pointers but then you can nullify the pointers you need to delete -- leaving holes in your vector, but at least you aren't moving things around. The other choice involves mutexes, and you'll be mutex-locked A LOT. This seems less useful.
70,007,518
70,007,936
Trying to understand initialization of array C++
I am working with C++ to construct an array, which is then passed into Python (similar to: Embed python / numpy in C++). I am new to C++ and I am confused with some of the details of the code. I'm hoping I can get an understanding of how this code works, because I need to change it. So my question is: what is this method of initializing an array? const int SIZE{ 10 }; double(*c_arr)[SIZE]{ new double[SIZE][SIZE] }; For the record, I've been able to make this a rectangular array by calling: const int numberRows = 5000; const int numberColumns = 500; double(*c_arr)[numberColumns]{ new double[numberRows][numberColumns] }; I fill the array: // fill the array from a file std::string line; int row = 0; int column = 0; while (std::getline(dataFile, line)) { std::stringstream lineStream(line); std::string cell; while (std::getline(lineStream, cell, '\t')) { c_arr[row][column] = std::stod(cell); column++; } row++; column = 0; if (row == numberRows) { break; } } I still don't understand what is meant by double(*c_arr). Whenever I try to initialize this array differently, I get errors. For example: double *c_arr[numberRows][numberColumns]; raises errors when I try to fill the array c_arr[row][column] = std::stod(cell);. If I change the initialization to be: double c_arr[numberRows][numberColumns];, then I get a segmentation fault when run. What I'd like to eventually achieve is a function that returns a pointer to an array; something like: double *load_data(int rows, int columns) { double(*c_arr)[columns]{ new double[rows][columns] }; //fill array here return (c_arr) } When I construct such a function, I get an error at the second occurrence of the columns variable: expression must have a constant value -- the value of parameter "columns" cannot be used as a constant. I don't really how to do this, but I'm hoping that if I can understand the array initialization, I'll be able to properly construct the load_data function.
double(*c_arr)[SIZE]{ new double[SIZE][SIZE] }; The above is/can be read as: c_arr is a pointer to an array of size SIZE. Next, new double[SIZE][SIZE] creates a 2D array and also returns a pointer to its first element(which is also an array of double). Next, the pointer c_arr is initialized with the pointer returned in the last step from new double[SIZE][SIZE]; Now lets take a look at: double *c_arr[numberRows][numberColumns]; In this case, c_arr is a 2D array of pointers to double. And so you cannot initialize this 2D array of pointers with a single pointer like: double d=15; double *c_arr[5][6]=&d ;//incorrect Now coming to your error: When I construct such a function, I get an error at the second occurrence of the columns variable: expression must have a constant value -- the value of parameter "columns" cannot be used as a constant This is because, in C++ the size of an array must be a compile time constant(constant expression). So for example, int n = 10; double arr[n]; //incorrect The correct way would be: const int n = 10; double arr[n];//correct So in your code the variable named columns is not a constant expression which is the reason you get the above mentioned error. To correctly return a pointer to an array, you can modify your load_data function to look like: auto load_data(int rows, int columns) -> double (*)[5]{ double(*c_arr)[5]{ new double[4][5] }; //fill array here return c_arr; } In the above modification of load_data, instead of using the numbers 4 and 5 you can use other constant expressions.
70,008,513
70,012,180
Why would the MPI_Status of a successful communication would report "-1" as source
Please look at the following MWE, which shows how what appears to me as a successful communication done using MPI_Irecv and MPI_ANY_SOURCE reports as its source the integer value "-1". The example includes command-line output, which is as follows. Affter this lines, it SigFaults as the "-1" index is later on used as the source for a send. Hi! (fun2) Hi! (fun1) Hi! (fun1) Hi! (fun2) Sent! 0 Flag was 1, source was -1, the error was 0, and statusflag was 0 Sent! 0 Flag was 1, source was -1, the error was 0, and statusflag was 0 #include <iostream> #include "mpi.h" #include <omp.h> #include <list> #include <set> #include <vector> #include <queue> #include <stdio.h> const int L = 10; void fun2(int &ready){ int world_size; int world_rank; MPI_Comm_size(MPI_COMM_WORLD, &world_size); MPI_Comm_rank(MPI_COMM_WORLD, &world_rank); printf("Hi! (fun2)\n"); // Build std::queue<int> Q; MPI_Request R[L]; int buffer[L]; int response[L]; for (int i=0; i<L; ++i){ Q.push(i); } int i=0; while (!Q.empty()){ i = Q.front(); buffer[i] = i; Q.pop(); MPI_Ssend(&buffer[i], 1, MPI_INT,(int) ( (world_rank + 1) % world_size), 2501, MPI_COMM_WORLD); printf("Sent! %d\n", buffer[i]); MPI_Recv(&response[i], 1, MPI_INT, (int) ( (world_rank + 1) % world_size), i, MPI_COMM_WORLD, MPI_STATUS_IGNORE); printf("Recieved! %d\n", response[i]); } return; } void fun1(int &ready){ int world_size; int world_rank; MPI_Comm_size(MPI_COMM_WORLD, &world_size); MPI_Comm_rank(MPI_COMM_WORLD, &world_rank); printf("Hi! (fun1)\n"); // Build int V[world_size]; int bigger_V[L]; const int BATCH = 4; MPI_Request R[BATCH]; MPI_Request R2[L]; int buffer[L]; int answers[L]; int j = 0; int atomic_int; int statusflag = 0; bool first = true; int b=0; for (int i=0; i<L; ++i) { // MPI_ANY_SOURCE is used here! statusflag = MPI_Irecv(&buffer[i], 1, MPI_INT, MPI_ANY_SOURCE, 2501, MPI_COMM_WORLD, &R2[i]); MPI_Status status; int flag; MPI_Wait(&R2[i], &status); MPI_Request_get_status(R2[i], &flag, &status); // This status has MPI_SOURCE = -1 !!! int q = status.MPI_SOURCE; printf("Flag was %d, source was %d, the error was %d, and statusflag was %d\n\n\n", flag, q, status.MPI_ERROR, statusflag);std::cout<<std::flush; answers[i] = i*5; MPI_Ssend(&answers[i], 1, MPI_INT, status.MPI_SOURCE, i, MPI_COMM_WORLD); } return; } int main(int argc, char** argv){ int ready = 0; int provided; MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided); #pragma omp parallel num_threads(2) { long MYNUM = omp_get_thread_num(); if (MYNUM == 0){ fun1(ready); } else { fun2(ready); } } MPI_Finalize(); } In order to compile it I hereby provide the following one-liner: mpic++ -fopenmp mwe.cpp ; mpirun -n 2 ./a.out
Your problem is that you use MPI_Request_get_status: MPI_Wait(&R2[i], &status); MPI_Request_get_status(R2[i], &flag, &status); Do you see that you have two calls that both have the status as output? That's suspicious. Your MPI_Wait already clears the request object (that's why it's passed by reference), so MPI_Request_get_status gives junk output. This call is for cases where you want to inspect a status without doing a wait call. You should have done status.MPI_SOURCE after the wait call. Btw, the value "-1" is MPI_PROC_NULL. I really wish they made that "-2", but it is what it is. You can also take this as an indication of trouble.
70,008,747
70,009,011
How to define a private member function only in cpp
So consider I have a class with a private member variable and a private function which I do not want to define in the header file, because I want to "hide" it from the user. How can I make this? I can not access the private variable without the declaration of the function in the header. So what works is something like this: // header file class Testclass { public: // ... private: const int m_i; void func() const; } // cpp file #include "TestClass.h" Testclass::func() const { int j = m_i; //access to a private member variable } // ... But I want something like this: // header file class Testclass{ public: //... private: const int m_i; } // cpp file #include "TestClass.h" Testclass::func() const { int j = m_i; //access to a private member variable } // ... Which possibilities do I have? I read something about the PIMPL Idiom, but I am not sure if this is what I want, since it looks a bit cumbersome coding-wise.
Normally one achieves this through the PIMPL (Pointer to IMPLementation) idiom. In your header file you have: class MainClass { public: void public_function(); private: class Impl; Impl* impl; }; Note that the header file does not contain the definition of the Impl class, only its declaration. You then define that class in your cpp file and forward the calls from your public interface to the functions of the impl class: class MainClass::Impl { void actualfunc() { //do useful stuff here } }; void MainClass::public_function() { return impl->actualfunc(); } Apart from your indended hiding of unwanted members from your class users, the PIMPL idiom provides the additional benefit that if no changes are made to the interface of the class, the users of the class need not be recompiled.
70,009,341
70,009,404
Why do I get an Undefined reference error when trying to compile?
Just had a little problem that I haven't been able to figure out yet. I was using a similar program structure for a different project, but the problem boils down to this. I have two cpp files, which are: Trading_dte.cpp : #include <iostream> using namespace std; class Dte { public: int addition(int a, int b) { return a + b; } }; dummy.cpp : #include <iostream> #include "Trading_dte.hpp" Dte obj; int check() { std::cout<<obj.addition(6,9); } I created a header file called Trading_dte.hpp : # pragma once #include <iostream> class Dte { public: int addition(int a, int b); }; Now when I try compiling using the command : g++ Trading_dte.cpp dummy.cpp I get the error : /usr/bin/ld: /tmp/ccCcM8R6.o: in function `check': dummy.cpp:(.text+0x1a): undefined reference to `Dte::addition(int, int)' collect2: error: ld returned 1 exit status I'm sure it's something small, but I just can't figure what. Thanks a lot in advance!
your cpp file need to be written differently #include "Trading_dte.hpp" #include <iostream> int Dte::addition(int a, int b) { return a + b; }
70,009,655
70,010,601
CLion does not see wxwidgets partially but compiles project
I use Artix linux on OpenRC, I have installed wxwidgets with wxgtk3-dev package (version 3.1.5) from AUR and I wanted to work with that library in CLion. CLion sees it and I'm able to include anything from wx/ dir. I have copied a hello world example from wxwidgets website and pasted it into my cpp source file and then CLion showed me a bunch of undeclired identifier errors (though some 'identifiers' like wxFrame are not 'undeclared'). But I'm able to build and run project and it works fine. What's wrong with CLion and what can I do to fix this? I've seen some guides but most of them tell about Windows and also they tell how to compile project that is not the problem in my case - it's compiling but CLion tells me that it won't compile (and still builds and runs it). Here's also my CMakeLists.txt if needed: https://pastebin.com/58NwS4AP
OK I solved my problem. As you can see in my CMakeLists.txt it uses C++14. It seems that CLion can not properly handle some code from example with C++14 although it's not a problem for cmake and make to build it. I just switched to C++11: set(CMAKE_CXX_STANDARD 11) and now everything works!
70,010,434
70,010,537
Expression evaluation from infix to postfix
#include <iostream> #include <string> #include <stack> using namespace std; float postix_evalute(string expr) { stack<float> stk; float val; for (int x = 0; x < expr.length(); x++) { if (isdigit(expr[x])) { stk.push((expr[x] - '0')); } else { float op2 = expr[x]; stk.pop(); float op1 = expr[x]; stk.top(); switch (expr[x]) { case '+': val = op1 + op2; break; case '-': val = op1 - op2; break; case '*': val = op1 * op2; break; case '/': val = op1 / op2; break; } stk.push(val); } } return stk.top(); } int main() { string line; cout << "The Value Of experssion" << endl; cin >> line; cout << postix_evalute(line) << endl; return 0; } This code to get postfix-evalue for string which user enter put when i try to run this code it give me random value not give me the right answer so i want to know what is the problem for example when i enter 32+ it give me 86
if (isdigit(expr[x])) { stk.push((expr[x] - '0')); } You're pushing individual digits one at a time. If you run postfix_evaluate("32"), this loop will push 3 onto the stack first, and then 2. Are you sure you don't want the single value 32 on the stack instead? You can, and should, debug this basic stuff before you write lots of code on a wobbly foundation. float op2 = expr[x]; stk.pop(); These lines copy a single character from the string (which we've just decided is not a digit), promote it to a float, and then discard the top of the stack without examining it at all. For example, if the char is '+' (and your encoding is ASCII), you'll have op2 = 43.0. You have the same problem with op1.
70,010,938
70,011,943
Should I ever store the result of set/map find() as reference?
Please consider the following example: #include <set> int main () { std::set<int> s; const auto it = s.find(1); const auto& it2 = s.find(1); return 0; } One could assume that it2 would be cheaper, but if I understand the generated assembly code correctly, it actually uses two more instructions: //const auto it = s.find(1); mov DWORD PTR [rbp-32], 1 lea rdx, [rbp-32] lea rax, [rbp-80] mov rsi, rdx mov rdi, rax call std::set<int, std::less<int>, std::allocator<int> >::find(int const&) mov QWORD PTR [rbp-88], rax // const auto& it2 = s.find(1); mov DWORD PTR [rbp-28], 1 lea rdx, [rbp-28] lea rax, [rbp-80] mov rsi, rdx mov rdi, rax call std::set<int, std::less<int>, std::allocator<int> >::find(int const&) mov QWORD PTR [rbp-96], rax lea rax, [rbp-96] mov QWORD PTR [rbp-24], rax I tried the code with various compilers (clang, gcc) and containers (map, unordered_map, unordered_set) and the result seems to be consistent. Is my understanding of the assembly code correct (using a reference is more costly)? Is there any use case where it2 (reference to iterator) would be preferred over it (iterator) as result of calling find() on map/set?
Set::find() doesn't return a reference: const_iterator find (const value_type& val) const; iterator find (const value_type& val); I'm surprised the compiler let you assign the value to a reference. As some of the commenters have suggested, it creates a temporary for your reference to point to. C++ is really quite efficient if you do this: auto ptr = set.find(...) When a method doesn't return a reference, you probably don't want to assign it to a reference.
70,011,468
70,807,481
GEOS (​JTS Topology Suite) BufferOp / Offset Curve producing additional points
I am using GEOS (the C port of the JTS Topology suite) to produce an offset curve of a linestring. I have successfully produced the offset curve however for some cases (namely where the start and end lines are both horizontal and end at the same x position / or vertical and end at the same y position), an additional point is created at the beginning and end of the offset. It's easiest to explain this in images: Example Image Example Image 2 I can't work out if there is something I have failed to do or if this is an bug with the library, here's my code: #include "geos_c.h" std::vector<vec2> Geos::offsetLine(const std::vector<vec2>& points, float offset, int quadrantSegments, int joinStyle, double mitreLimit) { // make coord sequence from points GEOSCoordSequence* seq = makeCoordSequence(points); // Define line string GEOSGeometry* lineString = GEOSGeom_createLineString(seq); if(!lineString) return {}; // offset line GEOSGeometry* bufferOp = GEOSOffsetCurve(lineString, offset, quadrantSegments, joinStyle, mitreLimit); if(!bufferOp) return {}; // put coords into vector std::vector<vec2> output = outputCoords(bufferOp, (offset < 0.0f)); // Frees memory of all as memory ownership is passed along GEOSGeom_destroy(bufferOp); return move(output); } GEOSCoordSequence* Geos::makeCoordSequence(const std::vector<vec2>& points) { GEOSCoordSequence* seq = GEOSCoordSeq_create(points.size(), 2); if(!seq) return {}; for (size_t i = 0; i < points.size(); i++) { GEOSCoordSeq_setX(seq, i, points[i].x); GEOSCoordSeq_setY(seq, i, points[i].y); } return seq; } std::vector<vec2> Geos::outputCoords(const GEOSGeometry* points, bool reversePoints) { // Convert to coord sequence and draw points const GEOSCoordSequence *coordSeq = GEOSGeom_getCoordSeq(points); if(!coordSeq) return {}; // get number of points int nPoints = GEOSGeomGetNumPoints(points); if(nPoints == -1) return {}; // output onto vector to return std::vector<vec2> output; // build vector for (size_t i = 0; i < (size_t)nPoints; i++) { // points are in reverse order if negative offset size_t index = reversePoints ? nPoints-i-1 : i; double xCoord, yCoord; GEOSCoordSeq_getX(coordSeq, index, &xCoord); GEOSCoordSeq_getY(coordSeq, index, &yCoord); output.push_back({ xCoord, yCoord }); } return move(output); }
Latest release of Geos resolves this now. See here: Issue
70,011,477
70,011,747
C++ compiler error: use of deleted function std::variant()
I am continually getting the following error message telling me that I am using a deleted function, which I think is the std::variant default constructor. In file included from main.cpp:2: Document.hpp: In instantiation of ‘Document<StateVariant, EventVariant, Transitions>::Document(StateVariant&&) [with StateVariant = std::variant<DraftState, PublishState>; EventVariant = std::variant<EventWrite, EventRead>; Transitions = TransitionRegister]’: main.cpp:7:61: required from here Document.hpp:33:37: error: use of deleted function ‘std::variant<_Types>::variant() [with _Types = {DraftState, PublishState}]’ 33 | Document(StateVariant &&a_state) { | ^ In file included from Document.hpp:6, from main.cpp:2: /usr/include/c++/11/variant:1385:7: note: ‘std::variant<_Types>::variant() [with _Types = {DraftState, PublishState}]’ is implicitly deleted because the default definition would be ill-formed: 1385 | variant() = default; | ^~~~~~~ /usr/include/c++/11/variant:1385:7: error: use of deleted function ‘constexpr std::_Enable_default_constructor<false, _Tag>::_Enable_default_constructor() [with _Tag = std::variant<DraftState, PublishState>]’ In file included from /usr/include/c++/11/variant:38, from Document.hpp:6, from main.cpp:2: /usr/include/c++/11/bits/enable_special_members.h:112:15: note: declared here 112 | constexpr _Enable_default_constructor() noexcept = delete; | ^~~~~~~~~~~~~~~~~~~~~~~~~~~ The code is roughly: #include <iostream> #include <variant> class DraftState { public: DraftState() = default; // default constructor DraftState(const DraftState &a_state) { m_msg = a_state.m_msg; } // copy constructor DraftState(const std::string &a_rMsg = "") { m_msg = a_rMsg; } // custom constructor DraftState(DraftState &&a_state) { m_msg = std::move(a_state.m_msg);} // move constructor DraftState& operator=(DraftState &&a_state) { if(this != &a_state) { m_msg = std::move(a_state.m_msg); } return *this; } // move assignable constructor ~DraftState() = default; // destructor std::string getState() { return "DraftState"; } std::string m_msg; }; class PublishState{ // similar to DraftState }; using State = std::variant<DraftState, PublishState>; template<typename StateVariant> class Document { public: Document() = default; Document(StateVariant &&a_state) { m_state = std::move(a_state); } StateVariant m_state; //... }; int main() { DraftState draftState("draft"); Document<State> doc(draftState); return 0; } I have tried adding a default constructor call in the custom constructor Document(StateVariant &&a_state)'s initializer list but that does not seem to work either. Any help understanding this cryptic message is appreciated thanks. Sorry for the long code.
While you do need to work on a minimal example, the core problem is your DraftState default constructor is ambiguous with your string constructor with a default argument. See https://godbolt.org/z/hTnsjoWaW To be default constructible, std::variant requires the first type argument to be default constructible. The ambiguity causes the compiler to think your class is not default constructible, and therefore neither is the variant. Also, your move constructor for Document should use the member initializer list, rather than assignment. And your DraftState is missing the copy assignment operator, though unless there's more to it, I wouldn't explicitly define all of the copy/move/destructor values. See the Rule of Five.
70,011,500
70,011,627
How to replace quotation marks with angle brackets between two patterns recursively for all file in a directory with sed?
The repository I am working on has multiple source files in a non-flat directory structure, e.g. project │ main.cpp │ └───moduleA │ A.cpp All these source files have code something like #include "A.h" WINDOWS_DISABLE_WARNING #include "externalA.h" #include "externalB.h" WINDOWS_ENABLE_WARNING // more code How can I use sed to replace all quotation marks include with angle brackets include between WINDOWS_DISABLE_WARNING macro and WINDOWS_ENABLE_WARNING macro for all files like below recursively? #include "A.h" WINDOWS_DISABLE_WARNING #include <externalA.h> #include <externalB.h> WINDOWS_ENABLE_WARNING // more code I know how to replace simple strings recursively like find ./ -type f -exec sed -i 's/oldtext/newtext/' {} \;, but I am struggling to figure out how to replace quotation marks with angle brackets between two patterns. The reason I am doing is this is because Visual Studio recently introduced /external:anglebrackets, if this flag is enabled, any headers included with angle brackets are treated as external, and the warnings coming from it can be turned off via /external:W0. That means no more ugly macros like WINDOWS_DISABLE_WARNING which is defined as __pragma(warning(push,0)) if on Windows, otherwise empty, via CMake's target_compile_definitions and similarly WINDOWS_ENABLE_WARNING which is defined as __pragma(warning(pop)) if on Windows, otherwise empty, via CMake's target_compile_definitions. Since using sed to remove the macros recursively is pretty straightforward, eventually the code can become clean like the below when working with loosely written third-party libraries with the new /external flags enabled. #include "A.h" #include <externalA.h> #include <externalB.h> // more code
Read about addressing lines in sed find ... -exec sed -i '/WINDOWS_DISABLE_WARNING/,/WINDOWS_ENABLE_WARNING/ { s/"/</; s/"/>/ }' '{}' + Make sure to back your files up (sed -i.bak) (or omit the -i option) before experimenting with -i