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
63,909,244
64,020,448
How can I get clang-format to put the parameters of a brace-initialized construction on the same line?
I'm running clang-format, with a .clang-format file which only specifies Language: Cpp, on this input (invalid C++, but that's unimportant for this): const auto SOME_VARIABLE_NAME = {{"key", { {"key2", std::array{ 0, 0, 0, 0, }}, }}}; I get this output: const auto SOME_VARIABLE_NAME = {{"key", ...
The issue is with the trailing comma immediately before the closing brace. The trailing comma (which is optional in c++) tells clang-format to put each element on a separate line. I don't know where this convention comes from, and it does not seem to be documented. In your case, it seems to be getting in the way. If yo...
63,909,437
64,002,332
C++ Instantiation of a struct which have a non-type template
Usually, we can create one or more instances of a struct the following way: struct { const uint8_t Address; struct { uint8_t GPIO1 : N; uint8_t GPIO2 : N; uint8_t GPIO3 : N; uint8_t GPIO4 : N; uint8_t GPIO5 : N; uint8_t GPIO6 : N; uint8_t GPIO7 : N; uint8_t GPIO8 : N; } Value; } ...
Unlike the case for general structures, The rules says that, "a template class without a name should not exist" And if you think about it it make sense. After the end of the definition for an anonymous structure there should be nothing other than name of objects. So there is no room for template parameters. Also even i...
63,909,969
63,910,558
Compliling C++ program in Visual Studio using g++ compiler generates % at the end
When compiling my program in Visual Studio Code using the g++ compiler, the output generated has the % sign. #include <iostream> int Main() { std::cout << "Hello World!"; return 0; } Terminal screenshot: I have deleted the question mark, so I think there is no control character.
On POSIX compliant systems, individual lines are by convention delimited by a newline character. zsh (which is the shell you’re using) uses % to indicate output that’s missing that terminating newline character. Try entering echo -n hello on your shell to replicate the behaviour. To fix this (and remove the % output), ...
63,910,017
63,910,063
std::condition_variable predictable spurious wake-ups?
I ran into this interesting behavior of spurious wake-ups. Consider this simple demo code: #include <iostream> #include <chrono> #include <thread> #include <condition_variable> #include <mutex> using namespace std; // I know using namespace std::chrono; using namespace std::chrono_literals; mutex mtx; // used for cv...
I realized immediately after I posted this question that this overload of condition_variable::wait (as described here) is equivalent to: while (!pred()) { wait(lock); } I was imagining it being equivalent to a do while instead. So really there are no spurious wake-ups here. Just that it wasn't waiting at all until...
63,910,119
63,910,200
recursive function in cpp gives error "Segmentation fault (core dumped)"
what I'm trying to do is to return the sum of all numbers bellow or equal to a number like n, that are multiples of 3 or 5, i tried to do this in c++ with a recursive function: #include <iostream> int getsum(int n); int main(int argc, char *argv[]){ std::cout<<getsum(10); return 0; } int getsum(int n){...
The problem is that when n reaches zero, you get into the block. if(n%3==0 || n%5==0) return n+getsum(n-1); Once n reaches a negative number, the recursive call keeps going for ever. That causes stack overflow. You should move the check against zero as the first thing. int getsum(int n) { std::cout << "n: " << ...
63,911,260
63,911,367
What exactly does it mean to say a C++ object is movable?
Given the following definitions: object -- a contiguous region of memory holding a value of some type. value -- the bits of an object interpreted according to the objects type. Section 6.4.1 of the C++ Programming Language book [4th ed], when discussing value categories, states: Movable: The object may be moved from...
What does "move its value to another location" really mean? It means that the other location has the value that the original had prior to the move, and that it is not important what value the original location has after the move. How can a value (a bit interpretation) be moved? For example, simply by copying. ...
63,911,585
63,940,935
QImage loaded from PPM file isn't displayed properly
So, I'm doing an image manipulation assignment for my class using QT, I was asked to save the current Image data that I have into PPM format manually, as well as loading it back to the QDialog program. I managed to save the image correctly (verified the output file with gimp) but loading from the file created a disaste...
One row of image has size of 3 * width bytes not width, hence this should be fixed everywhere in data[] indexing. I.e. code data[width*h+w] = (unsigned char)readVal; should be replaced with data[3*width*h+w] = (unsigned char)readVal; and code r = (int)data[width*h+w*3]; g = (int)data[width*h+w*3+1]; b = (int)data[wid...
63,911,656
63,911,727
What are possible causes for a C++ unordered map to produce the following gdb output?
I am using unordered maps in C++11 that have keys which are concatenated strings of various numbers and characters. An example of a key that I am using is: coeff_key = "_"+to_string(first_k_index) +"_"+ to_string(second_k_index) +"_"+ to_string(i) +"_"+ to_string(j)+"_"; I can fill all the maps, but once I try to acces...
There are multiple possible causes, the most probable being that there is not enough memory to construct the map. Also See: Debugging strategy to find the cause of bad_alloc Docs
63,911,820
63,911,842
Linking error in GMP when trying to generate prime numbers in C++
I'm trying to write a simple program that generates big prime numbers in GMP as part of a bigger project, so far I've sketched out the following function: primes.cpp #include"primes.h" void random_prime(mpz_t result){ gmp_randstate_t state; mpz_t prime; mpz_init(prime); gmp_randinit_default(state);...
The -l option is used when linking, and not compiling the individual .cpp files. link: main ${CC} -o main primes.o ... -lgmpxx -lgmp And get rid of the -l option everywhere else.
63,912,067
63,912,123
Convert a memcpy char[] into a string
I need to: convert a uint64 memcpy'd char[] into string pass to another part of the application then convert the string into back into uint64 via memcpy I have the serialized char[]. However when I turn it into a string the contents change: uint64_t a = 6232222100000000000; char key[sizeof(a)] = {0}; st...
Some of the bytes in the uint64_t are 0, so they will be treated as null terminators when you convert the char[] array to a std::string using the std::string(const char*) constructor that expects a pointer to a null-terminated character array as input. Thus, it will truncate your char data. Then your for loop after the...
63,912,168
63,912,233
What is the max size for an array of complex doubles?
In C++, what is the maximum size of a one dimensional array of complex doubles (i.e. std::complex<double> array[dimension])? Is there a difference to the max size if I declare the array in main versus globally?
The maximum size of the array will be M / sizeof(std::complex<double>) bytes where M is the remaining free memory in bytes. Amount of free memory is affected by how much total memory there is, and by how much memory is used for other purposes. If you declare the array as an automatic variable, then it will have automat...
63,913,005
63,913,131
How to test if console supports ANSI color codes?
I use fmt based logger with optionally color prints - which relies on ANSI color commands. Unfortunately on Windows 10 it is disabled by default. I know how to enable it but I still want to find out how to test whether the console supports ANSI commands or not. Does anybody know?
On Windows you can get/set the ANSI color support by checking/setting the ENABLE_VIRTUAL_TERMINAL_PROCESSING flag with SetConsoleMode() or GetConsoleMode(). There's also the HKEY_CURRENT_USER\Console\VirtualTerminalLevel registry key for global virtual terminal settings. See also https://learn.microsoft.com/en-us/windo...
63,913,007
63,913,041
operator& that returns an int and operates on 2 vectors?
I would like to define an & operator between two std::vector<int>. This operator should bit-wise and each element of both vectors together and return the number of non-zero components of the resulting vector. However, if I define int operator&(const std::vector<int> &lhs, const std::vector<int> &rhs), it the compiler d...
I would like to define an & operator between two std::vector<int>. You may not (at least not globally; it can in theory be done in a custom namespace but I recommend against it). Operator overloads for standard templates with no user defined type arguments are reserved to the standard library. I recommend writing a r...
63,913,013
63,927,996
GLSL having strange black faces with the second mesh
platform: Windows10 context: OpenGL, glew, Win32 So I loaded 2 meshes(using a simple OBJ parser, which only reads the triangulated mesh), with vertexpos,uv and normal data. The first mesh is lighted okay. No black faces.The second one looks like this. The Strange Effects my vertex shader: #version 440 i...
Sorry I made a very dumb mistake. Thank you for all your support @Rabbid76 (Yes I did inverted the normals yes) @paddy The problem was Binding the normal buffers. I bind glm::vec2 * size instead of glm::vec3 * size for normals' buffers
63,913,022
63,913,092
conversion from 'unsigned int' to 'int' requires a narrowing conversion
My code includes the following, and I get the error message above based on the last line below. struct List { int word_i; int mod_i; char mod_type; char mod_char; }; struct Morph { Options mode; deque<List> search_list; vector<string> dictionary; vector<bool> discovered; string outp...
You can replace the last line with: morph->search_list.emplace_back( morph->dictionary.size() - 1, 0, 0, 0 ); Thus the object is created not through brace initialization which does not allow narrowing conversion. The narrowing conversion is from the return value of the call to size which returns std::size_t which is u...
63,913,978
63,914,028
Is it dumb to make a dynamic 2d array where the second dimension is a constant?
I am trying to make an array with a variable number of rows, but it will always have 4 columns. Is doing something like: int** numGrades = new int* [num_exams]; for (int i = 0; i < num_exams; ++i) { numGrades[i] = new int[4]; } a good way to do this? I feel like there's an easier way, but I can't think of one. ...
You could make an array of rows. struct Row{ int values[4]; }; Row* numGrades = new Row[num_exams];
63,914,039
63,915,356
terminate called after throwing an instance of 'std::out_of_range'?
I am trying to see if a particular key exists in map and if so then I want to increase its value by 1. But while running the program I am getting the error terminate called after throwing an instance of 'std::out_of_range' what(): map::at Why is it going out_of_range can someone help? b is a map in this function. i...
You can write this whole thing in just 3-4 lines : for (int i = 0; i < n; ++i) { cin >> a[i]; ++b[a[i]]; } The subscript operator will automatically insert {a[i], 0}, if a[i] is not there as a key in map b. Then incrementing it makes it equivalent to your code where you try to insert a pair {a[i], 1}. What wa...
63,914,351
63,914,751
About NodeJS Buffers
Question about buffers. if i have this native code: unsigned char* data = static_cast<unsigned char*>(malloc(sizeof(int) * 4)); Napi::Buffer<unsigned char> buffer = Napi::Buffer::New(info.Env(), data, sizeof(int) * 4); // create buffer return buffer; it would return the buffer to js, does the GC handle the malloc'd d...
It looks like you should manually free it use other overload https://github.com/nodejs/node-addon-api/blob/master/doc/buffer.md#new-2 The Napi::Buffer object does not assume ownership for the data and expects it to be valid for the lifetime of the object. The data can only be freed once the finalizeCallback is invoked...
63,914,380
63,914,423
Why rename() function not working when I cut strings?
I am working With files. Currently I am sequentially renaming some files I know a little about fstream. I simply want to rename multiple file sequentially with loop.Why this code is not working? Is there any another way to do? i just want to done my job. Thank you for reading <3 #include <iostream> #include <cstdio> u...
std::rename takes two parameters of type const char *. But the result of string concatenation is std::string. You can use .c_str() to access to underlying C-style-string like so: auto oldFileName = "oldname" + to_string(i) + "txt"; auto newFileName = newname + to_string(i) + "txt"; rename(oldFileName.c_str(), newFileN...
63,914,421
63,914,576
extra print from a class function exported to python using pybind11
Here is the example.cpp code : #include <pybind11/pybind11.h> namespace py = pybind11; int add(int i, int j) { return i + j; } class mycl{ public: mycl(){}; mycl(int a){ age = a; }; void call(){ printf("I'm here!\n"); } int ask_age(){ printf("my age is %d\n", age);...
C++ printf returns the total number of characters printed (see here). You bind AskAge() to ask_age which returns an int. Since printf also returns an int, I guess that is whats causing the interprenter to print 13, since the sentence my age is 54 is 13 characters long (with the \n at the end). If you would run this pro...
63,914,631
63,915,388
Multiple inheritance of abstract class results in ambiguous definition
I am facing inheritance hierarchy error which I root caused to this code snippet. The definition of l() is defined in Template class Y, I don't understand why is the compiler finding it ambiguous.Class Z ptr_ is pointing to class Y object which has the definition of l() isn't this how it should work ? Unfortunately th...
Your problem is that you have an inheritance hierarchy that looks like this: C / \ A B | | D D <- Defines l() So when you call l() through a C type, then the compiler don't know if you want to call C::A::D::l() or C::B::D::l(). One way to fix this is to specify which branch you actually want to use in the C...
63,914,741
63,914,822
Cpp program not giving output
I am creating a script that calculates the sum of first n Fibonacci numbers and returns the last digit of the sum. The python script works perfect but the C++ script does not and the logic is same. Any help will be appreciated. Python Code def calc_fib(n): f = [0, 1] for i in range(2, 61): f.insert(i, ...
vector<int> f(n + 1); f[0] = 0; f[1] = 1; for (int i = 2; i <= 60; i++){ f[i] = (f[i-1] + f[i-2]) % 10; } The vector is size n+1 and you access until 60 => it's a bug This should fix : vector<int> f(60 + 1); Or vector<int> f; f.push_back(0); f.push_back(1); for (int i = 2; i <= 60; i++){ f.push_back((f[i-1] ...
63,914,784
63,915,154
How can I dismiss a custom delete function of a std smart pointer?
I have introduced a FreeGuard class that cleans up a resource if initialization fails: struct Resource {...}; class FreeGuard { public: FreeGuard(Resource* r) : resource(r) {}; ~FreeGuard() { if (!dismissed) { freeResource(resource); } } void dismiss() { dismissed = true; } ...
You can use the release() function of unique_ptr. This is a common pattern for exception-safe code when dealing with non-RAII resources (like C library handles): #include <memory> int freeResource(Resource* r) {...} int init(Resource* r) { std::unique_ptr<Resource, decltype(&freeResource)> guard(r, freeResource);...
63,915,309
63,915,403
Error:- Program to Split the Middle term using Quadratic Equation
I coded a Program that split the middle term of a quadratic and make it easy for student to solve complex equation in easy but when I tried to make both number positive by multiplying them "(-1)" it just does not change anything or it is not giving desired output. Full Code is include that code is on Line 43-45;It will...
try{ if(bracket_value < 0){ throw bracket_value; } } catch(double &bracket_value){ bracket_value *= (-1); } You need to use *= or x = x * (-1); Similarly when you are checking if (return_value_02 < 0){ return_value_02 * (-1); } else if(return_value_01 < 0){ return_value_01 * (-1); } You ne...
63,915,423
63,915,514
Why does this ternary result in a pointer being printed?
This ternary, when used as-is, spits out a pointer: std::stringstream ss; ss << pair.second ? pair.second->toString() : "null"; std::cout << ss.str() << '\n'; This is a sample output: { "glossary": 000002B96B321F48 } But when I surround the ternary operator in parenthesis, it works properly and gives me eithe...
https://en.cppreference.com/w/cpp/language/operator_precedence << has a higher precedence than ? ss << pair.second ? pair.second->toString() : "null"; is grouped as (ss << pair.second) ? pair.second->toString() : "null"; (ss << pair.second) evaluates to the state of the stream, which is normally true, so pair.second->...
63,916,012
69,470,830
Grpc ssl server crashes - C++
I have a Grpc server, written in C++, that works perfect with insecure connection. Now i am trying to change the connection to use a secured connection so i changed the credentials from grpc::InsecureServerCredentials() to grpc::SslServerCredentials(opts), but the server crashes because of segmentation fault. Here is m...
I've had a similar issue when gRPC client crashed in SSL_CTX_new. It turned out this was somehow caused by incorrectly linked openssl when building gRPC. I've rebuilt gRPC with -DgRPC_SSL_PROVIDER=package and it solved the problem.
63,916,378
63,916,829
How to make a class member function edit the value of global variable
int var1 = 0; int var2 = 10; class cls{ int varA; int *varB; public: cls(int valueA, int *valueB){ varA = valueA; *varB = *valueB; } void putValueAtoVar2(void){ *varB = varA; } } void setup(){ cls cls1(var1, &var2); } void loop(){ cls1.putValueAtoVar2(); } ...
You can use this before global variable are globalVar1=0 and globalVar2=10 after assigning instance variable cls.varA to globalVar2, becomes globalVar2=0 Below is the following code : #include <iostream> using namespace std; int globalVar1 = 0; int globalVar2 = 10; class cls{ int varA; int *varB; public: ...
63,916,434
63,917,215
LNK1104 with NuGet Packages : DirectXTKAudioWin8.lib
I have a Direct3D Application. We use the NuGet Package directxtk_desktop_2015. In recent packages like directxtk_desktop_win10 or directxtk_uwp, I have additional WICTextureLoader flags which I want and need. However, when I add these packages to NuGet, I receive the linker error LINK : fatal error LNK1104: cannot op...
You should use only one of those packages at a time. If you are currently using directxtk_desktop_2015 and you are using VS 2019, then you should use directxtk_desktop_2017 instead. I dropped VS 2015 support and deprecated directxtk_desktop_2015 starting with the February 2020 release The directxtk_desktop_2015 packa...
63,916,507
63,916,698
c++ CMake project structure for lib and executable
I have a question regarding how to structure a c++ project and build that using CMake (inside of CLion). I am very new to c++ (I started to learn the language only two weeks ago) and to CMake (I haven't ever configured a CMake file). I do however have a bunch of experience with other programming languages and their eco...
You declare separate CMake targets, i.e., in engine/src/CMakeLists.txt: add_library(engine math.cpp) while in game/src/CMakeLists.txt, you have add_executable(my-game main.cpp) target_link_libraries(my-game PRIVATE engine) When using e.g. make, you can build the targets individually by make engine # ...
63,916,509
63,916,640
Is it impossible to call constructor if object is created with template?
I wrote some simple code while I was trying to understand pointer stuff in c++. And I found out that a constructor does not work. I have no idea what is happening here. template <typename T> class Node { public: T* Data; Node<T>* right; Node<T>* left; }; class SimpleClass { public: SimpleClass() ...
Because you create an object for Class Node and not create any object of class SimpleClass so the constructor of this class is not called. int main(void) { Node<SimpleClass>* A = new Node<SimpleClass>[1]; Node<SimpleClass>* temp = new Node<SimpleClass>[1]; A->Data = new SimpleClass(); t...
63,916,528
63,926,049
VS2019: Compiling Cap'nProto Crashes C++ Compiler
So, the situation is that due to some unforeseen consequences I need to build Cap'nProto (https://capnproto.org/) for windows using Visual Studio 2019 (latest release as far as I know, 16.7.3). As you can see from the screenshot below, the compiler is very unhappy with the code, to the extent that it gives an internal ...
This is a Work around VS2019 ICE in KJ_CASE_ONEOF() that on code review now and hope soon will be merged into master
63,916,963
63,917,502
When converting pointers to integers, should I be using reinterpret_cast?
It is my understanding that when converting from a pointer to an integer, I should be using reinterpret_cast because that gives me a compile-time check that the integer variable is large enough to fit a pointer. Is that correct? As opposed to just casting where I have no guarantuee and could end up truncating addresses...
I should be using reinterpret_cast ... Is that correct? Correct... with the precondition that there is a need for such cast in the first place which is rare. .. because that gives me a compile-time check that the integer variable is large enough to fit a pointer. Is that correct? Not correct. There is no extra gua...
63,917,001
63,917,762
Get value from c10::Dict<c10::IValue, c10::IValue> in Pytorch C++
I'm using a TorchScript Model on Pytorch C++ Frontend. The model in Python returns an output dict as Dict[str, List[torch.Tensor]]. When I use it in C++, it returns a c10::Dict<c10::IValue, c10::IValue>. What is the equivalent of this Python code: value_a = output['key_a'] value_b = output['key_b'] in C++ to get valu...
You can find header file of c10:Dict here. What you want is at method (defined here), so: auto value_a = output.at(key_a); Should do the trick. Also you don't have to create torch::IValue key_ay("key_a") explicitly, this should be sufficient: auto value_a = output.at("key_a");
63,917,691
63,918,065
Use a url from C++ in Qml
I am trying to use QtCreator to create a UI that given a url in the C++ part of the code, it stores this url in a file and then pass it to the qml part of the code to diplay the site. With the code that follows, I can run fine the program but I get only a white page: main.cc #include <QGuiApplication> #include <QQmlApp...
Change your code to: QQmlApplicationEngine engine; QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, [](QObject *obj, QUrl Url) { if (obj != nullptr) ...
63,917,790
63,918,073
C++ Boost Asio - How to detect disconnection and make a list of all active connections
I am using Boost asio as a TCP server solution. I want my server and client to communicate over TCP binary protocol. Here is my server code: Server.cpp: #include "Server.h" #include "Session.h" using namespace Vibranium; void Server::do_accept() { acceptor_.async_accept(socket_, [this](boost::system::error_cod...
1.What should be the type of the vector containing all connections? Where should I fill it? You could create a vector of sockets for storing clients: vector<tcp::socket> clients; // adding by clients.push_back(move(socket)); after accept'ing or create some wrapper class around socket and use it, for ex. class Client...
63,918,492
63,918,836
Using std::search to search substrings in a std::string
I want to search in a string some substrings using std::search. I tried this: std::string str = "the quick brown fox jumps over the lazy dog"; std::string substr[] = { "fox","dog","bear" }; auto it = std::search(str.begin(), str.end(), substr, substr + 3); std::cout << "substring found at position :" << (it - str.begin...
You have an array of substrings so you need to compare each one individually, std::search can only look for one substring at a time. std::string str = "the quick brown fox jumps over the lazy dog"; std::string substr[] = { "fox","dog","bear" }; for(auto& sstr : substr){ auto it = std::search(str.begin(), str.end()...
63,918,760
63,918,997
Why will c++ assert() function brings overhead to program
I have the practice to use c++ assert to check if the program is running normally, such as this: cv::Mat im = imread("pic.jpg") assert(!im); This would check if the image is read correctly. This is useful since the image might not be correctly placed in the expected directory, so we need to check. I feel that using as...
First, assert() is not an ordinary function. It is macro that looks similar to this: #ifdef NDEBUG #define assert(condition) ((void)0) #else #define assert(condition) /*implementation*/ #endif and as you see it is only enabled and doing something when NDEBUG is not defined. It is meant to be used to do extra checks on...
63,918,910
63,918,957
How do you insert multiple input at the same time in python?
I had little experience with C++ and there is this function which I really like about it: (this is a simple example for a calculator with only addition) #include <iostream> using namespace std; int main(){ int a, b; cout << "insert numbers and calculations" << endl; cin >> a >> b; cout << a + b << endl...
You may try this way a, b = [int(x) for x in input("Enter two values: ").split()] print("First Number is: ", a) print("Second Number is: ", b) print()
63,919,240
63,919,570
CMake concatenate to each string in array
For example I have array: set(SOURCES main file app ) foreach(src ${SOURCES}) set(${src} "${src}.cpp") endforeach() foreach(src ${SOURCES}) message(${src}) endforeach() I need to receive main.cpp, file.cpp and app.cpp, but it doesn't work. Why? How can I solve it? Thanks in ad...
The command set(${src} "${src}.cpp") creates a variable, i.e. you create ${main}, ${file}, and ${app} variables in the loop. Instead, you need to modify the list SOURCES, as described in docs. list(REMOVE_ITEM SOURCES ${src}) list(APPEND SOURCES "${src}.cpp") But do not modify SOURCES it in the loop over SOURCES. Ins...
63,919,497
63,919,561
lifetime of automatic storage that enters a nested scope
Say there is an object with automatic storage duration, and that object is copy-initialized from within a nested scope, like a loop body. Is the lifetime of the values created from within the nested scope extended into the containing scope? #include<iostream> using namespace std; class Thing { public: int data; ...
This is perfectly legal, defined behavior. Your mistake is in thinking that the lifetime of the Thing created inside the block matters. It doesn't. After the copy, the copy-assigned t hasn't changed what it is; it's still the same t created outside the block, it just had its values updated. Its lifetime is entirely una...
63,919,622
63,919,848
Strange linkage error when using friend method
main.cpp #include "test.cpp" int main() { } test.cpp // test.cpp #include <iostream> using namespace std; class Test { public: friend ostream& operator<<(ostream& out, Test& o1); }; ostream& operator<<(ostream& out, Test& c) { return out; } Output: Error 1: Severity Code Description Project File Li...
The Error message is descriptive there, you are redefining the operator. That happen because you are trying to link objects that contains the same definition. The problem here is that you are including the "test.cpp" and you are probably compiling it (and then trying to link). You should include only files containing d...
63,919,794
63,985,681
How does visual studio 2015 add "\Zi" compile option to CUDA Linker? How to remove it?
I use cmake to build C++ project. I didn't add "/Zi" compile option to CMAKE_CUDA_FLAGS. But Visual Studio add "/Zi" to CUDA Linker automatically. My library will become pretty big with this option, so how can I remove it?
CUDA Visual Studio Integration doesn't make /Zi configurable by default. You can either modify HostCommandLineTemplate, RuntimeApiCommandLineTemplate, and CommandLineTemplate directly in C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\BuildCustomizations\CUDA 10.0.props or specify an extra .props file to customi...
63,919,889
63,920,212
declaring a friend function in the global namespace that returns a template class
i have a function declared in a namespace, that when it is defined as a friend, throws a compiler error. #include <string> #include <vector> namespace Example { std::vector<std::string> GetNames(); } class MyClass { public: MyClass() : name("data") {} private: std...
The compiler doesn't evaluate your friend declaration as you intended it to. Instead, the compiler reads the following: friend std::vector<std::string>::Example::GetNames(); It thinks that you want to declare the function GetNames that is within a namespace Example inside the vector class. That's why when you remo...
63,919,921
63,920,015
What is Fpermissive? How can i use it to solve errors?
Morning all, Im writing a small program in c++ where the user inputs certain yes/ no answers using while loops and if statements etc. I have encountered a problem that i dont know how to resolve, but the error messagse tells me that i can solve this using fpermissive. #include <stdio.h> #include <iomanip> #include <ios...
You have an extra ; at the end of for(int i=1;i<=3;i++); This means you don't really have a loop. i is incremented 3 times in a loop that does nothing, then, { cout<< setw(2)<<right<<(i*5)<<setw(20)<<left<<"Kilometers:"<<setw(10)<<left<< distance[i-1]<<left<<distance[i-1]<<; if(incomes[maxIndex]<incomes[i-1]){ max...
63,920,357
63,920,625
glBufferData not working outside main function
I have a problem that I don't know how to solve. I am using C++ with GLEW and GLFW, I initialise GLFW, create the window, make the window the current context, then I initialise GLEW. All of this happens on the main function. The problem appears when the code to create the VAO and the VBO is organised in methods, in cla...
The problem is here sizeof(data). Within your method data is a pointer, and sizeof(data) returns the size of the pointer, not the size of the original array. To solve pass the size as a parameter to the method along with the data. Or use a std::vector<float> instead of an array of floats.
63,920,669
63,930,612
why WM_KEYDOWN not working when WM_COMMAND is triggered?
When i click the button in my client window then i pressed the down arrow key, the WM_KEYDOWN is not being sent to my windows procedure, but the other cases always works, so to solve this issue, I have to click outside of my client window and then then click in my client window (but not the button) then the WM_KEYDOWN ...
The reason is that when you press the button, you focus on the current button, so your WM_KEYDOWN message is sent to that button. So you need to subclass the button and handle the button's WM_KEYDOWN message.You can refer to the document. Here is the modified sample: #include <iostream> #define _WIN32_WINNT 0x0501 #inc...
63,920,734
63,920,919
What determines the initial value of C++ variables
If I don't initialize a C++ variable, I find that it automatically gives it 0 on some android phones, but not on others, and zero on all IOS phones. So what determines whether you give it 0, is it the phone system, is it the compiler, is it some compiler option
What determines the initial value of C++ variables If I don't initialize a C++ variable I assume you refer to automatic storage. Variables in static or thread local storage are zero initialised implicitly. From perspective of the language: The initial value is simply indeterminate. Whether anything affects this value...
63,921,024
63,930,728
Self-willed behavior in response to return from handling of WM_NCHITTEST
I'm redrawing the non-client area completely, but willing to keep some default functionality. Windows doesn't allow me to put a close button wherever I want. Though it perfectly works when I say to windows that I want the whole window to be HTCAPTION, but not a close button. I know I can easily go around and make an ap...
You need to handle WM_NCLBUTTONDOWN separately. wParam The hit-test value returned by the DefWindowProc function as a result of processing the WM_NCHITTEST message. For a list of hit-test values, see WM_NCHITTEST. Therefore, the value you return from WM_NCHITTEST is sent in the wParam of other messages, notably WM_NC...
63,921,184
63,921,406
Why is if Statement not returning INFINITY? C++
I have writed this Program and it should print INFINITY if Divided by 0 for example according to the code 0/0 = infinity thus the output is not as I expect. Something is wrong with my code? or I need to do it on another way? #include <iostream> using namespace std; void optionMenu(); void userInput(char); int main ()...
You're checking if value2 is equal to 0 before receiving the user's input, when it is uninitialized. Do this: case '/': cout << " Enter your first Number: "; cin >> value1; cout << " Enter your second number: "; cin >> value2; if(value2) cout << " The result for the Entered values is...
63,921,741
63,921,916
Is it legal to declare but not define a function that is unused?
Let's say I have have the following files in C++: // bar.hpp int foo(); int bar(); // bar.cpp #include "bar.hpp" int bar() { return 3; } // main.cpp #include "bar.hpp" int main() { return bar(); } Note that foo() was declared (in both main.cpp and bar.cpp translation units) but never defined anywhere. On the other h...
Yes it's legal. Functions and variables are required to be defined only when they are odr-used. odr-use is a precise way of saying use them, which for functions loosely means you call it or take its address. To be a bit more precise, the function has to appear in a potentially-evaluated expression, which is everything ...
63,922,144
63,922,315
Why does constraining auto with an integral type render it uninvocable for views::filter?
I have written a simple predicate which I want to pass to std::ranges::views::filter: struct even_fn { constexpr bool operator()(std::integral auto&& e) const noexcept { return e % 2 == 0; } }; inline constexpr even_fn even; Sample usage: using namespace std::ranges; views::iota(1, 10) | views::fi...
This is because std::integral won't allow reference types to be deduce. In effect, the filter view will filter with something kind of like this: filter_function(*it); This, with most range type will return a lvalue reference to the element. Since it send a lvalue reference, the only way to make the call to your functi...
63,922,206
63,959,855
GLSL Sphere - ray intersection geometric solution
I'm trying to implement sphere ray intersection in GLSL, both the geometric and analytical solution. I'm having trouble solving the geom one, it should have something to do with how I return true or false: bool hitSphere(Ray ray, Sphere sphere, float t_min, float t_max, out float t_out) { // Geometric solution ...
The issue is caused by t_out. The algorithm has to compute t_out in that way, that X is the intersected point of the ray and the surface of the sphere, for: X = ray.origin + ray.direction * t_out; In the working algorithm t_out depends on the length of ray.direction. t_out becomes smaller, if the magnitude of the vec...
63,922,228
63,922,490
How to sort an array of pointers depending on their arguments
This is my function that needs to print all elements from transports array of pointers which have bigger price than the Transport *t element void pecatiPoloshiPonudi(Transport **ponudi, int brEl, Transport &T) { //cout<<T.getDestinacija(); for (int i=0;i<brEl;i++) { if(T.getPrice() < ponudi[i]->getP...
You can use std::sort with a custom comparator, as follows std::sort(ponudi, ponudi + brEl, [](const auto & lhs, const auto & rhs ) { return lhs -> getPrice() < rhs -> getPrice();});
63,922,586
63,922,786
String of Bytes to Byte array c++
Im trying to make function that takes this pattern string : "07 C5 8F E1 FD CA 8C E2 D4 FD BC E5 03 C6 8F E2" to return this BYTE array BYTE pattern[] = { 0x07, 0xC5, 0x8F, 0xE1, 0xFD, 0xCA, 0x8C, 0xE2, 0xD4, 0xFD, 0xBC, 0xE5, 0x03, 0xC6, 0x8F, 0xE2}; What i tried: BYTE strPatternToByte(std::string pattern, int len)...
The problem is that (byte) tokens[i] doesn't translate a string to another type, instead it asks the compiler to treat the std::string object in tokens[i] as a byte, which it isn't and can't be converted to. It's basically you telling a lie to the compiler. In fact, basically all C-type casting should be a red flag tha...
63,922,646
63,922,816
multithreading in c - WINAPI
I am trying to make a simple program that creates 4 threads and each one of them has to loop for 1000 times and each time print its thread number (1 to 4) and its position in the loop. I wrote this code but it doesn't work at all (prints weird stuff); I would be glad if someone will help me to find my mistake. #include...
You have an incorrect value for the last argument in your WaitForMultipleObjects call! The constant INFINITY (defined by math.h, or one of its 'children', as ((float)(_HUGE_ENUF * _HUGE_ENUF))) is a floating-point constant used for detection of overflow-related stuff. What you should use, instead, is the INFINITE const...
63,922,672
63,923,573
Trouble with UTF-8 input
My simple code has no trouble with Japanese characters when outputting, but for some reason it doesn't take input properly, is it lacking something? int main() { _setmode(_fileno(stdout), _O_U16TEXT); SetConsoleCP(CP_UTF8); std::wstring s = L"こんにちは, 世界!\nHello, World!"; std::wcout << s << endl; std::wstring te...
This code worked for me in the Windows 10 command prompt. #include <fcntl.h> #include <io.h> #include <string> #include <iostream> using namespace std; int main() { _setmode(_fileno(stdout), _O_WTEXT); // or _O_U16TEXT, either work _setmode(_fileno(stdin), _O_WTEXT); wstring s = L"こんにちは, 世界!\nHello, Wor...
63,922,776
63,923,048
Does cudaMallocManaged() create a synchronized buffer in RAM and VRAM?
In an Nvidia developer blog: An Even Easier Introduction to CUDA the writer explains: To compute on the GPU, I need to allocate memory accessible by the GPU. Unified Memory in CUDA makes this easy by providing a single memory space accessible by all GPUs and CPUs in your system. To allocate data in unified memory, cal...
So is cudaMallocManaged() creating synchronized buffers in both RAM and VRAM for convenience of the developer? Yes, more or less. The "synchronization" is referred to in the managed memory model as migration of data. Virtual address carveouts are made for all visible processors, and the data is migrated (i.e. moved...
63,923,826
63,923,886
What happens on allocating with "new []" and deleting with just "delete"
Okay, so i was experimenting with pointers in C++, as i have started to code again after almost an year and a half break(School Stuff). So please spare me if this seems naive to you, i am just rusting off. Anyways, i was screwing around with pointers in VS 2019, and i noticed something that started to bug me. This is t...
What happens on allocating with “new []” and deleting with just “delete” The behaviour of the program is undefined. Now I expected it to do some memory mishaps Your expectation is misguided. Undefined behaviour does not guarantee mishaps in memory or otherwise. Nothing about the behaviour of the program is guarante...
63,923,881
63,924,022
Why does accessing elements from an uninitilized array output strange values?
Main Problem I created array without initialization and used printf() function to access random element from it. Everytime I run my program I get strange values in the console. float yearsAvg[5]; printf("%f\n", yearsAvg[4]); // it's outputing -nan in the console or some random values Why is that happening?
Using uninitialized array will contain a garbage value and using them will produce some unexpected results for you. To fix it, just simply initialize it: // Initializing each element of array with 0.0 value float yearsAvg[5] = {0.0}; printf("%f\n", yearsAvg[4]); See it live on OnlineGDB. Note: To initialize 1.0 or so...
63,923,925
63,993,549
Undefined reference to opencv dnn on QtCreator
Error Unable to link OpenCV DNN module with QtCreator : /home/joseph/Documents/dev/dnn_opencv/utils.cpp:52: error: undefined reference to `cv::dnn::dnn4_v20200609::Net::Net() Context Hi, I am trying to load some models with OpenCV DNN (OpenCV 4.4.0) module in order to do some classification/segmentation as part of a bi...
For those who are facing the same kind of issue, I managed to install it correctly and use it in QtCreator using the Cmake GUI and checking out all the correct flags. I believe it was an installation mistake regarding the OpenCV-contrib modules. This link is a good tutorial to mark the correct flags : https://www.pyima...
63,924,329
63,924,515
Make dollar and caret only match at beginning/end of string, not before/after embedded newlines
This little code which follows outputs <hello> <world> demonstrating that ^ and $ are also matching after and before of \n respectively. How can I change this behavior, and have them only match at beginning and end of string? (In this case, there would be no match in the example str input.) #include <boost/regex.hpp> ...
You need to use the match_single_line flag: boost::sregex_iterator rit{ std::begin(str), std::end(str), boost::regex{tokenRegex}, boost::match_single_line // <-- here }; This is a match flag - you specify it when matching (or constructing an iterator which matches), not when compiling the regex.
63,924,541
63,932,350
CPLEX debug window freezes
I am trying to code my math model in CPLEX language using C++ (Concert Technology). when I run my code in the compiler window read my inputs and freezes. when trying to debug my code, the visual studio shows the following line as a breakpoint. //constraint 2 for (cc = 0; cc < NumberOfCourses; cc++) { IloExpr Constr...
Your code is wrong: In the very first inner iteration you add Constraint2 to your model and then you end() that variable. So in the second inner iteration, you are doing Constraint2 += ... while the Constraint2 object was already deleted. This will lead to undefined behavior (hang, crash, ...). I guess what you wanted ...
63,924,558
63,924,769
glm::quatLookAt Return a NaN quaternion
I have a LookAt function (taken from here) which calculate a Quaternion : Camera& Camera::LookAt(const glm::vec3& lookat)noexcept{ glm::vec3 direction = lookat - transform.GetPosition(); float directionLength = glm::length(direction); if(!(directionLength > 0.0001)){ // Check if the direction is valid; Also ...
You are asking GLM to create a quaternion that will make the Z direction (0, -1, 0) (the direction vector) and the Y direction also (0, 1, 0) (the up vector). This is impossible. No amount of rotation will make the Y and Z axes point in opposite directions from each other. You need to specify a different up vector. Not...
63,924,883
63,925,649
Can we access the compiler path from within a source file?
I am looking for a way of programatically accessing the path of the compiler that is compiling the current source file (I'd assume something like a macro here, think of __FILE__ and friends). Ideally something compiler-independent, but I also don't mind a compiler-specific extension (in that case preferably gcc), if on...
There is no standard way in C++. A simple approach is to pass the pass to the compiler path as a macro definition upon compilation. The syntax for that is compiler specific, but a build system generator can help with that. If std::embed proposal was accepted into a future standard, then following trick could work: std:...
63,924,895
63,926,054
How to make a C++ class gdb-friendly?
Consider the following example: std::string s = "Hello!!"; (gdb) p s $1 = "Hello!!"; Essentially, just providing the variable name is good enough to display the string. I don't have to, for example, type "p s.c_str()." Is gdb using any implicit operator to get the display string? I need to do something similar for my...
You need to write a pretty-printer for your class. It is not something you do in your C++ class, but something you do in gdb (although matching your C++ class). The easiest way to do that is through gdb's Python API (you can also use the Guile language). GDB already comes with pretty-printers for most of the standard l...
63,925,125
63,925,347
Get output of cmd command in real time in Qt
Im using this code in Qt to get output of a cmd commend QProcess c_output; c_output.start("some-exe", QStringList() << "param1" << "param2" << "param3..."); if (!c_output.waitForStarted()) std::cout << false; c_output.write("..."); c_output.closeWriteChannel(); if (!c_output.wai...
You can use waitForReadyRead instead of the waitForFinished , see at https://doc.qt.io/qt-5/qprocess.html#waitForReadyRead Here is a simple example with the usage: #include <QCoreApplication> #include <QFile> #include <QTextStream> #include <QProcess> #include <QDebug> int main(int argc, char *argv[]) { QCoreAppl...
63,925,320
63,941,096
How do I pass 'emcc' options through 'emcmake cmake/emmake make'?
I have a CMake project (C++) that I want to make available in JavaScript through WebAssembly. To configure it, I use emcmake cmake and to build it emmake make. I can compile parts successfully, when I do it manually: emcc --bind test.cpp But I want to profit from the advantages of emmake. I need the parameter --bind ...
It turned out, that you can pass the emcc options from within the CMakeLists.txt file, by using set_target_properties(...): CMakeLists.txt: cmake_minimum_required(VERSION 2.8) project(MyTest) add_executable(mytest test.cpp) set_target_properties(mytest PROPERTIES LINK_FLAGS "--bind") This approach works for nearly all...
63,925,350
63,925,612
LeetCode Question: Improve Execution Time w/o Hash?
My solution to find out if an integer is duplicated in an array, while correct, is getting rejected because the time limit LeetCode expects is exceeded. I understand that nested for loop is the culprit with an O(n^2). Is there a way to reduce this in any meaningful way without resorting to a hash? bool containsDuplicat...
The leetcode problem specifies no more than 30001 numbers between 2 and 30000 in value; only one number will be duplicated one or more times. We can make a 30001 sized array of unsigned char initialized to zeros, and then set an array val to 1 as we examine each one. Further, we check to see if we've already seen it ...
63,925,521
63,925,933
Unique/Smart Pointer Vector in c++
I am practicing using a smart pointer (in c++). And I am really stuck on a question: I need to code this representation, where normally one box represents the smart pointer, and the arrow points to a heap variable. In this question, the boxes are together, therefore it represents a vector of smart pointers. I have trie...
An instance of unique_ptr initially holds no value; it needs to be initialized first: unique_ptr<vector<unique_ptr<char>>> ptr_vec; ptr_vec = make_unique<vector<unique_ptr<char>>>(); Otherwise ptr_vec->push_back() will access a null pointer and the program will crash with a segmentation fault like you're observing. Bu...
63,925,547
63,941,556
Wait simulation time Omnet++
I need to modify UdpEchoApp (from Inet package) so that before it sends back the packet it waits "x" seconds of simulation time. I tried doing something like: simtime_t before; //something to calculate simtime_t after; if (after-before > x) {continue} else {do something and then recalculate after} but this crashes Qte...
Your code is wrong: simulation time is increased by simulation environment according to incoming events. In other words, simulation time is modified outside the standard methods that defines a behavior of a module. To simulate a delay during the simulation one has to use a selfmessage. In short: In socketDataArrived()...
63,925,636
63,928,397
Connecting mq client to mq server with encrypted channel using C++ API
I have a legacy app accessing MQ Server from an MQ Client using the C++ API. How is this API used to add encryption over the Server Connection Channel? I can't find a location where the certificate is provided to the imqChannel object.
You don't provide any code that is not working to help you with so I can provide only some general direction. You specify the cipher like this: pchannel->setSslCipherSpecification("TLS_RSA_WITH_AES_256_CBC_SHA256"); You can specify the location of the kdb and sth file like this: (note in this example it would expect t...
63,925,648
63,925,728
C++ Classes: Initializing attributes without constructor overloading
Coming from JavaScript and Python, I'm trying to understand the nuances and purpose around C++ class constructors. In the example below, why is it allowed to initialize attributes without a constructor? class MyClass { public: int a = 1; int b = 2; }; Does the default constructor include the above definitions/...
In the example below, why is it allowed to initialize attributes without a constructor? Because C++11 specifically added that feature. See Member initialization. Does the default constructor include the above definitions/initializations? Yes. This code: class MyClass { public: int a = 1; int b = 2; }; Is...
63,925,663
63,963,884
MiniDumpWriteDump() into a named pipe then ReadFile()
What I would like to do is use MiniDumpWriteDump() write to a named pipe and then read/write it myself. I am able to perform the dump successfully if I write the contents to a file directly. However, while writing to the named pipe has been successful the subsequent read/write operation does not go so well. I can read ...
It appears this cannot be done. See the comments for more information. Writing directly to a named pipe from MiniDumpWriteDump() cannot be done because the handle that is passed in must have the ability to seek. Named pipes do not have that functionality, therefore you must use a legitimate file handle.
63,926,055
63,926,577
why does mutiset don't act like set
Why is multiset a set while a set can only contains only different elements, while multiset can contain the same elements? It could of just be called sortedArray or sortedList. Even if it just wants a sorted "collections", why is it a set?
Why is multiset a set In mathematics there are two distinct concept of set and multiset. Standard library has two containers that model these concepts: std::set and std::multiset. These concepts are not the same and therefore container names are also different because they model different mathematical concepts.
63,926,529
63,926,774
Calling constructor of class member when using malloc
The following code breaks due to the constructor of std::string never being called, as the call to malloc seemingly doesn't call the constructors of the class members. How can I call the constructor for the std::string without using new? Or do I have to use placement new on the entire struct after memory for it has bee...
malloc is a C function, and has no knowledge of classes, constructors, etc. If you are dead-set on using this, you are going to have to always call placement new on each object (note: this requires including the header <new>), and also manually calling the destructor before deallocating. You will also need to store the...
63,927,298
63,927,366
C++ Why is my first data input with getline(cin, array[x]) is on the sameline and broken while my 2nd data input is fine?
#include <iostream> #include <iomanip> using namespace std; int main() { int person; cout << "How many person to data: "; cin >> person; int x = 0; int i = 1; string name[person]; string adress[person]; while(x < person){ cout << i << " person data" << endl; cout << ...
For starters variable length arrays string name[person]; string adress[person]; is not a standard C++ feature. Instead use the standard container std::vector<std::string> like #include <vector> //... std::vector<std::string> name( person ); std::vector<std::string> adress( person ); Or instead of two vectors you co...
63,927,837
63,929,938
How to properly use the aes cbc api from mbedtls
My current approach doesn't even produce the correct encrypted data as checked against golang's aes implementation. It also doesn't decrypt back to the original plaintext, but that's expected if the encryption step isn't working correctly. My best guess is that I'm misusing the api somehow. This is a self-contained exa...
Before calling mbedtls_aes_crypt_cbc to encrypt you should call mbedtls_aes_setkey_enc and before calling mbedtls_aes_crypt_cbc to decrypt you should call mbedtls_aes_setkey_dec. When both are called at initialization like in your code, the latter call to setkey_dec will overwrite important data in the context structur...
63,928,102
63,928,163
Code doesn't work in Visual studio, but work in C++ shell and CodeBlock, compiler issue?
#include <iostream> #include<string> using namespace std; void print_message(char *s) { cout << s << "\n"; } int main() { print_message("hello"); print_message("world"); } This code doesn't work in Visual studio, gives two error: error C2015: too many characters in constant , error C2664: 'void print_mes...
You are not allowed to convert a string literal to a char *. Your function needs to accept a char const * like this: void print_message(char const *s) { cout << s << "\n"; } Here's a demo.
63,928,304
63,928,600
"Symmetrical difference" for unsigned ints - assumed rollover
I made a simple function that I called symmetricDelta() which calculates the delta between value and previous "symmetrically". What I mean by that is: consider a number-line from e.g. 0 to ULLONG_MAX, where you connected the left and right ends of the number-line... To determine a "symmetric" delta, assume the change ...
Yes. The name is subtraction modulo 2^64. And it's identical to what your machine does with the instruction int64_t symmetricDelta(uint64_t value, uint64_t previous) { return (int64_t)(value-previous); } In C and C++, unsigned arithmetic is defined to wrap around, effectively joining the ends of the representable ...
63,928,734
63,928,766
In C++, what is the best way to allocate (and de-allocate) a very large array on a computer cluster?
Why does the following code produce an error, and how do I fix it? I have been working on this for 2 days, so I would appreciate any advice. Basically, I do not know how to allocate and deallocate a very large array on a computer cluster with 200 GB of memory on a node. What are the best practices for this? Thank you! ...
I don't believe that you actually need the contiguous array of this size. The solution is std::deque: this looks very similar to std::vector, but the elements are stored in chunks. The random access is constant, push_back is even faster than the vector's. This container is used for two major purposes: whenever you need...
63,928,820
63,929,095
Why am I getting this error message in c++ (error: cannot convert 'std::__cxxll::string' )
I am just starting out with C++ and I am stumped as to why I am getting this error. The problem occurs when I call display(students[i], marks[10][5]); Looks to me like I am passing the correct arguments and data types to the method. I would appreciate if somebody could point out and explain the problem. #include <iostr...
Your declaration and definition of display() do not match. You declared display() to take only a 1-dimensional array of ints, but you defined it to take a string and a 2-dimensional array of ints. When you call display(), the compiler hasn't seen the definition yet, only the declaration, so you get an error trying to ...
63,929,462
63,929,515
Problem converting one user-defined class to another user-defined class
I just get introduced to C++ OOP. I created two classes name Integer and Float and defined conversion constructor for every class. I have no problem converting Float to Integer, as shown below. The real problem comes when I remove the comment symbol to convert from Integer to Float. #include <iostream> using namespac...
When Float(const Integer&); is declared, the Integer class has been not declared yet. This should work for what you want: #include <iostream> using namespace std; class Integer; class Float { float x, y; public: Float() : x(0),y(0) {} Float(float a, float b) : x(a),y(b) {} Float(const Integer&); f...
63,929,668
63,938,966
cmake cross-compilation with sysroot returns wrong include paths
I am having an issue when trying to cross-compile (for an arm target) and including packages through cmake. Compilation works fine when compiled locally and also when cross-compiled without package dependencies. My toolchain file is: cmake_minimum_required(VERSION 3.3) set(CMAKE_SYSTEM_NAME Linux) set(CMAKE_SYSTEM_PROC...
Variable CMAKE_SYSROOT (and CMAKE_FIND_ROOT_PATH) re-roots only those paths, which are searched by different find_* commands: find_library, find_path, find_package(only search path for package file is modified). E.g. if find_library searches under /usr/lib by default, then with CMAKE_SYSROOT set it will search under ${...
63,930,098
63,930,164
how to pass in class' non-static method into class' data member's constructor
I have a class C with a method func. C also has a data member m_func_taker whose constructor takes a std::function argument. How can I pass in C::func into m_func_taker's constructor? I have some example code (click here to run): #include <iostream> #include <functional> template<typename out_t, typename in_t> struct ...
You could wrap the call to the method in a lambda: C() : m_func_taker([this](auto d) { return this->func(d); }) {} Here's a demo. To construct a std::function from a method of a class, you could use std::bind: using std::placeholders::_1; C() : m_func_taker(std::bind(&C::func, this, _1)) {} Here's a demo. From c++...
63,930,244
63,931,640
c++ issue with using commandline inputs in a forked execvp
When running the code below I get an incorrect output. I am fairly sure I am doing something wrong with the execvp call as I have tried changing everything and only this seems to be responsible. As far as I know the parameters for execvp should be the filename and the array which I pass using execvp(argv[0], argv). Rep...
For anyone curious turns out execvp(argv[1], &argv[1]) is the key to get it all working.
63,930,265
63,930,373
fgets() reading only last line
I'm trying to grab a specific line out of a text file. When using fgets() it seems to only read the last line. I'm aware that fgets() overrides the previous line it had read but it seems like its starting at the last line and then ending. The file I'm trying to read: PRETTY_NAME="Debian GNU/Linux 10 (buster)" NAME="De...
You appear to have inserted an extra semi-colon on the while loop line: while (fgets(buf, BUFFER_SIZE, fp) != NULL); This causes the loop to simply read each line but do nothing with it. The code inside the braces that you intended to be part of the loop runs only after the looping is complete and thus processes what...
63,930,374
63,930,443
How do I convert a cmake variable to a string in C++ code?
For example, in CMakeLists.txt, I can define path: add_definitions(-DMY_PATH="/my/path") In C++ code, I can access the variable by std::string my_path = MY_PATH This works fine. Now, if I instead define a variable in CMakeLists.txt as follows: add_definitions(-DMY_PATH=${CMAKE_BINARY_DIR}) Then, I get the following ...
When you use this defintion: add_definitions(-DMY_PATH=${CMAKE_BINARY_DIR}) you will get something like this in your code: std::string my_path = /home/my_path which obviously leads to a syntax error, you need to add double quotes: add_definitions(-DMY_PATH="${CMAKE_BINARY_DIR}")
63,930,510
63,930,614
My For Loop condition is not working even when the expression is
So I am trying to find the number of digits in a given int. The way I opted to find the digits was to divide the given int by powers of 10. Since I would be dividing by integers, the code would eventually reach a 0 when 10 is raised to a high enough power. There would be a tracker that tracks every iteration of this an...
First, you are NOT dividing it by integer. pow() returns double according to the c++ reference. Therefore, the result of x / pow(10, i) would be double. ruining everything. There is two option: Use x / (int)pow(10, i) != 0 within the for loop condition. And PLUS 1 to the result. But be aware, floating result of pow() ...
63,930,585
63,930,613
Trying to create a random number generator using Arrays and getting Identifier "i" is Undefined. Can anyone see the problem?
Trying to create a random number generator using Arrays, but the " a[i] = rand();" portion of my code creates an error of the type "Identifier i is Undefined". Can anyone find where I am going wrong here? Thanks #include <iostream> #include <string> #include <array> using namespace std; int main() { int a[10] = ...
$ clang++-7 -pthread -std=c++17 -o main main.cpp main.cpp:15:11: error: use of undeclared identifier 'i' a[i] = rand(); ^ main.cpp:13:38: warning: for loop has empty body [-Wempty-body] for (int i = 0; i < size(a); i++); { ^ main.cpp:13:38: note: put the ...
63,930,630
63,985,589
How to skip to next line in an ofstream object in c++
I'm trying to make a hash program that makes hashes for you. I know it's been done before but I'm trying to recreate it. The problem I'm having is that I'm trying to add logs for each hash and output it to a "DataLog.txt" file. So far it's going Great! The only problem is that I'm trying to add a newline before each ou...
Ah I see, you want to add a line before each line. I think what you are looking for lies in file << input << hash; So since file is your fstream output, you can treat it like cout. So the solution here would be file << input << hash << endl; Now also make sure to open file in append mode by file.open(filename, ios::app...
63,930,667
63,934,197
How to swap rows of Mat in opencv?
I want to swap two rows in a Mat M, and I have two minor problems: To swap two rows I will need a MatrixRow temp(pseudo code) to backup the first row to be replaced. But I don't know what should be the type of a row of a Mat. Mat temp = img.row(i).clone(); img.row(i) = img.row(j).clone(); img.row(j) = temp.clone(); ...
img.row(i) = img.row(j).clone(); and img.row(j) = temp.clone(); do not copy the cloned data because they invoke the following assignment operator Mat& cv::Mat::operator= (const Mat& m) See the documentation Matrix assignment is an O(1) operation. This means that no data is copied but the data is shared and the re...
63,931,047
64,014,377
System::Device::Location::GeoCoordinate returns wrong Latitude and Longitude
i have implemented the GeoCoordinate in my program for receiving the geographic coordinates, as shown below: double lat, lon; GeoCoordinate(lat, lon); GeoCoordinate^ coord = gcnew GeoCoordinate(lat, lon); lat = coord->Latitude; lon = coord->Longitude; geo->Text = "lat " + lat + " lon " + lon; for some reason i get...
so I figured out the problem... please see below code: GeoCoordinateWatcher^ watcher = gcnew GeoCoordinateWatcher(); watcher->TryStart(false, System::TimeSpan(System::TimeSpan::FromMilliseconds(1000))); lat = watcher->Position->Location->Latitude; lon = watcher->Position->Location->Longitude; it seems that I nedd...
63,931,100
63,931,422
Can't pass lvalue to construct an rvalue
Is there anyone who can help explain why UseString in my following example cannot accept an lvalue as a parameter? I know a temporary String is created in my case, but I cannot explain why it has to accept an rvalue here. #include <utility> using namespace std; struct String { String(const char* cstr) { }...
The problem is because UseString(cstr); does not do what you think it does. It is actually a variable declaration, not a constructor call. It is treated exactly the same as UseString cstr; And cstr was already declared earlier, hence the error. See Which part of the C++ standard allow to declare variable in parenthesis...
63,931,236
63,931,353
Class Function that Inserts values into a sorted array without ruining the order
So I am really confused on the logic here, I get the general Idea of taking my values in 1 by 1 and comparing them to the elements in the array. If the value is larger move on to the next element, if the value is smaller or equal to the element move over all the elements over 1 index and replace the original index with...
If I understood what you want, reading the array backwards should solve the problem. for (int i = 0; i < capacity; i++) { if (val > arr[i]) { for(int x = capacity - 1; x > i; x--) { arr[x] = arr[x - 1]; } arr[i] = val; break; } }
63,931,489
63,931,636
Is there a simple way for splitting one line of input separated by a space character into integers in C++?
I am a C++ beginner, and I have been working on a project in which you have to input some integers separated by a space and the program will have to output all possible arrangements of the integers. I know that in python, this could be done using [int(item) for item in input().split()], but I don't know how to do the s...
You see, you create a vector of integers from the string and then simply permute the vector: #include <algorithm> #include <iostream> #include <iterator> #include <sstream> #include <string> #include <vector> int main() { std::string str; std::getline(std::cin, str); std::istringstream iss(str); std::v...
63,931,629
63,931,827
C++ What's the best way to implement a Priority Queue with varying priority functions?
The accepted answer I've seen for swapping out a priority queue comparator is to overload the operator in a new compare class. class Foo { }; class Compare { public: bool operator() (Foo, Foo) { return true; } }; int main() { std::priority_queue<Foo, std::vector<Foo>, Compare> pq; return...
Do I have to make 10 different compare classes or is there an easier way to do this? You don't have to. The priority_queue requires that the comparator taking a Foo and return bool - with the default one is std::less template< class T, class Container = std::vector<T>, class Compare = std::less<typename C...
63,931,928
63,933,761
Different results when trying to use std::copy() with std::back_inserter to read from std::cin
When I was writing this answer, I was trying to scan a space-separated input string and store it in a vector. A user suggested the use of std::back_inserter and std::copy() to accept the input, over usage of std::istringstream: std::copy(std::istream_iterator<int>(std::cin), std::istream_iterator<int>(), std::back_inse...
I have figured out what's happening. When you use std::getline() to read some text and then put it in a std::stringstream to process it with a while loop, you read exactly one line of text (up until the enter key) and then stop reading input. When you use while(std::cin>>x) or use std::copy with a std::input_iterator i...
63,932,008
63,942,738
How do I define and load a resource in a Visual C++ project?
The code below compiles and runs. When I debug it, however, the resource is NULL and the size is zero. I imported "Resources\title.display.png" using the wizard, so I have to believe the path to the image is right. No error is thrown. These are the three files that comprise the project. I have wittled it down to t...
You are storing your image resource as a PNG resource, not an RCDATA resource. As such, when calling FindResource(), you need to change RT_RCDATA to TEXT("PNG"): HRSRC resource = FindResource(NULL, MAKEINTRESOURCE(IDB_PNG1), TEXT("PNG"));
63,932,415
63,932,556
Is there a function that can access a timer's functionalities (i.e. start and end the timer) in C++?
I am a C++ beginner and I have been working on a C++ question where I hope to look at how my algorithm is working. I want to be able to start and end a timer anywhere in the main method in a short and simple way if I wished (so that it doesn't really influence my function's CPU during timing). I hope to directly get th...
You can check chrono library, type on YouTube "The cherno Timing in C++" à very useful video for a beginner.
63,932,505
63,932,506
Problems Building C++ Static Library for XCode iOS
I have a large iOS project in Objective-c that also has a large number of C++ classes in a 6 subfolders. If I have all of the C++ source code in the iOS project and compile from the source files, everything compiles and works just fine. All good so far. I wanted to move all of this C++ code to a static library, so I c...
OK, So after a bunch of messing around I realized that just including the folders into the Static Library project didnt work. I had to create individual Groups for each folder and then import all of the files into those Groups as files in the folders. As there were multiple levels of files this was a pain in the ars...