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
74,367,090
74,368,006
Is there a fast way to 'move' all vector values by 1 position?
I want to implement an algorithm that basically moves every value(besides the last one) one place to the left, as in the first element becomes the second element, and so on. I have already implemented it like this: for(int i = 0; i < vct.size() - 1; i++){ vct[i] = vct[i + 1]; } which works, but I was just wondering if there is a faster, optionally shorter way to achieve the same result? EDIT: I have made a mistake where I said that I wanted it to move to the right, where in reality I wanted it to go left, so sorry for the confusion and thanks to everyone for pointing that out. I also checked if the vector isn't empty beforehand, just didn't include it in the snippet.
As a comment (or more than one?) has pointed out, the obvious choice here would be to just use a std::deque. Another possibility would be to use a circular buffer. In this case, you'll typically have an index (or pointer) to the first and last items in the collection. Removing an item from the beginning consists of incrementing that index/pointer (and wrapping it around to the beginning of you've reached the end of the buffer). That's quite fast, and constant time, regardless of collection size. There is a downside that every time you add an item, remove an item, or look at an item, you need to do a tiny bit of extra math to do it. But it's usually just one addition, so overhead is pretty minimal. Circular buffers work well, but they have a fair number of corner cases, so getting them just right is often kind of a pain. Worse, many obvious implementations waste one the slot for one data item (though that often doesn't matter a lot). A slightly simpler possibility would reduce overhead by some constant factor. To do this, use a little wrapper that keeps track of the first item in the collection, along with your vector of items. When you want to remove the first item, just increment the variable that keeps track of the first item. When you reach some preset limit, you erase the first N elements all at once. This reduces the time spent shifting items by a factor of N. template <class T> class pseudo_queue { std::vector<T> data; std:size_t b; // adjust as you see fit: static const int max_slop = 20; void shift() { data.erase(data.begin(), data.begin() + b); } public: void push_back(T &&t) { data.push_back(std::move(t); } void pop_back() { data.pop_back(); } T &back() { return data.back(); } T &front() { return data[b]; } void pop_front() { if (++b > max_slop) shift(); } std::vector<T>::iterator begin() { return data.begin() + b; } std::vector<T>::iterator end() { return data.end(); } T &operator[](std::size_t index) { return data[index + b]; } }; If you want to get really tricky, you can change this a bit, so you compute max_slop as a percentage of the size of data in the collection. In this case, you can change the computational complexity involved, rather than just leaving it linear but with a larger constant factor than you currently have. But I have no idea how much (if at all) you care about that--it's only likely to matter much if you deal with a wide range of sizes.
74,367,298
74,369,151
how to compare (strcmp) 2 char with space?
#include <iostream> #include <cstring> #include <cctype> using namespace std; int main(){ char string1 [50] {}; char string2 [50] {}; cout << "enter the string 1: "; cin.get(string1,50); cout << "your string1: " << string1 << endl; cout << "enter the string 2: "; cin.get(string2,50); cout << "your string2: " << string2 << endl; cout << strcmp(string1, string2); return 0; } How to use strcmp() wit string1 (with space) and string2 (with space)? What I've tried: Input: abc def Output: your string1: abc def enter the string 2: your string2: 1 The result that I want: Input: abc def abc def Output: 0
Here's the issue: cin.get(string1,50); reads up to 49 characters or until it encounters a \n but it doesn't consume the \n. When cin.get(string2,50); is reached the \n from the first line is the first character in the input buffer so nothing is read. There's a few ways I can think of to fix this. Keep using cin.get and add a cin.ignore() after the first read to consume the \n. If more than 49 characters were entered on a line the ignore would cause the 50th character to be lost. Switch to using cin.getline with the same parameters. The difference is that cin.getline does consume the \n. If more than 49 characters were entered on a line this wouldn't lose any characters, it would read from 50 to 99 or until a \n was reached. There are some other small differences with error handling that don't affect your code as written but you might review the linked documentation for each to decide which is best. If you are able to I strongly encourage using std::string for your variables and std::getline to read the data. The advantage to this is that you don't need to worry about specifying an explicit length. The amount of data that is provided will be read and the string resized to fit it. This would help to close the loophole where more than 49 characters were supplied on a line. Here's an example using cin.getline that gives the output you expect. Demo Output: enter the string 1: your string1: 'abc def' enter the string 2: your string2: 'abc def' 0 It's slightly different from your original code since I added single quotes around the string and a couple of newlines to make it a little more readable and help to validate what was going on.
74,367,778
74,369,432
How to introduce a new buffer in Base class without wasting extra spaces?
Before======================== struct RedBook : Book {...} struct BlueBook : Book {...} struct YellowBook : Book {...} struct Book { virtual ~Book() = default; // ... static constexpr int COLOR_BOOK_SIZE = 100 char color_book_buffer[COLOR_BOOK_SIZE] = {0}; // used only by ColorBook(i.e. RedBook/BlueBook/YellowBook) }; Now======================== struct GrayBook : Book // just added {} struct DarkBook : Book {} struct Book // updated Book structure { virtual ~Book() = default; // ... static constexpr int COLOR_BOOK_SIZE = 100 char color_book_buffer[COLOR_BOOK_SIZE] = {0}; // this buffer is ONLY used by RedBook/BlueBook/YellowBook // ... static constexpr int NOCOLOR_BOOK_SIZE = 200 char no_color_book_buffer[NOCOLOR_BOOK_SIZE] = {0}; // this buffer is ONLY used by GrayBook/DarkBook }; The code was written only required for ColorBook (i.e. support RedBook/BlueBook/YellowBook). All ColorBook use color_book_buffer. Now the design requirement has changed and I need to add support for NoColorBook(i.e. GrayBook/DarkBook). All NoColorBook only use no_color_book_buffer. Question> I don't like to add both buffers(i.e. color_book_buffer and no_color_book_buffer) into the struct Book because it wastes space. Also I don't like the proposed two solutions shown below. Is there a better way that I can address this issue? Solution 1> I can move buffer definition into subclass but this will introduce duplicated code within each subclass. Solution 2> I can add an extra layer as follows: struct ColorBook { virtual ~ColorBook() = default; // ... static constexpr int COLOR_BOOK_SIZE = 100 char color_book_buffer[COLOR_BOOK_SIZE] = {0}; }; struct RedBook : ColorBook {...} struct BlueBook : ColorBook {...} struct YellowBook : ColorBook {...} struct NonColorBook { virtual ~NonColorBook() = default; // ... static constexpr int NOCOLOR_BOOK_SIZE = 200 char no_color_book_buffer[NOCOLOR_BOOK_SIZE] = {0}; }; struct GrayBook : NonColorBook {} struct DarkBook : NonColorBook {} Solution 3> I found another solution. #include <iostream> #include <string> #include <vector> #include <algorithm> #include <string> struct ColorMessage { int a; double b; std::string message; }; struct NonColorMessage { float a; double b; bool has_message; }; constexpr unsigned int MAX_COLOR_MSG_COUNT = 3; constexpr unsigned int MAX_NON_COLOR_MSG_COUNT = 2; struct Book { virtual ~Book() = default; static constexpr int COLOR_MSG_SIZE = sizeof(ColorMessage) * MAX_COLOR_MSG_COUNT; static constexpr int NOCOLOR_MSG_SIZE = sizeof(NonColorMessage) * MAX_COLOR_MSG_COUNT; char book_buffer[std::max(COLOR_MSG_SIZE, NOCOLOR_MSG_SIZE)] = {0}; }; struct RedBook : Book {}; struct BlueBook : Book {}; struct YellowBook : Book {}; struct GrayBook : Book {}; struct DarkBook : Book {}; int main() { std::cout << "sizeof(ColorMessage): " << sizeof(ColorMessage) << std::endl; std::cout << "sizeof(NonColorMessage): " << sizeof(NonColorMessage) << std::endl; std::cout << "Book::COLOR_MSG_SIZE: " << Book::COLOR_MSG_SIZE << std::endl; std::cout << "Book::NOCOLOR_MSG_SIZE: " << Book::NOCOLOR_MSG_SIZE << std::endl; std::cout << "sizeof(Book::book_buffer): " << sizeof(Book::book_buffer) << std::endl; } /* sizeof(ColorMessage): 48 sizeof(NonColorMessage): 24 Book::COLOR_MSG_SIZE: 144 Book::NOCOLOR_MSG_SIZE: 72 sizeof(Book::book_buffer): 144 */ Thank you
I believe something like this was mentioned in the comments but you could add another class to the hierarchy which just holds the buffer (std::array). The read, write and count functions are for illustration purposes only. struct book { virtual void read() const = 0; virtual void write(const std::string_view content) = 0; virtual std::size_t count() const noexcept = 0; virtual ~book() = default; }; template<std::size_t N> struct book_buffer : book { std::array<char, N> buffer{}; }; struct color_book : book_buffer<200> { void read() const override { std::cout << "Reading color book: " << buffer.data() << '\n'; } void write(const std::string_view content) override { std::copy(content.begin(), content.end(), buffer.begin()); } std::size_t count() const noexcept override { return buffer.size(); } }; struct monochromatic_book : book_buffer<100> { void read() const override { std::cout << "Reading monochromatic book: " << buffer.data() << '\n'; } void write(const std::string_view content) override { std::copy(content.begin(), content.end(), buffer.begin()); } std::size_t count() const noexcept override { return buffer.size(); } }; struct red_book : monochromatic_book {}; struct rainbow_book : color_book {}; static void open_book(const book& b) { b.read(); std::cout << "Size: " << b.count() << '\n'; } int main() { rainbow_book b1{}; b1.write("All the colors!"); red_book b2{}; b2.write("I just like red!"); open_book(b1); open_book(b2); }
74,368,912
74,369,336
C++: Call constructor of object inside of a vector
I can't seem to find an answer to my question. Everything I've read on the matter seems to not quite connect and I'm starting to think what I want is impossible. I'm working on a very very very light database management system, it's a college project and in my group I'm tasked with the main functions. Here's my problem: We will run the project as project.exe commands1.txt commands2.txt commands3.txt for example. Now, I have to create a std::vector containing objects of the "File" class so they can be used later by my colleagues doing the parsing. This is the class code (not finished, still working on) class File { protected: std::string name; std::fstream file; public: File() {} File( // TO ADD REGEX std::string name ) { if (name != "") this->name = name; if (name != "" && !this->file) this->file.open(consts::path + name); } ~File( ) { this->name = ""; if (this->file) this->file.close(); } std::string getName( ) { return this->name; } void setName( std::string name ) { if (name != "") // TO ADD REGEX this->name = name; } std::fstream* getFile( ) { return &(this->file); } bool getStatus( ) { if (this->file) return true; else return false; } }; Also my main: int main( int argc, char* argv[] ) { std::string current_exec_name = argv[0]; std::vector<std::string> all_args; all_args.assign(argv, argv + argc); std::vector<Files::File> commands = new // ??? } How do I create a vector with n objects of the class File, so that each one is ran with the constructor File( std::string name ), with name being the equivalent argument in argv[ ]? Read everywhere that you can initialize them like (C++ FAQ) class Fred { public: Fred(int i, int j); ← assume there is no default constructor ... }; int main() { Fred a[10] = { Fred(5,7), Fred(5,7), Fred(5,7), Fred(5,7), Fred(5,7), // The 10 Fred objects are Fred(5,7), Fred(5,7), Fred(5,7), Fred(5,7), Fred(5,7) // initialized using Fred(5,7) }; ... } but I can't use this style since I don't know how many commands (.txts) will be sent.
I suppose the simplest approach is to just tell the compiler to construct your vector from a range. You could even use (almost) the same range you used to assign values to all_args. For example: #include <iostream> #include <string> #include <vector> class File { public: File(std::string name) { std::cout << "File: " << name << "\n"; // To confirm each construction } }; int main(int argc, char* argv[]) { std::vector<File> commands(argv + (argc > 0 ? 1 : 0), argv + argc); } This says that commands is to be constructed from a range. Each element (each char*) from argv+1 to argv+argc is used to construct an element of commands. (The weird expression (argc > 0 ? 1 : 0) is to handle the case where no arguments were provided.) Since char* implicitly converts to std::string, the constructor taking a std::string is used. I did tweak the range to exclude the first argument. I suspect you do not want to construct a File based on the name of your program (what you stored in current_exec_name), but you could always drop the "+ weird expression" if my suspicion is wrong. Since you did some digging around, here's a bonus reference for you: the vector constructors; I used #5.
74,369,079
74,369,120
Powershell subexpression doesn't recognize "pkg-config --cflags --libs opencv4" command
I want to compile an OpenCV C/C++ (MSYS2) program on Windows using solely the CLI. The GNU Bash way to do this is (which runs fine on MSYS2 MINGW64 Shell): g++ main.cc -o main `pkg-config --cflags --libs opencv4` Bash perfectly recognizes the backticks as a subexpression, however PowerShell doesn't: > g++ main.cc -o main `pkg-config --cflags --libs opencv4` g++.exe: error: unrecognized command-line option '--cflags' g++.exe: error: unrecognized command-line option '--libs' I've done some research, and the equivalent on PowerShell would be g++ main.cc -o main $(pkg-config --cflags --libs opencv4) Despite $(pkg-config --cflags --libs opencv4) being the right way to write a subexpression in PowerShell as an echo command shows it produces the right output (in this case compiler include and linker flags I need): > echo $(pkg-config --cflags --libs opencv4) -IC:/msys64/mingw64/bin/../include/opencv4 -LC:/msys64/mingw64/bin/../lib -lopencv_gapi -lopencv_stitching -lopencv_alphamat -lopencv_aruco -lopencv_barcode -lopencv_bgsegm -lopencv_ccalib -lopencv_cvv -lopencv_dnn_objdetect -lopencv_dnn_superres -lopencv_dpm (...) It simply won't work: > g++ main.cc -o main $(pkg-config --cflags --libs opencv4) main.cc:1:10: fatal error: opencv2/imgcodecs.hpp: No such file or directory 1 | #include <opencv2/imgcodecs.hpp> | ^~~~~~~~~~~~~~~~~~~~~~~ compilation terminated. Therefore, I need to use a verbose workaround to compile my file: > g++ main.cc -o main -IC:/msys64/mingw64/bin/../include/opencv4 -LC:/msys64/mingw64/bin/../lib -lopencv_gapi -lopencv_stitching -lopencv_alphamat -lopencv_aruco -lopencv_barcode -lopencv_bgsegm -lopencv_ccalib -lopencv_cvv -lopencv_dnn_objdetect -lopencv_dnn_superres -lopencv_dpm -lopencv_face -lopencv_freetype -lopencv_fuzzy -lopencv_hdf -lopencv_hfs -lopencv_img_hash (...) My PowerShell version: > $PSVersionTable Name Value ---- ----- PSVersion 5.1.22621.608 PSEdition Desktop PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...} BuildVersion 10.0.22621.608 CLRVersion 4.0.30319.42000 WSManStackVersion 3.0 PSRemotingProtocolVersion 2.3 SerializationVersion 1.1.0.1 My question is: how can I make this particular subexpression work in PowerShell so that I don't have to resort to the verbose fallback of copying and pasting the output of pkg-config --cflags --libs opencv4 after g++ main.cc -o main?
The equivalent of your bash command is: g++ main.cc -o main (-split (pkg-config --cflags --libs opencv4)) That is: (pkg-config --cflags --libs opencv4) executes your pkg-config call, and, by enclosing it in (...), the grouping operator, its output can participate in a larger expression. Using the unary form of -split, the string splitting operator, then splits the pkg-config call's output into an array of whitespace-separated tokens, which is (part of) the equivalent of what bash implicitly does via its shell expansion called word splitting. Passing an array as an argument to an external program in PowerShell causes its elements to be passed as individual arguments. Note: Using $(...), PowerShell's subexpression operator does not work in this case, because its output would be passed as a whole, as a single argument to the target executable (or, in the case of an external-program call that outputs multiple lines, each line in full would be passed as an argument). In general, where bash requires $(...) (or its legacy form `...`), in PowerShell (...) is usually sufficient (and in assignments not even it is needed, e.g., $var = Get-Date); the primary use case for $(...) in PowerShell is inside "...", i.e. inside expandable (double-quoted) strings More fundamentally, PowerShell has no equivalent of bash's shell expansions: Notably, parameter expansions (e.g. ${var//foo/bar}) are not supported, and require use of expressions instead (e.g. ($var -replace 'foo', 'bar')) Unquoted arguments are not generally subject to special interpretation, except if they contain metacharacters, which, if they are to be used verbatim, for syntactic reasons then must either be individually `-escaped (`, the so-called backtick, is PowerShell's escape character), or require the whole argument to be enclosed in quotes. It is up to each target command to interpret special characters such as an initial ~ as referring to the home directory, or to interpret arguments such as *.txt as wildcard patterns - whether such an argument was passed in quotes or not. Variable references (e.g., $var) and simple expressions based on them (e.g, $var.Property), (grouping) expressions (e.g. ((1 + 2)), as well as subexpressions ($(...)) and array subexpressions (@(...)) can be used as-is as arguments, even if what they evaluate to contains spaces - in the case of calling external programs, on Windows, PowerShell will double-quote the result on demand, behind the scenes; as stated, multiple outputs are each passed as an argument. See this answer for more information.
74,369,146
74,369,581
Boost Graph Library - Dijkstra's shortest path fails when the edge weights are large?
I have a question regarding the edge weights when using Dijkstra's algorithm in Boost. The problem I am facing is that when the edge weights are large, I do not get a solution from Dijkstra's algorithm. Let's say I have an adjacency list with bundled properties. My vertices are of type VertexType and edges are of type EdgeType. Here, VertexType resembles a person for a simple example. VertexType::pred is the predecessor when used with Dijkstra's algorithm. struct VertexType { std::string name; int age; int pred; }; struct EdgeType { double weight; }; Below is a simple example. void edgeWeightProblem() { // Graph and vertex descriptor typedefs. typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, VertexType, EdgeType > GraphType; typedef boost::graph_traits<GraphType>::vertex_descriptor VertexDescriptor; // Create graph and vertices vector. GraphType G; std::vector<VertexDescriptor> graphVertices; // Add vertices. graphVertices.push_back(add_vertex({"Tom", 23}, G)); graphVertices.push_back(add_vertex({"Frank", 25}, G)); graphVertices.push_back(add_vertex({"John", 42}, G)); graphVertices.push_back(add_vertex({"Emily", 22}, G)); // Add edges. add_edge(graphVertices[0], graphVertices[1], {.2564}, G); add_edge(graphVertices[0], graphVertices[2], {.3572}, G); add_edge(graphVertices[1], graphVertices[3], {.1246}, G); add_edge(graphVertices[2], graphVertices[3], {.5361}, G); // Dijkstra shortest path. dijkstra_shortest_paths(G, graphVertices.front(), predecessor_map(boost::get(&VertexType::pred, G)) .distance_map(boost::get(&VertexType::pred, G)) .weight_map(boost::get(&EdgeType::weight, G))); // Debug pred. std::vector<VertexType> vec; for (const VertexDescriptor& vd : graphVertices) { vec.push_back(G[vd]); } // Extract the shortest path. std::vector<VertexDescriptor> shortestPath; VertexDescriptor currentVertex = graphVertices.back(); while (currentVertex != graphVertices.front()) { shortestPath.push_back(currentVertex); currentVertex = G[currentVertex].pred; } shortestPath.push_back(currentVertex); std::reverse(shortestPath.begin(), shortestPath.end()); // Display graph. std::cout << "\nGraph Display: \n"; boost::print_graph(G); std::cout << "\n"; // Print the shortest path. std::cout << "Shortest Path: \n"; for (const auto& node : shortestPath) { std::cout << node << " -> "; } std::cout << "\n"; } As expected, I get the following output: Graph Display: 0 --> 1 2 1 --> 3 2 --> 3 3 --> Shortest Path: 0 -> 2 -> 3 -> But, if I remove the decimal of the edge weights, (ex: .2564 -> 2564), I will not be able to find the shortest path since the predecessor of each vertex will be itself. This also result in an infinite loop as a side affect for this example. You can see this by placing a breakpoint after the "Debug pred" section and inspecting "vec". What is going on here? I assume this is a misunderstanding of Boost as I am quite new to it. I have tried to play around with the weights, but it seems once the weights are larger, this issue happens. These weights are not so large that overflow should be a consideration, so I am quite confused as to what is happening.
You're passing pred as both the predecessor map and the distance map. One will overwrite the other at unspecified points during algorithm execution. The result is unspecified at best, undefined if you're lucky. Fixed that and simplified some of the code, now the result is the same for both weight inputs: Live On Coliru #include <boost/graph/adjacency_list.hpp> #include <boost/graph/dag_shortest_paths.hpp> #include <boost/graph/graph_utility.hpp> #include <iomanip> #include <iostream> struct VertexType { std::string name; int age; size_t pred; friend std::ostream& operator<<(std::ostream& os, VertexType const& vt) { return os << "{" << std::quoted(vt.name) << ", " << vt.age << ", pred:" << vt.pred << "}"; } }; struct EdgeType { double weight; }; int main() { // Graph and vertex descriptor typedefs. using Graph = boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, VertexType, EdgeType>; using V = Graph::vertex_descriptor; // Create graph and vertices vector. Graph g; // Add vertices. V v0 = add_vertex({"Tom", 23, 0}, g); V v1 = add_vertex({"Frank", 25, 0}, g); V v2 = add_vertex({"John", 42, 0}, g); V v3 = add_vertex({"Emily", 22, 0}, g); // Add edges. add_edge(v0, v1, {2564}, g); add_edge(v0, v2, {3572}, g); add_edge(v1, v3, {1246}, g); add_edge(v2, v3, {5361}, g); auto bundle = get(boost::vertex_bundle, g); auto pred = get(&VertexType::pred, g); auto weight = get(&EdgeType::weight, g); auto distances = std::vector<double>(num_vertices(g)); // Dijkstra shortest path. auto src = v0; dijkstra_shortest_paths(g, src, predecessor_map(pred) .distance_map(distances.data()) .weight_map(weight)); #if 0 // Debug pred. std::vector<VertexType> vertex_properties; for (auto vd : boost::make_iterator_range(vertices(g))) { vertex_properties.push_back(g[vd]); } #endif // Extract the shortest path. std::deque<V> path; for (V cur = num_vertices(g) - 1;; cur = pred[cur]) { path.push_front(cur); if (cur == src || cur == pred[cur]) break; } // Display graph. print_graph(g, bundle, std::cout << "Graph Display: \n"); // Print the shortest path. std::cout << "\nShortest Path: "; for (const auto& vd : path) std::cout << (vd == src ? "" : " -> ") << vd; std::cout << "\nWhich is: "; for (const auto& vd : path) std::cout << (vd == src ? "" : " -> ") << g[vd]; std::cout << "\n"; } Prints Graph Display: {"Tom", 23, pred:0} --> {"Frank", 25, pred:0} {"John", 42, pred:0} {"Frank", 25, pred:0} --> {"Emily", 22, pred:1} {"John", 42, pred:0} --> {"Emily", 22, pred:1} {"Emily", 22, pred:1} --> Shortest Path: 0 -> 1 -> 3 Which is: {"Tom", 23, pred:0} -> {"Frank", 25, pred:0} -> {"Emily", 22, pred:1}
74,369,338
74,372,915
Find and print three-digit positive integers which the value of the first digit is the sum of 2nd and 3rd ones?
I've tried to separate the last digit and the second one and then add them up to compare with the first. How many loops should I use and how to apply? I've tried to separate the last digit and the second one and then add them up to compare with the first one.But I don't know how to. #include <iostream> using namespace std; int main() { unsigned int x, counter = 0 ,s = 0, j = 1; for (int i = 100; i <= 999; i++) { x = i; s = s + (x % 10); x = x / 10; s = s + (x % 10); x = x / 10; if (x / 10 == 0) break; cout << x; } }
I can see some mistakes in the posted attempt. The variable s, which should represent the sum of the second and third digits, is declared and initialized outside the loop, but its value should be reset to 0 at the beginning of the loop, otherwise it accumulates the value of all those digits in all the three digits numbers tested. the if (x / 10 == 0) break line terminates the loop at its first iteration. It should neither divide x, as it's already the "first" digit, nor test it against 0 (why have you calculated the sum, if you are not using it?), nor break the loop. The line cout << x; is, well, unreachable (because of the previous test) and wrong, as it prints (or at least tries to) the "first" digit, while the assignment requires to print the three digits numbers that satisfy the rules. So you should (conditionally, when i == s) print i instead.
74,369,360
74,369,496
Recursive Merge Sort, wrong data type for argument?
I feel like ive properly solved the problem, but the program my school is using wants me to add to existing code. The types conflict, and i get this error: main.cpp: In function ‘void mergeSort(std::vector<int>&, int, int)’: main.cpp:21:25: error: cannot convert ‘std::vector<int>’ to ‘int*’ for argument ‘1’ to ‘void merge(int*, int, int, int)’ merge(array, p, mid, r); #include <vector> using namespace std; // Takes in an array that has two sorted subarrays, // from [p..q] and [q+1..r], and merges the array void merge(int array[], int p, int q, int r) { // This code has been purposefully obfuscated, // as you'll write it yourself in next challenge. int i, j, k; int n1 = q - p + 1; int n2 = r - q; int L[n1], R[n2]; for (i = 0; i < n1; i++) L[i] = array[p + i]; for (j = 0; j < n2; j++) R[j] = array[q + 1+ j]; i = 0;j = 0;k = p; while (i < n1 && j < n2){ if (L[i] <= R[j]) { array[k] = L[i]; i++;} else { array[k] = R[j]; j++; } k++; } while (i < n1) { array[k] = L[i]; i++; k++; } while (j < n2) { array[k] = R[j]; j++; k++; } } // Takes in an array and recursively merge sorts it void mergeSort(vector<int>& array, int p, int r) { if(p >= r) { return; } int mid = (p + r) / 2; mergeSort(array, p, mid); mergeSort(array, mid + 1, r); merge(array, p, mid, r); }; This is what is provided. I'm told to add the definition to mergeSort I have not tested the code, so it could be wrong. This is not about how to solve Merge Sort, it is about the different types and get merge to accept it. Forgive me if this question is not formatted right, first time here. Thanks in advance!
To get the underlying int* in array, use the .data() method: void mergeSort(vector<int>& array, int p, int r) { //stuff merge(array.data(), p, mid, r); }; The .data() method returns an int* representing the underlying buffer in which the elements of the vector are stored. This should remove the error.
74,369,679
74,370,484
Get the address of an intrinsic function-generated instruction
I have a function that uses the compiler intrinsic __movsq to copy some data from a global buffer into another global buffer upon every call of the function. I'm trying to nop out those instructions once a flag has been set globally and the same function is called again. Example code: // compiler: MSVC++ VS 2022 in C++ mode; x64 void DispatchOptimizationLoop() { __movsq(g_table, g_localimport, 23); // hopefully create a nop after movsq? static unsigned char* ptr = (unsigned char*)(&__nop); if (!InterlockedExchange8(g_Reduce, 1)) { // point to movsq in memory ptr -= 3; // nop it out ... } // rest of function here ... } Basically the function places a nop after the movsq, and then tries to get the address of the placed nop then backtrack by the size of the movsq so that a pointer is pointing to the start of movsq, so then I can simply cover it with 3 0x90s. I am aware that the line (unsigned char*)(&__nop) is not actaully creating a nop because I'm not calling the intrinsic, I'm just trying to show what I want to do. Is this possible, or is there a better way to store the address of the instructions that need to be nop'ed out in the future?
It's not useful to have the address of a 0x90 NOP somewhere else, all you need is the address of machine code inside your function. Nothing you've written comes remotely close to helping you find that. As you say, &__nop doesn't lead to there being a NOP in your function's machine code which you could offset relative to. If you want to hard-code offsets that could break with different optimization settings, you could take the address of the start of the function and offset it. Or you could write the whole function in asm so you can put a label on the address you want to modify. That would actually let you do this safely. You might get something that happens to work with GNU C labels as values, where you can take the address of C goto labels like &&label. Like put a mylabel: before the intrinsic, and maybe after for good measure so you can check that the difference is the expected 3 bytes. If you're lucky, the compiler won't put any other instructions between your labels. So you can memset((void*)&&mylabel, 0x90, 3) (after an assert on &&mylabel_end - &&mylabel == 3). But I don't think MSVC supports that GNU extension or anything equivalent. But you can't actually use memset if another thread could be running this at the same time. And for efficiency, you want a single 3-byte NOP anyway. And of course you'd have to VirtualProtect the page of machine code containing that instruction to make it writeable. (Assuming the function is 16-byte aligned, it's hopefully impossible for that one instruction near the start to be split across two pages.) And if other threads could be running this function at the same time, you'd better use an atomic RMW (on the containing dword or qword) to replace the 3-byte instruction with a single 3-byte NOP, otherwise you could have another thread fetch and decode the first NOP, but then fetch a byte of of the movsq machine code not replaced yet. Actually a plain mov store would be atomic if it's 4 bytes not crossing an 8-byte boundary. Since there are no other writers of different data, it's fine to load / AND/OR / store to later store the same surrounding bytes you loaded earlier. Normally a non-atomic load+store is not thread-safe, but no other threads could have written a different value in the meantime. Atomicity of cross-modifying code I think cross-modifying code has atomicity rules similar to data. But if the instruction spans a 16-byte boundary, code-fetch in another core might have pulled in the first 1 or 2 bytes of it before you atomically replace all 3. So the 2nd and 3rd byte get treated as either the start of an instruction, or the 2nd + 3rd bytes of a long-NOP. Since long-NOPs generally start with 0F 1F with an escape byte, if that's not how __movsq starts then it could desync. So if cross-modifying code doesn't trigger a pipeline nuke on the other core, it's not safe to do it while another thread might be running the code. Code fetch is usually done in 16-byte chunks but that's not guaranteed. And it's not guaranteed that they're aligned 16-byte chunks. So you should probably make sure no other threads are running this function while you change the machine code. Unless you're very sure of the safety of what you're doing and check each build to make sure the instruction starts at a safe offset, where safe is defined according to any possibility or anything that could go wrong.
74,370,205
74,372,929
calculate sum and avg of the numbers in data file
created a data file to store integers and after the program reads the numbers from the data file, i want to calculate the sum total and average of the numbers and output the total and the average from the second code that reads the data file. what do i need to do to get to that to work? #include <iostream> #include <fstream> using namespace std; int main() { //declarations ofstream outputfile; int num, integer, sentinel; //open file for output outputfile.open("savedata.dat"); //get input from user cout << "How many integers would you like to enter? " << endl; cin >> integer; //use a for loop to get integers from user and store them in the file for (int i = 0; i < integer; ++i) { cout << "Enter integer: " << endl; cin >> num; outputfile << num << endl; } //close file outputfile.close(); return 0; } #include <iostream> #include <fstream> using namespace std; int main() { //open file for input and read contents ifstream inputfile; int num; inputfile.open("savedata.dat"); cout << "Contents of file: " << endl; while (inputfile >> num) // read until end of file { cout << num << endl; } //close file inputfile.close(); return 0; } tried adding int sum to find sum total but am lost
This is not that complicated. As per definition, the average can be calculated by divdiding the sum of the values by the count of the values. So, we need to add 2 variables counter --> To count the values in the file sum --> To sum up the values The variables will be defined and initialized to 0 before your read-loop. In the for loop, we can simply incremented the counter add the newly read value to the sum. After the for loop, we can output all values. But we need to "cast" the values for "counter" and "sum" to a double value, because the average is typically not an integer. Your second program could then look like the below: int main() { main2(); //open file for input and read contents ifstream inputfile; int num; inputfile.open("savedata.dat"); cout << "Contents of file: " << endl; int counter = 0; int sum = 0; while (inputfile >> num) // read until end of file { cout << num << endl; sum += num; ++counter; } //close file inputfile.close(); cout << "\nNumber of value: " << counter << "\tSum: " << sum << "\t\tAverage: " << (double)sum/(double)counter << '\n'; return 0; }
74,370,747
74,370,814
Separating this code into a header and cpp file
I am new to modern c++, so I have difficulties to separate header and cpp file with below code (AES encryption and decryption). For example, how would I separate the code? https://gist.github.com/edwardstock/3c992fb71320391d3639696328a61115
Your API goes to the header file. That includes: Any classes your users might want to use Any function/variable declarations your user might want to use The implementation of this API goes to the CPP file: Most function definitions Most variable definitions Implementation details (classes, functions your user will never need, etc.) There are exceptions, like inline function definitions might still go to the header, and templates might have to be in header files as entirely, but this is the general overview.
74,370,800
74,371,235
How to produce binned histogram from vector using std::map in C++?
I have a std::vector of float which contains 1300 data, i.e. {1.45890123, 1.47820920, 1.48326172, ...} I would like to build the histogram of the vector using std::map and then plot the histogram with OpenCV. This is how I use std::map to get the count of each data but I have no idea on how to do the binning? size_t frames = 1300 float_t *tdata = (float_t *)malloc(frames * sizeof(float_t)); std::vector<float_t> hdata(tdata, tdata + frames); std::vector<double> hdata_range, hdata_count; std::map<float_t, int> hgram; for (const auto &x : hdata) ++hgram[x]; transform(hgram.begin(), hgram.end(), back_inserter(hdata_range), [](const auto& val){return val.first;}); transform(hgram.begin(), hgram.end(), back_inserter(hdata_count), [](const auto& val){return val.second;}); Then I do plotting of the histogram with OpenCV, Ptr<plot::Plot2d> plot_1b = plot::Plot2d::create(hdata_range, hdata_count); plot_1b->setNeedPlotLine(true); plot_1b->setShowText(false); plot_1b->setShowGrid(false); plot_1b->setPlotBackgroundColor(Scalar(255, 255, 255)); plot_1b->setPlotLineColor(Scalar(0, 0, 0)); plot_1b->setPlotLineWidth(5); plot_1b->setInvertOrientation(true); plot_1b->setPlotTextColor(Scalar(0, 0, 0)); plot_1b->render(cv_display_hdata); A window containing the histogram appears, but since I did not have binning, the counts are generally 1 for each data. But I would like to add binning to the histogram to produce the Gaussian (Normal) distribution histogram. How can I do that with std::map? Thanks, rolly With the solution by paddy, I am able to produce a much better histogram but the maximum count is different from that of Matlab, any idea why? No binning histogram Matlab histogram
If you want to use a std::map for binning data, you can simply choose the bin's starting value as the key. For that, divide by the bin size and then compute the floor. This will give you a whole number uniquely identifying the bin. float_t binsize = 1.0f; std::map<float_t, int> hgram; for (auto x : hdata) { ++hgram[std::floor(x / binsize)]; } To massage the histogram data range into the form used in your question, just scale the key by the bin size. You can choose whatever single value you want to represent the bin. It might be the start or end value of the bin. Or, in the example below I choose the center of the bin: hdata_range.reserve(hgram.size()); hdata_count.reserve(hgram.size()); for (const auto& keyval : hgram) { hdata_range.push_back((keyval.first + 0.5f) * binsize); hdata_count.push_back(keyval.second); }
74,372,488
74,372,610
Weird behaviour in strptime and mktime, 01-01-1970 (d-m-Y) is unix timestamp 354907420?
I have some weird behaviour in strptime and mktime on MacOS. Perhaps I am doing something wrong but I am getting some weird output. This the code. int main(int argc, const char * argv[]) { const char* timestamp = "01-01-2022"; const char* format = "%d-%m-%Y"; struct tm tm; if (strptime(timestamp, format, &tm) == NULL) { return -1; } time_t x = mktime(&tm); std::cout << x << "\n"; } Which generates the following output: 1995902620 Which is Thu Mar 31 2033 17:23:40 GMT+0000. When I edit the timestamp to 01-01-1970 the program outputs 354907420. What am I doing wrong here?
tm is uninitialized; you should initialize it before calling strptime(). This program works: #include <iostream> #include <ctime> int main(int argc, const char * argv[]) { const char* timestamp = "01-01-1970"; const char* format = "%d-%m-%Y"; struct tm tm = {}; if (strptime(timestamp, format, &tm) == NULL) { return -1; } time_t x = mktime(&tm); std::cout << x << "\n"; }
74,373,357
74,376,684
How does Windows terminates applications without a window or console on shutdown?
I am currently writing on an background application. It has no window or console running and is also no service. I am using the /SUBSYSTEM:WINDOWS inside my CMake. So I know there are the WM_CLOSE and the CTRL_CLOSE_EVENT and I could spawn an invisible window to wait for the WM_CLOSE. My question now is, what happens to the application if it doesn't do anything of this and windows wants to shut down? Does it simply kill my application "SIGKILL" style or am I missing something here? I want to know of the shutdown to clean some stuff up, mainly handles
On logoff / shutdown all processes associated with that session will be terminated. (equivalent to TerminateProcess(), i.e. the windows SIGKILL equivalent) This is described in Logging off / Shutting down on msdn. Notifications There are a few ways you can register a handler to get a notification before your process gets terminated, depeding on the type of your application: Console Applications can use SetConsoleCtrlHandler() GUI Applications can handle the WM_QUERYENDSESSION / WM_ENDSESSION messages Note that there's no guarantee you'll get a WM_CLOSE mesage GUI Applications can NOT use SetConsoleCtrlHandler(), due to the handler not being called on logoff / shutdown: SetConsoleCtrlHandler() Remarks Section: If a console application loads the gdi32.dll or user32.dll library, the HandlerRoutine function that you specify when you call SetConsoleCtrlHandler does not get called for the CTRL_LOGOFF_EVENT and CTRL_SHUTDOWN_EVENT events. Services can use RegisterServiceCtrlHandlerEx() Logoff / Shutdown can't be delayed forever Note that you can't delay logoff / shutdown forever with those notifications; after +/- 5 seconds (non-contractual) Windows will show a list of applications that are preventing shutdown, asking the user if he wants to forcefully close them. (this one) If the user chooses "Shutdown anyway" your process will be terminated instantly If the user chooses "Cancel" the logoff / shutdown gets cancelled and your process gets to live If the user doesn't choose either option within a few seconds then Windows will auto-pick "Shutdown anyway". (resulting in termination of your process) Good read about this topic: If one program blocks shutdown, then all programs block shutdown by Raymond Chen Cleanup you need to do Note that you don't have to free allocated memory, close handles, etc... before your process gets terminated. On process termination all allocated memory will be automatically freed, all handles will be closed, and all allocated resources will be freed. See Terminating a Process for more details. So the only thing you would need to worry about is application-specific state. (e.g. if you need to persist in-memory state to the disk) I think this quote from Raymond Chen about process shutdown really gets the point across: The building is being demolished. Don’t bother sweeping the floor and emptying the trash cans and erasing the whiteboards. And don’t line up at the exit to the building so everybody can move their in/out magnet to out. All you’re doing is making the demolition team wait for you to finish these pointless housecleaning tasks. i.e. don't bother freeing allocated memory, closing handles, etc... if you know your process is about to be terminated anyway; all you're doing is delaying shutdown / logoff for no reason. Good reads about this topic: Once you return from the WM_ENDSESSION message, your process can be terminated at any time When DLL_PROCESS_DETACH tells you that the process is exiting, your best bet is just to return without doing anything Why am I getting an exception from the thread pool during process shutdown?
74,373,411
74,373,630
Thread_local cost of unused variable
Variables declared thread_local are unique for each thread. But do they consume memory if the function is not called? Let's say I have a bunch of libraries that have thread_local variables in their functions. When I create a thread, are these variables going to be initialized even if I never call the functions that use them? Example: int lib1_foo() { thread_local int a, b; // ... } int lib2_bar() { thread_local BigObject c; // ... } int main() { std::thread t([]() { // Do a, b, c consume memory? // Are they initialized? )(); t.join(); }
They certainly consume memory. cppreference has this to say (emphasis mine): thread storage duration: The storage for the object is allocated when the thread begins and deallocated when the thread ends. Each thread has its own instance of the object. Only objects declared thread_local have this storage duration. As for initialisation, it then goes on to say: See Non-local variables and Static local variables for details on initialization of objects with this storage duration. From which we get: All non-local variables with thread-local storage duration are initialized as part of thread launch, sequenced-before the execution of the thread function begins. And: Static local variables ... are initialized the first time control passes through their declaration (plus some extra verbiage which is worth reading).
74,373,477
74,541,493
how to test public void function which calls void private function of the same class using google test
dummy code: void fun() { while (m->hasMessage()) { std::pair<std::string, Vector> msg_pair = m->getMessage(); auto topic = msg_pair.first; auto msg = msg_pair.second; for (auto const& x : msg) { auto const type = m->MessageType(x); if (type == "a") { funa(x,topic); } else if (type == "b") { funb(x,topic); } else if (type == "c") { func(x,topic); } } } } fun a,fun b , fun c are private functions and fun is public function of same class how to test function fun using google test
The approach that I have followed to test public function which in turn calling private function is adding throw conditions(exceptions) in private functions and in test case using macro EXPECT_NOTHROW to test the public function : EXPECT_NOTHROW(obj.publicfunction);
74,373,807
74,373,999
Example on FFT from Numerical Recipes book results in runtime error
I am trying to implement the FFT algorithm on C. I wrote a code based on the function "four1" from the book "Numerical Recipes in C". I know that using external libraries such as FFTW would be more efficient, but I just wanted to try this as a first approach. But I am getting an error at runtime. After trying to debug for a while, I have decided to copy the exact same function provided in the book, but I still have the same problem. The problem seems to be in the following commands: tempr = wr * data[j] - wi * data[j + 1]; tempi = wr * data[j + 1] + wi * data[j]; and data[j + 1] = data[i + 1] - tempi; the j is sometimes as high as the last index of the array, so you cannot add one when indexing. As I said, I didn´t change anything from the code, so I am very surprised that it is not working for me; it is a well-known reference for numerical methods in C, and I doubt there are errors in it. Also, I have found some questions regarding the same code example but none of them seemed to have the same issue (see C: Numerical Recipies (FFT), for example). What am I doing wrong? Here is the code: #include <iostream> #include <stdio.h> using namespace std; #define SWAP(a,b) tempr=(a);(a)=(b);(b)=tempr void four1(double* data, unsigned long nn, int isign) { unsigned long n, mmax, m, j, istep, i; double wtemp, wr, wpr, wpi, wi, theta; double tempr, tempi; n = nn << 1; j = 1; for (i = 1; i < n; i += 2) { if (j > i) { SWAP(data[j], data[i]); SWAP(data[j + 1], data[i + 1]); } m = n >> 1; while (m >= 2 && j > m) { j -= m; m >>= 1; } j += m; } mmax = 2; while (n > mmax) { istep = mmax << 1; theta = isign * (6.28318530717959 / mmax); wtemp = sin(0.5 * theta); wpr = -2.0 * wtemp * wtemp; wpi = sin(theta); wr = 1.0; wi = 0.0; for (m = 1; m < mmax; m += 2) { for (i = m; i <= n; i += istep) { j = i + mmax; tempr = wr * data[j] - wi * data[j + 1]; tempi = wr * data[j + 1] + wi * data[j]; data[j] = data[i] - tempr; data[j + 1] = data[i + 1] - tempi; data[i] += tempr; data[i + 1] += tempi; } wr = (wtemp = wr) * wpr - wi * wpi + wr; wi = wi * wpr + wtemp * wpi + wi; } mmax = istep; } } #undef SWAP int main() { // Testing with random data double data[] = {1, 1, 2, 0, 1, 3, 4, 0}; four1(data, 4, 1); for (int i = 0; i < 7; i++) { cout << data[i] << " "; } }
The first 2 editions of Numerical Recipes in C use the unusual (for C) convention that arrays are 1-based. (This was probably because the Fortran (1-based) version came first and the translation to C was done without regard to conventions.) You should read section 1.2 Some C Conventions for Scientific Computing, specifically the paragraphs on Vectors and One-Dimensional Arrays. As well as trying to justify their 1-based decision, this section does explain how to adapt pointers appropriately to match their code. In your case, this should work - int main() { // Testing with random data double data[] = {1, 1, 2, 0, 1, 3, 4, 0}; double *data1based = data - 1; four1(data1based, 4, 1); for (int i = 0; i < 7; i++) { cout << data[i] << " "; } } However, as @Some programmer dude mentions in the comments the workaround advocated by the book is undefined behaviour as data1based points outside the bounds of the data array. Whilst this way well work in practice, an alternative and non-UB workaround would be to change your interpretation to match their conventions - int main() { // Testing with random data double data[] = { -1 /*dummy value*/, 1, 1, 2, 0, 1, 3, 4, 0}; four1(data, 4, 1); for (int i = 1; i < 8; i++) { cout << data[i] << " "; } } I'd be very wary of this becoming contagious though and infecting your code too widely. The third edition tacitly recognised this 'mistake' and, as part of supporting C++ and standard library collections, switched to use the C & C++ conventions of zero-based arrays.
74,374,253
74,382,823
OpenACC: Why updating an array depends on the location of the update directive
I'm new to openacc. I'm trying to use it to accelerate a particle code. However, I don't understand why when updating an array (eta in the program below) on the host, it gives different results depending on the location of '!$acc update self'. Here is a code that re-produce this problem: program approximateFun use funs use paras_mod integer :: Nx real(dp) :: dx real(dp), dimension(:), allocatable :: x, eta real(dp), dimension(5) :: xp, fAtxp !$acc declare create(Nx) !$acc declare create(x) !$acc declare create(eta) !$acc declare create(dx) !$acc declare create(fAtxp) !$acc declare create(xp) Nx = 16 !$acc update device(Nx) xp = (/3.9, 4.1, 4.5, 5.0, 5.6/) !$acc update device(xp) allocate(x(1 : Nx)) allocate(eta(1 : Nx)) eta = 0.0d0 dx = 2 * pi / (Nx - 1) !$acc update device(dx) do i = 1, Nx x(i) = (i - 1.0d0) * dx end do !$acc update device(x) call calc_etaVec(x, Nx, eta) !$acc update self(eta) ! gives the correct results !$acc parallel loop present(dx, xp, eta, fAtxp) do i = 1, 5 call calcFunAtx(xp(i), dx, eta, fAtxp(i)) end do !$acc update self (fAtxp) !!$acc update self(eta) !---> gives wrong result write(6, *) 'eta', eta do i = 1, 5 write(6, *) 'xp, fAtxp', xp(i), fAtxp(i) end do deallocate(x) deallocate(eta) end program approximateFun The previous program uses the following modules MODULE funs use paras_mod implicit none CONTAINS subroutine calc_etaVec(x, nx, eta) integer, intent(in) :: nx real(dp), dimension(:), intent(in) :: x real(dp), dimension(:), intent(out) :: eta integer :: i !$acc parallel loop present(x, eta) do i = 1, nx eta(i) = sin(x(i)) end do end subroutine subroutine calcFunAtx(xp, dx, eta, fAtx) real(dp), intent(in) :: xp, dx real(dp), dimension(:), intent(in) :: eta real(dp), intent(out) :: fAtx integer :: idx !$acc routine seq idx = 1 + floor(xp / dx) fAtx = eta(idx) end subroutine calcFunAtx END MODULE and module paras_mod implicit none save INTEGER, PARAMETER :: dp = selected_real_kind(14,300) REAL(dp), PARAMETER :: PI=4.0d0*atan(1.0d0) end module paras_mod When using !$acc update self(eta) directly after call calc_etaVec(x, Nx, eta), eta is updated correctly. But when used after the loop, only the first five elements are correct, while the remaining are zeros. What are the reasons behind that? thanks The output when !$acc update self(eta) is used directly after call calc_etaVec(x, Nx, eta) is 0.000000000000000 0.4067366430758002 0.7431448254773941 0.9510565162951535 0.9945218953682734 0.8660254037844388 0.5877852522924732 0.2079116908177597 -0.2079116908177591 -0.5877852522924730 -0.8660254037844384 -0.9945218953682732 -0.9510565162951536 -0.7431448254773946 -0.4067366430758009 -2.4492935982947064E-016 which is correct. However, when used after the loop, the output is 0.000000000000000 0.4067366430758002 0.7431448254773941 0.9510565162951535 0.9945218953682734 0.000000000000000 0.000000000000000 0.000000000000000 0.000000000000000 0.000000000000000 0.000000000000000 0.000000000000000 0.000000000000000 0.000000000000000 0.000000000000000 0.000000000000000
This one was perplexing till I determined that its a compiler error. I've filed a problem report, TPR #32673, and sent it to engineering for review. When setting the environment variable NV_ACC_NOTIFY=2, which shows the data movement, I see that the compiler is only copying 40 bytes, versus the correct 128. However, if I remove "eta" from the preceding present clause, then it's correct. #ifdef WORKS !$acc parallel loop present(dx, fAtxp) #else !$acc parallel loop present(dx, fAtxp, eta) #endif do i = 1, 5 call calcFunAtx(xp(i), dx, eta, fAtxp(i)) end do Also, this only occurs when using an allocatable in a declare create directive. If you switched to using data regions, the issue doesn't occur. Probably why we didn't see it before (looks like the bugs been there since mid-2020). Using the declare directive in anything but a module is rare.
74,374,597
74,374,645
Why is my do/while loop in c++ not allowing me to input 'amount' more than once?
I am attempting to develop a vending machine in C++ in which the user can insert as many 50 cent, 20 cent, and 10 cent coins as they would like to then move on to the 'purchase' of a product. So far, my primitive code runs smoothly; the issue I am currently facing is that I can only 'insert' coins into the vending machine once, even though I think the 'while' condition in the 'do/while' statement is being executed. Below you can find my code: ` #include <iostream> using namespace std; int main() { int productid; string order, finished; int amount; cout << "Welcome to the coffee machine! We have a variety of beverages we can offer. \n Here is our selection: \n 1) Coffee- 50 cents \n 2) Tea- 60 cents \n 3) Cappuccino- 80 cents\n"; cout << "Please select your drink of choice by entering its ID: (1, 2, or 3)"; cin >> productid; if (productid != 1 && productid != 2 && productid != 3){ cout << "That is an invalid entry; please try again. \n"; cin >> productid; } cout << "Please insert your coins. \n This vending machine only accepts 50 cent coins, 20 cent coins, and 10 cent coins. \n "; cout << "When finished, please input '0'. "; cin >> amount; if (amount != 50 && amount != 20 && amount != 10 && amount != 0){ cout << "That is an invalid coin; please insert coins again.\n"; cin >> amount; } do { amount += amount; } while (amount != 0); return 0; } ` I was expecting to be able to insert coins until I input '0', but the code terminal says 'Process finished with exit code 0' after I insert coins once, thereby not allowing me to continue to insert coins. If anyone has any suggestions as to how I could fix this so that the user can continuously insert coins until they input '0' I would greatly appreciate it. Please feel free to leave any suggestions as to how to proceed as well. Thank you
You need to put the do { ... } while(...); around the entire block you'd like to repeat. Also, you need a separate variable for the sum. int amount, sum = 0; // ... cout << "Please insert your coins. \n This vending machine only accepts 50 cent coins, 20 cent coins, and 10 cent coins. \n "; cout << "When finished, please input '0'. "; do { cin >> amount; while (amount != 50 && amount != 20 && amount != 10 && amount != 0){ cout << "That is an invalid coin; please insert coins again.\n"; cin >> amount; } sum += amount; } while (amount != 0); I've also changed an if to a while in your code for the case when the user makes multiple mistakes. To solve these cases yourself, it's recommended that you either use a debugger and step through your code; or add some logging into the code an check what's going on (e.g., what the loop repeats).
74,375,099
74,376,062
When is `noexcept` required on move assignment?
I recently realized (pretty late in fact) that it's important to have move constructors marked as noexcept, so that std containers are allowed to avoid copying. What puzzles me is why if I do an erase() on a std::vector<> the implementations I've checked (MSVC and GCC) will happily move every element back of one position (correct me if I'm wrong). Doesn't this violate the strong exception guarantee? In the end, is the move assignment required to be noexcept for it to be used by std containers? And if not, why is this different from what happens in push_back?
Here I am only guessing at the rationale, but there is a reason for which push_back might benefit more from a noexcept guarantee than erase. A main issue here is that push_back can cause the underlying array to be resized. When that happens, data has to be moved (or copied) between the old and the new array. If we move between arrays, and we get an exception in the middle of the process, we are in a very bad place. Data is split between the two arrays with no guarantees to be able to move/copy and put it all together in a single array. Indeed, attempting further moves/copies could only raise more exceptions. Since we caa only keep either the old or the new array in the vector, one "half" of the data will simply be lost, which is tragic. To avoid the issue, one possible strategy is to copy data between arrays instead of moving them. If an exception is raised, we can keep the old array and lose nothing. We can also use an improved strategy when noexcept moves are guaranteed. In such case, we can safely move data from one array to the other. By contrast, performing an erase does not resize the underlying array. Data is moved within the same array. If an exception is thrown in the middle of the process, the damage is much more contained. Say we are removing x3 from {x1,x2,x3,x4,x5,x6}, but we get an exception. {x1,x2,x3,x4,x5,x6} {x1,x2,x3 <-- x4,x5,x6} move attempted {x1,x2,x4,<moved>,x5,x6} move succeeded {x1,x2,x4,<moved> <-- x5,x6} move attempt {x1,x2,x4,<moved>,x5,x6} move failed with an exception (Above, I am assuming that if the move assignment fails with an exception, the object we are moving from is not affected.) In this case, the result is an array with all the wanted objects. No information in the objects is lost, unlike what happened with resizing using two arrays. We do lose some information, since it might not be easy to spot the <moved> object, and distinguish the "real" data from the extraneous <moved>. However, even in that position, this information loss is much less tragic than losing half of the vector's objects has it would happen with a naive implementation of resizing. Copying objects instead of moving them would not be that useful, here. Finally, note that noexcept is still useful in the erase case, but is it not as crucial as it is when resizing a vector (e.g., push_back).
74,375,574
74,409,240
Which Sentry SDK should I install for my application?
I currently have an iOS application written in C++/Qt and I want to integrate Sentry in my app. The problem is : I don't know which Sentry SDK I should use between sentry-cocoa and sentry-native. How should I chose the SDK for my application ? I tried installing sentry-native but I get this error : [sentry] DEBUG discarding envelope due to invalid transport. Does this mean that if I go with the native SDK, I will have to rewrite a transport ?
After some days experimenting, I came to the conclusion that I just needed to install the sentry-cocoa SDK for my application to be working !
74,375,683
74,375,719
what does this variable name do in the Do-While loop expression and what is the meaning of its existence in it?
im trying to learn how to reverse a number but came across a problem about this Do-While loop. Specifically while (n1). Usually i just see people put in a condition with about comparison. #include <iostream> #include <conio.h> using std::cout; using std::cin; using std::endl; int main() { long int n1, n2, Rinteger = 0; cout << "Enter an integer: " << endl; cin >> n1; n2 = n1; do { Rinteger *= 10; int digit = n1 % 10; Rinteger += digit; n1 /= 10; } while (n1); cout << "Initial integer: " << n2 << "." << endl; cout << "Reversed integer: " << Rinteger << "." << endl; return 0; } There are other ways to reverse an integer but i am curious about how does this Do-While loop works
while(n1) without a comparison just means while (n1 != 0) (C treats zero/NULL values as false, all other values as true). So the loop body is always entered once (thanks to being a do/while, rather than a plain while), and continues as long as n1 is not reduced to zero.
74,375,751
74,375,849
Create const std::vector as the concatenation of two const std::vector
I would like to create a const std::vector to contain all the elements of two other const std::vector of the same type. Since the vector is const I can not concatenate it step by step with the two const std::vector using the method mentioned in Concatenating two std::vectors. #include <iostream> #include <vector> int main() { const std::vector<int> int_a{0,1}; const std::vector<int> int_b{2,3}; const std::vector<int> all_ints; for (int i: all_ints) std::cout << i << ' '; return 0; } For the example above I would like to define all_ints in a way that the output is 0 1 2 3. How could that be done?
Make a function that takes the other two vectors, creates a third one, inserts values from the first two, returns the result by value. Then assign this to your const vector: const std::vector<int> int_a{0,1}; const std::vector<int> int_b{2,3}; const std::vector<int> all_ints = concat(int_a, int_b);
74,375,991
74,376,360
How to write contents into a file in multiple steps?
I have a basic question: I opened an old log file in the readonly mode and stored content in QTextStream, and closed it. It basically contains 7 lines of texts. I opened another file to write and tried to read line by line. I can read line by line and write entire content into the new file. But I'm trying to do the follwoing: Write first 5 lines as it is to the new file do some change to Line 6 and 7 and write to the new line QString oldfilename = "log_file"; QString newfilename = "new_log_file"; QString path1 = QCoreApplication::applicationDirPath()+"/"+oldfilename +".txt"; QString path2 = QCoreApplication::applicationDirPath()+"/"+newfilename+".txt"; QFile readfile(path1); if(!readfile.open(QIODevice::ReadOnly | QIODevice::Text)){ qDebug() << "Error opening file: "<<readfile.errorString(); } QTextStream instream(& readfile); QFile writefile(path2); if(file.open(QIODevice::WriteOnly | QIODevice::Text)) { int nb_line(0); while(!instream.atEnd()) { QString line = instream.readLine(); // Here I need to write first five lines of the file as it is if(nb_line == 6 ) { // Do some manipulation here outstream <line_6<< '\n' } if(nb_line == 7 ) { // Do some manipulation here outstream <line_7<< '\n' } ++nb_line; } readfile.close(); writefile.close(); } Can some one suggest an efficient way (using loops) to select first lines as it is and to manage changes to line 6 and 7 I can write whole contents line by line into the new file but not sure how to use right loops to select for example if the contents of the old file is Apple Cherry Pineapple Pear Grape Mushroom Egg I need my new file as: Apple Cherry Pineapple Pear Grape Orange Watermelone
since it is 5 lines you could write a simple while loop (I am using the fstream library) void readFirstFiveLines() { std::ifstream file("file.txt"); std::ofstream file2("file2.txt"); std::string line; int i = 0; while (std::getline(file, line) && i < 5) { file2 << line << std::endl; i++; } }
74,376,259
74,376,386
Array decay, passing and recieving pointers to arrays
Please help me understand what happens here: #include <iostream> void foo(int *ar) {std::cout << sizeof(arr) << '\n' << arr[3];} // exceeding array bounds on purpose int main() { int arr[2]{3, 5}; foo(arr); return 0; } Is this an example of array decay? And what exactly is *arr? Is it a pointer-to-int, or is it a pointer-to-array (of int)? In case of the latter, does it carry information about the address of a memory block holding the array? If not, how is it possible to use array notation inside a function that only recieves a pointer to its first element? Then, #include <iostream> void foo(int *ar) {std::cout << sizeof(arr) << '\n' << arr[1];} int main() { int arr[2][1]{{3}, {5}}; foo(*arr); return 0; } What happens in case of a 2D array? What does *arr represent here when passed? Is it the pointer to the first element of the right array? What does it represent when taken as an argument by a function? edit: changed array name in foo
Yes, that is an example of an array decaying into a pointer. int* arr is a pointer to the first element of the array. The address is guaranteed to be the same as the address of the array, but the type is different. In foo(*arr), you are dereferencing a int[2][1], an array of 2 elements where each element is an array of 1 element. This gives you a int(&)[1] - a reference to an array of one elements. This then decays to a pointer to the first element of the 1 element array. Now, why does int*arr; arr[2] work? Well, ptr[n] in C and C++ is defined to mean *(ptr+n). So much so that n[ptr] works (!). (do NOT do n[ptr] ever) Array indexing on normal arrays even works this way. int arr[3]; arr[2] is actually doing a decay-of-array-to-pointer, then doing +2 on that pointer, then dereferencing. C was designed as a slightly portable assembly language. And in assembly, array indexing is adding (with some multiplication) then a load instruction. pointer + int in this model converts both to ints, then scales the int by the size of the pointed to thing, adds them up, then converts back to pointers and does a load. The C++ and C standards doesn't actually say this is what is going on, because they both talk about things more abstractly to permit a variety of implementations to exist. But that is the model they are based off of.
74,376,463
74,380,616
convert python float to 32 bit object
I'm trying to use python to investigate the effect of C++ truncating doubles to floats. In C++ I have relativistic energies and momenta which are cast to floats, and I'm trying to work out whether at these energies saving them as doubles would actually result in any improved precision in the difference between energy and momentum. I chose python because it seemed like a quick and easy way to look at this with some test energies, but now I realise that the difference between C++ 32 bit floats and 64 bit doubles isn't reflect in python. I haven't yet found a simple way of taking a number and reducing the number of bits used to store it in python. Please can someone enlighten me?
I'd suggest using Numpy as well. It exposes various data types including C style floats and doubles. Other useful tools are the C++17 style hex encoding and the decimal module for getting accurate decimal expansions. For example: import numpy as np from decimal import Decimal for ftype in (np.float32, np.float64): v = np.exp(ftype(1)) pyf = float(v) print(f"{v.dtype} {v:20} {pyf.hex()} {Decimal(pyf)}") giving float32 2.7182819843292236 0x1.5bf0aa0000000p+1 2.7182819843292236328125 float64 2.718281828459045 0x1.5bf0a8b145769p+1 2.718281828459045090795598298427648842334747314453125 Unfortunately the hex-encoding is a bit verbose for float32s (i.e. the zeros are redundant), and the decimal module doesn't know about Numpy floats, so you need to convert it to a Python-native float first. But given that binary32's can be directly converted to binary64's this doesn't seem too bad. Just thought, that it sounds like you might want these written out to a file. If so, Numpy scalars (and ndarrays) support the buffer protocol, which means you can just write them out or use bytes(v) to get the underlying bytes.
74,376,668
74,376,761
How do i create a template function definition with a template class as input
Say I have the following classes: /* Frame.hpp */ template<class PayloadType> class Frame { int address; PayloadType payload; } /* RequestPacket.hpp */ template<class PayloadType> class RequestPacket { // Also a similar ResponsePacket exists Command command; // Command is an enum PayloadType payload; } /* GetMeanTemperatureRequest.hpp */ class GetMeanTemperatureRequest { // Many different Requests and Responses Period period; // Again, Period is an enum } And I have the following function: /* Serializer.hpp */ template<class From, To> size_t Serializer::serializeTo(const From& input, To buffer); Then I would like to instantiate this function for, lets say Frame: /* Frame.cpp */ #include "Serializer.hpp" template<class PayloadType> // These 2 lines are the template<> // subject of my question size_t Serializer::serializeTo(const Frame<PayloadType>& input, uint8_t* buffer) { // implementation } Then I will get error: too many template-parameter-lists. If I remove template<> then I'll get error: prototype for std::size_t Serializer::serializeTo(const Frame<PayloadType>&, uint8_t*) does not match any in class Serializer If I change the two template<...>s around it doesn't help either What does the compiler want?
A specialization needs to match the primary declaration. In your primary declaration you have: template<class From, To> size_t Serializer::serializeTo(const From& input, To buffer); so your specialization needs to be in the form of template<> size_t Serializer::serializeTo(const concrete_from_type& input, concrete_to_type buffer); What you are doing is trying combine a specialization with another template to try and get a partial specialization but that is not allowed. What you can do instead is just add another overload of your function like template<class PayloadType, To> size_t Serializer::serializeTo(const Frame<PayloadType>& input, To buffer);
74,377,169
74,377,536
I can't add a new element to dynamic array
There is something wrong with the expand() method. #include <iostream> struct obj { int fInt; float fFloat; }; template <typename T> class dynamicArray { private: T* myArray; int elements; int size; public: dynamicArray(); void add(T dane); void expand(); void init(int el); T get(int index); }; template <typename T> dynamicArray<T>::dynamicArray() { this->size = 1; this->elements = 0; this->myArray = new T[this->size]; init(this->elements); } template <typename T> T dynamicArray<T>::get(int index) { return this->myArray[index]; } template <typename T> void dynamicArray<T>::init(int el) { for (size_t i = el; i < this->size; i++) { this->myArray[this->elements] = nullptr; } } template <typename T> void dynamicArray<T>::expand() { this->size *= 2; T* tempArr = new T[this->size]; for (int i = 0; i < this->elements; i++) { tempArr[i] = this->myArray[i]; //tempArr[i] = new T(*this->myArray[i]); } for (int i = 0; i < this->elements; i++) { delete this->myArray[i]; } delete this->myArray; this->myArray = tempArr; init(this->elements); } template <typename T> void dynamicArray<T>::add(T dane) { if (this->size == this->elements) this->expand(); this->myArray[this->elements] = dane; this->elements++; } int main() { dynamicArray<obj*>* arr = new dynamicArray<obj*>(); obj* so = new obj; so->fInt = 2; so->fFloat = 2; arr->add(so); obj* so2 = new obj; so2->fInt = 3; so2->fFloat = 3; arr->add(so2); so = arr->get(0); so2 = arr->get(1); std::cout << so->fInt << std::endl; std::cout << so->fInt; } In this for loop I would like to assign to temporary array elements of myArray but they are not the copies for (int i = 0; i < this->elements; i++) { tempArr[i] = this->myArray[i]; //tempArr[i] = new T(*this->myArray[i]); } and when I delete them they disappear from tempArr too. for (int i = 0; i < this->elements; i++) { delete this->myArray[i]; } I tried couple things but I can't find the solution. tempArr[i] = new T(*this->myArray[i]); I am not sure if this is the right track, but it's giving me a 'initializing': cannot convert from 'obj' to 'T' and '=' cannot convert from 'T*' to 'T'
You got yourself confused, you have a pointer to an array of T, not a pointer to an array of T*, but some of your code is written as if you had the latter. This (in expand) for (int i = 0; i < this->elements; i++) { delete this->myArray[i]; } delete this->myArray; should simply be delete[] this->myArray; You can't delete individual array elements because they are not (necessarily) pointers. And delete[] this->myArray; will invoke the destructor for all elements in your array. And init can simply be deleted, because again it assumes that your array elements are pointers. Try writing some code with dynamicArray<int>, so that your T is definitely not a pointer. That will find all the places where you've incorrectly assumed that T is a pointer (in case I've missed any).
74,377,297
74,377,928
How do I count the number of paths in this problem?
You are given an n×n grid where each square contains an integer between 1…n^2. A route in the grid starts from some square and moves always either vertically or horizontally into another square, which has a smaller number than the current square. The squares need not be adjacent, and a route can consist of only a single square (meaning every number themselves is a path already). How many different routes are there in the grid? Because the answer may be large, print it modulo 10^9+7, i.e. the remainder when dividing the answer by 10^9+7. Input The first line contains an integer n: the size of the grid. The following n lines each contain n integers: the contents of the grid. Output Print one integer: the number of routes modulo 10^9+7. Example Input: 3 2 1 3 1 1 1 9 2 7 Output: 46 Explanation: In this example, the following three are possible routes among others: Time complexity for this should be max. O(n^2). But I am sure there is a solution for O(n) or O(n log n). How should I edit my code to calculate every path, including for example those that go vertically first and then horizontally and still continue their way somewhere. So far, my code only calculates paths directly from each number to smaller one(s) vertically and horizontally. ` #include <bits/stdc++.h> using namespace std; int main() { int n, k = 0, l = 0, row, column, paths = 0; cin>>n; int grid[n][n]; for (row = 0; row < n; row++) { for (column = 0; column < n; column++) { cin>>grid[row][column]; } } for (row = 0; row < n; row++) { for (column = 0; column < n; column++) { k = 0; l = 0; for (k = 0; k < n; k++) { if(grid[row][column]>grid[row][0+k] && grid[row][0+k] != 0) { paths++; } } for (l = 0; l < n; l++) { if(grid[row][column]>grid[0+l][column] && grid[0+l][column] != 0) { paths++; } } } } cout<<paths; } `
This problem describes a directed graph: every square has a number of (directed) neighbours that are in a horizontal or vertical direction with a smaller number than the start square. The number asked for then devolves to finding all possible paths in this graph. A solution sketch: Create a vertex for every item in the grid. Its value is the value in the grid. For every vertex, add neighbours that are in the same row or column with a smaller number. For every vertex, count the number of paths that are reachable, including the "single-tile" path. Now, to make this efficient, you can use dynamic programming to remember the number of paths starting from a given vertex. Furthermore, you can walk the vertexes in increasing number order to make sure all down stream paths have already been computed. This algorithm is O(n) in the number of grid cells.
74,378,225
74,379,873
std::memset with zero count and invalid pointer
Is it safe to call std::memset(pointer, ch, count) with invalid pointer (e.g., nullptr or junk) when count equals 0?
No, that causes undefined behavior. For example: void* p = get_address(); // may return null size_t sz = get_size(); // zero if previous returned null memset(p, 0, sz); // Compiler may assume that p is not null if (p) { // this null-check can be omitted since we "know" p is not null foo(p); } And indeed, if you look at the code generated by GCC: main: push rbx call get_address() mov rbx, rax call get_size() mov rdi, rbx xor esi, esi mov rdx, rax call memset mov rdi, rbx call foo(void*) ; <-- unconditional call xor eax, eax pop rbx ret You can see that the "if" branch is omitted.
74,378,277
74,379,976
Is there a way to check a variable is already initialized in c++?
Let us say I'm initializing a vector vector<bool> V(n);. Is there a way I can know if V[n] is initialized or not? I need this for dynamic programming purposes. If the V[n] is initialized, I would utilize the value V[n] to obtain the result. If it's not initialized yet, I'd apply a function foo(.., n) or something to obtain the value of V[n]. I am asking this because I don't want to initialize a vector<int> V(n, -1); with 3 states like -1(for unassigned, or yet to find), 0(for false), and 1(for true). Instead, if there is a way to know if a variable V[n] is unassigned, I may be able to save some space for large values of n.
Just gathering all the comments into a readable answer. All the members of a vector that exist are intialised, so to solve the problem we really need to represent 3 states, Uninitialised, False, True, and create the entries as Uninitialised. We would want the vector to initially contain nodes in state Uninitialised. So how best to represent this tristate? Considerations: Code maintainability; speed of access; memory usage. vector<bool> is a special implementation of vector which /may/ be optimised to store more than 1 value per byte. It is possible to squeeze 8 bool bits into a byte. So a vector of 1000 bool will only use 125 bytes. If you create any other vector of data, it will store an object of the size of that data type, so char, for example, or more exactly a vector<int8_t>, would use 1 byte per entry. 1000 chars would use 1000 bytes. A vector<int> would use a number of bytes per entry, probably at least 4, so would cost 4000 bytes to hold 1000 elements. But you would only be using 3 of the possible 255 states in a char, so using a vector of char would be more efficient than a vector of int, but is still somewhat wasteful of storage vs the vector<bool>. You might not care about that, and that is a fair approach. The code generated by vector<bool> is more complex than for the normal vector, so your code would be slower.. Let's go mad and use an enum: enum class State: int8_t { uninitialised = -1, False: 0, True: 1 }; std::vector<State> V(n,State::uninitialised); But what about vector<bool> ? The tighter forms suggested are to use 2 vectors of bool, one to say whether the entry is valid and the second to say that its value is set. This will cost 2*125 bytes, or 256 bytes for 1000 entries. That is still a saving over a vector of char. Or you could write your own wrapper for vector where you treat 2 consecutive entries as the valid and set flags, and you allocate it twice as large as you wanted. This has the advantage of locality of reference, and potentially the optimiser can somewhat merge consecutive questions "is it valid" then "is it set". So you save some storage, for the cost of some additional complexity (speed loss). You could wrap this in a class with accessors to hide the complexity. If you were going to do that, you could write your own wrapper round a vector<unit8_t> which divides the input index by 4 and splits the stored value into 4 2-bit tri-state values. This would possibly be slightly faster overall, as you would not separately ask the vector "is it valid" then "is it set". You /could/ squeeze more than 4 tristates into a byte - you can get 5, but that generates very slow code all round. The compiler knows how to divide by 4 very efficiently, and is less able to quickly divide by 5, or by powers of 3. These days we tend to choose speed and simplicity over space saving, so do the vector<bool> thing for fun if you like, but stick with the vector of char. That's all good. I guess the other question I have to ask, though, is under what conditions is an entry invalid? Are they made valid sequentially? If the number of valid entries an indication that the higher indices are not yet valid? In which case you could just start with an empty vector<bool> and push new values onto it as you need them - use index < size() to decide if the current index is valid or not? You can use reserve() to avoid the vector reallocating as it grows. This saves half the required storage, and keeps the code complexity manageable, so it is worth considering. Of course in your case initialised/validity may be a completely random state in which case this is not an option for you.
74,378,408
74,378,650
How can I get the type of underlying data in a SFINAE template definition?
Say I have a library function int foo( const T& ) that can operate with some specific containers as argument: std::vector<A> c1; std::list<B>() c2; auto a1 = foo(c1); // ok auto a2 = foo(c2); // ok too std::map<int, float> c3; auto a3 = foo( c3 ); // this must fail First, I wrote a traits class defining the allowed containers: template <typename T> struct IsContainer : std::false_type { }; template <typename T,std::size_t N> struct IsContainer<std::array<T,N>> : std::true_type { }; template <typename... Ts> struct IsContainer<std::vector<Ts...>>: std::true_type { }; template <typename... Ts> struct IsContainer<std::list<Ts... >>: std::true_type { }; now, "Sfinae" the function: template< typename U, typename std::enable_if<IsContainer<U>::value, U>::type* = nullptr > auto foo( const U& data ) { // ... call some other function return bar(data); } Works fine. side note: bar() is actually inside a private namespace and is also called from other code. On the contrary, foo() is part of the API. But now I want to change the behavior depending on the types inside the container i.e. inside foo(): call bar1(data) if argument is std::vector<A> or std::list<A> and call bar2(data) if argument is std::vector<B> or std::list<B> So I have this: struct A {}; // dummy here, but concrete type in my case struct B {}; template< typename U, typename std::enable_if< ( IsContainer<U>::value, U>::type* = nullptr && std::is_same<U::value_type,A> ) > auto foo( const U& data ) { // ... call some other function return bar1(data); } template< typename U, typename std::enable_if< ( IsContainer<U>::value, U>::type* = nullptr && std::is_same<U::value_type,B> ) > auto foo( const U& data ) { // ... call some other function return bar2(data); } With bar1() and bar2() (dummy) defined as: template<typename T> int bar1( const T& t ) { return 42; } template<typename T> int bar2( const T& t ) { return 43; } This works fine, as demonstrated here Now my real problem: the types A and B are actually templated by some underlying type: template<typename T> struct A { T data; } template<typename T> struct B { T data; } And I want to be able to build this: int main() { std::vector<A<int>> a; std::list<B<float>> b; std::cout << foo(a) << '\n'; // print 42 std::cout << foo(b) << '\n'; // print 43 } My problem is: I don't know how to "extract" the contained type: I tried this: template< typename U, typename F, typename std::enable_if< ( IsContainer<U>::value && std::is_same<typename U::value_type,A<F>>::value ),U >::type* = nullptr > auto foo( const U& data ) { return bar1(data); } template< typename U, typename F, typename std::enable_if< ( IsContainer<U>::value && std::is_same<typename U::value_type,B<F>>::value ), U >::type* = nullptr > auto foo( const U& data ) { return bar2(data); } But this fails to build: template argument deduction/substitution failed: main.cpp:63:21: note: couldn't deduce template parameter 'F' (see live here ) Q: How can I make this work? Side note: please only C++14 (or 17) if possible, I would rather avoid C++20 at present.
There is a simple solution: define a trait IsA in exactly the same way you defined IsContainer: template<class> struct IsA : std::false_type {}; template<class T> struct IsA<A<T>> : std::true_type {}; and then write IsContainer<U>::value && IsA<typename U::value_type>::value Depending on your exact use case, you might even not need the first trait, because for U = std::map<...>, IsA<typename U::value_type>::value will be false anyway.
74,379,582
74,379,734
Texture drawn at wrong coordinates?
I tried drawing a '1' texture at mouse coordinates when I press the 1 key: switch (e.type) { case SDL_QUIT: { quit = true; break; } case SDL_KEYDOWN: { switch (e.key.keysym.sym) { case SDLK_1: { SDL_Rect rect = {e.motion.x - 8, e.motion.y - 8, 16, 16}; SDL_RenderCopy(gRenderer, gT[3], NULL, &rect); printf("1\n"); break; } } break; } } I cannot comprehend why this doesn't work. gT[3] is the texture of the '1'. I thought maybe it is because its e.key.keysym.sym but I'm not sure.
SDL_Event::motion is only valid when SDL_Event::type is SDL_MOUSEMOTION. Stop trying to use SDL_Event::motion when SDL_Event::type is SDL_KEYDOWN, perhaps by recording the X and Y coordinates of the most recent SDL_MOUSEMOTION event and using those instead.
74,380,505
74,380,569
C++ Inheritance and use of Const
I'm currently learning c++ and in inheritance. I have an issue concerning use of const. Here's the code : #include <iostream> using namespace std; class Base { public : virtual void pol() const { cout<< " Base "; } }; class Derived : virtual public Base { public: void pol( ) { cout<< "derived"; } }; int main( ) { const Base *b = new Derived(); b-> pol(); return 0; } My teacher absolutely wants me to use "const Base *b" in the function main() When I compile and execute this code the result printed is "Base" , while I'm expecting getting an "derived". I know it come from the " const" use in : virtual void pol() const But it's for the moment the only way I found to get this compile. Thanks for your time
The problem is that in the derived class const-ness for method pol is missing and therefore is considered a different method, not an override. Add const there too and it will work as you expect
74,380,520
74,381,788
std::invoke_result<F, Args...> does not seem to give a const type
I'd like to start with a simplified example: const bool Foo() { return false; } bool Bar() { return false; } int main() { std::cout << std::is_same<const bool, std::invoke_result_t<decltype(Foo)>>::value << std::endl; std::cout << std::is_same<bool, std::invoke_result_t<decltype(Foo)>>::value << std::endl; std::cout << std::is_same<bool, std::invoke_result_t<decltype(Bar)>>::value << std::endl; } I expected 1 0 1 but the result was 0 1 1. Is this expected? If so, is this different from compiler to compiler, or determined by the C++ standard? My understanding was we can still return const T but it just does not make much difference/does not make sense since C++11. Thus, I thought the return type is still const T (const bool here) and the compiler would warn me, which does not appear to be the case. I'd like to understand what is going on.
std::invoke_result does not give you the declared return type of the function. It gives you the decltype that an INVOKE expression, i.e. a function call expression in this case, would have with the given argument types. That is specified essentially exactly like this (with a bit more technical wording) in the standard. A function call expression of a function returning by-value (instead of by-reference) is a prvalue expression. If a prvalue expression is of non-class type, it has its const-qualifier always stripped. There is no difference between a const and non-const non-class prvalue in the language. So that is why you don't get a const. const on a function returning a non-class type by-value is essentially pointless and compilers will warn you about that with warnings enabled. The only effect the const has here is to change the type of the function. There is no difference in actual calls to the function. Even const on a class type returned by-value is mostly useless. There are only few special cases where it makes sense (e.g. to disallow calling modifying member functions directly on the call expression), but also comes with significant issues (i.e. potentially disabling move semantics). This was more common in early C++, but since C++11 it is also only seldom used.
74,380,580
74,380,773
How to draw texture at mouse coords using keyboard
Its like the title suggests, i want to draw a "1" texture at mouse coords using a keyboard key press. I am using switch statements for input: switch (e.type) { case SDL_QUIT: { quit = true; break; } case SDL_MOUSEBUTTONDOWN: { switch (e.button.button) { case SDL_BUTTON_LEFT: { SDL_Rect rect = {e.motion.x - 10, e.motion.y - 10, 20, 20}; SDL_RenderCopy(gRenderer, gT[0], NULL, &rect); printf("nod\n"); break; } } break; } case SDL_KEYDOWN: { switch (e.key.keysym.sym) { case SDLK_c: { SDL_SetRenderDrawColor(gRenderer, 255, 255, 255, 255); SDL_RenderClear(gRenderer); printf("tot ecranul\n"); break; } case SDLK_1: { SDL_Rect rect = {e.motion.x - 8, e.motion.y - 8, 16, 16}; SDL_RenderCopy(gRenderer, gT[3], NULL, &rect); printf("1\n"); break; } } break; } } I tried some random things, and no success so far. gT[3] is the "1" texture.
e.motion only makes sense when e is a mouse event. Call SDL_GetMouseState to get the current mouse position.
74,380,618
74,380,781
Is there a way to display a vector IN ORDER using a reverse iterator? C++
I have this vector of names: vector <string> names; names.push_back("William"); names.push_back("Maria"); names.push_back("Petterson"); names.push_back("McCarthy"); names.push_back("Jose"); names.push_back("Pedro"); names.push_back("Hang"); I need to display this vector IN ORDER using a reverse iterator. This is my attempt: //Define a reverse iterator for the vector object vector<string>::reverse_iterator itR = names.rend(); itR = itR - 1; //Use the reverse iterator to display each element in the vector cout << "\tNames:\n"; while (itR != names.rbegin()) { cout << *itR << endl; itR--; } This will display all names in correct order BUT it cuts off "Hang" at the end, any tips?
If you go from the end of a range to the beginning, you should check the equality first and then decrement inside the loop body. Otherwise there either is no iteration for the last element or the iterator gets decremented past the end resulting in undefined behaviour. You could use the following loop: // print elements in original (= non-reversed) order for (auto pos = names.rend(); pos != names.rbegin();) { --pos; std::cout << *pos << std::endl; }
74,380,637
74,380,980
boost::adaptors::transformed fails with std::filesystem::directory_iterator
Why entry is empty inside boost::adaptors::transformed() ? I tried without filter, but it does not help. #include <boost/range/adaptors.hpp> #include <boost/static_string/static_string.hpp> #include <boost/utility/string_view.hpp> #include <filesystem> #include <iostream> const auto root = std::filesystem::path("."); const auto names = boost::make_iterator_range( std::filesystem::directory_iterator(root), std::filesystem::directory_iterator {} ) | boost::adaptors::filtered([](const std::filesystem::directory_entry& entry) { const auto name = entry.path().stem().string(); const auto suff = entry.path().extension().string(); return suff == ".cfg" && !boost::string_view(name).starts_with("__"); }) | boost::adaptors::transformed([](const std::filesystem::directory_entry& entry) { auto result = boost::static_string<64>{}; result = entry.path().stem().string(); std::cout << result << std::endl; return result; }); UPDATE // append this lines std::cout << boost::size(names) << std::endl; std::cout << boost::size(names) << std::endl; First call of boost::size() returns right count of names, but second returns 1. I think this is a special behavior of the std::filesystem::directory_iterator
I have copied your image into a self-contained program an cannot see your issue: Live On Coliru #include <boost/range/adaptors.hpp> #include <boost/static_string/static_string.hpp> #include <boost/utility/string_view.hpp> #include <filesystem> #include <iostream> int main() { std::filesystem::path root = "."; const auto names = boost::make_iterator_range(std::filesystem::directory_iterator(root), std::filesystem::directory_iterator{}) | boost::adaptors::filtered([](const std::filesystem::directory_entry& entry) { const auto name = entry.path().stem().string(); const auto suff = entry.path().extension().string(); return suff == ".cfg" && !boost::string_view(name).starts_with("__"); }) | boost::adaptors::transformed([](const std::filesystem::directory_entry& entry) { auto result = boost::static_string<64>{}; result = entry.path().stem().string(); return result; }); for (auto&& name : names) { std::cout << " - " << name << "\n"; } } Creating some files like: touch test{001..022}.cfg touch __hidden.cfg Prints - test001 - test006 - test013 - test017 - test015 - test021 - test008 - test012 - test016 - test002 - test007 - test005 - test010 - test009 - test020 - test014 - test019 - test022 - test018 - test011 - test004 - test003 BONUS Simplification and style: Live On Coliru #include <boost/range/adaptors.hpp> #include <boost/static_string/static_string.hpp> #include <boost/utility/string_view.hpp> #include <filesystem> #include <iostream> namespace fs = std::filesystem; bool is_config(fs::path const& p) { auto name = p.stem().string(); return p.extension() == ".cfg" && !boost::string_view(name).starts_with("__"); }; auto stem(fs::path const& p) { return boost::static_string<64>{p.stem().string()}; } auto cfgs(fs::path root) { using namespace boost::adaptors; auto files = boost::make_iterator_range(fs::directory_iterator(root), {}); return files | filtered(is_config) | transformed(stem); } int main() { for (auto cfg : cfgs(".")) std::cout << " - " << cfg << "\n"; } Same output, obviously.
74,381,187
74,382,139
Find indexes of multiple minimum value in an array in c++
Please don't write that I should do my homework myself. I have tried but cannot find the answer. Input: arr[11]={1,2,3,4,1,5,6,7,8,1,9} Output: 0 4 9 Returned position numbers are to be inserted into another array, I mean: arr_min_index[HowManyMinValues]={0,4,9} I tried to end it in many different ways, but I failed. #include <iostream> using namespace std; int main() { int n; cout<<"How many elements should be in the array?"<<endl; cin>>n; int arr[n]; int i, j, MIN = arr[0], position=0, how_many; for(i=0; i<n; i++) { cin>>arr[i]; } for(i=0; i<n; i++) { if(arr[i]<MIN) { MIN = arr[i]; how_many=0; } if(tab[i]==MIN) { how_many=+1; } } }
Actually you are almost there, if you are new to c/c++, it is a good start. only two modification on you code could make it work: #include <iostream> // using namespace std; // is not a good practice int main() { int n; std::cout<<"How many elements should be in the array?"<<std::endl; std::cin >> n; int arr[n]; int idx[n]; // define an array to store indices, maximum same size as input int i, j, position=0, how_many = 0; for(i=0; i<n; i++) { std::cin>>arr[i]; } int MIN = arr[0]; // select initial guess for minimjum after array is initialized for(i=0; i<n; i++) { if(arr[i]<MIN) { MIN = arr[i]; how_many=0; } if(arr[i]==MIN) { idx[how_many++] = i; //only in this line you can store your new idx and increment } } for(i=0; i < how_many; i++) { if(i == 0) {std::cout << "{" ;} std::cout<< idx[i] << ", "; if(i == 0) {std::cout << "}" << std::endl ;} } } I have indicated only lines which needed to be modified. but as suggested by other, it is better to use std::vectors and avoid unnecessary big array size, and more managed, safe code. However this is just to show that you thinking was correct and was almost close.
74,381,238
74,381,338
How to define default constructor and user-defined constructor in the same line?
In my university class we are messing around with inheritance, though my professor's code confused me and seemed to be a little off. class Circle { protected: double radius; public: Circle(double = 1.0); double calcval(); }; Circle::Circle(double r) { radius = r; } Here she is creating a default constructor within the class then creating a separate user-defined constructor outside of the class. When I initially saw this I thought there has to be a way to do this more efficiently and in return take up less space, making the code more readable. After some searching online I found some resources at which I tried, though I am still getting some errors. Here is the constructors for class "Circle" which I tried. class Circle { protected: double radius; public: double calcVal(); Circle(double r = 1.0) : radius(r) {} }; Is this correct? I am trying to make the default constructor set radius = 1.0 and have a constructor that sets radius = to 'r', the user input. We also have another derived class "Cylinder" which I tried doing something similar but received errors. Here is my professor's implementation. class Cylinder : public Circle { protected: double length; double volume; public: Cylinder(double r, double len); double calcval(); }; Cylinder::Cylinder(double r, double len){ length =len; this->radius =r; } Then here is what I attempted. class Cylinder : public Circle { private: double length; double volume; public: double calcVal(); Cylinder(double r, double len) : length(len) this->radius(r) {} }; However, I get an error on the beginning of "this", which says "expected a "{"." How, if possible, would I create a default constructor and user-defined constructor in the same line for readability and cleaner code? Thank you so much for reading. My overall implementation for your convenience. :) class Circle { protected: double radius; public: double calcVal(); Circle(double r = 1.0) : radius(r) {} }; double Circle::calcVal() { return (PI * (radius * radius)); } class Cylinder : public Circle { private: double length; double volume; public: double calcVal(); Cylinder(double r, double len) : length(len) this->radius(r) {} }; double Cylinder::calcVal() { return (length * PI * (r * r)); }
Here she is creating a default constructor within the class then creating a separate user-defined constructor outside of the class. No, she is declaring the default constructor inside the class's declaration, and then defining the body of that constructor outside of the class declaration. This is perfectly legal and correct code. I am still getting some errors That is because you have mistakes in your code. Here is the constructors for class "Circle" which I tried ... Is this correct? In that example, yes. We also have another derived class "Cylinder" which I tried doing something similar but received errors ... Then here is what I attempted ... However, I get an error on the beginning of "this", which says "expected a "{"." Since radius is a member of Circle, you should let Circle's constructor initialize radius. Don't do that in your derived Cylinder's constructor. But, you are not calling Circle's constructor yourself, so the compiler will call it for you, passing in its default argument value. You are also missing a , in your Cylinder's constructor member initialization list, which is a syntax error. Try this instead: Cylinder(double r, double len) : Circle(r), length(len) {} Now, that being said, there are some other things worth pointing out in your code. Your Cylinder class has a volume member that is never initialized or used, so it should be removed completely. Inside of Cylinder::calcVal(), r is undefined. It is a local variable in the Circle and Cylinder constructors only. You need to use the radius member instead (just like how Circle::calcVal() does, and how Cylinder::calcVal() is using the length member instead of the len constructor argument), eg: return (length * PI * (radius * radius)); You are declaring double calcVal(); in both classes, but Circle::calcVal() is not marked as virtual, so Cylinder::calcVal() will not override it. If you were to ever make a Circle*/Circle& refer to a Cylinder object and then call calcVal() on that, only Circle::calcVal() would be called, not Cylinder::calcVal(). So, make Circle::calcVal() be virtual, eg: virtual double calcVal(); And for good measure, Cylinder should then mark its calcVal() as override: double calcVal() override; Since you want to reduce complexity in your classes, you can inline calcVal() in both classes, eg: class Circle { protected: double radius; public: virtual double calcVal() { return (PI * (radius * radius)); } Circle(double r = 1.0) : radius(r) {} }; class Cylinder : public Circle { private: double length; public: double calcVal() override { return (length * PI * (radius * radius)); } Cylinder(double r, double len) : Circle(r), length(len) {} }; And then, since Circle::calcVal() and Cylinder::calcVal() are both calculating the same PI * radius * radius value, where Cylinder is just multiplying the result by length, you can actually call Circle::calcVal() inside of Cylinder::calcVal() to do the common work, eg: double calcVal() override { return (length * Circle::calcVal());
74,382,382
74,384,256
how do i compare types in c++?
i'm trying to divide two integers, and if the output is not an integer, it doesn't continue. for some reason this refuses to work no matter what i try. int numeratorOutput{}; int denominatorOutput{}; for (int i{ 2 }; i < 100; ++i) { auto test = numerator / i; auto test2 = denominator / i; if (typeid(test) == typeid(int) && typeid(test2) == typeid(int)) { cout << i << '\n'; cout << "yes\n\n"; numeratorOutput = numerator / i; denominatorOutput = denominator / i; break; } else { cout << "no\n"; } } i tried typeid, sizeof, is_same, etc.; but it let to no avail
how do i compare types in c++? In your given example, you can use decltype along with std::is_same to check if test is the same as int and test2 is the same as int as shown below: #include <type_traits> static_assert(std::is_same_v<decltype(test), int>); static_assert(std::is_same_v<decltype(test2), int>);
74,382,530
74,382,545
How to use comparer function inside class with algorithm header?
This is what my compare function looks like: bool smallest_weight(const size_t& i, const size_t& j) { return this->abs_weight[i] < this->abs_weight[j]; } I use this function inside the constructor of the class to initialize some other arrays. This is the code that uses it: size_t best_node = *min_element( this->pointer_list[i + 1].begin(), this->pointer_list[i + 1].end(), smallest_weight ); When I try to compile, I get the following error: error: invalid use of non-static member function ‘bool TimeCalculator::smallest_weight(const size_t&, const size_t&)’ I can't make the function static since it won't be able to access the data inside the class, I'd also like to avoid making the arrays global if possible. How can I achieve that?
Try this: size_t best_node = *min_element( this->pointer_list[i + 1].begin(), this->pointer_list[i + 1].end(), [&](const auto& i, const auto& j) noexcept { return this->smallest_weight(i, j); } );
74,382,886
74,383,373
Store character in 2d array and print
I am trying to make a program that plays battleship. I have a 2D array that is printed to the console with nested for loops to display a 10x10 grid of dots that represent the grid. I would like to be able to have the user input an x and y coord for the ship and have it displayed on the grid with a different character like a "+" for example and have it stored every time I "re-draw" the grid. char playerBoard[][] is initialized earlier in the global scope. void drawPlayerBoard() { int yLabel = 0; char xLabel = 65;// ascii for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { playerBoard[i][j] = 46;// ascii } } cout << " "; for (xLabel = 65; xLabel < 75; xLabel++) { cout << xLabel << " "; } cout << "\n"; for (int i = 0; i < rows; i++) { yLabel++; if (yLabel >= 10) { cout << yLabel << " "; } else { cout << yLabel << " "; } for (int j = 0; j < columns; j++) { cout << playerBoard[i][j] << " "; } cout << "\n"; } }
You can make this a lot easier on yourself. For instance, initializing every value of playerBoard to '.' can be as simple as: std::fill_n((char*)playerBoard, rows * columns, '.'); You probably don't want to do that in the drawPlayerBoard function, because you'll erase your board whenever you want to display it. Make a separate function: #include <algorithm> const int rows = 10; const int cols = 10; char playerBoard[rows][cols]; void clearPlayerBoard() { std::fill_n((char*)playerBoard, rows * cols, '.'); } For outputting X-labels, similarly avoid using magic numbers representing ASCII values. For instance, you can write char('A' + i) to get the letter you want. To manage your spacing, use I/O manipulators to control the output width. This avoids ugly code like you're doing with your yLabel tests right now. Simply use std::setw, and avoid cluttering your code with strings of spaces. Putting this together: #include <iomanip> #include <iostream> void drawPlayerBoard() { const int colWidth = 2; const int rowLabelWidth = 3; // Draw X labels std::cout << std::setw(rowLabelWidth) << ""; for (int col = 0; col < cols; col++) { std::cout << std::setw(colWidth) << char('A' + col); } std::cout << '\n'; // Draw rest of board for (int row = 0; row < rows; row++) { std::cout << std::setw(rowLabelWidth) << row + 1; for (int col = 0; col < cols; col++) { std::cout << std::setw(colWidth) << playerBoard[row][col]; } std::cout << '\n'; } } Notice how you can now control the layout with those two "width" values. The most useful here would be the rowLabelWidth value, which effectively controls how much indentation your board has. To test, just some simple driver code from main: int main() { clearPlayerBoard(); drawPlayerBoard(); } And you get the output: A B C D E F G H I J 1 . . . . . . . . . . 2 . . . . . . . . . . 3 . . . . . . . . . . 4 . . . . . . . . . . 5 . . . . . . . . . . 6 . . . . . . . . . . 7 . . . . . . . . . . 8 . . . . . . . . . . 9 . . . . . . . . . . 10 . . . . . . . . . . Now you can write a simple function to add your ships: void placeShip(int row, int col, int size, bool horizontal, char player) { if (horizontal) { for (int i = 0; i < size; i++) playerBoard[row][col+i] = player; } else { for (int i = 0; i < size; i++) playerBoard[row+i][col] = player; } } Example: char player = '#'; placeShip(3, 2, 5, false, player); placeShip(2, 4, 4, true, player); placeShip(0, 9, 3, false, player); placeShip(6, 6, 3, true, player); placeShip(8, 7, 2, true, player); drawPlayerBoard(); Output: A B C D E F G H I J 1 . . . . . . . . . # 2 . . . . . . . . . # 3 . . . . # # # # . # 4 . . # . . . . . . . 5 . . # . . . . . . . 6 . . # . . . . . . . 7 . . # . . . # # # . 8 . . # . . . . . . . 9 . . . . . . . # # . 10 . . . . . . . . . .
74,383,298
74,383,542
Input information into a string array - overwriting other parts?
I have a string array that I would like to hold information input at runtime. I'm using an int var to control how many 'rows' there are in my array, but there will only ever be a set number of 'columns'. #include <iostream> using namespace std; int main() { int rows; cout << "How many rows? "; cin >> rows; string data[rows][2]; for(int i = 0; i < rows; i++) { cout << "Column 1: "; cin >> data[i][0]; cout << "Column 2: "; cin >> data[i][1]; cout << "Column 3: "; cin >> data[i][2]; } for(int i = 0; i < rows; i++) { cout << "Row " << i+1 << endl; cout << "Column 1: " << data[i][0] << endl; cout << "Column 2: " << data[i][1] << endl; cout << "Column 3: " << data[i][2] << endl; } } Expected output: Row 1 Data 1: 123 Data 2: 456 Data 3: 789 Row 2 Data 1: aaa Data 2: bbb Data 3: dcc Actual output: Row 1 Data 1: 123 Data 2: 456 Data 3: aaa Row 2 Data 1: aaa Data 2: bbb Data 3: dcc This works for entering a single row, but if I'm entering more than one rows worth of data at a time, the last column's data is overwritten by the first column's data for the next row (so [0][2] holds the same data as [1][0]). (Unfortunately, I am very new at C++ so can't figure out what's going on :()
Well, if I understood correctly that the task is to store strings with text in an array that imply the use of newline hyphenation, then here: #include <iostream> #include <vector> #include <string> using namespace std; int main() { int rows; cout << "How many rows? "; cin >> rows; vector <string> page; for (int i = 0; i < rows; i++) { string temp; cout << "Column 1: "; cin >> temp; page.push_back(temp); //test temp = "Column: \n Column:2"; page.push_back(temp); //end test cout << "Column 3: "; cin >> temp; page.push_back(temp); } for (auto & item : page) { cout << "\n page = {\n" << item<<"}\n"; } } and yes, in a static array, you cannot specify its variable size, since the value of the variable is not known during compilation, which is why the maximum possible amount of memory is allocated for the array
74,383,367
74,383,393
How to designated initialize a C++ struct that has a construcotr?
I have a very large struct that has customized copying constructor, customized moving constructor, customized moving assignator, and customized copying assignator, but I also need to use Designated Initialization syntax somewhere to initialize it, because it is very large, while I just want to initialize only few fields of it and let the rest fields to keep default values. For example: struct SA_t { int a; int b; int c; }; int main() { SA_t sa1 { .a = 2, .b = 3, .c = 4,}; // no problem return EXIT_SUCCESS; }; But when I added a customized constructor for it, I can NOT use Designated Initializing method at all. struct SA_t { SA_t() { a = 0; b = 1; c = 2; }; int a; int b; int c; }; int main() { SA_t sa1 { .a = 2, .b = 3, .c = 4,}; /* no matching function for call to ‘SA_t::SA_t(<brace-enclosed initializer list>)’ */ return EXIT_SUCCESS; }; Is there a way, I can keep the customized constructor and use Designated Initialization syntax at same time?
There isn't. Designated initializers work only for aggregates. Aggregates are types that satisfy a few conditions, notably: no user-declared or inherited constructors
74,383,685
74,383,710
C++ programming project header/implementation files
So i am practicing header files and implementation files for c++ and i cannot seem to display the letter grade for this program. Everything else is working as it should and displaying the correct data except for the letter grade. I have been trying to figure it out and i think it may be something so simple that i am missing but i need an extra set of eyes. i would really appreciate the help! //Main program #include <iostream> #include <string> #include "studentType.h" using namespace std; int main() { studentType student; studentType newStudent("Brain", "Johnson", '*', 85, 95, 3.89); student.print(); cout << "***************" << endl << endl; newStudent.print(); cout << "***************" << endl << endl; return 0; } Header File: #include <string> using namespace std; class studentType { private: string firstName; string lastName; int grade; int average; char courseGrade; int testScore; int progScore; double GPA; public: studentType(string fn = "", string ln = "", char courseGrade = '*', int tscore = 0, int pscore = 0, double gpa = 0); string getFirstName() const; string getLastName() const; int getGrade(); char getCourseGrade() const; int getTestScore() const; int getProgScore() const; double getGPA() const; void setFirstName(string fn); void setLastName(string ln); void setGrade(); void setCourseGrade(char courseGrade); void setTestScore(int tscore); void setProgScore(int pscore); void setGPA(double gpa); void print(); }; Implementation file: #include <iostream> #include <string> #include <iomanip> #include "studentType.h" using namespace std; studentType::studentType(string fn, string ln, char courseGrade, int tscore, int pscore, double gpa) { firstName = fn; lastName = ln; courseGrade = courseGrade; testScore = tscore; progScore = pscore; GPA = gpa; } string studentType::getFirstName() const { return firstName; } string studentType::getLastName() const { return lastName; } int studentType::getGrade() { return grade; } char studentType::getCourseGrade() const { return courseGrade; } int studentType::getTestScore() const { return testScore; } int studentType::getProgScore() const { return progScore; } double studentType::getGPA() const { return GPA; } void studentType::setFirstName(string fn) { firstName = fn; } void studentType::setLastName(string ln) { lastName = ln; } void studentType::setGrade() { int average = (testScore + progScore) / 2; if(average >= 90){ courseGrade = 'A'; } else if(average >= 80){ courseGrade = 'B'; } else if(average >= 70){ courseGrade = 'C'; } else if(average >= 60){ courseGrade = 'D'; } else{ courseGrade = 'F'; } } void studentType::setCourseGrade(char courseGrade) { courseGrade = courseGrade; } void studentType::setTestScore(int tscore) { testScore = tscore; } void studentType::setProgScore(int pscore) { progScore = pscore; } void studentType::setGPA(double gpa) { GPA = gpa; } void studentType::print() { cout << "Name: " << firstName << " " << lastName << endl; cout << "Grade: " << courseGrade << endl; cout << "Test Score: " << testScore << endl; cout << "Programming Score: " << progScore << endl; cout << "GPA: " << GPA << endl; } I think it has something to do with the constructor like adding my grade() function but to be honest my brain is fried and i just need some help i have been staring at this for way to long...
You are never calling setGrade(). Maybe you should call it in the class's constructor?
74,383,819
74,383,887
program that reads an integer, and prints all the perfect numbers
int n; int sum; cout << "write a number"; cin >> n; for (int i = 1; i < n; i++) { sum = 0; for (int j = 1; j <= i; j++) { if (i % j == 0) sum = sum + j; } if (sum == i) cout << i<< endl; } Why do I always get 1 as a result? I couldn't understand the logic of it. When I change the second for loop and make it i/2, I get the correct result, but I couldn't understand how it worked. input 1000 expected result = 6 28 496
Remind about mathematics. Refer to wiki In number theory, a perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. So, in your code, you are making sum of ALL divisors of i include itself. That's why you only get result 1. You should change it simply. for (int j = 1; j < i; j++)
74,384,200
74,384,993
How to extract value from json array with QJsonDocument format
I'm getting a json format like this and I want to get the value of "Duration", "Id", "LoadCumulLimit" and "Notes". QJsonDocument({"d":{"results":[{"Duration":"420.000","Id":"123456789XYZ","LoadCumulLimit":"15.000","NavWpNioshToOpNoish":{"__deferred":{"uri":"http://xxx/WorkplaceNOISHDataSet('123456789XYZ')/NavWpNioshToOpNoish"}},"Notes":"123456789XYZ","__metadata":{"id":"xxx/WorkplaceNOISHDataSet('123456789XYZ')","type":"xxx.WorkplaceNOISHData","uri":"xxx/WorkplaceNOISHDataSet('123456789XYZ')"}}]}}) I tried to do this but it doesn't work and it return empty with array ` QJsonDocument document = QJsonDocument::fromJson(content.toUtf8()); QJsonArray documentArray = document.array(); QStringList wordList; for (const QJsonValue &i : documentArray) { //qInfo() << i.toString() << endl; wordList << i.toString(); } Could you guys give me a help or any suggest?
You could convert the QJsonDocument to a QVariant. Then you can use QVariantMap or QVariantList to walk the document and use the appropriate toString() or toDouble() to retrieve the values. The following is hard-coded to your JSON there are only minimal validation checks included. (i.e. it is a disclaimer that the code is presented for educational purposes only and made not be production ready). bool parse() { QString json = "{\"d\":{\"results\":[{\"Duration\":\"420.000\",\"Id\":\"123456789XYZ\",\"LoadCumulLimit\":\"15.000\",\"NavWpNioshToOpNoish\":{\"__deferred\":{\"uri\":\"http://xxx/WorkplaceNOISHDataSet('123456789XYZ')/NavWpNioshToOpNoish\"}},\"Notes\":\"123456789XYZ\",\"__metadata\":{\"id\":\"xxx/WorkplaceNOISHDataSet('123456789XYZ')\",\"type\":\"xxx.WorkplaceNOISHData\",\"uri\":\"xxx/WorkplaceNOISHDataSet('123456789XYZ')\"}}]}}"; QJsonDocument document = QJsonDocument::fromJson(json.toUtf8()); if (document.isEmpty() || document.isNull()) return false; QVariantMap root = document.toVariant().toMap(); if (root.isEmpty()) return false; QVariantMap d = root["d"].toMap(); if (d.isEmpty()) return false; QVariantList results = d["results"].toList(); if (results.isEmpty()) return false; foreach (QVariant varResult, results) { QVariantMap result = varResult.toMap(); if (result.isEmpty()) return false; bool ok = true; double duration = result["Duration"].toDouble(&ok); if (!ok) return false; QString id = result["Id"].toString(); if (id.isEmpty() || id.isNull()) return false; double loadCumulLimit = result["LoadCumulLimit"].toDouble(&ok); if (!ok) return false; QString notes = result["Notes"].toString(); if (!notes.isEmpty() || notes.isNull()) return false; qDebug() << id << duration << loadCumulLimit << notes; // "123456789XYZ" 420 15 "123456789XYZ" } return true; } Alternatively, you can just use QJsonDocument, QJsonValue and QJsonArray to walk the document and use the corresponding toString() and toDouble() to retrieve the values. Again, there are minimal validation checks included: bool parse2() { QString json = "{\"d\":{\"results\":[{\"Duration\":\"420.000\",\"Id\":\"123456789XYZ\",\"LoadCumulLimit\":\"15.000\",\"NavWpNioshToOpNoish\":{\"__deferred\":{\"uri\":\"http://xxx/WorkplaceNOISHDataSet('123456789XYZ')/NavWpNioshToOpNoish\"}},\"Notes\":\"123456789XYZ\",\"__metadata\":{\"id\":\"xxx/WorkplaceNOISHDataSet('123456789XYZ')\",\"type\":\"xxx.WorkplaceNOISHData\",\"uri\":\"xxx/WorkplaceNOISHDataSet('123456789XYZ')\"}}]}}"; QJsonDocument document = QJsonDocument::fromJson(json.toUtf8()); if (document.isEmpty() || document.isNull()) return false; QJsonValue d = document["d"]; if (d.isNull() || d.isUndefined()) return false; QJsonArray results = d["results"].toArray(); if (results.isEmpty()) return false; foreach (QJsonValue result, results) { double duration = result["Duration"].toDouble(); QString id = result["Id"].toString(); if (id.isEmpty() || id.isNull()) return false; double loadCumulLimit = result["LoadCumulLimit"].toDouble(); QString notes = result["Notes"].toString(); if (!notes.isEmpty() || notes.isNull()) return false; qDebug() << id << duration << loadCumulLimit << notes; // "123456789XYZ" 420 15 "123456789XYZ" } return true; }
74,384,437
74,384,794
How to define a multiline wstring with content from another file
I would like to define the content of a file in a wstring, so I can print it with an ofstream later on. Example: // Working std::wstring file_content=L"€"; // Working file_content=L"€" L"€" L"€"; // NOT Working file_content=L"€" L"€"" L"€"; // Working file_content=LR"SOMETHING(multiline with no issues)SOMETHING"; For some reason, the last solution is not working for me WHEN I paste in the file content (Multibyte). Errors: E0065 expected a ';' E2452 ending delimiter for raw string not found
You need to escape double-quote characters inside of a string literal, eg: // Working file_content=L"€" L"€\"" // <-- L"€"; Alternatively, use a raw string literal instead, which does not require its characters to be escaped, eg: // Working file_content=L"€" LR"(€")" // <-- L"€";
74,384,496
74,384,544
Memory fault when print *pointer
Why do I have a memory fault in the below code? How do I fix it? I want to read the progress of the outside function. But I only get the output get_report_progress:100 #include <iostream> int* int_get_progress = 0; void get_progress(int* int_get_progress) { int n = 100; int *report_progress = &n; int_get_progress = report_progress; std::cout << "get_report_progress:" << *int_get_progress <<std::endl; } int main() { get_progress(int_get_progress); std::cout << "main get process:" << *int_get_progress << std::endl; return 0; }
Your global int_get_progress variable is a pointer that is initialized to null. You are passing it by value to the function, so a copy of it is made. As such, any new value the function assigns to that pointer is to the copy, not to the original. Thus, the global int_get_progress variable is left unchanged, and main() ends up deferencing a null pointer, which is undefined behavior and in this case is causing a memory fault. Even if you fix the code to let the function update the caller's pointer, your code would still fail to work properly, because you are setting the pointer to point at a local variable that goes out of scope when the function exits, thus you would leave the pointer dangling, pointing at invalid memory, which is also undefined behavior when that pointer is then dereferenced. Your global variable (which doesn't need to be global) should not be a pointer at all, but it can be passed around by pointer, eg: #include <iostream> void get_progress(int* p_progress) { int n = 100; *p_progress = n; std::cout << "get_report_progress:" << *p_progress << std::endl; } int main() { int progress = 0; get_progress(&progress); std::cout << "main get process:" << progress << std::endl; return 0; } Alternatively, pass it by reference instead, eg: #include <iostream> void get_progress(int& ref_progress) { int n = 100; ref_progress = n; std::cout << "get_report_progress:" << ref_progress << std::endl; } int main() { int progress = 0; get_progress(progress); std::cout << "main get process:" << progress << std::endl; return 0; } Alternatively, don't pass it around by parameter at all, but return it instead, eg: #include <iostream> int get_progress() { int n = 100; std::cout << "get_report_progress:" << n << std::endl; return n; } int main() { int progress = get_progress(); std::cout << "main get process:" << progress << std::endl; return 0; }
74,385,153
74,386,828
How to optimize Fibonacci using memoization in C++?
I'm struggling with getting the correct implementation of finding the nth number in the Fibonacci sequence. More accurately, how to optimize it with DP. I was able to correctly write it in the bottom-up approach: int fib(int n) { int dp[n + 2]; dp[0] = 0; dp[1] = 1; for (int i = 2; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2]; return dp[n]; } But the top-down (memoized) approach is harder for me to grasp. This is what I put originally: int fib(int n) { std::vector<int> dp(n + 1, -1); // Lambda Function auto recurse = [&](int n) { if (dp[n] != -1) return dp[n]; if (n == 0) { dp[n] = 0; return 0; } if (n == 1){ dp[n] = 1; return 1; } dp[n] = fib(n - 2) + fib(n - 1); return dp[n]; }; recurse(n); return dp.back(); } ...This was my first time using a C++ lambda function, though, so I also tried: int recurse(int n, std::vector<int>& dp) { if (dp[n] != -1) return dp[n]; if (n == 0) { dp[n] = 0; return 0; } if (n == 1){ dp[n] = 1; return 1; } dp[n] = fib(n - 2) + fib(n - 1); return dp[n]; } int fib(int n) { std::vector<int> dp(n + 1, -1); recurse(n, dp); return dp.back(); } ...just to make sure. Both of these gave time limit exceeded errors on leetcode. This, obviously, seemed off, since DP/Memoization are optimization techniques. Is my top-down approach wrong? How do I fix it?
You set up the memoization storage in fib, and then create the recursive part of your solution in the lambda recurse. That means that here: dp[n] = fib(n - 2) + fib(n - 1); you really should call recurse not fib. But in order to do that with a lambda, you need to give the lambda to the lambda so to speak. Example: #include <iostream> #include <vector> int fib(int n) { std::vector<int> dp(n + 1, -1); // Lambda Function auto recurse = [&dp](int n, auto &rec) { if (dp[n] != -1) return dp[n]; if (n == 0) { dp[n] = 0; return 0; } if (n == 1) { dp[n] = 1; return 1; } dp[n] = rec(n - 2, rec) + rec(n - 1, rec); return dp[n]; }; recurse(n, recurse); return dp.back(); } int main() { std::cout << fib(12) << '\n'; }
74,385,642
74,385,814
converting heap based vector to stack
I would like to convert it to vector of vectors but I'm confused about the code above it's better to store it on stack rather than heap, that's why I want to change it to vector of vector std::vector<DPoint*>* pixelSpacing; ///< vector of slice pixel spacings pixelSpacing = new std::vector<DPoint*>(volume.pixelSpacing->size()); for (unsigned int i = 0; i < pixelSpacing->size(); i++) { (*pixelSpacing)[i] = new DPoint(*(*volume.pixelSpacing)[i]); }
Okay, as per the comment, I am making an answer. std::vector<DPoint> pixelSpacing(volume.pixelSpacing->size()); for (unsigned int i = 0; i < pixelSpacing.size(); i++) { pixelSpacing[i] = DPoint(/*DPoint constructor args*/); } Or alternatively: std::vector<DPoint> pixelSpacing; //Reserving size is optional. pixelSpacing.reserve(volume.pixelSpacing->size()); for (unsigned int i = 0; i < volume.pixelSpacing->size(); i++) { pixelSpacing.emplace_back(/*DPoint constructor args*/); }
74,386,082
74,386,303
C++ maps with variables
Is it possible to create a dynamically changing map? For example, i want to use it in the for loop, and use i as a variable in map value: uint8_t i{}; std::map<uint8_t, int16_t> substitutions{ {0, array[i][0]}, {1, array[i][1]}, {2, array[i][2]}, {3, array[i][0] * array[i][1]}, {4, array[i][0] * array[i][2]}, {5, array[i][1] * array[i][2]}, {6, array[i][0] * array[i][1] * array[i][2]}, {7, pow(array[i][0], 2)}, {8, pow(array[i][1], 2)}, {9, pow(array[i][2], 2)}}; for (i = 0; i < 3; i++) { anmSum += substitutions.find(a)->second * substitutions.find(b)->second; } Right now it just substitutes 0 (because i = 0) and leaves it at that. Maybe instead of fixed values use lambda-function?
I'd probably solve your problem by not using a map at all. I'd use a switch statement instead (it should be slightly faster): for (uint8_t i = 0; i < 3; i++) { auto substitute = [i](uint8_t value) { switch (value) { case 0: return array[i][0]; case 1: return array[i][1]; case 2: return array[i][2]; case 3: return array[i][0] * array[i][1]}; case 4: return array[i][0] * array[i][2]}; case 5: return array[i][1] * array[i][2]}; case 6: return array[i][0] * array[i][1] * array[i][2]}; case 7: return pow(array[i][0], 2)}; case 8: return pow(array[i][1], 2)}; case 9: return pow(array[i][2], 2)}; default: throw std::invalid_argument("invalid value"); }; }; anmSum += substitute(a) * substitute(b); } Using your approach you'd have to make your map contain some sort of function pointer.
74,386,327
74,386,611
How to check whether a mutex lock have been destroyed or not?
I have a problem where my code tries to call pthread_mutex_destory() twice. I need to check whether the lock have been destroyed before or not. How can I do this? Will this work: void deinit() { if(1 == pthread_mutex_trylock(&this->m_lock)) { (void) pthread_mutex_destroy(&this->m_lock); } } Will trylock only check weather the mutex is locked or not or will it also show me weather it is deleted or not?
Once you destroy a a c object, the data left behind is garbage. c++ doesn't let you do this. (It does but you have to explicitly ask for it.) But you are using a c library, so you have to do everything yourself. So you have a few options: use std::mutex which works nicely with c++. But as such, you mutex will have the same lifetime as your containing class. (which is neates) only use pthread_mutex_destroy in your destructor. Same result as above. You mutex is destroyed as you object is destroyed, which happens exactly once. use an std::optional to shield the mutex data if it is not initialized. Wouldn't recommend, as it is an ugly mix of c and c++. use a bool to keep track whether you mutex is inited. This is also tricky and ugly as it is prone to mistakes. I cannot be more specific because i don't know the rest of the code.
74,386,612
74,403,322
How to expose native to managed - C++/CLI on x64 Platform
I have a static lib in my project and I want to use this in my .net project. I have taken this project as a starting point. Exposing native to managed - C++/CLI My use case is the Second Approach. So far everything works, but when I change the architecture from x86 to x64 I get a lot of linker errors: Currently I do not understand where the problem is and why these errors come:
Do you change library when switching architecture? If not the linker would look for the wrong mangled
74,387,597
74,388,381
std::map::try_emplace return value results in a dangling pointer when retrieving a unique_ptr
I have a factory function that returns a non-owning pointer to the created object after it is inserted into a resource-owning map to be later stored as a non-owning pointer elsewhere; however, by using the return value of std::map::try_emplace which should be an iterator to what was/is inserted, this causes the internal contents of the std::unique_ptr to be invalid when accessed through the referring non-owning pointer. Instead, I have to call std::map::find and basically search for a value twice. I don't quite understand what's wrong with the non-working version of the code below. Shouldn't the return value of std::map::try_emplace be directly usable/copyable? What I wanted to do, but doesn't work: std::map<std::string, std::unique_ptr<Feature>> Feature::s_registry{}; Feature* Feature::CreateFeature(Map* map, const XMLElement& elem) { auto new_feature = std::make_unique<Feature>(map, elem); //Copy name out so it isn't erased via the move operation. std::string new_feature_name = new_feature->name; if(auto&& [where, inserted] = s_registry.try_emplace(new_feature_name, std::move(new_feature)); inserted) { return where->second.get(); } else { if(where != std::end(s_registry)) { return where->second.get(); } } return nullptr; } Instead I have to call find to get a valid iterator: std::map<std::string, std::unique_ptr<Feature>> Feature::s_registry{}; Feature* Feature::CreateFeature(Map* map, const XMLElement& elem) { auto new_feature = std::make_unique<Feature>(map, elem); //Copy name out so it isn't erased via the move operation. std::string new_feature_name = new_feature->name; if(const auto where_inserted = s_registry.try_emplace(new_feature_name, std::move(new_feature)); where_inserted.second) { if(const auto found = s_registry.find(new_feature_name); found != std::end(s_registry)) { return found->second.get(); } } else { if(const auto found = s_registry.find(new_feature_name); found != std::end(s_registry)) { return found->second.get(); } } return nullptr; }
The code can be as simple as Feature* Feature::CreateFeature(Map* map, const XMLElement& elem) { auto new_feature = std::make_unique<Feature>(map, elem); return s_registry.emplace(new_feature->name, std::move(new_feature)).first->second.get(); } If the new_feature was not inserted because the slot is already occupied, .first points to the already existing value. Otherwise, it points to the newly inserted object. In both cases, that object's ->second should be valid. Furthermore, std::move does not move anything. The members that new_feature points to can be used until the final destination is initialized, at which point the std::map will already know where to insert the value. Therefore, it is not necessary to keep new_feature->name in a separate value. There is some discussion of this behavior in this post.
74,387,787
74,388,539
C++ equivalent to std::all_of but working with a range loop?
I am trying to re-write a piece of code that currently looks like this: if (nchildren > 7 && parent->isChildValid(0) && parent->isChildValid(1) && parent->isChildValid(2) && parent->isChildValid(3) && ... parent->isChildValid(7) ) { } It tests the parent->isChildValid(i) 8 times where i, is an index within the range [0:7] in this particular case. I was looking (as an exercise) for a way of making this more efficient (imagine the range changes later) using something that would be similar to std::all_of but I understand these functions only work with constructs that support iterators. So something like this: std::all_of(0, 7, [&](int i){ return parent->isChildValid(i); }); Would of course not work. But I would like to know if there a similar/alternative options (I am sure there is)) without (of course) declaring i is a vector and setting its content with {0, 1, 2, 3, 4, 5, 6, 7}. I am trying to avoid this as well, and look instead for something similar to all_of but where I could set the min and max indices (range loop kind of) over which I'd like the function to be tested for. edit: I can't use boost.
In C++20, you can use views::iota and ranges::all_of to do this if (nchildren > 8 && std::ranges::all_of(std::views::iota(0, 8), [parent](auto i) { return parent->isChildValid(i); }) ) { }
74,387,901
74,387,948
Using .c_str' with pointers (and also pointers to pointers)
so, I encountered a little problem and I am kinda stuck. Basically I am trying to pass the value of a string** in C-type form to a char* string The code is as follows: static int BuildDBListSql( std::string **SqlBuf, const char* ColumnNames, const char* TableNames, const char* CmdText, sUINT Mode) { int rtnval = sSUCCESS; const char * testSql = ( Mode & 02 ) ? ColumnNames : CmdText; if ( SU_DbControl::DbCreateTradeTempTables(testSql) != sSUCCESS ) { sLogMessage("Problem with temporary table results", sLOG_ERROR, 0); return( sERROR ); } if ( Mode & 02 ) { *SqlBuf = new std::string[strlen(ColumnNames) + SQL_MAX_SELECT*40]; *SqlBuf = &std::string(ColumnNames); if ( !( Mode & 010 ) ) { // Attach State/Retrieval SQL. char* SqlBufcopy = (*SqlBuf)->c_str(); sSQLInsertStateAndRetrieval( sDbConvertMode( Mode ), SqlBufcopy); } } // SQL fragments are being passed: else { size_t sqlBufLength = 0; if ( Mode & 010 ) { sqlBufLength = strlen(ColumnNames) + strlen(TableNames) + strlen(CmdText) + SQL_MAX_SELECT; *SqlBuf = new std::string[ sqlBufLength ]; //sprintf( *SqlBuf, "SELECT %s FROM %s %s ", *SqlBuf = fmt::format("SELECT {} FROM {} {} ", ColumnNames, TableNames, CmdText); // ColumnNames, TableNames, CmdText ); } else { std::string *sqlPtr = new char[strlen(CmdText) + 2*SQL_MAX_SELECT]; strcpy( sqlPtr, CmdText ); sSQLSpecializeWhereClause( TableNames, sqlPtr ); sqlBufLength = strlen(ColumnNames) + strlen(TableNames) + SQL_MAX_SELECT; sqlBufLength += strchr(TableNames, ',') ? strlen(CmdText) : strlen(sqlPtr); *SqlBuf = new char[ sqlBufLength ]; sprintf( *SqlBuf, "SELECT %s From %s %s", ColumnNames, TableNames, strchr( TableNames, ',' ) ? CmdText : sqlPtr ); delete [] sqlPtr; // Attach State/Retrieval SQL rtnval = sSQLInsertStateAndRetrieval( sDbConvertMode( Mode ), *SqlBuf ); } } if (Mode & 0100) { char * tempBuf = sEntitySQLToDbSQL(*SqlBuf); if( tempBuf ) { delete [] *SqlBuf; *SqlBuf = new char[ strlen(tempBuf) + 1]; strcpy(*SqlBuf, tempBuf); } else { sLogMessage("Error in sEntitySQLToDbSQL", sLOG_ERROR, 0); return( sERROR ); } } return rtnval; } i get this error when running the solution: related to this line of code char* SqlBufcopy = (*SqlBuf)->c_str(); left of '.c_str' must have class/struct/union, type is std::string** I kinda understand that the error is there due to me trying to get a c-type string out of a pointer, but I dont know the correct syntax to do what i want to do. I tried with char *SqlBufcopy = *SqlBuf.c_str() also with char *SqlBufcopy = *SqlBuf->c_str() and it didnt work, help pls
To fix the error you ask about, change char *SqlBufcopy = *SqlBuf.c_str(); to char *SqlBufcopy = (*SqlBuf)->c_str(); Reason: SqlBuf is pointer to pointer (which makes no sense at all), so to get to the actual object, you need to dereference it twice.
74,388,124
74,502,988
Can assignment operations which declared as default have reference qualifiers?
When declaring assignment operations as default, is there anything wrong to make them reference qualified to prevent assignment to temporaries? (Most often than not, it prevents stupid errors). Common resources, do not say anything about reference qualifiers for "default" operations, and almost every example I've seen so far, doesn't declare them with proper ref-qualifier. Does language standard say anything about reference qualifiers declaring assignment operations as default. It is allowed? Is there anything wrong about doing that? After all, with very few exceptions, assigning to rvalues doesn't make sense. I understand that they were not made reference qualified by default for backwards compatibility, however is there a reason not to that? (In case that the answer to first question is "yes" and the answer to the second one is "no").
It is allowed to define a defaulted assignment operator with an additional ref-qualifier. See [dcl.fct.def.default]/2.1. Whether or not you should actually do it is an opinion-based question. I don't see anything obviously wrong with adding a &, but I suspect that you'll encounter resistance if you try to convince everyone on your team to do it, because it may indeed catch some bugs, but very few, and almost all of those bugs are likely to be inside unit tests anyway. (In contrast, bugs like if (x = 3), where the left side is an lvalue, are much more common, and you won't catch those, but maybe the compiler will issue a warning.) It's sort of like how you might have trouble convincing people to declare their const char* variables as const char* const if they know the pointer isn't going to change. Sure, it increases safety by a bit, but it also requires extra typing.
74,388,676
74,390,469
Is THRUST stable_sort_by_key O(n)?
Can I assume that Thrust stable_sort_by_key performed on unsigned int has complexity O(n)? If not what should I do to be sure that this complexity will be achieved? (Except of implementing radix sort on my own)
It depends a bit on your circumstances/view. Just from the docs/API there doesn't seem to be a guarantee for thrust::stable_sort_by_key on unsigned int keys using a radix sort. On the other hand the necessary algorithm cub::DeviceRadixSort::SortPairs is implemented in the CUB library which is used by Thrust in the backend and there is no good reason for Thrust not to use it as the prerequisites can easily be queried at compile time. From the code in thrust/system/cuda/detail/sort.h(the "detail" should warn you that this is not part of the public API) one can see that thrust::stable_sort_by_key can launch a cub::DeviceRadixSort::SortPairs under the right circumstances (arithmetic key type and using thrust::less or thrust::greater as comparison operation) at least on the main branch of Thrust at the time of writing (ca. v2.0.0rc2) but probably for a long time already. Else it will fall back to a merge sort. Directly using cub::DeviceRadixSort::SortPairs could have benefits even if this is enough for you, as this makes it easier to reuse temporary buffers and avoid unnecessary synchronization. Both can be done in Thrust via a auto exec = thrust::cuda::par_nosync(custom_allocator).on(custom_stream); execution policy (the most recent CUDA Toolkit 11.8 still comes with old Thrust v1.15 without v1.16 par_nosync). One thing that can not be avoided using Thrust is the in-place nature of the sorting algorithms which is achieved by potentially copying the results back to the input buffers. These copy operations can only be elided using CUB.
74,388,697
74,388,836
_mm256_load_ps segmentation fault
I'm developing a high throughput low latency real-time program that involves several matrix operations. I have decided to use AVX2 or AVX512 to boost the performance of system. This is my first first attempt to use AVX instruction set of SIMD in general. I'm using the AVX Intrinsics functions available in g++. The problem I am facing is when I use _mm256_load_ps function I get segmentation fault error but when I use _mm256_set_ps the program runs. I was told _mm256_load_ps will have better performance than _mm256_set_ps in my application. What am I doing wrong? This is a program to use AVX2 to add 2 matrices. Code #include <immintrin.h> #include <string.h> const std::uint64_t MAX_COUNT = 100000; int main() { float mat1[MAX_COUNT], mat2[MAX_COUNT], rslt[MAX_COUNT]; for(int i = 0; i < MAX_COUNT; i++){ mat1[i] = i; mat2[i] = 100-i; } for(int i = 0; i < MAX_COUNT; i +=8) { //Working Properly //auto avx_a = _mm256_set_ps(mat1[i+7], mat1[i+6], mat1[i+5], mat1[i+4], mat1[i+3], mat1[i+2], mat1[i+1], mat1[i+0]); //Working Properly //auto avx_b = _mm256_set_ps(mat2[i+7], mat2[i+6], mat2[i+5], mat2[i+4], mat2[i+3], mat2[i+2], mat2[i+1], mat2[i+0]); //Resulting in segmentation fault auto avx_a = _mm256_load_ps(&mat1[i]); //Resulting in segmentation fault auto avx_b = _mm256_load_ps(&mat2[i]); auto avx_c = _mm256_add_ps(avx_a, avx_b); float *result = (float*)&avx_c; memcpy(&rslt[i], result, 8*sizeof(float)); } return 0; } Aligning Data __declspec(align(32)) float mat1[MAX_COUNT] Error test_2.cpp: In function ‘int main()’: test_2.cpp:11:21: error: too few arguments to function ‘void* std::align(std::size_t, std::size_t, void*&, std::size_t&)’ 11 | __declspec(align(32)) float mat1[MAX_COUNT]; | ~~~~~^~~~ In file included from /usr/include/c++/11/memory:72, from /usr/include/x86_64-linux-gnu/c++/11/bits/stdc++.h:82, from test_2.cpp:2: /usr/include/c++/11/bits/align.h:62:1: note: declared here 62 | align(size_t __align, size_t __size, void*& __ptr, size_t& __space) noexcept | ^~~~~ test_2.cpp:11:5: error: ‘__declspec’ was not declared in this scope 11 | __declspec(align(32)) float mat1[MAX_COUNT]; | ^~~~~~~~~~
_mm256_load_ps requires aligned memory. _mm256_set_ps doesn't even require contiguous addresses. You want _mm256_loadu_ps - unaligned load, but still from a contiguous array.
74,389,216
74,389,396
How can I use the C++ regex library to find a match and *then* replace it?
I am writing what amounts to a tiny DSL in which each script is read from a single string, like this: "func1;func2;func1;4*func3;func1" I need to expand the loops, so that the expanded script is: "func1;func2;func1;func3;func3;func3;func3;func1" I have used the C++ standard regex library with the following regex to find those loops: regex REGEX_SIMPLE_LOOP(":?[0-9]+)\\*([_a-zA-Z][_a-zA-Z0-9]*;"); smatch match; bool found = std::regex_search(*this, match, std::regex(REGEX_SIMPLE_LOOP)); Now, it's not too difficult to read out the loop multiplier and print the function N times, but how do I then replace the original match with this string? I want to do this: if (found) match[0].replace(new_string); But I don't see that the library can do this. My backup place is to regex_search, then construct the new string, and then use regex_replace, but it seems clunky and inefficient and not nice to essentially do two full searches like that. Is there a cleaner way?
You can also NOT use regex, the parsing isn't too difficult. So regex might be overkill. Demo here : https://onlinegdb.com/RXLqLtrUQ- (and yes my output gives an extra ; at the end) #include <string> #include <sstream> #include <iostream> int main() { std::istringstream is{ "func1;func2;func1;4*func3;func1" }; std::string split; // use getline to split while (std::getline(is, split, ';')) { // assume 1 repeat std::size_t count = 1; // if split part starts with a digit if (std::isdigit(split.front())) { // look for a * auto pos = split.find('*'); // the first part of the string contains the repeat count auto count_str = split.substr(0, pos); // convert that to a value count = std::stoi(count_str); // and keep the rest ("funcn") split = split.substr(pos + 1, split.size() - pos - 1); } // now use the repeat count to build the output string for (std::size_t n = 0; n < count; ++n) { std::cout << split << ";"; } } // TODO invalid input string handling. return 0; }
74,389,226
74,403,906
Are resources global in scope in a C++ (VS) program and consequently where is the ideal place to load a list into a combo box?
I'm using a resource file for my dialog boxes, menus, etc. in a C++ program in Visual Studio. Just wondering if a resource file has a global scope? Also, as a consequence of this, where is the ideal place in the program to call GetDlgItem to get the handle of a combobox and to load its list (as well as other similar tasks)? Can someone give a simple example of adding a list item to a combo box in the context in which a resource file is being used rather than a when a combo box created explicitly in the code is being used?
The information given in the comments answered the question sufficiently. What initially prompted the question was my desire and attempts to put items in a combo box list. The code below successfully accomplished this. This is mostly a Visual C++ autogenerated message handling procedure for a drop down menu entry called "Add" under a main menu "Edit." In the dialog generated by selecting Add there is a combo box which is designated here as IDC_COMBO1. (IDC_COMBO1 is the name given to the combobox in the resource file and is defined in resource.h so it is recognized here.) I added three lines to the code to put the entry "1st" into the combo box list. Also, as suggested by Richard Critten, I handled this in the WM_INITDIALOG message case which makes sense beside being simple and concise. The three lines were: HWND hWndCB1; hWndCB1 = GetDlgItem(hDlg, IDC_COMBO1); SendMessage(hWndCB1, CB_ADDSTRING, 0, (LPARAM)TEXT("1st")); The entry "1st" appeared in the list when I built the project. Thanks to those who commented, and I hope that this helps someone else who is attempting to accomplish this. The code of the message handling procedure is below. INT_PTR CALLBACK Add(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { HWND hWndCB1; UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: { hWndCB1 = GetDlgItem(hDlg, IDC_COMBO1); SendMessage(hWndCB1, CB_ADDSTRING, 0, (LPARAM)TEXT("1st")); return (INT_PTR)TRUE; } break; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; }
74,389,275
74,389,323
convert struct to uint8_t array in C++
I have a typedef struct with different data types in it. The number array has negative and non-negative values. How do I convert this struct in to a unint8t array in C++ on the Linux platform. Appreciate some help on this. Thank you. The reason I am trying to do the conversation is to send this uint8_t buffer as a parameter to a function. typedef struct { int enable; char name; int numbers[5]; float counter; }; appreciate any example on doing this. thank you
For a plain old data structure like the one you show this is trivial: You know the size of the structure in bytes (from the sizeof operator). That means you can create a vector of bytes of that size. Once you have that vector you can copy the bytes of the structure object into the vector. Now you have, essentially, an array of bytes representation of the structure object. In code it would be something like this: struct my_struct_type { int enable; char name; int numbers[5]; float counter; }; my_struct_type my_struct_object = { // TODO: Some valid initialization here... }; // Depending on the compiler you're using, and its C++ standard used // you might need to use `std::uint8_t` instead of `std::byte` std::vector<std::byte> bytes(sizeof my_struct_object); std::memcpy(bytes.data(), reinterpret_cast<void*>(&my_struct_object), sizeof my_struct_object);
74,389,562
74,389,701
wrong printed sorted array
I'm new to C++ and I've been doing bubbleSort, but when I want to show the numbers in the terminal, the leading number is a problem. Sorry for my bad english btw. where am i doing wrong? this is the code: #include <iostream> void printArray(int *myArr, int lenght) { for (int i = 0; i < lenght; ++i) { std::cout << myArr[i] << ", "; } } int bubbleSort(int *myArr, int lenght) { for (int i = 0; i < lenght; ++i) { for (int j = 0; j < lenght-1; ++j) { if (myArr[j] > myArr[j+1]) { int temp = myArr[j]; myArr[j] = myArr[j+1]; myArr[j+1] = temp; } } } return *myArr; } int main() { int myArr[] = {10,14,13,19,15,12,16,18,17,11}; int newArr = bubbleSort(myArr, 8); printArray(&newArr, 8); return 0; } this is what i get: 10, 10, 12, 13, 14, 15, 16, 18, there is no 19 and double 10s and is there any eaiser way to get lenght of array in function? Thank you...
The problem is that you are confusing pointers with arrays with single integers. int bubbleSort(int *myArr, int lenght) { // ... not actually that important what happens here ... return *myArr; } Your bubbleSort gets a pointer to first element of an array passed, you do some sorting and eventually you return the first element of that sorted array (return type is int!). This is wrong, or maybe not wrong but doesn't make much sense but the real drama will only come later... ...when here int newArr = bubbleSort(myArr, 8); printArray(&newArr, 8); you copy that single integer returned from bubbleSort into newArr (an int), then take its address (still "ok") and then in printArray act like it points to an array which it doesn't (now it goes BooooM!). myArr[i] in printArray is undefined behavior when i > 0, because myArr points to a single integer. It does not point to an array. TL;DR: Do not use c-arrays. c-arrays are advanced C++, they are easy to get wrong and hard to get right. Use std::vector for dynamically sized arrays and std::array for compiletime sized arrays.
74,389,801
74,389,917
Is there a way to make a struct take a variadic list of elements in a nested struct to be constexpr without initializing it in multiple parts?
Say I have this struct layout: #include <vector> struct A { char const* name; std::vector<char const*> list; }; struct B { char const* group_name; A an_A; int other_stuff; }; Which I initialize thusly: B b = { "My B", { "My A", {{ "My", "variable", "length", "list" }} }, 42 }; Is there any way to define this so that b can be constexpr without having to resort to declarations of subitems before the main item? Thought this might work using a initializer_list: #include <initializer_list> struct A { char const* name; std::initializer_list<char const*> list; }; struct B { char const* group_name; A an_A; int other_stuff; }; B b = { "My B", { "My A", {{ "My", "variable", "length", "list" }} }, 42 }; But alas I get the following errors: <source>:20:1: error: could not convert '{{"My", "variable", "length", "list"}}' from '<brace-enclosed initializer list>' to 'std::initializer_list<const char*>' 20 | }; | ^ | | | <brace-enclosed initializer list> ASM generation compiler returned: 1 <source>:20:1: error: could not convert '{{"My", "variable", "length", "list"}}' from '<brace-enclosed initializer list>' to 'std::initializer_list<const char*>' 20 | }; | ^ | | | <brace-enclosed initializer list> Execution build compiler returned: 1 Demo
The problem is that you've specified extra braces around { "My", "variable", "length", "list" } in your second example. Thus to solve this you need to remove those extra braces {} as shown below: B b = { "My B", { "My A", //-v--------------------------------------v---->removed extra braces from here { "My", "variable", "length", "list" } }, 42 }; Working demo
74,389,905
74,390,040
Can a factory method return 0 in case of an error?
I am studying a bit of code, which contains a factory method, if I am remembering my object orientation correctly. The factory method and the related classes can be described by the following pseudo-C++. The class Actor is the base class for the various implementations of concrete actions or operations, which in turn are implemented as derived classes. The factory method createActor receives arguments which are read from an input script, hence prior to calling a constructor some error checking is being done. I noticed, that in all cases when an error is detected, I find a return 0 statement. This can obviously be done, since the code (not written by me) compiles and runs. However, the factory method is supposed to return a pointer to an Actor-class. Is in this case return 0 simply an obscure way to return NULL? Maybe I am overthinking this. class Actor { class ActorVariantA : Actor { } // all other ActorVariants are omitted for brevity Actor* createActor(arguments) { if (errorCondition) return 0 if (conditionA) return new ActorVariantA(arguments) } } I found a somewhat related question, which in turn led me to Stroustrup himself. So, the answer to my question would be: sort-of, but don't do it.
yes, you are overthinking this. It should really be return nullptr, but in this case return 0 is equivalent.
74,390,711
74,390,798
Why adding `explicit` to a defaulted copy constructor prevents returning an object?
Considering this MRE (the real case involves some class with some inheritance and some member variables) class A { public: A() = default; explicit A(const A&) = default; // explicit A(A&) = default; ///Adding this serves no purpose explicit A(A&&) = default; A& operator=(const A&) = default; A& operator=(A&&) = default; }; auto dummy_a() { A a; return a; //no matching function for call to 'A::A(A)' } int main() { const auto a = dummy_a(); } I get the following error unless I remove explicit from either the copy or the move constructor. (Can be tested here) main.cpp: In function 'auto dummy_a()': main.cpp:14:12: error: no matching function for call to 'A::A(A)' 14 | return a; //no matching function for call to 'A::A(A)' | ^ main.cpp:4:5: note: candidate: 'constexpr A::A()' 4 | A() = default; | ^ main.cpp:4:5: note: candidate expects 0 arguments, 1 provided Why is that the case?
In your function dummy_a your return value requires implicit copy construction auto dummy_a() { A a; return a; // implicit 'A::A(A)' } If you indeed want your copy constructor to be explicit then this should be modified to auto dummy_a() { A a; return A{a}; // explicit 'A::A(A)' }
74,390,977
74,392,274
Boost Geometry compilation error in version 1.80.0 using custom point type
I'm using Boost 1.80.0. I would like to use boost geometries with a custom point type. To do that I register my custom point into boost::geometry. I am then lock when I want to use boost::geometry::within() function. I got a compilation error that I do not understand well. See some errors: boost/1.80/include/boost/geometry/algorithms/detail/relate/boundary_checker.hpp:99:38: error: no matching function for call to ‘std::vector<boost::geometry::model::point<double, 2, boost::geometry::cs::cartesian>, std::allocator<boost::geometry::model::point<double, 2, boost::geometry::cs::cartesian> > >::push_back(const point&)’ /usr/include/c++/10/bits/predefined_ops.h:194:23: error: no match for call to ‘(boost::geometry::less<boost::geometry::model::point<double, 2, boost::geometry::cs::cartesian>, -1, boost::geometry::cartesian_tag>) (boost::geometry::model::point<double, 2, boost::geometry::cs::cartesian>&, const point&)’ But, if I compile with a previous Boost version (for example Boost 1.79.0) it compiles fine. Edit : It appears to be a boost::geometry regression, and not a misuse from my part. As I am not familiar with boost::geometry and Boost does not mention any change for boost::geometry from version 1.79.0 to 1.80.0, I assume I am missing something with my comprehension of using boost type with custom points. Code sample: #include <iostream> #include <boost/geometry.hpp> #include <boost/geometry/geometries/register/point.hpp> struct point { double x, y; point(double x = 0, double y = 0) : x(x), y(y) {} }; BOOST_GEOMETRY_REGISTER_POINT_2D(point, double, boost::geometry::cs::cartesian, x, y); using line = boost::geometry::model::linestring<point>; using multiline = boost::geometry::model::multi_linestring<line>; using polygon = boost::geometry::model::polygon<point>; int main(int argc, char** argv) { multiline inMultiline; polygon inPoly; bool isWithin = boost::geometry::within(inMultiline, inPoly); // error return EXIT_SUCCESS; } Note 1 : within() "Supported Geometries" table state that it is correct to use it with multi_linestring and polygon. Note 2 : Remplacing my custom point by using point = boost::geometry::model::point<double, 2, boost::geometry::cs::cartesian> works fine in this sample. Edit: As It seems that come from a bug from boost:geometry I edited the title for newcomers.
So I dove into the code/message and noticed that inside the algorithm an equal_range call is used comparing between a helper geometry (built with helper_geometry<>) and yours. It ends up calling a comparator with incompatible point types: using mutable_point_type = bg::helper_geometry<MyPoint, double>::type; bg::less<mutable_point_type, -1, bg::cartesian_tag> cmp; mutable_point_type a; MyPoint b; cmp(a, b); This gives the same error message, because the less<> implementation doesn't accept generic point types. It looks as though that's an implementation issue, because there exists a bg::less<void, 2, void> implementation that does correctly apply the default comparison-strategy for heterogenous point types: template <int Dimension> struct less<void, Dimension, void> { typedef bool result_type; template <typename Point1, typename Point2> inline bool operator()(Point1 const& left, Point2 const& right) const { typedef typename strategy::compare::services::default_strategy < strategy::compare::less, Point1, Point2, Dimension >::type strategy_type; return strategy_type::apply(left, right); } }; However, pathching the relevant line in boost/geometry/algorithms/detail/relate/boundary_checker.hpp:160 to use it: @@ -157,7 +157,7 @@ public: template <typename Point> bool is_endpoint_boundary(Point const& pt) const { - using less_type = geometry::less<mutable_point_type, -1, typename Strategy::cs_tag>; + using less_type = geometry::less<void, -1, void>; auto const multi_count = boost::size(m_geometry); reveals more places where boundary_checker assumes identical point types: line 99 attempts to push a MyPoint into vector<> of "helper" points (mutable_point_type): boundary_points.push_back(front_pt); Consequently I could get your code to compile only by patching the implementation (L:148) to use your point type as the helper point type as well. @@ -145,7 +145,7 @@ template <typename Geometry, typename Strategy> class boundary_checker<Geometry, Strategy, multi_linestring_tag> { using point_type = typename point_type<Geometry>::type; - using mutable_point_type = typename helper_geometry<point_type>::type; + using mutable_point_type = point_type; This only works for cases where the point type is mutable, of course, so it won't be a good general-purpose fix. I'd file an issue about this with the library devs: https://github.com/boostorg/geometry/issues?q=is%3Aissue+boundary_checker - it looks like it wasn't previously reported there.
74,391,415
74,391,523
Change values of a matrix in C++
I need to get the upper triangle of a matrix by setting everything under the diagonal to 0. Here is the code I wrote: #include <iostream> #include <vector> using namespace std; vector<vector <int>> upper_triangle(vector<vector <int>> n) { int rij = n.size(); int kolom = n.size(); vector<vector<int>> result = n; for (int i = 0; i < rij; i++) { for (int j = 0; j < kolom; j++) { if (i > j) { result[i][j] = 0; } } return result; } } The output that I get is simply the matrix itself which is not what I need. {{10,11,12},{13,14,15},{16,17,18}} {{1,2,3},{4,5,6},{7,8,9}} {{1,2},{3,4}} The output I need would be: {{10,11,12},{0,14,15},{0,0,18}} {{1,2,3},{0,5,6},{0,0,9}} {{1,2},{0,4}}
You simply have return result; in the wrong place. Like this vector<vector <int>> upper_triangle(vector<vector <int>> n) { int rij = n.size(); int kolom = n.size(); vector<vector<int>> result = n; for (int i = 0; i < rij; i++) { ... } return result; } not this vector<vector <int>> upper_triangle(vector<vector <int>> n) { int rij = n.size(); int kolom = n.size(); vector<vector<int>> result = n; for (int i = 0; i < rij; i++) { ... return result; } } Of course the point of indenting code is to make errors like this easier to spot.
74,392,924
74,393,071
determining variadic template arguments are compile time
Let's assume i want to define a type that depends on some types: struct TimerPump{}; struct GuiPump{}; struct NetworkPump{}; template<class... Pumps> class DispatcherT{}; using Dispatcher = DispatcherT< TimerPump, GuiPump, NetworkPump >; I would like to make the gui and network pumps be optional. Either one might be needed or both or none. I could write a preprocessor macro: using Dispatcher = DispatcherT< TimerPump #ifdef GUI_ENABLED , GuiPump #endif #ifdef NETWORK_ENABLED , NetworkPump #endif >; but i'm looking for a way to control those arguments through traits struct Traits { static constexpr bool gui = true; static constexpr bool network = false; }; using Dispatcher = DispatcherT< TimerPump , Traits::gui ? GuiPump : null <--- need help here , Traits::network ? NetworkPump : null >; Is there a neat way to determine arguments passed to a template taking variadic arguments?
Basically, you'd like optional list append. To do that, you first need list append: template<typename... Ts> struct list { template<typename T> using append = list<Ts..., T>; template<bool b, typename T> using appendIf = std::conditional_t<b, list<Ts..., T>, list<Ts...>>; template<template<class...> LT> using applyTo = LT<Ts...>; }; Then you might start with list<> (or whatever types you surely have), then, at each step, use ::appendIf<condition, type> and end with applyTo<DispatcherT>. using Dispatcher = list<TimerPump> ::appendIf<Traits::gui, GuiPump> ::appendIf<Traits::network, NetworkPump> ::applyTo<DispatcherT>;
74,394,749
74,394,791
why the result is different add thread by loop
I am the novice of multithreading, and I want to try to use the 2048*2048 height map texture to generate a set of vertices. void HeightMap::CalculateVertices(Vector3 vertex_scale, Vector2 texture_scale, int start, int end, GLubyte* data) { for (unsigned int z = start; z < end; ++z) { for (unsigned int x = 0; x < width; ++x) { unsigned int offset = z * height + x; vertices[offset] = Vector3(x, data[offset], z) * vertex_scale; textureCoords[offset] = Vector2(x, z) * texture_scale; } } } The problem is when I try to add thread to vector, if I add them one by one: threads.push_back(std::thread([&] {CalculateVertices(vertex_scale, texture_scale, 0, dataSize, data); })); threads.push_back(std::thread([&] {CalculateVertices(vertex_scale, texture_scale, dataSize, dataSize * 2, data); })); threads.push_back(std::thread([&] {CalculateVertices(vertex_scale, texture_scale, dataSize * 2, dataSize * 3, data); })); threads.push_back(std::thread([&] {CalculateVertices(vertex_scale, texture_scale, dataSize * 3, dataSize * 4, data); })); Then everything run properly. But if I use loop to add thread: for (int i = 0; i < 4; ++i) { threads.push_back(std::thread([&] {CalculateVertices(vertex_scale, texture_scale, dataSize * i, dataSize * (i + 1), data); })); } , the error occured, it shows the parameter "end" in the function "CalculateVertices" is 2560. Logically, the range should not exceed 2048. Then I try to do some change, I just calculate the "start" and "end" not in the parameter list: for (int i = 0; i < 4; ++i) { int start = dataSize * i; int end = dataSize * (i + 1); threads.push_back(std::thread([&] {CalculateVertices(vertex_scale, texture_scale, dataSize * i, dataSize * (i + 1), data); })); } , now the out of range problem is fixed, but the result still wrong, it seems only generate half of the vertices. I am not familiar to multithreading, and this is my first attempt to use multithreading, I want to know the reason of the problem. According to my experience, I just change one-by-one code to loop, the logic should not be different.
The secret is your lazy auto-capture-by reference: std::thread([&]{ /*...*/ }) This is almost always a bad idea. In this case, you are capturing i by reference, which means when the thread invokes the lambda, i might not even exist and will certainly not have the correct value. At the very least, capture i by value. In fact, you can probably capture all this stuff by value in this case. std::thread([=]{ /*...*/ })
74,394,819
74,396,261
How can an object access another objects data?
Yet another question about my project for my university! We are creating a cash register program which has an inventory, both held in their own respective header files with their own classes and objects. Here is our current iteration of our header files, thought it may be messy from debugging. Inventory.h: class inventory { protected: vector <item> itemList; fstream infile; public: void printList(); void fillInventory(); void fileOpen(); }; class item { protected: double price; string name; int amount; friend class inventory; }; Register.h: class cashRegister : protected inventory { private: vector <int> userChoice; double total = 0; public: void input(); void printReceipt(); void calcTotal(); const double getTotal(); }; void cashRegister::input() { int temp; try { do { cout << "\nPlease select an item using the corresponding item number.\n=> "; cin >> temp; if (cin.fail()) { throw(256); } else { if (temp == -1) { break; } else if (temp >= 0 && temp <= 10) { if (inventory.stockChecker(temp) == 1) { userChoice.push_back(temp); } } else { throw(1); } } cout << "\n\n"; printInventory(); } while (true); } catch (int error) { cout << "Input error: " << error << endl; cout << "Please enter a value from 0 to 10 to select an item (-1 to exit).\n"; cout << "----------------------------------------------------------------\n"; cin.clear(); cin.ignore(256, '\n'); input(); } } The problem here is once we pass ourselves into Register.h, we take user input then call the printInventory inventory method after every entry. But when we go to printInventory we no longer have the itemList data that the inventory object held. Here is main.cpp for clarification on the objects: #include"Inventory.h" #include"Register.h" int main() { inventory inv; inv.fileOpen(); inv.fillInventory(); inv.printInventory(); cashRegister register1; register1.input(); register1.calcTotal(); register1.printReceipt(); } Our object inv holds a vector of item objects, which has the data members price amount name. So when we create the register1 object then try to print the inventory again, we now have an empty vector. How would I achieve being able to print the inv object's itemList or other data in general? EDIT: Also to note I did try passing the inv object by reference and then calling the methods with that object. It did work but it felt awfully messy.
If you want to access the data of inv from a cashRegister object; instead of passing the inv object as reference every time you use it's data, you may want to hold a pointer in cashRegister class. inventory class will have member functions for manupilating and accessing it's data. Therefore you will be able to access to same cashRegister from multiple inventory objects, easily doing operations on cashRegister. With this approach, you will just need to initialize your cashRegister class with a pointer to inventory class. class inventory { public: void printList(); void changeData(); ... }; class cashRegister { private: inventory* inv; public: cashRegister(inventory *inv) : inv(inv) {} void printInventory() { inv->printList(); } ... }; int main() { inventory inv; inv.fileOpen(); inv.fillInventory(); inv.printInventory(); cashRegister register1(&inv); cashRegister register2(&inv); register1.input(); register1.calcTotal(); register1.printReceipt(); register1.printInventory(); register2.printInventory(); }
74,394,852
74,394,872
Write a function that multiplies each element in the array "myArray" by the variable "multiplyMe". c++
I'm supposed to use a function to multiply all elements of an array by 5 and print the numbers after. I don't understand how to put the array in the function definition. What i tried: #include <iostream> using namespace std; // TODO - Write your function prototype here int MultiplyArray(int[], int); int main() { const int SIZE = 10; int myArray[SIZE] = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50}; int multiplyMe = 5; // TODO - Add your function call here MultiplyArray(myArray, multiplyMe); // print the array for(int i=0; i < SIZE; i++) { cout << myArray[i] << " "; } cout << endl; return 0; } // TODO - Write your function definition here int MultiplyArray(int myArray[10], int m) { for (int i = 0; i <= 10; i++) { myArray[i] *= m; } } The output:  sh -c make -s  ./main signal: segmentation fault (core dumped) Expected output: 25 50 75 100 125 150 175 200 225 250
You are very close. Simply remove the 10 from the [] in the function's parameter type, and use < instead of <= in your function's loop. Your loop is going out of bounds of the array (look at the loop in main(), it is using < correctly). int MultiplyArray(int myArray[], int m) { for (int i = 0; i < 10; ++i) { // <-- myArray[i] *= m; } } That being said, consider passing the array's size as a parameter, too: #include <iostream> using namespace std; // TODO - Write your function prototype here int MultiplyArray(int[], int, int); int main() { const int SIZE = 10; int myArray[SIZE] = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50}; int multiplyMe = 5; // TODO - Add your function call here MultiplyArray(myArray, SIZE, multiplyMe); // print the array for(int i = 0; i < SIZE; ++i) { cout << myArray[i] << " "; } cout << endl; return 0; } // TODO - Write your function definition here int MultiplyArray(int myArray[], int size, int m) { for (int i = 0; i < size; ++i) { myArray[i] *= m; } }
74,394,991
74,395,593
What is the minimal way to write a free function to get the member of a class?
(This question popped to my mind after reading this one and its accepted answer.) Assume a class Foo that you cannot modify, that has a public member bar, but no getter for it. You might want to write a function to get that memeber when passed a Foo, so that you can use it in higher order functions, such as std::transform and similar. In other words, given a class like this struct Foo { int bar{}; ~Foo() { bar = -1; } // on most compilers this helps "verifying" that the object is dead }; I would like some getFoo such that getBar(expr-of-type-Foo) has the same semantics as expr-of-type-Foo.bar, where expr-of-type-Foo is any object of type Foo, which can be a prvalue, an xvalue, or an lvalue. How do you write it? What I initially came up with is: constexpr auto getBar = overload( [](auto& foo) -> decltype(auto) { return (foo.bar); }, [](auto const& foo) -> decltype(auto) { return (foo.bar); }, [](auto&& foo) -> auto { return foo.bar; } ); (-> auto is redundant, but I think it's informative in this context.) My reasoning was as follows. I need this getBar to behave differently for the different value categories, so it's a good idea to write it as an overload set; for this purpose I'm using boost::hana::overload. However I'm not sure the solution I found it's minimal (assuming it is sufficient). For instance, Given one of the overloads given I've overloaded on auto&/auto const&/auto&&, the latter will only catch rvalues, so in the other two cases I know I want to return a reference, so I could return -> auto& and -> auto const& instead of decltype(auto) and even remove the parenthesis from the returned expression: constexpr auto getBar = overload( [](auto& foo) -> auto& { return foo.bar; }, [](auto const& foo) -> auto const& { return foo.bar; }, [](auto&& foo) -> auto { return foo.bar; } ); At this, point, though, I don't think I need two overloads (auto&) -> auto&/(auto const&) -> auto const&, because the former will naturally resolve to the latter when fed with a const expression, so I think I could go for this: constexpr auto getBar = overload( [](auto& foo) -> auto& { return foo.bar; }, [](auto&& foo) -> auto { return foo.bar; } ); But I don't see a way to simplify it further, at the moment. Here are my attempts to test it: #include<assert.h> #include<boost/hana/functional/overload.hpp> struct Foo { int bar{}; ~Foo() { bar = -1; } }; int main() { { constexpr auto getBar = overload( [](auto&& foo) -> auto { return foo.bar; }, [](auto& foo) -> auto& { return foo.bar; } ); { Foo foo{3}; assert(&getBar(foo) == &foo.bar); assert(getBar(foo) == 3); foo.bar = 4; assert(foo.bar == 4); assert(getBar(foo) == 4); getBar(foo) = 5; assert(foo.bar == 5); assert(getBar(foo) == 5); } { Foo const foo{3}; assert(&getBar(foo) == &foo.bar); assert(getBar(foo) == 3); //foo.bar = 3; // Expectedly fails to compile. //getBar(foo) = 3; // Expectedly fails to compile. } { auto const& foobar = getBar(Foo{3}); assert(foobar == 3); //foobar = 5; // Expectedly fails to compile. } { //auto& foobar = getBar(Foo{3}); // Expectedly fails to compile. //auto& foobar = Foo{3}.bar; // Expectedly fails to compile. } } }
Well, for minimal work: const auto getBar = std::mem_fn(&Foo::bar); This particular use case appears to do what you want. In C++20, it was upgraded to be constexpr, but that might or might not be available. Unlike the other question, which has overloadable member functions, a member variable isn't ambiguous. So I would fall back to the above.
74,395,291
74,400,887
Sum up values in multidimensional array in c++ and store it in another multidimensional array
I try to sum up the values in an array, and would like to store it in another array. #include <cstdlib> #include <iostream> using namespace std; int main() { int rev[2][12] = {{10,20,30,40,50,60,70,80,90,100,110,120}, {100,200,300,400,500,600,700,800,900,1000,1100,1200}}; int temp = 0; for (int j = 0; j<2;j++){ for(int i = 0; i<12; i++){ temp += rev[j][i]; } cout << "rev in year " << j+1 << ": " << temp << "\n"; temp = 0; } int revYear[2][1]; for (int j = 0; j<2;j++){ for(int i = 0; i<12; i++){ revYear[j][0] += rev[j][i]; } } cout << "rev in year 1: " << revYear[0][0] << "\n"; cout << "rev in year 2: " << revYear[1][0] << "\n"; return 0; } The first two for loops give me the desired output I'd like to store in revYear, which I tried in the second step. But it returns: rev in year 18363800 rev in year 278010 Can anyone help me with this? Is it a compiler issue? I´m using Mac and Xcode but I also ran the code with MS VS on Windows. Same problem, different output. Please note: in the upper part, i just wanted to show that I found a way to get the desired output.
The first two for loops give me the desired output Let's see why // This variable is declared and contextually assigned a meaningful value: zero. int temp = 0; for (int j = 0; j<2;j++){ for(int i = 0; i<12; i++){ // Here it's updated, we want it to hold the sum. temp += rev[j][i]; } // Now it has reached its final value and can be shown. cout << "rev in year " << j+1 << ": " << temp << "\n"; // Here it is RESETTED, so that it's ready for the next iteration. // It would be an error to start the sum from any value other than zero. temp = 0; } This snippet produces the correct result, but it's not quite idiomatic. You could rewrite it like the following: for (int j = 0; j<2; j++) { int temp = 0; // <--- Initialize inside the loop, at the beginning. for(int i = 0; i<12; i++) { temp += rev[j][i]; } std::cout << "rev in year " << j+1 << ": " << temp << "\n"; } Even better, you could use one of the algorithms of the Standard Library, std::accumulate: for (size_t i{}; i < std::size(rev); ++i) { std::cout << "revenue in year " << i + 1 << ": " << std::accumulate( std::begin(rev[i]), std::end(rev[i]) , 0 ) // <--- Initialization of the sum << '\n'; } Now it should be clear why the second nested loop in the question's posted code fails. // This variable is declared, but NOT initialized. Its elements have // UNDETERMINED values, they could be equal to zero only by accident. int revYear[2][1]; for (int j = 0; j<2;j++){ for(int i = 0; i<12; i++){ // While the code accumulates the values correctly, we don't know // the initial value, so the result will be likely wrong. revYear[j][0] += rev[j][i]; } } To fix it, we can properly initialize the array (it's still unclear to me why they want a 2D one, but that seems part of assignment). int revYear[2][1]{}; Which IMHO is preferable to set the correct value at the beginning of the loop. int revYear[2][1]; for (int j = 0; j<2;j++) { revYear[j][0] = 0; // <--- // ... std::cout << "revenue in year " << j + 1 << ": " << revYear[j][0] << "\n"; }
74,395,393
74,424,628
Gtkmm add/Remove widget leaks Why?
When I add a widget to container, then I remove it. Widget is leaked, why ? I used a "MyWidget" to spy widget deletion but I get same result from a classic Gtk::Label. Code below have been tested on two distro. #include <iostream> // gtkmm30-3.24.5-1.el9.x86_64 // or gtkmm3 3.24.7-1 (arch) #include <gtkmm/main.h> #include <gtkmm/builder.h> #include <gtkmm/label.h> #include <gtkmm/window.h> #include <gtkmm/box.h> #include <cassert> using namespace std; class MyWidget : public Gtk::Label{ public: MyWidget(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& builder); virtual ~MyWidget(); }; MyWidget::~MyWidget(){ cout << "MyWidget::~MyWidget()" << endl; } MyWidget::MyWidget(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& builder) : Gtk::Label(cobject) { assert(builder); } int main() { Gtk::Main main; // Create widget auto builder = Gtk::Builder::create_from_file("widget.glade"); MyWidget* widget = nullptr; builder->get_widget_derived("widget", widget); { Gtk::Window window; window.add(*widget); // Use window .... window.remove(); // No leak if this line is commented } builder.reset(); cout << G_OBJECT(widget->gobj())->ref_count << endl; // Print => 1 // Expected to see "MyWidget::~MyWidget()" but No ! Why ? } I expected to see ~MyWidget destructor executed. This is my glade file content <?xml version="1.0" encoding="UTF-8"?> <!-- Generated with glade 3.40.0 --> <interface> <requires lib="gtk+" version="3.24"/> <object class="GtkLabel" id="widget"> <property name="visible">True</property> <property name="can-focus">False</property> <property name="label" translatable="yes">widget</property> </object> </interface>
The incorrect assumption we made here is that Gtk::Window::remove() destroys the widget it removes, but in reality, it only removes its reference from the parent container. I instrumented your code with extra couts to see what was happening and when this line is executed: builder->get_widget_derived("widget", widget); A MyWidget instance is created by the builder. At this point, the builder owns a reference to it and the ref count is one. Then, when the following line is executed: window.add(*widget); the window, which is a one element container as you pointed out, takes a (owning) reference on the MyWidget instance. So the reference count on the MyWidget instance is now 2: one for the builder, one for the window. This is where it gets tricky. When executing: window.remove(); the window "removes" its reference to the MyWidget instance, in the sense that it will no longer show it, but the reference count on it is not decremented. At this point, there are still two references on the MyWidget instance: one for the builder, and one that is not owned by anyone (it is leaked, unless someone explicitly calls delete on it). When this line is executed: builder.reset(); The builder is destroyed, and its reference to the MyWidget instance is removed, bringing the reference count on it to one. This is why printing the reference count always prints "1" in your case. Now if we comment out: window.remove(); What happens it that at the end of main, the window destroys itself and the widget it references (if any). In your case, this is the MyWidget instance, so the destructor is called and the reference count is brought to 0. You don't see it printed because it happens after the cout call, at the } (end of scope for main).
74,395,552
74,452,644
Prevent clang-tidy from running on generated files
We have a project that includes protobuf files that get pre-compiled into C++ files. Unfortunately, those files (like the other source files in the project) get checked by clang-tidy and generate a large number of warnings. The relevant top-level CMakeLists.txt statements are: # For all targets set(CMAKE_CXX_CLANG_TIDY ${CLANG_TIDY_EXECUTABLE}; --header-filter=.) # Generated protobufs include_directories(SYSTEM ${CMAKE_BINARY_DIR}/grpc_interface) target_link_libraries(${PROJECT_NAME} # ... grpc_services ) And the grpc_interface/CMakeLists.txt contains: project(grpc_services) set(PROTO_IMPORT_DIRS ${CMAKE_SOURCE_DIR}/protocols/protobuf/ ) set(PROTOS ${CMAKE_SOURCE_DIR}/protocols/protobuf/test_message.proto ) add_library(${PROJECT_NAME} STATIC ${PROTOS}) target_link_libraries(${PROJECT_NAME} PUBLIC protobuf::libprotobuf gRPC::grpc++ ) get_target_property(GRPC_CPP_PLUGIN gRPC::grpc_cpp_plugin LOCATION) protobuf_generate( TARGET ${PROJECT_NAME} IMPORT_DIRS ${PROTO_IMPORT_DIRS} LANGUAGE cpp ) protobuf_generate( TARGET ${PROJECT_NAME} IMPORT_DIRS ${PROTO_IMPORT_DIRS} LANGUAGE grpc GENERATE_EXTENSIONS .grpc.pb.h .grpc.pb.cc PLUGIN "protoc-gen-grpc=${GRPC_CPP_PLUGIN}" ) One option is to copy a .clang-tidy file that disables all warnings into the ${CMAKE_BINARY_DIR}/grpc_interface directory, but I think that that would still incur the time penalty of clang-tidy parsing those files. The "grpc_services" target only contains generated files. Is there a better way of disabling clang-tidy processing in just that folder?
Since the "grpc_services" target only contains generated files, you can just set the CXX_CLANG_TIDY target property on that target to be nothing.
74,395,595
74,398,359
CXX translate - const char * to rust equivalent
I am writing an integration of C++ and Rust via CXX https://cxx.rs/index.html The C++ function signature in myclient.h public: bool connect(const char * host, int port, int clientId = 0); What do I put in the main.rs in order to have it callable from rust? I've tried a lot of combos fn connect(host: &mut , port: u64, clientId: u64 ) -> bool; fn connect(host: *char , port: u64, clientId: u64 ) -> bool; fn connect(host: *const char , port: u64, clientId: u64 ) -> bool; all of these error out.. not very good at C++ or Rust so.. just hoping someone can point me to how to convert this .. thanks! error[cxxbridge]: unsupported type: char ┌─ src/main.rs:15:33 │ 15 │ fn connect(host: *const char , port: u64, clientId: u64 ) -> bool; │ ^^^^ unsupported type EDIT : After getting a bit closer.. it seems to complain about pointer argument requires that the function be marked unsafe #[cxx::bridge(namespace = "com::enserio")] mod ffi { unsafe extern "C++" { include!("twsapi_grpc_server/include/twsapi-client.h"); include!("twsapi_grpc_server/include/AvailableAlgoParams.h"); include!("twsapi_grpc_server/include/AccountSummaryTags.h"); include!("twsapi_grpc_server/include/Utils.h"); type TWSApiClient; fn new_twsapi_client() -> UniquePtr<TWSApiClient>; fn init_connect(&self, host: *const c_char , port: i32, client_id: i32) -> bool; } } error[cxxbridge]: pointer argument requires that the function be marked unsafe ┌─ src/main.rs:16:32 │ 16 │ fn init_connect(&self, host: *const c_char , port: i32, client_id: i32) -> bool; │ ^^^^^^^^^^^^^^^^^^^ pointer argument requires that the function be marked unsafe
char in rust is not what you want (in rust char is a unicode chacrter, while in C it is a single byte). What you want is libc::c_char. use libc::c_char; extern "C" fn connect(host: *const c_char , port: u64, clientId: u64 ) -> bool { true } However I'm not sure the bool as the return type will work reliably, I'd probably return a type with a concrete size like u32 instead.
74,395,672
74,395,892
Why do I need std::move twice in a row?
I'm fudging around with some code because I think I found a solution to another problem. I'm writing a little test program and I got it to work. But only if I use std::move() twice in a row. Here's the example code: using namespace std; class Serializable { public: virtual string serialize() = 0; }; class Packet: public Serializable { string payload; public: virtual string serialize() { return payload; } Packet(string payload): payload(payload) { cout << "Packet made" << endl; } }; class Frame: public Serializable { unique_ptr<Serializable> packet; string head; public: virtual string serialize() { return head + packet->serialize(); } Frame(string head, unique_ptr<Serializable>&& packet): head(head), packet(move(packet)) { // Second Time cout << "Frame made" << endl; } }; int main() { unique_ptr<Serializable> packet = make_unique<Packet>("World!"); Frame frame { "Hello ", move(packet)}; // First Time cout<<frame.serialize(); return 0; } When I remove the "First one" (in main()), I get this error: main.cpp:49:29: error: cannot bind rvalue reference of type ‘std::unique_ptr&&’ to lvalue of type ‘std::unique_ptr’ When I remove the other, I get this error: main.cpp:39:34: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Serializable; _Dp = std::default_delete]’ I understand the one in the constructor, you can't copy a unique_ptr. But what about the one in main()? I'm stumped.
If you do: Frame("", packet) The compiler will try to copy the argument packet into the parameter packet. As you know, std::unique_ptr cannot be copied. Even if you are passing this into a parameter, since you cannot copy, you need to move the std::unique_ptr. And then, in the constructor: Frame(string head, unique_ptr<Serializable>&& packet) : head(head), packet(move(packet)) { ... } The std::move() here moves the constructor parameter packet to the member variable packet. Since we cannot copy, this needs to be a move operation as well. Summary: argument packet moves into constructor parameter packet, then parameter packet moves into member variable packet. So we need to do two move operations.
74,395,948
74,414,040
C++ lambda as parameter with variable arguments
I want to create an event system that uses lambda functions as its subscribers/listeners, and an event type to assign them to the specific event that they should subscribe to. The lambdas should have variable arguments, as different kinds of events use different kinds of arguments/provide the subscribers with different kinds of data. For my dispatcher, I have the following: class EventDispatcher { public: static void subscribe(EventType event_type, std::function<void(...)> callback); void queue_event(Event event); void dispatch_queue(); private: std::queue<Event*> event_queue; std::map<EventType, std::function<void(...)>> event_subscribers; }; No issues here, but when I go to implement the subscribe() function in my .cpp file, like this: void EventDispatcher::subscribe(EventType event_type, std::function<void(...)> callback) { ... (nothing here yet) } The IDE shows me this: Implicit instantiation of undefined template 'std::function<void (...)>'
After the input from @joergbrech and @HolyBlackCat I made this enum class EventType { WindowClosed, WindowResized, WindowFocused, WindowLostFocus, WindowMoved, AppTick, AppUpdate, AppRender, KeyPressed, KeyRelease, MouseButtonPressed, MouseButtonRelease, MouseMoved, MouseScrolled, ControllerAxisChange, ControllerButtonPressed, ControllerConnected, ControllerDisconnected }; class IEvent { public: IEvent(EventType event_type) { this->event_type = event_type; } EventType get_event_type() { return event_type; } private: EventType event_type; }; class IEventSubscriber { public: /** * @param event The event that is passed to the subscriber by the publisher; should be cast to specific event * */ virtual void on_event(IEvent *event) = 0; EventType get_event_type() { return event_type; } protected: explicit IEventSubscriber(EventType event_type) { this->event_type = event_type; } private: EventType event_type; }; class FORGE_API EventPublisher { public: static void subscribe(IEventSubscriber *subscriber); static void queue_event(IEvent *event); static void dispatch_queue(); private: static std::queue<IEvent*> event_queue; static std::set<IEventSubscriber*> event_subscribers; }; I've tested it and I get the expected result from this solution. For the full code solution -> https://github.com/F4LS3/forge-engine
74,396,388
74,396,797
C/C++ macro conflict from external libraries
I'm trying to combine boost/asio library with ncurses, but they have macro conflict. It gives this error message: [build] /usr/local/include/boost/asio/basic_socket_streambuf.hpp:640:39: error: expected expression [build] socket().native_handle(), timeout(), ec_) < 0) [build] ^ [build] /usr/include/curses.h:1245:47: note: expanded from macro 'timeout' [build] #define timeout(delay) wtimeout(stdscr,(delay)) [build] To be precise, I have a ui.hpp file and it is later included in main code. ui.hpp includes <ncurses.h> and then defines classes. One of the classes declares variables that are from <ncurses.h> header so I can't move #include <ncurses.h> from ui.hpp file to ui.cpp (unless there is a workaround): class BorderedWindow { protected: // I need #include <ncurses> to declare these 2 vars WINDOW *window_; WINDOW *border_; Should I compile ui in a static library separately and then link it to main application, or is there an easier way of doing it?
To prevent a macro conflict you need to redo a structure of your project that way, so no file include both ncurses.h and boost/asio.hpp headers simultaneously. To do this you need to wrap one library in .hpp+.cpp pair and also make sure that .hpp doesn't include the header of this library and only .cpp does. Then only use the wrapper instead of the library. In my case, variable definitions made it harder because I can't use the library types without including header. But I changed all my vars defined in ui.hpp from ncurses.h header to void*, casted all of them to respective types in ui.cpp and deleted #include <ncurses.h> from header and my code compiled. It's not a good solution, but it works.
74,396,641
74,396,780
Is there a way to change the color of the text in a ChooseFont() dialog in the Win32 API?
I am developing a basic text editor program with the Win32 API's file editor example, using Dev-C++ from bloodshed.net. How can I change the text color when I select it on the ChooseFont() dialog? In that dialog, everything works except the color changing option. Below is my code. Choose font dialog, and in the switch case I called that function from the menu format and font: CHOOSEFONT cf = {sizeof(CHOOSEFONT)}; LOGFONT lf; GetObject(g_hFont, sizeof(LOGFONT), &lf); cf.Flags = CF_EFFECTS | CF_SCREENFONTS | CF_INITTOLOGFONTSTRUCT; cf.hwndOwner = g_hwnd; cf.lpLogFont = &lf; cf.rgbColors = g_editcolor; if (!ChooseFont(&cf)) return; HFONT hf = CreateFontIndirect(&lf); if (hf) { g_hFont = hf; SendMessage(g_hEdit, WM_SETFONT, (WPARAM)g_hFont, TRUE); } g_editcolor = cf.rgbColors;
A font doesn't have a color. A device context has a color assigned which it uses when rendering text using a font. To set a text color for a standard EDIT control, have the parent window handle the WM_CTLCOLOREDIT and WM_CTLCOLORSTATIC window messages: An edit control that is not read-only or disabled sends the WM_CTLCOLOREDIT message to its parent window when the control is about to be drawn. By responding to this message, the parent window can use the specified device context handle to set the text and background colors of the edit control. A static control, or an edit control that is read-only or disabled, sends the WM_CTLCOLORSTATIC message to its parent window when the control is about to be drawn. By responding to this message, the parent window can use the specified device context handle to set the text foreground and background colors of the static control. Use SelectObject() to assign your HFONT to the provided HDC, and set the HDC's text color using SetTextColor().
74,396,733
74,396,742
C++ - Why is a Static Library unusable without source files?
So from what I understand, a static compiled mylib.a file should just be usable as plug-and-play. But I can't use it without the source code, I'm trying to avoid that. I adapted this tutorial to compile using CMake with the following directory structure: / lib libmy_math.a main.cpp my_math.h my_math.cpp CMakeLists.txt The contents of the files are exactly as in the tutorial. The only added file is CMakeLists.txt which basically just runs the library compiling part before building: CMakeLists.txt cmake_minimum_required(VERSION 3.21) project(Test) ### Uncomment this ONCE to compile a libmy_math.a file # add_library(my_math STATIC my_math.cpp) add_executable(Test main.cpp) find_library(MY_MATH_LIB my_math HINTS ./lib) target_link_libraries(Test PUBLIC ${MY_MATH_LIB}) As the CMake file says, uncommenting Line 5 compiles the library, which is then linked to my code when compiling. I'm trying to package my code so that I don't show my client the source code for the compiled library (my_math), but if I delete the my_math.h and my_math.cpp files, I get a "file not found" error on import: /Users/Joe/Desktop/Test/main.cpp:1:10: fatal error: 'my_math.h' file not found #include "my_math.h" ^~~~~~~~~~~ I thought you could compile libraries without needing the source code. What am I missing here?
A static library does not contain each and every definition a header can contain - think of macros, etc. Thus you still need the header. However, you don't need the .cpp anymore to link the library.
74,396,872
74,397,379
Declare a template pointer without knowing the type
I have this code with a template function. The function can accept any object that is inherited from Object or with an operator providing a pointer to an Object instance. Inside the function I need to get the Object pointer, but it is a template type and I can't figure out the way how to specify the template type. here is the code: class IObject { }; template<class T> class Object: public IObject { typedef T value_type; public: void test() { } operator Object<T>*() { return this; } }; template<class T> class Wrapper { typedef T value_type; public: T object; operator T*() { return &object; } }; template<class T> class Container { public: void func() { data.resize(1); typename T::value_type& ref = data[0]; //IObject* object = ref; //works Object<?>* object = ref; // How can I specify the template type here? object->test(); }; T data; }; int main() { Container<std::vector<Object<float>>> container1; container1.func(); Container<std::vector<Wrapper<Object<int>>>> container2; container2.func(); return 0; } I tried playing with value_type, but as there are technically 2 types of objects can be used as an input, it doesn't work. Also I tried adding extra argument to the function template, but the argument type can't be deduced by the compiler.
First off, either your Wrapper is wrong or your usage of it is wrong. You instantiate Wrapper<Object<int>> but in the class you have: Object<T> object; operator Object<T>*() which is instantiated as Object<Object<int>> object; operator Object<Object<int>>*() You should either instantiate Wrapper<int>, which would "wrap" a Object<int>, or change your class to have this instead: T object; operator T*() but then the typedef T value_type is wrong. In any case, you can create a type trait to "unwrap" the type: template<class T> struct UnwrapT { using type = T; }; template<class T> struct UnwrapT<Wrapper<T>> { using type = Object<T>; }; template<class T> using Unwrap = typename UnwrapT<T>::type; You can then use this in func: Unwrap<typename T::value_type>* object = ref; Demo
74,397,068
74,397,305
pointer variable defined by typedef
I know that the code below works. int* pn; pn = new int; So I tried to apply it in same way, in my custom class. class Matrix { private: typedef struct ex_node* ex_pointer; typedef struct ex_node { int ex_data; ex_pointer next; }; public: void examplefunction() { ex_pointer node; node = new ex_node; //error here } }; The error says that I cannot assign "ex_node*" type value to "ex_pointer"type entity. But ex_pointer is defined as ex_node*. Is ex_pointer different type from ex_node*? How can I remove this error?
I like the question and Jason Liam already provided different ways to fix your code. But I'd like to answer your first questions, which are entirely valid: "The error says that I cannot assign "ex_node" type value to "ex_pointer"type entity. But ex_pointer is defined as ex_node*. Is ex_pointer different type from ex_node*?" Let's check exactly what the compiler says: error: incompatible pointer types assigning to 'Matrix::ex_pointer' (aka 'ex_node *') from 'Matrix::ex_node *' node = new ex_node; ^~~~~~~~~~~ So, the problem is that node is of type Matrix::ex_pointer, that is a ex_node *. new ex_node instead is of type Matrix::ex_node *. The former is a pointer to a struct ex_node defined in the global namespace, while the latter is a pointer to a struct ex_node defined within class Matrix. Apparently forward declaring a struct within a typedef assumes that the struct is in the global namespace, which in your case is not correct. You can fix it (as suggested also by Jason Liam) by forward declaring your struct before the typedef: class Matrix { struct ex_node; typedef struct ex_node* ex_pointer; struct ex_node { int ex_data; ex_pointer next; }; public: void examplefunction() { ex_pointer node; node = new ex_node; } }; Finally: don't hide that pointer behind a typedef.
74,397,873
74,397,890
What is a Token in C++?
I am feeling really dumb right now but I am not understanding the concept of tokens. I am currently reading Dr. Stroustrup's textbook, Programming Principals and Practices, am and in Chapter 6 learning about tokens and writing programs in C++. I have gotten every concept in the book thus far, but this has really got me stuck. Can anyone please dumb it down for me? Thank you! I have honestly tried to watch YouTube videos that have not been of any help along with reading the textbook that hasn't helped either.
A token corresponds roughly to a word of source-code. For example, in a line of source code like this: int a = 10; The tokens would be "int", "a", "=", "10", and ";". In a compiler, it's the job of the tokenizer to interpret the source code files (which are really just plain-text files, i.e. a series of characters) into a series of tokens (which have some sort of specific meaning in the context of the language). The series of tokens will then be fed into the next stage of the compiler for further processing.
74,398,728
74,399,696
Completing a Birthday Problem using a 2-D String Array
I'm really new to C++ so I apologize in advance if my code is horrendous. I have a birthday problem in which I am required to create a program that asks for a total of 5 friends names and their corresponding birthdays and store those values in a 2-D array and then print them all at the end. I have no idea how to do that exactly however here is the best attempt I've completed thus far. Any advice and feedback is appreciated! // Import libraries #include <iostream> #include <string> #include <iomanip> using namespace std; // Main function int main() { // Declare variables const char NAME = 5, BIRTHDAY = 5; // Define array char birthSimulator [NAME][BIRTHDAY]; // Output header cout << "\n\t\t\tWelcome to the Birth simulator 0_o"; // Print string stored in array for (int i = 0; i < NAME; i++){ cout << "\nThe name of the " << birthSimulator[NAME] << " friend is: "; getline(cin, birthSimulator[NAME][BIRTHDAY]); } for (int i = 0; i < BIRTHDAY; i++){ cout << "\nThe name of the " << birthSimulator[BIRTHDAY] << " friend is: "; getline(cin, birthSimulator[NAME][BIRTHDAY]); } for (int i = 0; i < NAME; i++){ cout << birthSimulator[NAME] << "'s birthday is on: " << birthSimulator[BIRTHDAY]; } return 0; }
To do this project, you can get help from the STL library, which makes the work easier. you could use std::vector or std::arrays , also instead of char array you can use std::string. but if you want to use C-style array than your array will look like this : std::string birthSimulator[5][2]; you create a array of 5 string and those are two parts. name1 birthday1 name2 birthday2 name3 birthday3 name4 birthday4 name5 birthday5 and than you initialaze them: for(short i = 0 ; i < 5; i++){ for(short j = 0 ; j <2; j++){ std::getline(std::cin , birthSimulator[i][j]); }//end for 'j' }// end for 'i' and you input name and birthday. And for Printing array you do thesame : for(short i = 0 ; i < 5; i++){ for(short j = 0 ; j <2; j++){ std::cout << birthSimulator[i][j] << ' '; }//end for 'j' std::cout << '\n'; }// end for 'i'
74,398,966
74,399,073
How do I make the if statement return to the previous step?
so I want to return to 'Enter a new email address: " once the user enters an incorrect email address rather than it move on to the next step. cout<<"\n\t Enter a new email address: "; cin>>str; if(Email_check(str)) { cout<<""; //i dont know how to check it without it giving any output, so i did "" } else{ cout<<"\n\t Email Address is not valid."<<endl; //HERE I WANT IT TO RETURN TO "ENTER A NEW EMAIL ADDRESS" cout<<"\n\t Enter a new ID number: "; cin>>newid; I could only manage to return 0; which ends the program but thats not what i want.
Whenever you want to do something repeatedly you need some kind of loop. Since you want to repeat until an email address is valid a do ... while loop seems appropriate. Here's one way to do it bool email_valid = false; // track whether email is valid do { cout << "\n\t Enter a new email address: "; cin >> str; if (Email_check(str)) { email_valid = true; // email is valid } else { cout << "\n\t Email Address is not valid." << endl; } } while (!email_valid); // repeat if email not valid cout << "\n\t Enter a new ID number: "; cin >> newid;
74,399,033
74,401,467
Cannot reboot system from C++
I've a C++ program running in a docker container. I want to reboot container via my program but I cannot. Dockerfile: FROM gcc WORKDIR /client COPY . . RUN apt-get update && apt-get install qt5-qmake qtbase5-dev libmosquitto-dev -y RUN qmake mainapp.pro && make RUN chmod +x docker-entrypoint.sh docker-entrypoint.sh #!/bin/bash ./mainapp -e Here is my reboot function (cleared from unnecessary codes): Logger::getInstance()->write(QString("Sync")); sync(); Logger::getInstance()->write(QString("Setuid")); setuid(0); Logger::getInstance()->write(QString("RB_AUTOBOOT")); reboot(RB_AUTOBOOT); Logger::getInstance()->write(QString("Reboot")); system("reboot"); I can see ALL the outputs and then it prints an error message. Here is the error message: System has not been booted with systemd as init system (PID 1). Can't operate. Failed to connect to bus: Host is down Failed to talk to init daemon. I tried to reboot from container but it doesn't work as well: root@93501f6d7fc8:/client# reboot System has not been booted with systemd as init system (PID 1). Can't operate. Failed to connect to bus: Host is down Failed to talk to init daemon. root@93501f6d7fc8:/client# shutdown -r System has not been booted with systemd as init system (PID 1). Can't operate. Failed to connect to bus: Host is down I've searched this problem and tried most of the suggestions but they didn't solved my problem. I am open to all your ideas and suggestions.
Thanks for the answers. I added this to my docker compose yaml file: privileged: true restart: always After that, reboot(RB_AUTOBOOT); rebooted my container and started the app successfully.
74,399,683
74,399,770
Strcat not appending a character
char* oledScreen::getCurrentTime(){ char* hour = malloc(16); snprintf(hour, 16, "%d", getHour()); char* minute = malloc(16); snprintf(minute, 16, "%d", getMinute()); char* firstPart = strcat(getHour() < 10 ? strcat("0",hour) : hour, ":"); const char* secondPart = getMinute() < 10 ? strcat("0",minute) : minute; return strcat(firstPart, secondPart); }; I'm trying to append two integers, which I can obtain using getHour() and getMinute(). However, I need to check if one of these two are less than 10: if so, I need to append a 0 so that the output is such that: 0X, where X is getHour() or getMinute(). My problem is that it does not append the : character. For instance, if getHour() = 9 and getMinute() = 15. The output of getCurrentTime() is 0915 and not 09:15. Do you have any idea why this is like this?
To begin with, strcat("0",hour) will lead to undefined behavior as you attempt to modify the literal string "0" which isn't allowed. Instead of using multiple strcat calls, why not simply create a string large enough to fit the result, and use snprintf to put contents into the string? Using snprintf will also make it easier to optionally add a zero-prefix to the hour value. Perhaps something like this: // Allocate memory, and actually create the string // 2 for hour, 2 for minutes, 1 for colon, 1 for terminator char *result = malloc(6); snprintf(result, 6, "%02d:%02d", getHour(), getMinute()); return result; As mentioned in comments, a better solution would be to pass in the result array as an argument to the function. The would handle ownership of the result array better, and might not even need dynamic allocation. [Note that the above is a pure C solution, it's not even valid in C++. I wrote it before noticing that the code in the question is really C++.] Considering that you really seem to be programming in C++, not C, then a solution using string streams and std::string would be more appropriate: std::string oledScreen::getCurrentTime(){ std::ostringstream oss; oss << std::setw(2) << std::setfill('0') << getHour() << ':' << std::setw(2) << std::setfill('0') << getMinute(); return oss.str(); }
74,399,833
74,423,951
What is the machinery behind stack unwinding?
I'm trying to understand the machinery behind stack unwinding in C++. In other words I'm interested in how this feature is implemented (and whether that is a part of the standard). So, the thread executes some code until an exception is thrown. When the exception is thrown, what are the threads/interrupt handlers used to record the state and unwind the stack? What is guaranteed by the standard and what is implementation specific?
The thread executes some code until the exception is thrown, and it continues to do so. Exception handling still is C++ code. The throw expression creates a C++ object, running in the context of the throwing function. While the constructor of the exception object is running, all objects in the scope of the throwing function are still alive. Directly after, however, the stack unwind happens. The C++ compiler will have arranged for a return path that does not require a return object, but which does allow passing of the exception object. Just like a normal return, objects that are local to a function are being destroyed when the function returns. At binary level, this is pretty straightforward: it's just a bunch of destructor calls, and typically a stack pointer is also adjusted. What the standard also does not specify, is the mechanism used to determine how many scopes need to be exited. The standard describes in terms of catch, but a typical CPU has no direct equivalent. Hence, this is commonly part of the C++ ABI for a given platform so that compilers sharing a ABI agree. ABI compatibility requires that a caller must catch the exceptions from a callee, even if they've been compiled with different compilers. And obviously, destructors have to be called, so the ABI also needs to arrange that mechanism. The intermediate functions could even have been compiled by a third compiler - as long as they share an ABI, it's all supposed to work. As noted in the comments, C++ has no notion of interrupts. If the OS needs something to happen with interrupts, the compiler needs to take care of that. It matters little what exactly the C++ code is doing at that time.
74,401,144
74,409,272
QListView with Two QTextEdit 's as Item
In Qt Widget Application (c++), a part of my *.ui file consists of a QListView with two QTextEdits as its items like the below figure. As you can see custom widget includes two QTextEdit that each one has its text and stylesheet. As I searched on the net, there are solutions like HtmlDelegate classes for rendering text of items on QListView. But these classes only present ONE QTextEdit as item for QListView. In future, I want sync the QListView scrol status with a QMultimedia status like Podcast apps. Does anyone have any idea?
well first of all you should create your custom widget like this: Then you add it to your Model of QListView by using setIndexWidget function like this: QStandardItemModel *model = new QStandardItemModel(120, 1); ui->listView->setModel(model); for (int r = 0; r < 120; r++) { ui->listView->setIndexWidget(model->index(r, 0), new CustomTextEdits); } Final Result: you can see the source code here: https://github.com/parisa-hr/SO-addwidgettoqlistview
74,401,246
74,403,903
Can C++-modules be consumed by non-modularized code?
I have a rather large codebase, that I want to start porting to C++20-modules. The layout is (roughly) like this: SDK/System > Engine > Editor In the order of they reference each other (editor uses engine, etc...). My main interest would be, to first port SDK, and then Engine to modules. Editor is the least important in that regard. However, from my first attempts and research, you would have to start bottom-up, since if "SDK" is modularized, if "Editor" still uses header-includes, it wouldn't be able to use the modules. Is this correct? If so, is there any way around it? I have seen some attempts by using #ifdefs to have both modules and header based approaches, but this would remove much of the benefit from using modules in the first place. Or do I really have to port all the consumer-code before I can start porting the shared libraries?
A file that is not a module unit can import module units just fine. You can even #include a header which has import directives in it (not that this is a good idea). And module units can #include headers just fine, so long as you do it in the global module fragment, before the main module declaration. What you can't do is create a module unit and expose its interface to some other file via a header that does not import that module unit. Once something is in a module, it can only be accessed via import.
74,401,373
74,402,621
Can this_thread::sleep() be interrupted on linux?
When using nanosleep, we need to check the return value to detect whether we have been interrupted by a signal: while ((nanosleep(&rqtp, &rmtp) == -1) && (errno == EINTR)) { if (rmtp.tv_nsec != 0 || rmtp.tv_sec != 0) { rqtp = rmtp; continue; /* Wait again when interrupted by a signal handler */ } } I want to use std::this_thread::sleep_for() instead of nanosleep(). Is it possible that a call to this_thread::sleep_for() is also interrupted (ends earlier as specified)?
If you use GCC's libstdc++, you can find the corresponding code here: while (::nanosleep(&__ts, &__ts) == -1 && errno == EINTR) { } with the timespec __ts prepared accordingly. So it basically does the same thing as your code loop and restarts the sleep after a signal interrupt. The C++ standard itself says: The functions whose names end in _­for take an argument that specifies a duration. These functions produce relative timeouts. Implementations should use a steady clock to measure time for these functions. Given a duration argument Dt, the real-time duration of the timeout is Dt+Di+Dm. Where Di and Dm are delays introduced by the implementation and by the resource management, as described in the previous sentence of the standard. Assuming that these delays are positive (which they should be), the sleep time is always at least as long as the specified time. Thus in my opinion, the standard guarantees that the sleep does not end early.
74,401,389
74,401,507
Push back string into vector<T>
I'm finally trying to learn templates and I created a template function that will return an std::vector with a generic type. When compiling I get an error: error: no matching function for call to ‘std::vector::push_back(std::string&)’ Is there a way to support std::string or a comparable type in the template vector in addition to the primitive types? Here is a 'Minimal, Reproducible Example' that doesn't compile due to this error (this is obviously not my code, it just illustrates the error): #include <iostream> #include <vector> enum types{ TINT = 0, TDOUBLE = 1, TSTRING = 2, }; class TestClass{ public: template<typename T> std::vector<T> getData(types type) { std::vector<T> entries; int i_value; double d_value; std::string st_value; switch (type) { case types::TINT: i_value = 1; entries.push_back(i_value); break; case types::TDOUBLE: d_value = 0.1; entries.push_back(d_value); break; case types::TSTRING: st_value = "foo"; entries.push_back(st_value); //Pushing an std::string causes a compile error break; default: break; } return entries; } }; int main() { TestClass bar; std::vector<int> test = bar.getData<int>(types::TINT); return 0; } Commenting the line entries.push_back(st_value); makes everything compile again.
The code does not compile because you try to check the types at runtime. This is too late. Use std::is_same to make a compile time check. template<typename T> std::vector<T> getData() { std::vector<T> entries; int i_value; double d_value; std::string st_value; if constexpr(std::is_same_v<T, int>) { i_value = 1; entries.push_back(i_value); } else if constexpr(std::is_same_v<T, double>) { d_value = 0.1; entries.push_back(d_value); } else if constexpr(std::is_same_v<T, std::string>) { st_value = "foo"; entries.push_back(st_value); } return entries; }
74,401,584
74,403,491
About the Windows BYTE and PBYTES data types
What is "BYTE" and "PBYTE" used for?.I couldn't find any information on the internet. #include <iostream> #include <Windows.h> using namespace std; BYTE by='a'; PBYTE pby= &by; int main(){ cout<<"by : "<<by<<endl; cout<<"&by : "<<&by<<endl; // Why doesn't it return the memory address? cout<<"pby : "<<pby<<endl; cout<<"&pby: "<<&pby; return 0; } The console shows: by : a &by : a pby : a &pby: 00007FF6CC10A008 I just want to know what BYTE and PBYTE are used for. I can not understand. Thanks
BYTE,PBYTE is very old style in windows programming. If you want to allocate heap memory for your image loader for example, you can write unsigned char* img = new unsigned char[1024 * 1024]; load_image(img, ....); conv_image(img, ....); But your finger would be tired, so you can write PBYTE img = new BYTE[1024 * 1024]; Yes, microsoft invented these defined types over 20yr ago. But it is not portable and not follows standards and cause memory leaks, so in the 21st century, you should write as described below. auto img = make_shared<uint8_t>(1024 * 1024); or vector<uint8_t> v(1024 * 1024); or array<uint8_t, 1024 * 1024> a; // need enough stack memory
74,401,680
74,411,120
Calling managed function inside CommandBuffer hang domain reload
I'am trying to call managed function inside CommandBuffer via IssuePluginEventAndData. It accepts (void* function pointer, int eventId, void *data). Here's the function: [UnmanagedFunctionPointer(CallingConvention.StdCall)] public unsafe delegate void PluginDelegate(int eventId, void* data); [MonoPInvokeCallback(typeof(PluginDelegate))] private static unsafe void MakeGraphicsCallback(int eventId, void* data) { //Completely empty. } Then store delegate inside non-static MonoBehaviour class and add it to CommandBuffer: //Prevent delegate to be garbage collected. private static PluginDelegate makeCallbackDelegate; public void Start() { makeCallbackDelegate = MakeGraphicsCallback; cmdBuffer.IssuePluginEventAndData( Marshal.GetFunctionPointerForDelegate(makeCallbackDelegate), 0, IntPtr.Zero); } Everything works fine (even if function is not empty), but then, when game is stopped, and runned again it hang on domain reload, here's how editor log ends: Reloading assemblies for play mode. Begin MonoManager ReloadAssembly Then goes nothing, and the only way to make editor work again is to restart it. I've also tried to call this function from my C++ native plugin function, and also tried to call it from C++ with different calling conventions (cdecl and stdcall explicitly stated in typedef, changed accordingly for UnamangedFunctionPointerAttribute): typedef void (__stdcall *PluginCallback)(int32_t eventId, void *data); auto func = static_cast<PluginCallback>((void*)funcPtr); func((int32_t)eventIdValue, (void*)dataValue); Result is always the same. When function is called from main thread -- everything goes fine, but once it called from another thread (unmanaged) by pointer -- assembly reload hangs forever.
Ok, I found the solution. The thing is that if function pointer obtained by GetFunctionPointerForDelegate is called from non-managed thread, you need to first initialize a thread with mono_attach_thread(domain). So before calling function by pointer, you need to somehow call mono_attach_thread before, as stated in Mono Embedding Guide. If your application creates threads on its own, and you want them to be able to interact with Mono, you have to register the thread so that the runtime knows about it. To do so, call the mono_thread_attach() function before you execute any other Mono API or before manipulating any managed object. Here's my workaround native plugin for this. https://github.com/Meetem/ManagedRenderEvent
74,401,974
74,404,075
Fastest way to get Storage Buffer to host from compute shader in Vulkan
I have a large Storage Buffer of ~4.6MB I am sending via compute buffer and then retrieving at the host at the end of the render loop. I was hoping someone could provide guidance on a possible optimal way of going about this? The performance of the app without the host read is about 3000 FPS on my machine and 800 FPS with it. Whilst trying to improve performance I ended up with: 2 Storage Buffers, 1 which is both host visible and host cached which is used to both read and write with the host, and a 2nd Storage Buffer which is used to store the output of the compute shader and is then copied into the 1st buffer. At the moment my input Storage Buffer which receives data from the host has usage: VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT And properties: VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT And my second, compute buffer output buffer has usage: VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT And properties: VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT As I use the same Storage Buffer in the fragment shader, for Descriptor Sets I ended up with stage flags: VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_COMPUTE_BIT The synchronization I am using is a Compute to Compute barrier and a Compute to Graphics barrier and the rest is from the docs
The performance of the app without the host read is about 3000 FPS on my machine and 800 FPS with it. This is a prime example of FPS being a misleading performance metric. Using raw time is better, as it makes it much more clear what the absolute time difference is. The compute-only process really takes 0.33ms, while the compute+transfer takes 1.25 ms. This means the difference, the cost of the transfer, is only 0.92 ms. That's hardly unreasonable for moving 4.6MiB of data. If you look at how many MiB per second that works out to, you'll find that it's about 5GiB. Which is quite reasonable (depending on hardware) and not something you would expect to be able to be "optimized" much further. The only tricks really left that might buy you anything is to use a dedicated transfer queue to do the copies if you're not already doing so.
74,402,203
74,402,295
incrementing unsigned char *image
void draw(unsigned char *image) { for (int y = 0; y < HEIGHT; y++) { for (int x = 0; x < WIDTH; x++) { if (someCondition) { int red = x * 256 / WIDTH; int green = 255; int blue = y * 256 / HEIGHT; image[0] = (unsigned char)blue; image[1] = (unsigned char)green; image[2] = (unsigned char)red; } else { image[0] = 0; image[1] = 0; image[2] = 0; } image += 3; } } } What does incrementing image+=3; actually do here. I'm trying to convert the same c++ code to C#, but unable to achieve this. I'm using byte[] image in C#, now how should I do image+=3 in C#. Is it scaling the image?
From the code it is evident that the pointer points to an element of an array of unsigned char: [ ][ ][ ][ ] ........... [ ] ^ | image Next consider that image[i] is equivalent (really equivalent, that is how it is defined) to *(image + i), ie it increments the pointer by i and dereferences it. You can write image[0] to get the element image points to. You can type image[1] to get the next element in the array. Lets call the actual array x then you can access its elements via incrementing image like this: x[0] x[1] x[2] x[3] x[4] x[5] image[0] image[1] image[2] (image+3)[0] (image+3)[1] (image+3)[2] In other words, the author could have used some offset in the outer loop which increments by 3 in each iteration and then instead of image[ i ] they would have used image[ i + offset ]. Instead they choose to increment image which has the same effect.