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
64,050,059
64,050,164
std::vector reserve being more costly than expected
So I need to manually handle the memory allocated by an std::vector for efficiency purposes. And I noticed that my program was slower than expected, so I added this idiom everywhere in my code base: const uint new_edges_capacity = mesh.edges.size() + 6; if(new_edges_capacity > mesh.edges.capacity()) mesh.edges.rese...
You're not reimplementing reserve, you're reimplementing the resize operation when capacity is exhausted. Problem is, if you do this every time you insert an item, you're resizing every time, making every operation O(n) (as it has to move all the items from the original backing storage to the new, larger, storage). If ...
64,050,139
64,171,107
How to read data from SOME/IP protocol in C++
Currently I read some data using boost udp socket. I created socket like this read_socket = new udp::socket(read_socket_service, udp_listener_endpoint); where boost::asio::io_service read_socket_service(); udp::endpoint udp_listener_endpoint(some_ip, some_port); Then I take data read_socket->receive_from(boost::asio...
One of the possible solution is use of libtins library It allows you to extract raw UDP data from network traffic. Here is more detailed tutorial: libtins sniffing tutorial Of course later you will have to extract data from such package. This may be more complex work than reading it because all data must be decoded for...
64,050,188
64,050,466
Printing wrong index values in mergesort recursion
#include<iostream> using namespace std; void merge(int* arr, int l, int mid, int r) { int n1=mid-l+1; int n2=r-mid; int L[n1],R[n2]; for(int i=0; i<n1; i++) L[i]=arr[l+i]; for(int i=0; i<n2; i++) R[i]=arr[mid+1+i]; int i=0,j=0,k=l; while(i<n1 && j<n2){ if(L[i]<=R[j])...
As l == r so MS(0,0) can't be printed. if you use if(l <= r) then there will be an infinite loop. So, your code is accurate. if(l<r){ int mid= l + (r-l)/2; printf("MS(%d, %d)\n", l,r); mergesort(arr, l, mid); printf("MS(%d, %d)\n", l,r); mergesort(arr, mid+1, r); printf("...
64,050,747
64,051,035
How does std::optional construct std::variant in place from initializer list?
#include <optional> #include <variant> #include <utility> #include <set> int main() { std::optional<std::variant<std::pair<int, int>, std::set<int>>> foo(std::in_place, {1, 4}); } This compiles. But how is that possible when std::variant does not have a constructor that takes std::initializer_list<T> as its firs...
It's a bit complicated, so bear with me. optional<T> has a constructor that takes an in_place_t and an initializer_list<U> (and optional extra arguments). It will then attempt to construct T as if by this statement: T t(list, ...); Where list is the initailizer list and ... are any extra arguments. T is of course a va...
64,051,262
64,052,194
hit roadblock while trying to compile lua for emscripten usage, using windows, "unable to find ar rcu"
i've been stuck on this problem for hours, without finding any solutions. I'm currently trying to compile lua 5.3.4 for Emscripten for use in my project. ive hit a roadblock thought, I need to compile it to a liblua.a file which ill later use when doing the emcc command line. but theres problems. heres the console outp...
It looks like the makefile requires Un*x tools so I suggest: Install Windows Subsystem for Linux 2 (WSL2). Install the Ubuntu 20.04 distribution in WSL2. Start a bash shell by double clicking the Ubuntu 20.04 LTS icon. From the bash shell, install the tools needed. A minimal set for this whould be: sudo apt install g+...
64,051,598
64,052,958
Why does this overload resolution select the signature with the rvalue reference?
The following program uses the append_list function with the rvalue reference signature, not the const reference one. Why? #include <stdio.h> #include <iterator> #include <memory> #include <vector> class foo { public: std::vector<int> bar{1}; }; template<typename T, typename U> static void append_list(T &t, cons...
In your example code, U is a forwarding reference and not an RValue reference: template<typename T, typename U> static void append_list(T &t, U &&u) { // ^~~~~ Forwarding references behave differently than the usual template deduced types in that U will become the exact type of its input, ma...
64,052,773
64,052,800
‘gettimeofday’ cannot be used as a function
What am I missing here, this is my main program, I also have a makefile and everything works the error is somewhere in here. #include <iostream> #include <observer.h> #include <fstream> using namespace std; int main(int argc, char* argv[]) { std::fstream in; int gettimeofday; //CPUtypeandmodel struct t...
You named a local int variable gettimeofday, which prevents you from calling the function gettimeofday() three lines later. Don't do that. Name the variable something else, or (given it seems unused) just get rid of it.
64,053,282
64,060,660
C++ Actor Framework handling SIGINT
I'm having a difficult time determining how to shutdown a CAF actor system when the app receives SIGINT (^C). I'm aware of the csignal, but that takes a function (not a class function and not a lambda) hence I can't get the actor_system var in scope to send a message to my actors.
@parktomatomi already mentioned this example as a reference: https://github.com/actor-framework/actor-framework/blob/5ead6f95182e1e2fee683de59579ef35f58588da/examples/curl/curl_fuse.cpp To add a bit more context: the reason the example polls an atomic in a loop comes from the limitations the C and C++ standards impose ...
64,053,801
64,053,979
How do I quit a while(scanf_s...) loop?
My Visual Studio tells me to use scanf_s(), and now that I've used it, my while loop goes on forever. Let's say I'm reading lines, where each line has two numbers separated with a space. Once I've inserted all the numbers, my while never stops. How do I quit my loop? int main() { int i,j; while (scanf_s("...
My Visual Studio tells me to use scanf_s, Dubious advice, but standard in MS-land (as an alternative to scanf). and now that i've used it my while goes on forever. That's not a distinction between scanf_s and scanf. Both return the number of fields successfully converted and assigned. Both will keep waiting indef...
64,054,070
64,054,152
What is the difference between std::lower_bound and std::upper_bound?
The code below does not compile with both MSVC2017 and GCC11: #include <deque> #include <chrono> #include <algorithm> using Clock = std::chrono::system_clock; using TimePoint = std::chrono::time_point<Clock>; struct PricePoint { TimePoint dt; double buy; double sell; }; inline bool operator < (const Time...
error: no match for 'operator<' This sort of error suggests that some template code is trying to use an operator you haven't defined. lower_bound and upper_bound do opposite comparisons.< (const TimePoint & dt, const PricePoint & a) is fine for upper_bound, but lower_bound needs you to define this: inline bool operat...
64,054,243
64,054,291
Template for container and container content type C++
I essentially want template <typename Container, typename T> void copy(Container<T> &A, const Container<T> &B) { (copy contents from B to A) ... } But afaik, it cannot be done this way. Usage wise, it would copy contents from (example) vector<int> A, B, but also work for list<float> A, B, for instance. So the singl...
You need to make Container a template template parameter: template <template<typename...> typename Container, typename T> Container<T> copy(Container<T> A, Container<T> B) { // (copy contents from B to A) ... } Alternatively, you could simply write: template <typename Container> Container copy(Container A, Contain...
64,054,386
64,055,193
Dealing 5 cards per player using vectors
I am trying to push_back 5 elements from vector deck_of_cards to vector player1_hand and pop_back those elements to reduce the deck_of_cards, then the next 5 elements from vector deck_of_cards for vector player2_hand, etc. I can push_back with the current code for player1_hand. Player2_hand pushes the same elements so ...
Consider these lines for (int d = 0; d < 6; d++) { int& element = deck_of_cards[d]; // <- Unused variable player1_hand.push_back(deck_of_cards[d]); // ^ The FIRST 6 cards of the deck are added // to the player hand deck...
64,054,390
64,151,575
How to ensure TLS1.3 in gRPC in c++
If I am using TLS in gRPC how can I force the use of TLS1.3? I am using c++. I have TLS working but if there a way to enforce a specific TLS version?
gRPC uses TLS1.3 in c++ by default, this is true as of gRPC version 1.32.0 anyway. This has been verified with wireshark.
64,054,990
64,055,074
c++ when working with class containing vectors - candidate expects 2 arguments, 0 provided
class myItem { int key; string name; public: // Constructor myItem(int key, string name) { key = key; name = name; } }; class myCollection { vector<myItem> col; public: void insert(myItem &i); void print(); }; int main() { myCollection c; ...
The vector you are using in myCollection internally uses the default constructor. Try using a pointer of myItem in the vector or specify the default and copy constructors too.
64,055,231
64,059,590
C++: Using std::apply to iterate through a tuple in 2 parts: up to an index applying a lambda and then after an index applying a different lambda
If I want to iterate through a tuple using std::apply but not apply one function to the entire thing, how can I separate the tuple, i.e. apply one function to the first n values and another to all values after it? some_values would be a tuple which could have any length and types and length_of_first_part (likely named ...
Gave this a shot. Looking at the "possible implementation" here: https://en.cppreference.com/w/cpp/utility/apply It passes an std::index_sequence to a helper function to call std::invoke. I changed it to pass std::make_sequence<N> (N being the split index) instead of the tuple size. Then I passed the inverse (tuple siz...
64,055,477
64,055,805
How to pass std::less to a class template?
I want to pass a std::less but pass it as a template to a class, like this: template<typename Comparator> class MyClass{ static Comparator comp;//Looks like this class in not multithread-safe :p public: int value; bool operator<(const MyClass& other){return comp(this->value, other.value);} }; int main() { ...
Like any other static class variable, you would need to provide a storage definition for comp for every specific template instantiation that you want to use, eg: template<typename Comparator> class MyClass{ static Comparator comp;//Looks like this class in not multithread-safe :p public: int value; bool ope...
64,055,771
64,055,818
Why the intermediate values in matrix inverse calculations are slightly different between C# and CUDA C++?
I wrote two programs to calculate the inverse of a matrix using Gaussian elimination, the first program was in C# and the second in CUDA C++. The two programs follow exactly the same procedure and gives the same final results. However, when I checked the values within the intermediate steps, I found slightly different ...
From the NVIDIA documentation (about 2/3 of the way down): The consequence [of rounding] is that different math libraries cannot be expected to compute exactly the same result for a given input. This applies to GPU programming as well. Functions compiled for the GPU will use the NVIDIA CUDA math library implementation...
64,056,008
64,056,036
Inconsistent C style string output between different operating systems / compilers
I have a C++ program: #include <iostream> char * foo (char * bar, const char * baz) { int i = -1; do { i++; *(bar + i) = *(baz + i); } while (*(baz + i)); return bar; } int main (int argc, char *argv[]) { char bar[] = ""; char baz[] = "Hello"; foo(bar, baz); std...
char bar[] = ""; This guarantees to create a region of memory one byte long (basically just long enough to hold the '\0'). An implementation may give you more but you cannot rely on that. Hence it's not big enough to store the string "Hello", which would require six bytes. This is covered in, for example, C++20 [expr....
64,056,413
64,056,523
How would I return a value while running a function from a thread
using the std #include how would i return a value if I want a thread to run it? For example include <iostream> #include <thread> usingnamespace std; int func(int a) { int b = a*a return b; } int main() { thread t(func); t.join(); return 0; } How would I modify thread t(func); so that I can get b
You can't return a value from a function using std::thread but you can change the structure of the std::thread to get your value or use std::sync which returns an std::future<T> holding your value, as follows #include <iostream> #include <thread> int func(int a) { int b = a * a; return b; } int main() { i...
64,056,438
64,059,226
C++ correct way of wrapping array of subobjects for my new object?
class myObject{ private: subOBJ* subList; int size public: myObject(subOBJ list[]); } For example, my object looks something like this and I want to create an object that will do something with an array of subOBJs passed in. myObject::myObject(subOBJ list[]) { size = sizeof(list); subList = new subOBJ[size]; ...
In C++, you don't need to work with pointers in most cases. There are already classes that take care of that for you. Such as std::array<T> or std::vector<T>. myObject(subOBJ list[]); You need atleast one additional parameter: the length of/number of elements in the array. in C++, passing arrays to functions doesn't p...
64,056,454
64,056,489
How to give meaningful Ω and Big-O bounds for this function?
Can someone please explain this for me I don't quite understand how to solve this. I need to give meaningful Ω and Big-O bounds for this function and be able to justify it. bool algo1(int a[], int n){ if ((n < 1) || (a[0] % 2 == 0)) return true; int z = 0; for (int i = 1; i < n; i *= 2) fo...
algo1 has for (int i = 1; i < n; i *= 2) which is logarithmic on n (divide by half repeatedly). For each of those log(n) iterations we have for (int j = 1; j < n; j++) which is linear on n. Everything else is constant time. Multiplying the outer and inner loops gives O(n log(n)). algo2 is exponential time, O(2n), becau...
64,056,505
64,057,030
How to make sure file exists and it is opened
I am trying to make a program which checks if a file exists, otherwise it creates and opens it. This is what I tried doing: fstream file("data.txt"); if (!file.is_open()) { ofstream file("data.txt"); file.close(); } fstream file("data.txt"); The program tries to open the data.txt file and if it does not exist,...
Simply create a file stream without specifying without telling which file to open. fstream file; file.open("data.txt"); Then use .fail() to check if it has FAILED in opening the file if (fileStream.fail()) { ofstream file("data.txt"); } file.open("data.txt"); Then open it again. fstream (Filestream) is just simp...
64,056,627
64,057,434
Why is my LinkedList reading an extra node at the end of my list?
I'm trying to write a function moveLasttoFront for my LinkedList class, but it seems to read another Node in before the nullptr at the end of the list. For example, let's says I have a linked list {0, 1, 2, 8, 3, 4}. I want to run a pointer through the list until it equals nullptr and stop. But instead of stopping afte...
I've made this example in C. Main.c #include "linked_list.h" Node* moveLastToFront(Node* head) { Node* secondLast; Node* last = head; while (last->next != NULL) { secondLast = last; last = last->next; } (*secondLast).next = NULL; (*last).next = head; head = last; retur...
64,056,721
64,056,771
Returning T(t) with T=int&, how?
template<typename T> T foo(T&& t) { return T(t); } int main() { int x; foo(x); } So, I know T=int& here but I don't understand what happens at return line to make this vaild. Can someone explain how?
T(t) performs explicit conversion (functional cast), when T is int&, as the effect T(t) produces a reference binding to t, and then returns as the return value (return type is int& too).
64,056,783
64,058,811
how to populate values in my Qdialogbox's linedits?
In my main window, I have a QlistWidget named employee_list and the items in this QListWidget are like this : <FIRM-1> name="Anna Ken" age="25" job="QtMaster" , <FIRM-2> name="Sir Ron" age="50" job="QtSlave" So when I click the items in employee_list QlistWidget, a dialogbox shows up with 3 fields name,age,job like th...
you have to fill and then display i.e. setText() and after that show() or exec(): if (test_s.find("<FIRM-1>") != std::string::npos) { GrpComd grpComd; grpComd.setName(clickedName); grpComd.setJob(clickedJob); grpComd.setAge(clickedAge); grpComd.exec(); } or even better, if not already define...
64,056,792
64,056,843
How to iterate through characters in each string in a vector of strings?
Trying to iterate through every character in each string from a vector and verify all characters are 'O' or '.' //read file, put it in vector, and handle some errors string line; vector<string> currentgen; while (getline(input_stream, line)) { currentgen.push_back(line); } //iterate through every character in eac...
Problems: You used || where you should have used &&; obviously, a character is always not equal to one of 'O' or '.', so the condition is always true as written; you want: if(currentgen[i][j] != 'O' && currentgen[i][j] != '.'){ ^^ changed There's also a missing semi-colon after e...
64,056,801
64,056,850
compiling c++ with g++ from -c to -std=c++11
When I run my code for these files with g++ -c I don't get any errors, but when I run it with g++ -std=c++11 I am getting a linker error. I am assuming that means that the error isn't in the code of the files, but in the makefile. How can I fix this? parse: parse.o scan.o g++ -std=c++11 -Wall parse.o scan.o -o pars...
-c means run only the compiler and not the linker. You should keep it when adding the other flag if your intention is only to change the c++ version.
64,056,886
64,057,029
Why does std::min only support initializer_list?
We can use std::min in below way: // 1. int a = 1, b = 2; std::min(a, b); // 2. std::min({1,2,3,4}); But why can't use a std::vector or std::list, Because the param in the template is initializer_list. template <class T, class Compare> pair<T,T> minmax (initializer_list<T> il, Compare comp); What is the reason for...
To explain "why it doesn't accept a container", take the semantic into consideration: std::min({ "foo", "bar", "hello" }) The semantic of std::min() means "find the minimum value in the input parameters". Thus std::min()/std::max() takes two arguments, or an initializer_list as "more arguments". std::min() doesn't prov...
64,057,048
64,078,140
OpenGL : How can I pass multiple texture to a shader with one variable?
I loaded the material and texture information from the Obj file based on this code (https://github.com/Bly7/OBJ-Loader). Now I want to load Sponza and render it. However, there are 10 or more textures, and even if all are passed to the shader, it is necessary to correspond to the appropriate vertices. Looking at the re...
As your model has only one texture per mesh, I can suggest this simple code to use: do { glActiveTexture(GL_TEXTURE0); glUniform1i(glGetUniformLocation(shaderID, "myTex"), 0); for (unsigned int i = 0; i < mesh_count; i++) { glcall(glBindTexture(type, texture[i])); // Bind verte...
64,057,235
64,057,884
Switch statement default in simple grid movement exercise
I'm pretty new to coding, so I've been making little programs while going through an online course. I'm playing around with the idea of moving the character 'X' around a small grid using the arrow keys on the keyboard. I've managed to get it working using looping and switch statements, but the default statement keeps ...
The _getch function is documented as follows: When reading a function key or an arrow key, each function must be called twice; the first call returns 0 or 0xE0, and the second call returns the actual key code. Perhaps you want something like this: int ch = _getch(); int key = (ch == 0 || ch == 0xE0) ? _getch() : 0; ...
64,057,436
64,057,468
C++ different outputs on different runs
I am running a very simple C++ code to find the highest of 5 user-entered integers. The code is sometimes working (usually after compiling with g++) and aometime not. #include <iostream> using namespace std; int main() { int arr[5], max; cout<<"Enter the 5 scores: "; cin>>arr[0]; for (int i=1; i<5; i+...
You have not initialized max, so your program has undefined behavior. It's a good idea to enable all warnings in your compiler. With g++, that would be -Wall. This will help you detect several kinds of basic mistakes that can lead to undefined behavior. For this program, the compiler will easily be able to see that m...
64,057,688
64,057,786
Is it possible to create a variable at an assigned address location
Suppose i create a new float; float *pointer = new float; now i delete this pointer. delete pointer; Now can i create a new float at the same memory location the pointer was pointing to ? float *pointer1 = new float;
Is it possible to create a variable at an assigned address location No. The language implementation is responsible for choosing the address of all variables. It is possible to create a dynamic object at an address, as long as that address satisfies certain preconditions. In particular, the memory has to be allocated,...
64,058,036
64,058,537
Preventing multiple #define when including headers
coming from python and am a bit tripped up on what the proper approach to this is. I am trying to include this library in my project: https://github.com/nothings/stb/blob/master/stb_image.h to do so, i have to #define STB_IMAGE_IMPLEMENTATION exactly once before importing the file (as per that file's doc) This makes se...
Create a cpp file (or whatever extension you are using for your source files) whose sole purpose is to have #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> and don't forget to include this cpp file into your project so that it is compiled and the result is linked into your program. In all other places where ...
64,058,215
64,061,058
C++ alternative of rust's proc macros
Rust have very amazing feature to generate code at compile using proc_macros which are pure rust code. is there is anything similar in C++ which lets me executes real C++ code to generate code instead of ugly defines.
There is nothing built into C++ to achieve the equivalent of Rust proc-macros, at the moment. Traditionally, in C++, I have seen 2 different ways to achieve a similar effect: Code generation: a separate executable runs as part of the build to generate C++ files. For example LLVM features TableGen. Preprocessing: a sep...
64,058,882
64,059,682
Multiple Conditional Variables : threads out of sync problem
I have a thread that is doing "work", it is supposed to report progress when conditional variable notifies it. This thread is waiting for conditional variables. Other thread is waiting for a x amount of milliseconds and then notifies conditional variable to proceed. I have 5 conditional variables (this is an exercise f...
The loopCheckPoints() thread holds a lock for some time, sets m_check then releases the lock and immediately goes on to grab the lock again. The loopWork() thread may not have woken up in between to react to the m_check change. Never hold locks for long times. Be as quick as possible. If you can't get the program to w...
64,059,085
64,060,915
CMake CUDA C++ Linking Error - Undefined reference to `someFunction()`
I am trying to call a CUDA kernel from a C++ program. I am using CMake to manage the build process. CMakeLists.txt cmake_minimum_required(VERSION 3.18) project(SeamCarving LANGUAGES CUDA CXX VERSION 0.1.0) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CUDA_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED True) set(CMAKE_CUDA_STAND...
MyLibrary is not a variable, it's a CMake target. The syntax ${variable} is used to substitute the contents of a variable. The correct syntax to create a dependency to MyLibrary is this: target_link_libraries( myProject PRIVATE MyLibrary ) The syntax is probably correct in the case of ${OpenCV_LIBS}. It's common practi...
64,059,150
64,059,151
Include ft2build.h in project on Linux
I've been trying to compile a JUCE project on Linux debian but a line is giving me an error: #include <ft2build.h> And stops compilation. How do I link to this file?
So I've had this issue before and found the straight answer this time. First, check if you have libfreetype installed. I used: pkg-config --cflags freetype2 I do have the library installed, so I got this as a result: -I/usr/include/freetype2 -I/usr/include/libpng16 If you don't have it installed, do: sudo apt-get ins...
64,059,468
64,060,259
Using extern function instead of including a header defining that function
I know that extern is very important with variables as per this question What's the difference between using extern and #including header files? and I totally see the point and rationale of using extern variable. But I can't still digest the idea behind extern function, I know how it works and linking and all of that, ...
Header files are added to your source .c code in the preprocessing. The C compiler compiles one large file with the all the header files added to this file. https://godbolt.org/z/Eo3n1Y Providing in your source file the same function prototypes and extern object declarations as in the .h files will have the same effe...
64,060,572
64,063,118
Default initializing a pointer in a template
In the following code, Get() returns the default value of the template type. I was wondering why and how this is correct/defined for pointer types #include <iostream> #include <string> template <typename ValueType> inline ValueType Get() { return ValueType(); } int main() { int* IntPtr = Get<int*>(); //in...
When the compiler evaluates ValueType() in Get, I would have expected it to become (int*)(), but since this is invalid, is it treated differently? A C++ template, while being very similar to a macro, does not perform a literal replacement. ValueType remains an actual type within the scope of the template. So yes, ret...
64,060,919
64,061,444
What is the right way to have namespaces in seperate files in C++?
What is the right way to have namespaces in other files so I can use them with #include<> test.h #ifndef TEST_H_INCLUDED #define TEST_H_INCLUDED namespace numbers{ const int foo = 8; } #endif //TEST_H_INCLUDED However, I have also seen this test.h #ifndef TEST_H_INCLUDED #define TEST_H_INCLUDED namespace number...
With the first method you are going to get multiple definitions (assuming you have multiple includes), that's allowed because global constants are exempted from the One Definition Rule. With the second method there is only one definition, in test.cpp. The first method is more likely to lead to compiler optimisations be...
64,060,929
64,063,598
Why does the implementation of declval in libstdc++-v3 look so complicated?
The code below comes from libstdc++-v3 std::type_traits, which is an implementation of std::declval: template<typename _Tp, typename _Up = _Tp&&> // template 1 _Up __declval(int); template<typename _Tp> // template 2 _Tp __declval(long); template<typename _Tp> // template 3 auto declval() noex...
std::declval is actually: template<class T> typename std::add_rvalue_reference<T>::type declval() noexcept; Where std::add_rvalue_reference<T> is usually T&&, except in cases where that is invalid (Like if T = void or T = int() const), where it is just T. The main difference is that functions cannot return arrays, but...
64,061,131
64,061,953
Boost Asio async_send_to multicast with use_future does not work
ITNOA I have program that want to send a message with async_send_to to one multicast group. but I want to this action is blocking not async, so I use use_future for achieve this goal like below gw::BoostMessageSender::BoostMessageSender(const std::string& group_address, const std::string& interface_name, uint16_t port_...
io_context::run returns when there is no pending jobs to be executed. You can create work guard to ensure that run doesn't finish even if no async tasks were initiated. Use make_work_guard function: boost::asio::io_context io_context; auto workGuard = boost::asio::make_work_guard(io_context);
64,061,498
64,061,865
Custom string sort gives segmentation fault
I am solving a problem in which you are given a bunch of numbers in string format and you have to concatenate them in such a way that the result is the maximum number possible. E.g: Input: 6 61 68 Output: 68661 So I am using a custom sorter with std::sort to sort the strings and I am getting weird, random segmentation ...
As far as I can see the main problem is this piece of code: if (i1 == n1 && i2 == n2) { // strings are equal return 1; } which should be if (i1 == n1 && i2 == n2) { // strings are equal return false; } The first version implies that two identical strings should be sorted before each other, i.e. you co...
64,061,910
64,062,150
Function call not ambiguous if {} is used
#include <stdio.h> #include <vector> #include <deque> // 1st function void f(int i, int j = 10){ printf("Hello World what"); }; void f(std::vector<int>){ printf("Hello World vec"); }; void f(std::deque<int>){ printf("Hello World deq"); }; int main() { f({}); return 0; } If the 1st function is c...
Edit: I would like to delete this post because it's false (sorry for that, I forgot that the initialiser list constructor of vector/deque is not a template). Unfortunately I cannot do this as long as it is the accepted answer. Single argument constructors to std::vector and std::deque are explicit. Automatic type dedu...
64,062,086
64,063,187
Problems with linking inline functions in C++
test2.h #ifndef TEST2_H_INCLUDED #define TEST2_H_INCLUDED #include "test1.h" inline int add(int,int); #endif // TEST2_H_INCLUDED test2.cpp #include "test2.h" inline int add(int a,int b){ return a+b; } main.cpp #include <iostream> #include "test2.h" int main() { std::cout << add(1,2); return 0; } Eror...
//test2.h #ifndef TEST2_H_INCLUDED #define TEST2_H_INCLUDED #include "test1.h" inline int add(int a,int b) { return a+b; } #endif // TEST2_H_INCLUDED
64,062,237
64,145,165
Unfulfilled EXPECT_CALL in gtest when passing vector by setargreferee
#include <gtest/gtest.h> #include <gmock/gmock.h> enum class InfoState : uint8_t { OFF = 0, ON = 1, }; class MyInfo { public: MyInfo(){}; MyInfo(const MyInfo&){}; MyInfo& operator=(const MyInfo&){} MOCK_METHOD0(getState, InfoState(void)); }; class ServiceClient { public: MOCK_ME...
As Quarra comment, the main problem is a copy constructor. I am not a Google Test specialist, yet I found a solution to your problem. As per GMock, I found out that mocked objects cannot be copied - this is the design principle and the decision of Google Test implementers. Here this decision has been justified back in ...
64,062,450
64,072,026
C++ comparing a pre-reserved hash map(std::unordered_map) with integer key and contiguous data array(std::vector)
Assume that using a hash map structure with int key type: std::unordered_map<int, data_type> um; Plus, when the total(or maximum) number of elements N is known, hash table can be constructed in advance. um.reserve(N); // This will chainly call rehash() function... Here, an integer itself can be used as an identity(ha...
Plus, when the total(or maximum) number of elements N is known, hash table can be constructed in advance. um.reserve(N); // This will chainly call rehash() function... Here, an integer itself can be used as an identity(hash) function for a hash table, as far as I know. That's true, and reasonable in two very differen...
64,062,490
64,063,504
How to properly prepare makefile for bigger project?
I have a problem with compiling and linking my project with directories organisation as showed below. /project | |____/Components (header files and source codes of all components) | | | |____/X (header files and source codes of component) | | | |____/src (source codes) | ...
In general: Not sure exactly what your problem is, but this is what I do. The project has a single global object directory (OBJDIR). Every source directory has its own Makefile, which looks like this: # list of sources in *this* directory CCSRC = a.cc b.cc etc OBJS := $(addsuffix .o, $(CCSRC)) VPATH = $(OBJDIR) .SUF...
64,063,109
64,065,921
Boost Asio async_recieve_from multicast with use_future does not work simultaneously with async_send_to
ITNOA I want to write program that send and receive multicast simultaneously like below int main() { const string group_address = "235.127.1.1"; constexpr uint16_t PORT_NUMBER = 8765; boost::asio::io_context io_context; auto work_guard = boost::asio::make_work_guard(io_context); BoostMessageSender...
You are getting no_state because get on future can be called only once. Below std::make_pair(result.get() != 0, result.get()); get is called twice. See reference: Notes The implementations are encouraged to detect the case when valid() is false before the call and throw a std::future_error with an error condition of ...
64,063,215
64,063,262
C++ std::sort custom comparator runs indefinitely when the comparator returns true
So I encountered this very weird behavior on an edge case when sorting a vector using a custom comparator. When running this code, it will not halt, and goes forever: int main() { auto comp = [](int lhs, int rhs) { return true; }; vector<int> vec{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; ...
This comparator: auto comp = [](int lhs, int rhs) { return true; }; violates the requirement of std::sort that the comparator must establish a strict-weak-ordering. Note that this function returns true regardless of the order of arguments, implying that 2 elements can both be less than the other, which doesn't real...
64,063,310
64,063,630
Could I have an explanation of a few lines in the following code?
I would like to understand how the following code works. It can basically be used to sort of "Debug" C++ containers, but I'm having some trouble understanding lines 3, 4, 12 and 13 and what they do. It would be great if I could receive a brief explanation. Thanks. template <typename T> class range { public: T begin, en...
The following declarations are using a technique that relies on SFINAE (substitution failure is not an error): // #3 : works only if (std::cerr << *x) works template <typename T> auto dec (T* x) -> decltype(std::cerr << *x, 0); // #4 : works for everything, but only if #3 fails template <typename T> char dec (...); ...
64,063,401
64,193,310
C++: safe usage of vsprintf
I have a largish code base that does log_msg("Here comes %s", "the text"), where log_message is a macro that adds function name and line numbers to the log message. GCC/G++ warn about errors when the format string doesn't match the supplied arguments. Unfortunately sometimes the code calls log_msg(get_the_text()). The ...
Thanks to @SamVarshavchik this is what I came up with: #include <iostream> #include <cstdio> #include <tuple> template<typename ... Args> void log(Args ... args) { if (sizeof...(args) == 1) { auto t = std::make_tuple(args...); std::puts(std::get<0>(t)); } else { std::printf(args...); ...
64,063,957
64,065,708
how to convert String in arduino library to std::string in c++
I have problem converting a String to std::string, to pass it to my function as the sample of my code is String dataString = configFile.readString(); rawData = simplifyData("try to fetch data as string from dataString");
Since std::string has a constructor accepting a const char* as parameter you can copy your String by using this, e.g.: rawData = simplifyData(std::string(dataString.c_str())); Or, since this constructor is implict, you can simplify it in your function call, such as rawData = simplifyData(dataString.c_str());
64,064,053
64,064,929
this code is about SSN and i need to see errors in it because its for a college project and i can't do it
Please help me with the errors that come up with the code. for example if you enter 1650712999999 it should display male 65.07.12 and 1 at the start represents male and 2 at the start represents female and then the birthdate YY.MM.DD and the other numbers are irrelevant #include <iostream> using namespace std; int ma...
%10 in n=n/1000000 %10; is deleting required data, so you should remove that. There are no condition for the inner if statement, so you have to add that. Stray s=1 should be removed because lack of semicolon after that will lead to compile error. Some curly braces are missing around the inner if statement, so you have...
64,064,195
64,065,324
Why does my 2D IDFT produce double the expected amplitudes? (FFTW)
I am using a complex-to-real 2D IDFT to visualize complex signals as an image. I initialize the complex frequency domain by manually setting modes. However, some modes produce real output that seems to be double what is expected. My code: int N = 8; int logical_width = N / 2 + 1; // Logical width of frequency domain da...
You are applying a C2R transform. As I explained in my answer to your previous question, it expects a conjugate symmetric input. You provide half the input, the other half is assumed to be the conjugate symmetric of your input. Thus, you are setting two modes, not one, each with a magnitude of 16. Together they form a ...
64,064,236
64,064,339
Using Default Parameter in Functions with Two 'For Loops'
I am trying to sort an array in descending order and ascending order. The program's output will print the unsorted array, the one sorted is descending order and the one sorted in ascending order. The thing is that I have to declare a single function and use default parameters. I cannot use function overloading. This is...
Note that the only difference between your "functions" is the following line: if (arr[j] > arr[smallest]) You can simply make this condition be dependent on var like this: if (var ? arr[j] < arr[smallest] : arr[j] > arr[smallest]) which is equivalent to: if ((var && arr[j] < arr[smallest]) || (!var && arr[j] > arr[sm...
64,064,371
64,064,521
Define a function that accepts a function as a parameter
I'm using library ArduinoJson and I need to create a function which will open a file on SD card, deserialize JSON and then calls a mapping function which will map deserialized values into a struct. I need one of the function parameters be a maping function but not sure how to do that. This does not compile: #include <A...
What you actually want is not the type of a function, but the type of a function pointer. So your typedef would look like this: typedef void (*mappingFunctionPtrType)(StaticJsonDocument); You then can use it like so: void foo(mappingFunctionPtrType func) { StaticJsonDocument doc; func(doc); //call the function...
64,064,967
64,065,064
Create a type trait that can be called both on types and on variables
There are two operators in C++ that can be called both on types and on variables: sizeof and typeid. Suppose we want to implement our own operation with a similar behavior, something like*: template<bool is_type> struct type_traits_T; template<> struct type_traits_T<true> { template<typename T> struct type_tra...
You can use function templates: template<typename> constexpr bool is_type() { return true; } template<auto> constexpr bool is_type() { return false; } #define type_traits(V) type_traits_T<is_type<V>()>::type_traits<V>
64,065,100
64,065,476
I am having troubles linking multiple classes together via their pointers
I am having a few simple troubles regarding my code. What I am trying to do is build my own "list" code for 2 reasons. First of all, I want to get a deeper understanding of how linked lists work in practice. And secondly, because I am working on a project that requires a list of references, not just copied objects like...
Just like magic, the moment I post this, THEN stackoverflow decides to point me to a useful post. I've been looking online for hours! Thanks for the (Surprisingly) quick responses! I managed to find a better way of doing it. Turns out that I was goind about it a bit of an unnecessarily complicated way. The following co...
64,065,112
64,066,223
Boost asio tcp data lost between packet when sending large data
I try to send a large data (1mb+) from a server to a client using the boost's asio library. I split the data into chunks of size 16000 and use async_write_some to send them. I read the data with async_read or async_read_some in the client. When both the server and the client are my local machine, everything works fine ...
The commenters already spot the problem: you should be using write_some repeatedly until the full buffer has been sent. Of course, this task is so common, why not use asio::async_write which does just that? void SendData(const char* data, int size) { const int tr_size = std::min(CHUNK_SIZE, size); async_write(*...
64,065,374
64,065,416
Can't push_back() after 1000th element in a vector in c++11
#include <iostream> #include <vector> #include <bits/stdc++.h> using std::vector; using std::cin; using std::cout; int main(){ vector <long long> vec(2000,1); vec.reserve(2000); int count = 0; vec.push_back(31); for (int i = 0; i < vec.size(); ++i){ count ++; } cout << count << " ...
The 1000th element is actually just 1 due to this constructor. vector <long long> vec(2000,1); // fill with 2000 elements, each set to 1 Then after this line vec.push_back(31); // element [2000] is now 31 Therefore your final vector is {1, 1, 1, ..., 1, 1, 31} // length 2001 elements
64,065,763
64,067,686
Loss of precision with pow function when surpassing 10^10 limit?
Doing one of my first homeworks of uni, and have ran into this problem: Task: Find a sum of all n elements where n is the count of numerals in a number (n=1, means 1, 2, 3... 8, 9 for example, answer is 45) Problem: The code I wrote has gotten all the test answers correctly up to 10 to the power of 9, but when it reach...
The main reason of problems is pow() function. It works with double, not int. Loss of accuracy is price for representing huge numbers. There are 3 way's to solve problem: For small n you can make your own long long int pow(int x, int pow) function. But there is problem, that we can overflow even long long int Use lo...
64,065,780
64,065,860
How to Call function with default parameter?
I have a function define in header file as this: int myfunction(VpTR*& viewporttable, wchar* vpname=L"*Active", OpenMode f=fR); how i can call this function but ignore second argument? I tried calling it with the following code but an error message appeared: expected an expression myfunction(myviewporttable,, fR); c...
The syntax doesn't allow to omit parameter values at arbitrary positions, only those at the very end of the list. You have to overload 2 versions: int myfunction(VpTR*& viewporttable, OpenMode f=fR) { return myfunction(viewporttable,L"*Active",L"*Active",f); } int myfunction(VpTR*& viewporttable, wchar* vpname=L...
64,065,948
64,066,093
How to expose dynamically amount of data to QML
I have an app were I need to fetch random questions from a database and expose them to qml dynamically. So I created a class to store each dataset: class Question : public QObject { Q_OBJECT Q_PROPERTY(int id READ id) Q_PROPERTY(QString askedQuestion READ askedQuestion) public: Question(int id, ...
You can't use QVector<Question> because QObjects are not copyable. But you can use a QVector<Question*> (note the pointer). You can make as many copies as you want of a pointer. There's other ways to solve your problem too. Like a QAbstractListModel. But the easy solution is just a pointer.
64,065,972
64,066,049
Why does this particular code for a leap year program not work?
I'm new into coding and I'm trying to make a program to decide whether a 4-digit year is a leap year or not. I know I can find other working code for it here, but I specifically want to know why this particular code I tried didn't work. Could somebody please explain? I tried to input common years (e.g. 9999), but it ga...
If you enter 2020 as input, after for (len = 0; year > 0; year = year / 10) { len++; } year will be 0. Then, you'll check year % 4, which will also be 0. You simply need to create another variable to copy the year in, and use this other variable to check the division by 10. Or, you could check (year < 10000) and (...
64,066,275
64,066,443
chrono parse including timezone
I'm using @howard-hinnant 's date library (now part of C++20) to parse a date string that includes a timezone abbreviation. The parse takes place without errors, but it appears that the timezone is ignored. For example: istringstream inEst{"Fri, 25 Sep 2020 13:44:43 EST"}; std::chrono::time_point<std::c...
Unfortunately there is no way to reliably and uniquely identify a time zone given just a time zone abbreviation. Some abbreviations are used by multiple time zones, sometimes even with different UTC offsets. So in short, the time zone abbreviation is parsed, but does not identify a UTC offset which can be used to alte...
64,066,403
64,066,811
Slow rendering after large transfer from GPU to RAM?
I was trying to render a point cloud (>100 million points), I transferred all the data to GPU and just use the buffer name to access it. Everything works fine until I implemented a feature that requires me to transfer all the data back to the RAM. This is how I pass the data to the GPU: glBindVertexArray(vao); // some...
You made a promise to OpenGL. Then you broke your promise. So OpenGL punished you for it. You told OpenGL this about how you were going to use this buffer object: GL_STATIC_DRAW That means you told OpenGL that you would be writing to the buffer (DRAW) but not reading from it. And you said you would be writing to it ...
64,066,633
64,081,224
How is constraint overloading resolved by the partial ordering of concept?
Per cppreference, the partial ordering of constraints over subsumption is used to determine "the best match for a template template argument". And in the example section, the option that is "more constrained", i.e. the stronger/tighter, condition is selected. But in practice I've found some confusing behavior when the ...
When compiler checks if one set of requirements is more constrained than another one, it recursively expands concepts. It also understands the meaning of &&, ||, ( ) (so the order of conjuncts/disjuncts doesn't matter, the superfluous ( ) don't matter, etc), even inside of concepts. This part is pretty intuitive. What...
64,066,714
64,067,077
Using QProcess to call an external program, with arguments
I have a exe folder located in one folder, and then all of my config files in another. In order to run the program: I need to direct the terminal to the config file folder Then run the exe folder, with arguments. Shown below, I have this working correctly using system calls, but I need a system agnostic way of doing ...
Name of executable would be starting with ".\" if it is in local folder to be system-agnostic. Linux shell and PowerShell require that. ">" - output redirection isn't an argument of process, that won't work. You have to redirect output channel to your or a secondary process. p.setStandardOutputFile("log_file.txt")
64,067,632
64,068,497
SetLocalTime causing PC to lag, how can I optimize it?
I want to create a program that will slow down Windows' time. I will be using SetLocalTime() for this. However, when I open the program, my PC starts to micro-stutter and game performances drops even though the process isn't using nearly any CPU. #include <iostream> #include "Windows.h" #include <thread> #include <chr...
If you change the system clock, all the programs that use it for timing will also slow down. From your comments, I could gather that you wish to time scale an application that uses time. So far, you didn't get more specific, so I cannot suggest anything more than a general approach. Create a time manager class that, wh...
64,067,985
64,070,117
Where can I see Code execution time VS2019?
Where in the VS2019 can I see the execution time of the code? Sorry for stupid question
That depends on the precision you're interested in. If milliseconds then in Visual Studio 2019 you can see the time between two breakpoints under Diagnostic Tools -> Events -> Duration (opens automatically in Debug mode, or use Ctrl+Alt+F2). Some notes: Make sure to measure performance of the Release configuration. D...
64,068,001
64,068,167
What's the point of template specialization in C++ if you can do the same without templates?
Here is a simple example: #include <iostream> template <class T> void print(T in){ printf("NOT printing int\n"); } template <> // <-- template specialization void print<int>(int in){ printf("printing int\n"); } int main(){ print(5); // printing int return 0; } But the int version can be written without ev...
The point is that you cannot do everything with overloads. Consider for example a case where there is no argument: template<class T> void foo(); There is no way to overload this function because there are no arguments. But it can be called with explicit instantiation: foo<int>(); And those instantiations can be speci...
64,068,598
64,068,896
C++ Change conditional evaluation of for loop
I have a for loop where the start, stop, step are parameters that are passed in by the user: for (double i(start); i <= stop; i += step) This works fine if the stop > start. But I also need to support the case where the start could be larger than the stop (the step would be a negative number in this case): for (double...
You can split the computation of the number of step from the actual stepping: // compute how many steps int stepCount = (stop - start) / step + 1; // iterate over that many steps for (int i = 0; i < stepCount; i++) { double value = start + step * i; // use value here } To me, that's the cleanest and simplest ...
64,068,778
64,068,942
Pair and curly brace check
#include <bits/stdc++.h> using namespace std; int main() { pair<int,int>p = {1,3}; if (p=={1,3}) cout << "yeyey\n"; } I want to check whether this pair is same as the integer inside the braces, but it returns error "expected unqualified-id before ')' token if (p=={1,3}) cout << "yeyey\n";" can someo...
The type of {1,3} cannot be used to deduce a std::pair<K,T> directly. You'll need to use std::make_pair() to overcome this: #include <utility> #include <iostream> int main() { std::pair<int,int>p = {1,3}; if (p==std::make_pair(1,3)) std::cout << "yeyey\n"; } Since c++17 you can alternatively use a...
64,068,914
64,069,019
Where to find Vulkan C++ specification?
Where I can find C++ specification for Vulkan (same like the official C one on Khornos pages), describing the particular Vulkan api primitives and functions? Does it even exist (I was trying to find it with no success)? Personaly I am using the C api even with C++ as I already got used to its style and it fits my needs...
There is no "Vulkan C++ specification". There's a header file containing some functions and types that make using Vulkan more C++-friendly. But those are not part of any actual specification. The mapping from "VulkanHpp" into regular C Vulkan is pretty obvious in most cases and can be deduced just from the nature of th...
64,068,958
64,068,973
How can I correctly pass a pointer to a function?
I can't seem to pass pointer to memory address. I thought the following code would pass the memory address that ptr points at, to my func(), then when I print out the address within func() it would show the same address as ptr did from within main(), however that's not what I'm seeing. p's address is different from ptr...
In this declaration: void func(int* p) the variable p is indeed a copy of ptr, and so they have different memory addresses. The same rules apply here as they do for an int parameter. There's nothing special about pointers in this context. Don't be confused by the fact that the pointed at values are the same, i.e *p an...
64,069,400
64,069,583
Algorithm to check all adjacent points
I am trying to find the most efficient way to traverse all adjacent cells in a grid. For example let's say I have a 2D Array represented as: vector <Item> grid; and I have a point within this grid (represented by the blue cell): grid[x][y]; and I want it to traverse all the adjacent coordinates. So for example if my p...
Here's one way to iterate the neighbours: for (int i : {-1, 0, 1}) for (int j : {-1, 0, 1}) if (i && j) std::cout << grid[x + i][y + j]; // prints all the neighbours Make sure to account for the edges of the grid as well. This is just a readable way to iterate neighbors. Don't worry about efficiency unle...
64,069,424
64,069,760
Multiple requests using one tcp socket
I'm learning socket programming(and c++). I wrote a function like below that requests for sum of an array(using boost library): std::future<void> AsyncClient::ReqSum(const std::vector<double>& numbers) { return std::async( std::launch::async, [&, numbers]() { // Setup connection....
It looks like you are trying to receive all data from the server: boost::asio::streambuf receiveBuffer; boost::asio::read(_socket, receiveBuffer, boost::asio::transfer_all(), err); The only way that read() commands finishes is if the server indicates the end of the stream. Since you are receiving a valid response the ...
64,069,727
64,070,319
Implementing a coroutine in python
Lets say I have a C++ function result_type compute(input_type input), which I have made available to python using cython. My python code executes multiple computations like this: def compute_total_result() inputs = ... total_result = ... for input in inputs: result = compute_python_wrapper(input) update...
First, an inaccuracy in the question needs to be corrected: If my compute_threaded_python_wrapper would be part of asyncio, I could simply rewrite it as [...] The rewrite is incorrect: await means "wait until the computation finishes", so the loop as written would execute the code sequentially. A rewrite that actuall...
64,070,131
64,070,548
c++ std::lock_guard scope reach
let's assume I have a function that acquires a lock and executes a fuction passed by argument: template <typename T> T acquireLock(std::mutex& _lock, const std::function<T()>& execution) { try { std::lock_guard<std::mutex> mutex (_lock); return execution(); } catch (std::logic_error& error) { std::c...
According to [stmt.return]/p3: The copy-initialization of the result of the call is sequenced before the destruction of temporaries at the end of the full-expression established by the operand of the return statement, which, in turn, is sequenced before the destruction of local variables ([stmt.jump]) of the block en...
64,071,018
64,071,058
How to implement a virtual function in derived class?
Consider the following UML: When I try to implement the virtual function rate() in Single.cpp, I get an error: cannot allocate an object of abstract type 'Single' Booking* b = new Single(); The addBooking() function should make a pointer of Single of type Booking, add the pointer to the QList (BookingList derives fr...
You need to declare your method override in the class definition class Single : public Booking { public: Single(); double rate() override; // this line }; then you can actually implement the method in your cpp file as you did double Single::rate() { return Booking::SINGLE_PPPN; }
64,072,259
64,072,347
How to concatinate multiple vectors of shared_ptr's?
I've seen other post but I am trying to do this using some of the <algorithm> methods. I have a pointer to a map which contains a key to a vector of pointers to BaseElement classes like the following. using ElementV = std::vector<std::shared_ptr<BaseElement>>; using ElementM = std::map<int, ElementV>; using SElementM =...
You can get pairs of keys (first) and values (second) via iteraters of std::map, so inserting each vectors via std::for_each is one way. ElementV allElems; std::for_each(elements->begin(), elements->end(), [&allElems](const auto& p) { allElems.insert(allElems.end(), p.second.begin(), p.second.end()); });
64,072,300
64,082,802
Porting a Raku grep closure with functions and operators into C++
Here is a sample Raku code which uses a grep closure with a sample criteria consisting of a function and logical operators: print "$_, " for ( grep { is-prime $_ and $_ > 5 and not ($_ == 11 or $_ == 13) }, 1..20); # Output is: 7, 17, 19 I'd like to port this into C++ using a vector or a list and a lambda in which I ...
What Perl calls grep here is called a filter in C++ (and some other contexts). C++20 offers std::ranges::filter_view for the purpose, but since this question is tagged for C++17… The find_if approach you tried doesn't make sense because it still involves iterating over every element (and asks the library to search wit...
64,072,448
64,072,580
Environment Variables for Arudino / ESP32 module code
I have some simple FastLed & wifi code on my ESP32 module, but I don't want to store my WIFI ssid & password in the code (on github). So i'd like to have that info in a separate file that doesn't get checked into source control but DOES get compiled and loaded onto the ESP32 during the upload process. Is this possible?...
I have a separate header with projects like this with a name like WiFiCredentials.h The body of that file will just be: #define SSID myssidwhatever #define PASSWORD mypassword And that is all that's in the file. I include that file in the main project so it has access to those defines but I don't include the file in...
64,072,732
64,072,906
get target type of a pointer in c++ template
I have written a template function which may be passed either a QTcpServer or a QBluetoothServer. It gets the next pending connection and binds a couple of it's event handlers. (the real function also contains some error handling and other stuff but they are not relavent to the question so I have left them out). templa...
Passing an lvalue (such as from deferencing your clientsocket variable) to decltype() returns a reference type, so if you want to use decltype then you will need to use std::remove_reference or std::remove_pointer to access the type being referenced, there is just no getting around that. In C++14 and later, you can use...
64,072,934
64,072,954
Ostream & istream as constructor arguements
I need to use istream and ostream as constructor arguments for my class but im getting a no typename in std error. Can anyone help?? This is ugent. ... #ifndef MENUINTERFACE_H #define MENUINTERFACE_H #include <iostream> namespace core { class MenuInterface { public: /** * @brief MenuInterface * @param d...
std::cout and std::cin are variable names, not type names. You need to use istream and ostream, so use them. MenuInterface(std::ostream &display, std::istream &input);
64,073,023
64,073,047
Efficiently placing object randomly in a virtual 2D Environment
I have an environment made of 2 dimensions. I would like my environment to be big (1000x1000 at least) and deals with at most that amount of entities. For memory concerns I decided to not implement any 2D array or a vector of vector (am I wrong ?). I just have an Environment object with a width and height attributes, ...
Change type of coordinates from std::list<std::pair<unsigned short int, unsigned short int>> coordinates; to std::vector< std::pair<unsigned short int, unsigned short int> > coordinates;
64,073,139
64,073,172
Creating and Adding Unlimited Objects into an Array in C++
For example, I have an object called Patient. I will have unknown numbers of Patient in a day and have to store these patients records for a week. I will have an object array to store "patient" in a day A weekArray of size 7 to store each day record? I am quite brain stuck on how to proceed with this. How do i create...
You should use std::vector when the number of elements to store is unknown. #include <iostream> #include <string> #include <vector> using std::cout; using std::cin; using std::string; struct Patient { string name; int age; }; int main (){ std::vector<Patient> weekArray[7]; for (int i =0; i<7; i++){ boo...
64,073,533
64,073,790
Conditionally to choose which classes to inherit
So, I've got a diamond hierarchy. class Base { // ... } class Derived_A : public Base { // ... } class Derived_B : public Base { // ... } class Join : public Derived_A, public Derived_B { // ... } Depending on a template variable, I would like to conditionally choose to inherit A and/or ...
Specifying the base classes instead of using bool as template parameter seems more straightforward. e.g. template<class... Base> class Join : public Base... {}; then use it like Join<Derived_A, Derived_B>, Join<Derived_A>, Join<Derived_B>, and Join<> (inherit nothing).
64,073,756
64,073,924
Does clang++ 12 support C++20 std::construct_at?
I'm playing with recently approved C++20 standard features std::construct_at() and trying to get more familiar with them... I've built an example based on the example from CppReference.com: #include <memory> struct S { int a; int b; }; int main() { std::allocator<S> alloc; S * s = alloc.allocate(1); ...
This has nothing to do with construct_at. S is an aggregate; outside of its default and copy/move constructors, it has no constructors to be called. So S can only be constructed with values through aggregate initialization. This normally requires a braced-init-list (eg: S{3, 5}). But C++20 includes a feature that allow...
64,074,026
64,074,037
(C++) Why are additional blank lines in the text file not being counted?
I have created this function to return the number of lines in a text file: int numberOfLinesInFile(string dataFile){ ifstream inputFile; inputFile.open("data.txt"); int numberOfLines, data; while(!inputFile.eof()){ inputFile >> data; numberOfLines++; } cout << "Numb...
Firstly, you are doing numberOfLines++; after inputFile >> data; without checking if the reading is successful. This is bad and lead to an extra counting. Secondly, inputFile >> data; reads integer and skip whitespace characters before integers. To avoid these problems, you should use std::getline() to count lines. Als...
64,074,068
64,074,108
Can't use lambda as hash for unordered_set of pairs?
I am trying to define a type that's an unordered_set over pairs of unsigned int: typedef std::pair<unsigned int, unsigned int> Loc; auto HashLoc = [](const Loc &l) { return l.first << 16 ^ l.second; }; typedef std::unordered_set<Loc, decltype(HashLoc)> LocSet; This was based on the accepted answer to creating unorde...
You need to compile with C++20 mode, i.e. with the option -std=c++2a. Before C++20 lambda closure types have no default constructor. Closure types are not DefaultConstructible. Closure types have no default constructor (until C++20) If no captures are specified, the closure type has a defaulted default constructor. (s...
64,074,286
64,074,300
I can't understand how to use size_t in C++
When I have to use size_t, can I use such expressions? /* size_ is size_t type and has some value*/ and I want to change the value like ++size_; or --size_; And I also want to make array using size_t like array[size_]=something; Are they valid?
Yes, you can use all of them because size_t is an unsigned integer type. Example: #include <iostream> int main(void) { size_t size_ = 0; int array[10] = {0}; int something = 42; std::cout << "initial: " << size_ << std::endl; ++size_; std::cout << "incremented: " << size_ << std::endl; ...
64,074,832
64,074,888
c++ inserting values into arrays using a template function
I am trying to insert a value into the sorted arrays in the right place using a template function. I have the program working if the number is the biggest or the smallest in the array, but not if it's in the middle. So my question is what kind of for loop/if statement combination do I need to get a middle number into t...
I have the program working if the number is the biggest or the smallest in the array, but not if it's in the middle. Yes, your for loop is misleading because it appears to consider all elements from the last to the first, but all it contains is two if cases for the last and first elements! You haven't written any co...
64,075,135
64,075,256
'class MainClass' has no member named 'procent
#include <iostream> #include <vector> using namespace std; class MainClass{ public: virtual void getData() = 0; virtual void printData() = 0; }; class Car : public MainClass{ private: int hp; int motor; public: Car(int _hp = 0, int _motor = 0){ hp = _hp; ...
procent() is not a member of class MainClass. The pointee type of p is MainClass. Hence, you can only access what is known in MainClass. That the pointer p actually holds an address of a Car instance doesn't count for this. getData() and printData() are known but procent() not. (It's part of the derived class Car.) Tha...
64,075,210
64,075,538
How can I support using streams in an exception handling macro in C++?
I have a little error function that looks like this: template<typename ErrorType> void throwError(const std::string &file, const std::string &function, unsigned int line, const std::string &msg = "") { std::ostringstream errMsg; errMsg ...
If you're willing to change the syntax slightly then a simple helper macro could be used. Given your current function template... template<typename ErrorType> void throwError(const std::string &file, const std::string &function, unsigned int line, const std::string &msg ...
64,075,523
64,141,107
Incorrect bone rotations, based on bone structure in edit mode
I am having a trouble/question regarding assimp and blender exporting. I export model from blender to gltf binary (.glb), and everything is working correct, unless the bones inside blender are rotated not inside the pose mode (created and rotated inside edit mode) i am curious if the trouble can be solved inside the co...
By debugging various things, i found out that blender/assimp gltf2 importer put the bone translations (rotation,location,size) and offset of nodes (static bones) in location/rotation/scale frames, i solved that by : creating 'unanimated' sequence which as name suggest, contains unanimated bones saving the unanimated l...
64,076,138
64,077,584
cquery no matching funtion for call 'to_upper'
#include <iostream> #include <string> #include <boost/algorithm/string.hpp> using namespace std; int main() { string city1, city2; cout << ("Please enter your citys name"); cin >> city1; cout << ("Please enter your citys second name"); cin >> city2; cout << city1 [0,1,2,3,4]; cout << city2 [0,1,2,3,4]; ...
boost::algorithm::to_upper is declared as (from boost reference) template<typename WritableRangeT> void to_upper(WritableRangeT & Input, const std::locale & Loc = std::locale()); so you can pass only one string to this function. Replacing boost::to_upper(city1, city2); with boost::to_upper(city1); boost::to_upper(ci...
64,076,314
64,076,750
How to printing all 8 neighbors in a 2D vector (Segmentation Fault)
I am attempting to access ALL 8 neighbors of an index on a 2D vector. I then try to do the following pseudocode to find all 8 neighbors cout << grid[columnindex-(-1->1)][rowIndex-(-1->1)] << endl; However, when I do this I get a segmentation fault. I am unsure why.
I get a segmentation fault. Code is indexing outside array bounds with negative indices. Index calculation needs to wrap around. Use modulo arithmetic. // cout << grid[c-incc][r-incr] << endl; int ci = (c-incc + vecSize)%vecSize; int ri = (r-incr + veciSize)%veciSize; cout << grid[ci][ri] << endl; Code uses (c-incc...
64,076,606
64,076,711
List and Iterator after and before sorting behavior
I am going through STL in cpp and I found List. Wrote below code : #include <bits/stdc++.h> using namespace std; int main() { list<int> ls; ls.push_back(23); ls.push_front(34); ls.push_front(39); ls.push_front(334); ls.push_front(434); ls.push_front(7834); ls.push_front(634); ls.pus...
it10 is an iterator to the element 934 in the list. it11 is an iterator to the end of the list. After sorting it10 is an iterator to the element 934 and it11 is an iterator to the end of the list. The elements starting from 934 after sorting are: 943 7834 From cppreference about std::list::sort: std::sort requires r...