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
67,369,741
67,369,888
Nested function template instantiation without forward declaration compiles on GCC but not on clang
The following doesn't compile in clang, but does in GCC (godbolt): template <typename K, typename V> std::ostream& operator<< (std::ostream& o, const std::map<K, V>& map) { const char* sep = "{"; for (const auto& x : map) { o << sep << "{" << x.first << ", " << x.second << "}"; sep = ", "; ...
Clang is right. You should move operator<<'s declaration for std::vector before operator<<'s definition for std::map. In unqualified name lookup, (emphasis mine) For a dependent name used in a template definition, the lookup is postponed until the template arguments are known, at which time ADL examines function decla...
67,370,379
67,370,926
Linking shared library that also links a different shared library in cmake
I am currently trying to create a C++ program in Ubuntu that embeds a shared library. For this I have locally the .so file (in my case: libSimpleAmqpClient.so). The library itself also calls preinstalled shared libraries (in my case: librabbitmq.so and librabbitmq.so.4). I use the following CMAKE code: cmake_minimum_re...
The shared library files can identify their dependencies on their own during execution, Given that you have linked them during the compilation process Here's a Link to Read about that. Linking with dynamic library with dependencies What cmake code below makes sure that compiler ( linker ) finds all the required functio...
67,370,445
67,370,638
I am not being able to open my Qt exe. file outside of Qt's IDE
I am developing a program using Qt and it is opened normally whenever I open it from Qt's IDE, though when I try to open it directly from the exe file in the debug folder it simply requests a lot of dlls and even if I download all dlls requested. I already have VC++ installed. The error I am getting: https://i.stack.im...
There are several tools I just want to mention that can be helpful here. The first tool is Dependency Walker that can help identify the missing DLLs, the dll versions that are being used, and the path to the dlls. The other tool is provided by Qt called WindeployQt which copies all the Qt dependencies in your applicati...
67,370,701
67,370,982
I can't assign the struct node's variables in linked list class. when I assign them to anything it creates undefined behaviour
//method for printing list void printList(const ReservationList& ls){ for(int i = 0; i < ls.getLength(); i++){ std::cout<<"ls["<<i<<"]== "<<i+1<<ls.retrieve(i,i+1)<<std::endl; } } //main method int main(){ ReservationList r; std::cout<<"program starts!"<<std::endl; std::cout<<"before printing empt...
This code snippet ReservationNode* tmp; std::cout<<"inside insert 1"<<std::endl; tmp->Code = resCode;/*mistake is hear */ std::cout<<"inside insert 2"<<std::endl; tmp->next = NULL; invokes undefined behavior because the pointer tmp is uninitialized and does not point to a valid object of the type ReservationNode. It s...
67,370,772
67,371,867
Compiler differences with use of templated overloads
I have a pretty specific situation where I'm feeding a bunch of data to a hasher-like class. In particular, one data type that I use has a member whose type depends on the supertype's type parameter. Long story short, here's a piece of code that illustrates this behaviour : #include <assert.h> #include <iostream> #incl...
Thanks to feedback from Igor Tandetnik, I got rid of the ::Range-specific overload and simply went for checking std::is_same_v<T, std::string>. A little less modular than I'd like, but it'll do the trick. // A single function will do the trick template <class T> Catcher& operator<<(Catcher& c, const ValueOrRange<T>& v)...
67,371,551
67,381,206
extern int main(int argc, char* argv[]) use?
I've been reading SFML's source code. I found the way it wraps the win32 in a fashion like this: #ifdef _WIN32 //something like that #include <windows.h> extern int main(int argc, char* argv[]); int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, INT) { return main(__argc, __argv); } #endif so line 4 I see this typical...
What are the extern main and return main(__argc, __argv) doing? If you are compiling on a windows platform, SFML defines the WinMain entry point for you, and calls your main(int argc, char* argv[]) with __argc and __argv which are explained by the relevant documentation: The __argc global variable is a count of the ...
67,371,647
67,371,677
C++ Menu Ordering System won't accept multiple words when inputting to the txt file
My code below, whenever I input the menu items, will automatically end the program if I add more than one word such as "Tequila Sunrise" rather than "Tequila". How do I fix this to make it so I can add items with more than one word in the name? #include <iostream> #include <fstream> #include <string> using namespace st...
Use std::getline(): while (i == 1) { cout << "Please enter your next drink: "; std::getline(std::cin >> std::ws, myDrinks); ....
67,371,974
67,397,888
Parallelizing my custom compiler with out of order execution
I have built my own parser that, for now at least, will only deal with statements similar to, return a * b * c * (d + e) / f What I will see while walking along the Abstract Syntax Tree (AST) that it generates looks like this (in the exact order that I see it, and in a hopefully descriptive pseudo-language): RETURN_STM...
You're essentially solving a constraint programming problem. You have constraints like "operation a depends on result of b", "operation a result is available in 3 clock cycles", "a and c share the same resource" (e.g., a multiplier), etc. One quick and dirty trick of how to get such solutions for free is to simply reus...
67,372,070
67,372,243
QListWidget add item at the bottom of the list
I'm making a messaging app using Qt5. I use a QListWidget to display the messages, and I want the message that the user sends to be added at the bottom of the list. I have tried this: QString message_content = "new message"; messages_list.insertItem(0, message_content); but the message still appeared at the top of the...
You have to use the addItem() method: messages_list.addItem(message_content);
67,372,097
67,372,176
std::vector<char> VS std::string, which one is faster?
I've been messing around with cellular-automata for a while now, and the way I chose to implement them is by creating a 2D vector of cells, where each cell was initially a vector of integers itself (because I want each cell to store more than one value), which I later changed to short unsigned integers, and then to cha...
which one is faster? Depends. Either one, depending on how you use them. You can find out whether one is measurably faster than the other by... measuring. They both use fundamentally the same abstract data structure, and have the same asymptotical complexity for all operations. according to my surface-level knowledg...
67,372,416
67,372,615
how would I compile multiple files in a folder?
so, I have decided to completely write my game (turn based RPG) in C++. I have seen other people on youtube create a folder with different cpp files and somehow they compile it all. my question is, how would I compile multiple files in a folder? if needed I am using MSYS.
Using cmake You can either write a makefile, which would contain all the files to be compiled in a folder or for a better management you can use cmake to compile all the files into a library and use them again. By using cmake you can efficiently maintain and build a huge code base. Lets say, your Main directory has th...
67,372,693
67,372,769
Partial specialization C++
Good day! I am trying to build a template class with its several partial specializations as follows: #include <iostream> struct MainT {}; struct Foo {}; template <int dim> struct Tensor {}; template <int dim> struct Bar { using Sub = Tensor<dim>; }; template<typename T, typename R> struct A { A() { std::co...
There is no 1:1 relation between Bar<dim>::Sub and dim as there is between Bar<dim> and dim. Consider you are a compiler. I tell you Bar<2>, then you know "ah ok, they want dim=2". That is: Given Bar<2> you can deduce dim=2. I tell you Tensor<42>, then you cannot possibly know that I actually meant the Tensor<42> that ...
67,373,209
67,374,393
pass a variable into curl_easy_setopt C++
how to pass a global variable into curl_easy_setopt int agent_num = rand() % 100000; std::string agent_name = "https://127.0.0.1:443/agent/" + agent_num; curl_easy_setopt(curl, CURLOPT_URL, agent_name); Ive tried different things and they give giving me a seg fault any help thanks!
std::string is not automatically converted to char *. Use its c_str() method for that: curl_easy_setopt(curl, CURLOPT_URL, agent_name.c_str());
67,373,307
67,378,304
MacOS M1 -> fatal error: 'GLFW/glfw3.h' file not found
I have a project (here) that works both on Linux and intel MacOS, but in my Mac m1 it doesn't. Whenever I try to compile it, I get the following errors (ops.: I'm using vscode m1 native): pedrohaccorsi@MacBook-Air-de-Pedro dev % make g++ -o app src/glad.c src/AudioManager.cpp src/Character.cpp src/SceneManager.cpp src/...
My issue was partially solved. There were two problems, GLFWand SDL2. GLFW The fix was the same proposed in this thread; in a nutshell it consists in: $ nano ~/.zshrc > export CPATH=/opt/homebrew/include > export LIBRARY_PATH=/opt/homebrew/lib This will tell the compiler to look for things in opt/homebrew, which is wh...
67,373,346
67,373,730
How to make a template class object as a tuple?
class Farmacie { string proprietar; string denumire; int angajati; vector<int>profit; public: Farmacie(){} }; class Farmacie_online:public Farmacie { string proprietar; string web; int nr_vizitatori; int discount; public: Farmacie_online(){} Farmacie_onlin...
std::tuple doesn't have accessor like .first and .second. Instead, you would need to use std::get<INDEX>(yourTuple) to access each elements. If you want to assign each item separately, you could do: std::get<0>(date[index]) = f.web; std::get<1>(date[index]) = f.nr_vizitatori; std::get<2>(date[index]) = f.discount; Or,...
67,373,764
67,373,839
Passing Vector as a Reference to Std::Tuple and Modifying It
I am trying to use tuples inside a priority_queue and my tuples contain vectors. I want to be able to modify these vectors but when I delete items from a vector, it does not change the actual content. I think I am modifying the values instead of references but I am not very experienced with c++ and need some help with ...
I think I am modifying the values instead of references That is the correct diagnosis of the problem. As has been pointed out in a comment, the other issue is that you cannnot modify modify elements in a std::priority_queue directly. You'll have to: Get an element by value. Modify the element. Pop the element from t...
67,374,065
67,397,861
How do I find out the type of the GLuint id passed to glGetObjectLabel?
OpenGL sends all debug message through the callback with the declaration: void MessageCallback(GLenum eSource, GLenum eType, GLuint eId, GLenum eSeverity, GLsizei sLength, const GLchar* strMessage, const void* userParam) The GLuint eId resembles the obj...
I don't think this can work at all with OpenGL generated messages. The MessageCallback eID is a message identifier according to the web pages at the Khronos web site and the OpenGl SuperBible. It is not guaranteed to be an actual OpenGL object. Could be an incrementing serial number. Even if the eID is a texture/buffer...
67,374,463
67,374,512
Two classes that refer to each other in their constructor
I want to create one 2-dimensional vector datatype and one 3-dimensional vector datatype, but both of them should be compatible to eachother. Here are the class definitions class vec2; class vec3; class vec2 { public: FLOAT x, y; vec2(FLOAT X = 0, FLOAT Y = 0) { x = X; y = Y; } //...
Since vec2::vec2(vec3 V) is implemented in the .h file, make it inline. inline vec2::vec2(vec3 V) { x = V.x; y = V.y; } Otherwise, every .cpp file that includes the .h file has a non-inline implementation of the constructor. That causes the problem reported by the linker. The other option will be to move the d...
67,374,635
67,374,874
Inversion of two matrices on a gpu using cublasSgetriBatched
I am new to cublas. I want to calculate the inverse of two matrices in parallel on a GPU. The matrices are [4 8;3 9] and [5 2;1 7]. Is it possible to do so using cublasSgetriBatched? Here is my code, I am getting incorrect result with this. Here I took 2x2 matrices, but I want to find a way to solve this problem for mu...
You have at least 3 usage problems with your code: You are not setting up the array-of-pointers for d_A correctly. You are not setting up the array of pointers for c_A correctly. Your final cudaMemcpy statement for r_A is only transferring one matrix worth of data (N*N). The following code has the items fixed, and ru...
67,374,637
67,374,702
How to write a custom hash_function for std::unordered_map<T> in cpp?
I want to write my own Hash_function for an std::unordered_map instead of using the default one. I could find unordered_map::hash_function() on many websites. But using this i can only get the Hash value generated, using something like this : /*Sample map of strings*/ unordered_map<string, string> sample; // inserts ...
std::unordered_map is templated off of a Hasher that defaults to std::hash<Key>. You can change your variable to std::unordered_map<string, string, CustomHasher>. unordered_map will then default construct a CustomHasher (it can also be passed in the constructor if you can't default construct your hashing object). A cus...
67,374,683
67,374,786
Unexpected binary output
I'm writing a code to add the first and last integer of a number. But the output results in binary instead of integer. //Code #include <iostream> #include <string> using namespace std; int main() { int t, n; cin >> t; for (int i = 0; i < t; i++) { cin>> n; string s = to_string(n); c...
You should at least write int a = first - '0'; int b = last - '0'; cout << a + b;
67,374,756
67,375,791
I am getting error 2 in my winreg function
My code: HKEY hKey; char *path = "SYSTEM\\CurrentControlSet\\Control\\IDConfigDB\\Hardware Profiles\\0001\\HwProfileGuid"; LONG result = RegOpenKeyExA(HKEY_LOCAL_MACHINE, path, 0, KEY_ALL_ACCESS, &hKey); QString q = QString::number(result); if (result == ERROR_SUCCESS) { QMessageBox messageBox1; messageBox1.cr...
You have HwProfileGuid in the wrong place. HwProfileGuid is a value inside of the 0001 key, but you are trying to open HwProfileGuid as a sub-key of 0001 instead, which is why you are getting error 2 (ERROR_FILE_NOT_FOUND), because there is no sub-key named HwProfileGuid. Also, KEY_ALL_ACCESS is too many rights to requ...
67,375,163
67,375,828
cmake find_package, find_library can locate glfw, but TARGET glfw is false
my glfw3 was built from source and a FindGLFW.cmake was used to find the library: find_path( GLFW_INCLUDE_DIR NAMES GLFW PATHS include) find_library( GLFW_LIBRARY NAMES glfw glfw3 glfw3dll PATHS lib) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(GLFW REQUIRED_VARS GLFW_...
Your FindGLFW.cmake file is insufficient. In fact, it shouldn't be needed or exist at all. GLFW provides a config package already. Here's how you should build and use any well-behaved CMake package: First, get the sources, build the package, and install it to a local prefix: $ git clone https://github.com/glfw/glfw Clo...
67,375,628
67,375,774
Why is the C++ standard library aligning large string buffers to 32 bytes?
I'm decompiling a binary built in C++ and have noticed that upon allocation and reallocation strings buffers are being aligned to the nearest 32 bytes when the buffer size ('alloc_bytes') is >= 0x1000. Here is my decompiled code illustrating this: if (alloc_bytes < 0x1000) { new_char_buffer = STD__allocate_bytes(al...
While I don't know the official reason your compiler/library behaves this way, I can certainly see an immediate benefit: SIMD. Single Instruction Multiple Data instructions are operations that allow you to get very cheap parallelism. However, they do have some requirements before you, or more likely your compiler, can ...
67,375,725
67,376,179
C++ Makefile, is it possible to factorize it even more?
I have a project for school and I want to write a Makefile, I have seen some examples of using Makefile with multiple source directories and multiple executables but still could not implement it properly to my Makefile. PS: I'm using doctest for the unit testing (and I can't change it). Here is the project structure (a...
Mostly your makefile is pretty good. There are some simplifications you can make, but they're just syntax and not really performance etc.: DEP_DIR := .dep/ You never use this by itself so if you change its definition to: DEP_DIR := $(BUILD_DIR).dep/ you can simplify the references to it. DEPENDS := $(patsubst %.o, $...
67,376,425
67,376,668
Failing regex_match for "/someKey someValue /someOtherKey someOtherValue ..." with regex "\/[^\/]*"
I am trying to do a regex match with the following code: std::wstring a1 = L"/key1 val1 /key2 val2 /key3 val3"; std::wregex re(L"\/[^\/]*"); std::wsmatch ws; if (std::regex_match(a1, ws, re)) { //do something } I am expecting to see the following pair of matches: /key1 val1 /key2 val2 /key3 val3 However, I am n...
Couple of things you are doing wrong. The problem is that std::regex_match must match the entire string but you are trying to match only part of it. You need to either use std::regex_search or alter your regular expression to match all three parts at once: You are not required to escape slashes in c++. Your regex s...
67,376,692
67,388,118
C++ rtsp stream in Windows Forms
I have a program that receives rtsp video from the camera and transmits it to the picturebox. It only works for a few seconds, then the program hangs, help find the error. private: System::Void start_Click(System::Object^ sender, System::EventArgs^ e) { if (start->Text == "Start stream"){ start->Text = "Stop stream...
Fixed by changing while(expression) cv::VideoCapture stream = cv::VideoCapture(ip[n]); cv::Mat frame; if (stream.isOpened()) { flag = true; while (cv::waitKeyEx(1) != 27) { stream.read(frame); System::Drawing::Graphics^ graphics...
67,377,087
67,377,449
Algorithm name?: Concatenate the ranges returned by a function applied to each element of a range
Maybe I'm missing something. Is there a function in <algorithm> that does this? If not, what would you call it? It seems like a particular flavor of transform-reduce that is so specific it needs a name: template <typename Iter, typename OutIter, typename Fn> void transformed_concatenated(Iter beg, Iter end, OutIter out...
With the ranges and views introduced in C++20, you could write: std::ranges::copy(input | std::views::transform(f) | std::views::join, std::back_inserter(result)); Here's a demo. Note that your function f is incorrect. It needs to be const auto f = [](int n) { ...
67,377,288
67,380,955
How to create pointer variable from a reference type in c++?
I want to create a global pointer so that all the functions can access the reference. I've tried assigning the address of reference to a pointer but when I try to access the values getting compilation error. vector<vector<char>>* table; class Solution { public: void solveSudoku(vector<vector<char>>& board) { ...
It should be (*table)[0][0]. table[0] is equivalent to (*table) (the vector of vector board). so table[0][x] is just board[x]. and vector is not streamable.
67,377,859
67,381,264
ambiguous template specialization in variadic function template
I am trying to write a variadic function template to calculate the byte size of a struct. This is going to be used in a network programming project I am working on. The first step I came up with this without the variadic template that works: #include <cstdint> #include <iostream> struct Position { int32_t x; i...
You don't use variadic... You might do (C++17) template <typename ... Ts> constexpr std::size_t sizeT() { return (0 + ... + sizeof(Ts)); } template <> constexpr std::size_t sizeT<Position>() { return sizeT<decltype(Position::x), decltype(Position::y)>(); } Demo But sizeT<Position, Position> would return 2 * sizeo...
67,377,988
67,388,083
Reading pointer from Rust in C
I'm trying to use Rust with C, by creating DLL and connect it to my C-project. And now, I have some troubles with passing pointers. I wrote some example and tried to understand this problem: #[no_mangle] pub extern fn hex2ascii(hex_len : usize, hex_in: *const u8, ascii_len : &mut usize, ascii_out : *mut c_char) -> *mut...
If you got everything to build and link properly the solution you're looking for is inside of std::ptr::copy. It will copy N bytes from source to destination. "std::ptr::copy is semantically equivalent to C's memmove, but with the argument order swapped." If you've stumbled across this post, and haven't got linking or ...
67,378,659
67,378,727
Visual Studio 2019 debugger steps into header file instead of cpp
I have created a small c++ application with a header file, a cpp file, and a main function. I expected that the header file would be an interface, that would just define my functions and properties, but the cpp file would be the one to implement. However when I create my files, in my main function I have a breakpoint a...
Two things: You have to write in the cpp file void DbConnection::ConnectToDatabase(const std::string databaseName) { ... } and so for the Retrieve function to tell the compiler that this is the function of the class. You actually implemented the function in the header file when you put {} after the function declara...
67,378,691
67,378,805
Can I initialize std::unique_ptr of array without default initialization ( I want just let it have dummy value )
Can I initialize std::unique_ptr of array without default initialization ( I want just let it have dummy value ) I'm trying to use unique_ptr of array for preventing memory leak. but It looks always initializing values with 0 ( look "movups XMMWORD PTR [rax+48], xmm0" ) I don't need this. I just want vector2 have dumm...
make_unique performs value-initialization on the array. You can use make_unique_for_overwrite (since C++20) instead, which performs default-initialization. a.vector2 = std::make_unique_for_overwrite<Vector2[]>(10); Before C++20, you can new the array by yourself. a.vector2 = std::unique_ptr<Vector2[]>(new Vector2[10])...
67,380,018
67,380,199
Why does the Fibonacci Series using Iterator and Range throw error
I am practicing C++ code snippets in the CPP Crash Course Book (Chapter-8, Exercise 1), Link the below does not compile and the error of the program has been provided below. It would be helpful if any suggestions or links for understanding is provided. :). #include <cstdio> struct FibonacciIterator { bool operator!...
Your begin and end member functions return different types. Pre-C++17, these types need to be the same, as the error message says error: inconsistent begin/end types in range-based ‘for’ statement From C++17, this restriction on range-for loops was relaxed As of C++17, the types of the begin_expr and the end_expr do...
67,380,087
67,380,263
C++ multi-threading Error: Single producer Multiple consumer
I am trying to achieve Single producer Multiple consumer , however below code is not able to compile. Can someone help with this error ? Also would it work to wake all threads from this pool & a random thread would be able to acquire the lock? TIA ` threadPool/main.cpp:4: /Library/Developer/CommandLineTools/usr/bin/...
std::move(testObj) should be &testObj (a pointer to the object to call consumer on) - or std::ref(testobj) (which becomes a reference_wrapper (holding a pointer to the object too). You should call produce at least as many times as you have threads, or else the program won't finish. You don't need to unlock manually. T...
67,380,450
67,400,522
How to serialize / deserialize INTs in C++
So, I´d want to implement simple serialization for some int variables in C++ and I really don´t know how... My goal is the following: I essentially want to be able to convert any integer to binary, preferably with a simple function call. // Here´s some dummy code of what I essentially want to do int TestVariable = ...
First of all, there is a little "inconsistency": you're asking for binary serialization, in something that looks like a text file. I will assume you really want a binary output. The only thing to take care about when serializing integers is the endianness of the machine (even though most of machines are little endian)....
67,381,540
67,382,220
Copy elision and trivially copyable types
From the standard 6.7.7 (temporary objects), we can see: When an object of class type X is passed to or returned from a function, if X has at least one eligible copy or move constructor ([special]), each such constructor is trivial, and the destructor of X is either trivial or deleted, implementations are permitted to...
Does it mean that copy elision is not mandatory with trivially copyable types? In principle, yes, but the goal of the section you quoted was not to exempt POD types from copy elision but to bypass ABI restrictions on how objects are passed in function calls. It allows POD objects to be passed via registers. This is t...
67,381,553
67,381,698
Function Objects & multithreading Pool giving same thread ID
For below program, thread Pool always picks the same thread ID 0x7000095f9000! Why so? Should every push condi.notify_one() wake up all threads same time? What could be the reason same thread ID get picked? Computer supports 3 threads. Any other info on using function objects would be helpful!! O/P Checking if not empt...
The very short unlocking of the mutex that happens in the consumer threads will in your case most probably let the running thread acquire the lock again, and again and again. If you instead simulate some work being done after the workload has been picked from the queue by calling consumerMain (which sleeps a little) in...
67,381,677
67,393,170
Why does PoCo HTTP server consume CPU on complete idle
I've experimented with PoCo HTTP server and found it consumes some CPU even on complete idle. This is not high usage but if we have a lot of instances running it may become a problem.
For network services using poll it's normal to permanently use small amount of cpu time. Nginx and redis also have some cpu consumption on idle. To achieve zero cpu usage on idle you well have to use another approach to network communications.
67,382,022
67,382,275
I got an infinite while loop with this string
so I got this part of my code here: string stringparam; string stringparam1; double d; unsigned x; cout << "Welcome" << endl; cout << "Choose one (ASUS, MSI, Gigabyte, ASrock)" << endl; cin >> stringparam; while (stringparam != "ASUS" || "MSI" || "Gigabyte" || "ASrock") { cout << "you gave bad input \n" << en...
Here the main problem is that you can't do what you want with "or" operator, because in that way while condition it will always be True. For example: if you type "ASUS", the result of while is True, this because you need ONLY one || expression = True to "come in" while's body (this caused infinite loop). So you have to...
67,382,110
67,382,261
Lifetime of primitive/object value when it's returned from a function
class Foo { private: int num; std::string str; public: Foo& operator=(const Foo& rhs) { this->num = rhs.num; this->str = rhs.str; return *this; } Foo& operator+(const Foo& rhs) { Foo tmp(this->num + rhs.num, this->str + rhs.str); return tmp; } }; If I w...
You already correctly asserted that tmp is only local to Foo::operator+ and thus the returned reference is invalid (a dangling reference). But int value(this->num + rhs.num) is passed well without problems. I think you refer to code like this: int operator+(const Foo& rhs) { int tmp(this->num + rhs.num); return...
67,382,346
67,383,780
In C/C++, how do I determine if a library is statically linked or not
I have a static library that provides some functionality. I have applications that use this library. Some of these applications are command line applications or run as daemons/services. Some of these applications are GUI applications. The library offers functionality to provide GUI elements to allow it to be configured...
This does not need to be done as runtime. The common solution is to use a weak symbol. This is a symbol in a library that's used when there is no "normal" symbol to link against. Your base library provides the weak symbols, your GUI library optionally provides replacements, and the static linker figures it out.
67,382,448
67,382,540
What's the real type of int (*T::*)(long);
This is the sample code: typedef int (T::*t1)(long); typedef int (*T::*t2)(long); t1 p1 = NULL; t2 p2 = NULL; The type t2 get's extra * (by mistake), but this code compile and run OK. But when t2 is not NULL, it gets error: struct T { int func(long) {return 0;} }; t2 p2 = &T::func; error: cannot convert ‘int (...
Eliminate the pointer-to-member bit of syntax (by applying the spiral rule heuristic), and a specific type stands out: int (* /* T::*t2 */)(long) -> int (*)(long). So t2 is a pointer to a member of T, which is itself a pointer to a free function. int bar(long) { return 0; } struct T { int (*func) (long) = &bar; };...
67,382,785
67,420,979
Why does MinGW-w64 floating-point precision depend on winpthreads version?
I use the MinGW-w64 g++ compilers 10.2 and 10.3. I have built both myself using https://github.com/niXman/mingw-builds. There is an oddity with g++ on Windows: the main thread of an application will do floating-point operations with double precision, but additional threads will do them with extended precision. This can...
The described behaviour is a MinGW-w64 bug. Different to the description in the original post, it has nothing to do with g++ versions, but only with MinGW-w64 versions. It has been reported here: https://sourceforge.net/p/mingw-w64/bugs/897/. What does that mean? With mingw-builds the MinGW version can be specified whe...
67,382,826
67,383,357
Exposing C++ unmanaged code class pointers to C# with C++/CLI
Apologize for my very basic knowledge of C++/CLI, but it has only been introduced to me recently as a necessity. I am trying to create a wrapper for an unmanaged C++ library using C++/CLI. I have followed this helpful guide and can confirm that it (somehow) does the trick. The problem I have is with C++ pointers which ...
My C# knowledge, is not quite as good as my C++, just as a note. I dont quite get what you are doing here: UnmanagedCode::ClassB* classB() { return m_Instance->classB(); }; This line returns a pointer to a ClassB object, that you retrieve in C#. This would require the ClassB to also be a managed object, as far as i kn...
67,382,919
67,383,099
SIGTRAP does not show up if I write "cout"
I am writing a Particle-In-Cell code to simulate plasma-laser interactions. The core of the code is the following (all the variables have been initialized properly before this): for(int it = 0; it < Nt-1; it++) { //cout << "it = " << it << endl; pos = pos_update(pos, vel, qm, E_P, it); ...
SIGTRAP suggests that your C++ code has Undefined Behavior. But SIGTRAP is just one of the infinite ways in which Undefined Behavior can manifest itself. It's not that strange that adding another statement causes Undefined Behavior to show up in a different manner. As for your comment, new[] and delete are primitives t...
67,382,974
67,383,369
Trying to run grep comman using exec
I am trying to run the grep command in my child process after fork system call. It displays an error: grep: .: No such file or directory. My code for exec is below: execl("/bin/grep","grep","a","*.*",NULL); If i replace * . * with a file name it works fine. What is my mistake?
The argument *.* is passed on to grep literally. It's not interpreted by the shell - so grep tries to open a file named *.* (and fails). If you want to do shell like globbing from within your program, you could take a look at the glob functions: #include <glob.h> int glob(const char *pattern, int flags, int (...
67,383,394
67,383,527
Cannot understand uncommon syntax
I have recently come across a function which calculates the day of the week for any given date. The function is shown below. unsigned int getDayOfWeek(const unsigned int day, const unsigned int month, unsigned int year) { static unsigned int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; year -= month < 3; r...
month < 3 is a boolean expression. false converts to 0 true converts to 1. You might rewrite it as: if (month < 3) { year = year - 1; }
67,383,418
67,383,454
Meaning of function call inside a struct in c++
I have come across structs that are defined seemingly with function calls inside, in some actual c++ code, that I need help to interpret. For example, in Resource.h from the AOSP, there is the following struct definition /** * A binary identifier representing a resource. Internally it * is a 32bit integer split as fo...
These lines are just constructors of struct ResourceId: ResourceId(); ResourceId(const ResourceId& rhs); ResourceId(uint32_t res_id); // NOLINT(google-explicit-constructor) ResourceId(uint8_t p, uint8_t t, uint16_t e); Indeed, structs can have constructors: Struct Constructor in C++? See also https://en.cppreference....
67,383,602
69,312,115
How to manually select unreal engine compiler
I recently switched to the Unreal Engine and saw that it uses the microsoft VS compiler for the compilation of its c++ programs. I am using unreal version 4.26 and I have 2 versions of the visual studio build tools installed, 2017 and 2019. I am not using the VS IDE, I am using VS code as an editor. I am curious as to ...
In the editor under Edit>Project Settings>Platforms>Toolchain there is a drop down to specify the compiler version.
67,383,799
67,383,877
lambda function does not update the reference array
I have a method which basically updates each value of the passed reference array by 5. Initially I tried the below options but it wouldn't update the reference array. Option 1: void Int_Array_Update(std::vector<int>& param) { auto f1 = [](int n) { return n + 5; }; std::for_each(param.begin(), param.end(), f1...
std:.for_each does not update the elements in the range the way you expect. std::for_each applies the lambda to each element, but does not care about the return value from the lambda. You want std::transform for that: std::transform(param.begin(), param.end(), param.begin(), f1); // ...
67,384,514
67,384,662
How to populate a graph using objects
I have an object defined like: class Item { long id; CString type; long pointingTo; }; std::list <Item> itemsFiltered; And let's say that I have 10 of them in the list. They form a graph using id and pointingTo values. 10000 - 10001 // id - pointingTo 10001 - 10002 10002 - 10003 10003 - 10004 10005 - 100...
It seems you are accessing out-of-range by using the large ids as the indice of the array. If you want to use arbitrary values that can be represented by the type, you should use std::map (or std::unordered_map, if it is supported in your environment). To use std::map, replace std::list<long> *adj; with std::map<long,...
67,384,654
67,386,060
How to keep one object alive as long as another object exists?
Is there a way to prevent one particular object of being destroyed while another object still exists, without explicitly making the class of the second one to know about the first? Here is an example: class A { /* A creates B*/ }; class B {}; int main() { auto spA = std::make_shared<A>(); auto spB = spA->getB(...
shared_ptr has something called an aliasing constructor. A shared_ptr<B> can be created from a shared_ptr<A> and a B*. The destructor of this shared_ptr<B> will delete the A object, not the B. In your case, your A object could itself hold a unique_ptr<B>, or even an outright B member.
67,384,979
67,385,092
Point to a struct member?
I have the following typedefined struct: typedef struct { uint8_t u8Byte1; // This byte takes the needed values sometimes uint8_t u8Byte2; // Not used uint8_t u8Byte3; // This byte takes the needed values the other times uint8_t u8Byte4; // Not used } tstr...
There is pointer to member: uint8_t tstrMapMetadata::*member = condition ? &tstrMapMetadata::u8Byte1 : &tstrMapMetadata::u8Byte3; while (true) { tstrMapMetadata* pstrMapMetadata = something(); if (pstrMapMetadata->*member == SOMETHING) // usage with ->* ( .* for objet ) { //Do something special...
67,385,154
67,385,672
Data polymorphism pattern in C++
I'm not sure "data polymorphism" is a actually a thing, but it seemed like a reasonable expression for what I'm looking for: How would you represent multiple types that share a functionality, but operate on different static data? Take for instance: class A { static constexpr std::array<int, 5> m_static_data{1, 2, 3...
You can try using static polymorphism (CRTP idiom). It will allow you to use common functionality at compile time. #include <iostream> #include <memory> #include <array> template<typename Derived> class Base { public: void foo() { const auto& arr = static_cast<Derived*>(this)->m_static_data; std::c...
67,385,604
67,385,660
inherit constructor from template-dependent base class
How can I inherit the constructor of a base class, if its name depend on a template parameter (of the derived class)? Example: #include <type_traits> struct A { }; struct B { }; template <bool Abase> struct C : public std::conditional_t<Abase, A, B> { using std::conditional_t<Abase, A, B>::(std::conditional_t<Ab...
You can define a type alias firstly. template <bool Abase> struct C : public std::conditional_t<Abase, A, B> { using base = std::conditional_t<Abase, A, B>; using base::base; }; LIVE
67,385,788
67,385,922
SFINAE Template implementation outside of the class declaration
Is there a way to have separate declaration and implementation of a template class that has SFINAE? The following example, give this error error C2039: 'method1': is not a member of 'A<T,nullptr>': // A.hpp #include <type_traits> template<typename T, typename std::enable_if_t<std::is_arithmetic_v<T>, T>* = nullptr> cl...
The definition should match the declaration. e.g. template<typename T, typename std::enable_if_t<std::is_arithmetic_v<T>, T>* ptr> inline void A<T, ptr>::method1() { }
67,386,277
67,386,360
Is there any way to print following pattern without using nested loops?
This image contains a pattern. The '*' is getting subtracted and '-' being added. Where I am confused that I am not allowed to use nested loop. I don't know why it confused me. #include <iostream> using namespace std; int main(){ string a="*"; for (int i=0; i<4; i++){ cout<<a<<endl; a=a+"*"; ...
You can change (overwrite) characters in strings. #include <iostream> #include <string> using namespace std; int main(){ const int n=4; string a(n,'*'); for (int i=0; i<n; i++){ cout<<a<<endl; a[n-i-1]='-'; } }
67,386,292
67,386,328
string::find() is unable to find substring a from large string b
I want to search substring a from string b which is storing a continuously by input and I want to know if a is repeatedly input So, I am adding substring a to b, one by one and after input and find a in b so that if it is already present it can give output as found #include<iostream> #include<string> using namespace s...
Strings can resize when needed, but not via operator[]. You are invoking undefined behavior here: for(int j=0; j<a.length();j++){ b[j+t]= a[j]; } b starts out as an empty string and you never increase its size, hence b[j+t] is an out-of-bounds access for any j+t != 0 (std::string::ope...
67,386,748
67,386,856
adding variables to curl_easy_setopt (seg fault)
#include <curl/curl.h> #include <cstdlib> #include <iostream> int rad = rand() % 100000; std::string agent_name = "https://127.0.0.1:443/agent/" + rad; std::string full_agent_name = agent_name + std::to_string(rad); int main(int argc, char **) { CURLcode ret; CURL *curl; curl = curl_easy_init(); curl_easy_s...
std::string agent_name = "https://127.0.0.1:443/agent/" + rad; This does not do what you expect. This adds rad bytes to the address of the string literal. Try std::string agent_name = "https://127.0.0.1:443/agent/" + std::to_string(rad); or using namespace std::string_literals; std::string agent_name = "https://127.0...
67,386,822
67,414,718
Why does clang-format destroy Unicode characters within eclipse?
I am using Eclipse CDT Eclipse C/C++ Development Tools 10.2.0.202103011047, CppStyle 1.5.0.0 and clang-format from clang 12.0.0. My C++ source file contains a line QString fileExportDirectory = "./"; because I am writing a unit test for handling Unicode paths. As soon as I format any part of the file, the line gets ...
The described misbehaviour is a reported CppStyle bug (https://github.com/wangzw/CppStyle/issues/39). As a workaround -Dfile.encoding=UTF-8 can be added to "eclipse.ini", then formatting works as expected.
67,386,941
67,418,208
Using x86 libraries and OpenMP on macOS arm64 architecture
I have a MacBook M1 and have installed a library on my machine that was compiled for an x86 / Intel architecture. I have some source code that uses OpenMP. I would like to compile my code and link my executable to the x86 library using a clang compiler. I am able compile source code with no x86 dependencies by follo...
Using an x86 installation of brew solves the problem for me. Here is a minimal set of commands for installing x86 variants of brew and clang, and then compiling my C/C++ code: # launch x86_64 shell arch -x86_64 zsh # install x86_64 variant of brew arch -x86_64 /bin/bash -c "$(curl -fsSL https://raw.githubuserconten...
67,387,293
67,387,379
Problem assigning an int pointer to an index of void* array
I have a class defined in a header file, Array.h. Class Code: class Array { private: int length; void **data; public: Array(); void push(void *); }; I also have the Array.cpp file. Code: #include <string.h> #include <stdlib.h> #include <stdio.h> #include "Array.h" Array::Array...
The local variable int x; will vanish when the execution of its block ends, and after that you must not dereference pointer to that. Instead of pushing &x, you have to allocate new region to store value and push its pointer. ints.push(new int(x)); The next step will be defining a copy constructor, an assignment operat...
67,387,539
67,387,606
Set random seed in Eigen
I am currently filling a vector with random numbers using Eigen::VectorXd::Random(n). Is it possible to seed Eigen's random number generator for deterministic results? Or alternatively, pass a random number generator to Eigen? I found no mention of either in the Eigen wiki, but it seems odd that such a feature would be...
It calls rand() from the standard library. You can set the seed by calling srand(). Matrix::Random uses the random number generator of the standard library, so you can initialize the random number sequence with srand(unsigned int seed), for instance: srand((unsigned int) time(0));
67,387,566
67,405,255
How To Speed Up Printing Unicode?
I'm using windows.h "TextOutW" function to print text to a bitmap. Printing regular ascii is really fast, but the printing in the unicode range seems to cause a huge slowdown. Here's my code to print a unicode square & test the duration: wchar_t b = 0x25A0; LPCWSTR s = &b; TextOutW(hMyDC, x, y, s, wcslen(s)); Are ther...
You are hitting Uniscribe. ExtTextOutW and TextOutW check if text should be threaded through Uniscribe or passed directly to GDI. To avoid Uniscribe overhead (NOT RECOMMENDED) you can pass ETO_IGNORELANGUAGE to ExtTextOutW, but you will miss some more advanced scripts (CJK aka Chinese+Japan+Korean, right to left writin...
67,387,669
67,396,996
How to convert an object and its method into a function callable just with method’s arguments
There is a function template<typename Class, typename MemberFuncPtr> auto makeCallback( Class* a, MemberFuncPtr func ) { return [a, func]( auto&&... args ) { return ( a->*func )( std::forward<decltype( args )>( args )... ); }; } that converts an object pointer and its member method into a lambda ca...
You might do, with some change: template<typename Class, typename MemberFuncPtr> auto makeCallback( Class* a, MemberFuncPtr func ) { return [a, func]( auto&&... args ) { return std::invoke(func, a, std::forward<decltype( args )>( args )... ); }; } int main() { Derived d; auto cb = makeCallb...
67,387,928
67,388,430
Error in Removal of Duplicates from a Sorted Array in C++ using Pointers
I have a task to remove the duplicates from a sorted array. However, when I try this it doesn't remove anything and still gives me the same values in the output as the original. I think I'm missing something in the removeDuplicates() function. Also pointer notation would be recommended. Thank you! void removeDuplicates...
For starters variable length arrays as the array declared in your function int arr1[s] = {}; is not a standard C++ feature. And moreover in C where variable length arrays exist you may not initialize them in their declarations. Moreover if the source array contains only one or two different elements then the value of ...
67,388,148
67,388,176
C++ value evaluation in concepts
How to properly evaluate a value in concept declaration / requires clauses ? Considering a concept is_red which check if a given type has a color static cx member set to /*undefined*/::red, where `/undefined/ in an enum; template <typename T> concept is_red = requires(T) { { T::color == decltype(T::color)::red }; };...
A concept can take an arbitrary boolean expression on the right-hand side. A requires-expression is just one such boolean expression, but it doesn't have to be that. You can write a comparison directly: template <typename T> concept is_red = T::color == decltype(T::color)::red;
67,388,587
67,398,985
Rest API with restc-cpp post data assertion error
I'm trying to post json data in C++ with the restc-cpp library and I have this error: Assertion failed: false, file lib\restc-cpp\include\restc-cpp/SerializeJson.h, line 1273 I have followed the examples on this page Post data to the server struct Post { int i; }; // The C++ main function - the place where any ad...
I have found the error. I have read the documentation about enable_if in type_traits standard library. It appears it is a check for integral_type, floating_point, ... in ... typename std::enable_if< !boost::fusion::traits::is_sequence<dataT>::value && !std::is_integral<dataT>::value && !std::is_...
67,388,624
67,389,295
cout not printing string of vector after getline
I have a .csv file with following contents: 1.0,2.0 2.0,3.0 Now i want to read this file and print it to the terminal. I want the output look like this: 1.0|2.0| 2.0|3.0| But all i get is: | | When i run the debugger the vector contains the correct data but it just wont print it. Vector array while cout (debugger): ...
The problem is within the data.cls i wanted to read. The debugger shows an \r (escape sequence) at the end of every line. This might have appeared after opening data.cls with Excel and the autosave ticked. Problem was solved after writing a new data.cls with standard windows texteditor. Got the solution thanks to comme...
67,389,118
67,389,666
Recursive spaceship operator
I have written this simple code but it does not compile because the comparison is implicit deleted. struct Tree { std::vector<Tree> child; friend auto operator<=>(const Tree &a, const Tree &b) = default; } int main(){ Tree t; std::cout<<(t<t)<<std::endl; } Can anybody explain to me how to fix the prob...
You cannot usually define a recursive function with a deduced return type. In order to deduce it, you need to already know it, so this is a no go. Replacing auto with an explicit return type std::weak_ordering fixes the problem.
67,389,190
67,389,548
Is operator->() guaranteed to be available for a standard C++ container's iterator?
#include <map> int main() { auto coll = std::map<int, int>{{1, 2}}; auto pos = coll.begin(); (*pos).first; // OK. Conforming to the C++ standard. pos->first; // Does this conform to the C++ standard too? } According to cppref, an iterator object pos must guarantee *pos and ++pos are valid expr...
The C++17 named iterator requirements for InputIterator, and therefore all derivations, does require that iterators provide operator->. However, the C++20 iterator concepts do not. Particular implementations may provide them, and the standard library containers follow the rules of both the C++17 requirements and C++20 ...
67,389,386
67,560,861
Least common multiple for more than two numbers
I want to find out Least Common Multiple(LCM) of more than two numbers. I know the formula of lcm(a,b) = (a * b) / gcd(a,b). Let's say, I have an array of numbers: [2, 6, 8, 13] and the the lcm should be modulo M = 1000000007. I have seen below code to calculate the LCM of multiple numbers but I am not understanding ho...
Knowing that gcd(a, b) represents the product of all the prime factors shared by a and b, what is the significance of a / gcd(a,b)? a / gcd(a, b) is equal to the prime factors of a that are not in b. Therefore, when you multiple that quantity by b, you get a product of all the prime factors of b and all the prime facto...
67,389,581
67,390,343
C++ how to replace type in variadic template by its index
How can I replace 1 type from variadic template by its index? For example I have: //-------------static_list------------- template<class ...Elements> struct static_list {}; struct execute_command<index, static_list<Commands...>> { static constexpr int value = execute_s<index + 1, static_list<Commands...>>::value; ...
I suppose there are many ways... For example, given an helper class as slrh (Static List Replace Helper) template <std::size_t, typename...> struct slrh; template <std::size_t N, typename R, std::size_t ... Is, typename ... Ts> struct slrh<N, R, std::index_sequence<Is...>, Ts...> { using type = static_list<std::condi...
67,389,590
67,389,825
Refer to class members with aliases
I have a vector class class vec3 { public: FLOAT x, y, z; vec3(FLOAT X = 0, FLOAT Y = 0, FLOAT Z = 0) { x = X; y = Y; z = Z; } }; And I need to be able to use this vector as either spacial dimension using x, y, z, or as color using r, g, b or as measure dimensions using w, h, l...
Actually your solution should work since you're returning by reference. The only caveat is you have to use () on each access. class vec3 { FLOAT _x, _y, _z; public: inline FLOAT &r() { return _x; } inline FLOAT &g() { return _y; } inline FLOAT &b() { return _z; } inline FLOAT &x() { return _x; } ...
67,389,677
67,391,465
How to remove the special character that write_json is adding to the string in boost C++
write_json is converting the string "test/123" as "test\/123". How to remove the special character (\) that write_json is adding to the string in boost C++ Thanks,
It's being escaped. It's valid JSON, so any JSON parser should be able to read it correctly. Put bluntly, yours is not a problem. If you think it is, you're doing something wrong. Other than that, please don't use Boost Property Tree as if it were a JSON library. It is not. Boost 1.75 introduced Boost Json, which is. L...
67,389,713
67,399,969
openssl equivalent to `ippsRSAVerify_PKCS1v15`
I am porting some code using Intel IPP lib to OpenSSL (Apple Silicon port). I have some code checking an XML file signature that looks like this: <Signature xmlns="http://www.w3.org/2000/09/xmldsig#"> <SignedInfo> <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" /> ...
So after a bit more experimenting, I realised that indeed, ippsRSAVerify_PCKS1v15 and RSA_Verify expect different data for their respective pMsg and m arguments. The Intel function wants to be given the entire message to sign/verify, and computes the SHA1 digest (or other digest) internally, whereas the OpenSSL functio...
67,390,029
67,390,137
C++ array of strings terminator
I am new to C++, I know that character arrays/char*(c-strings) terminate with a Null byte, but is it the same for string arrays/char**? My main question is: how can i know if I reached the end of a char** variable? Will the following code work? #include <cstddef> char** myArray={"Hello", "World"}; for(char** str = my...
For starters this declaration char** myArray={"Hello", "World"}; does not make a sense, You may not initialize a scalar object with a braced-list with more than one expression. It seems you mean a declaration of an array const char* myArray[] ={ "Hello", "World"}; In this case the for loop can look like for( const ch...
67,390,269
67,401,122
MakeFile C++ problem only have .Object files
As the title say i have a problem compiling so i have my makefile who compile great my .cpp , then I have .o in the bin directory but after that its off I stay with my .o files and nothing change , It seems it doesnt take into account the few lines i wrote after and cant have my .exe I think its something to do with th...
Please see below code/reference example which will compile-link and generate the end executable.OFcourse, the dependency check can also be added in this # Define options and paths CFLAGS = -Wall -O SRCDIR = ./Src INCDIR = ./Inc BINDIR = ./Bin TARGET = ./Bin # Program name EXE_PROG = $(BINDIR)/simradio.exe all: $(EXE_...
67,390,581
67,392,372
Crypto++ : Hash generation hangs on windows 10
I have the following simple program : #include <cryptlib.h> #include "sha.h" #include <sha3.h> #include <filters.h> #include <hex.h> #include <beast/core/detail/base64.hpp> using namespace CryptoPP; using namespace boost::beast::detail::base64; int main(int argc, char** argv) { if (argc < 2) { std::cout ...
Change the line SHA3 digestAlgo = SHA3_256(); to SHA3_256 digestAlgo;
67,390,626
67,411,289
Get new connected display via existing IDXGIDevice
I have a program that creates ID3D11Device device on start and destroys on shutdown. I encountered the issue when I connected the second monitor after ID3D11Device was created. In this simplified piece of code it enumerates adapter outputs and this enumeration returns only one monitor, the first one that had been conne...
The method IDXGIFactory1::IsCurrent() should help. If it returns FALSE, then you should destroy and re-create the factory to refresh the information. Just check it after each all to Present. I use this method to support HDR10 output in my directx-vs-templates project. See DX11 and DX12.
67,390,939
67,391,922
Why cannot I convert a string with an en dash into a wstring?
The following code fails and I can't seem to figure out why. std::string s = "–"; std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; std::wstring wide = converter.from_bytes(s); I tried reading up on UTF-8, but I couldn't figure it out. Storing the initial string as a wstring, converting it to a string ...
Most likely, your C++ source file is not saved as UTF-8, or the compiler is not interpreting it as UTF-8, either way causing "–" to not actually represent U+2013 EN DASH at runtime. You can easily verify that at runtime, such as with a debugger, or just printing out the raw bytes of your string. Make sure your C++ fil...
67,391,030
67,391,312
Passing array variables between scopes
My first ever question. On 'maning-up' to learn c++ I have myself in a tangle over scope. My understanding is that variables defined in functions should cannot be passe dout of scope. But I have been this like the below A LOT and it works everytime with no problems. What am i missing? I have defined some inline functi...
C++ has a really stupid quirk where functions cannot take a array by value as a parameter. inline void func1(float x[3]); //x isn't actually an array :( Normally, all parameters are copies of the values. Except for arrays. Instead, C++ silently converts all array-value parameters to be just pointers. So it's actually:...
67,391,065
67,391,861
How do I avoid creating a temporary vector in C++?
In the following minimal example, v1 and v2 and slices of vector v and these slices are elements of other vector vv. #include<vector> int main(){ std::vector<int> v{0,1,2,3,4,5}; std::vector<int> v1(v.begin(), v.begin() + 2); std::vector<int> v2(v.begin() + 2, v.end()); std::vector<std::vector<int>> vv(2); vv[0]...
You can use vector::assign(), eg: #include <vector> int main(){ std::vector<int> v{0,1,2,3,4,5}; std::vector<std::vector<int>> vv(2); vv[0].assign(v.begin(), v.begin() + 2); vv[1].assign(v.begin() + 2, v.end()); }
67,391,300
67,391,458
what's the most efficient way to fill 2d std::array and std::vector?
I usually use .fill() with 1D arrays and vectors but it seems to not work with multidimensional ones. I've seen around a lot of ways to fill them, but i wonder what the most efficient is. std::array<std::array<bool, 3>, 3> wasPlayed; wasPlayed.fill(false); This doesn't work, what would be the most performant way of fi...
As referenced from here using std::fill on a 2D int vector, Nested loop may be the best option to fill them faster (Based on comment by @juanchopanza ) vector<vector<int> > a(3,vector<int>(3)); for (int i = 0 ; i < 3; i++) fill(a[i].begin(),a[i].end(),falseValues); For c++14 and above you can also use for_each(a.b...
67,391,625
67,392,051
Pass thrust device_vectors to device function and modify them
when I'm running this piece of code, the compiler says I'm calling a host function from global function. I want to assing something a bit more complicated than zeros to A[i] and B[i] but I just wanted to test the functionality. I need to modify values in both vectors. Later I'd like to reduce the table A. int main(void...
In spite of its naming, a thrust::device_vector is not directly usable in CUDA device code. The device_vector is an object/container, and it is intended to be usable in host code only. This is why you get the messages about "calling a host function..." For the example you have shown here, to access the data directly, ...
67,391,866
67,392,101
ifstream EOF executing early
I'm working with socket programming and am currently attempting to transfer a 1MB file through 16KB at a time. The data does initially transfer 16KB at a time; however, my ifstream reaches EOF prematurely which makes it so the file transfer is incomplete. int main() { int SIZE = 16000; char file_buffer[SIZE]; int i = ...
It looks like you discard the data at the end of the file if the file size isn't an exact multiple of SIZE. Also, even if the file size is an exact multiple of SIZE you'll be reading the last character and then eof() will not return true. Not until you've tried reading the next character will eof() return true, and tha...
67,391,891
67,392,138
How to split bitset of any size into list of 64 bits bitsets?
I have a bitset of any size and I would like to know the fastest way to get a list of 64 bits bitsets from my original bitset ? For example, from bitset<10000> b('010001110 ...'), I would like to get a list of 64 bits bitsets containing the 1st 64th bits, then the next 64th bits from my original bitset, and so on.
Sadly, there isn't any functionality to efficiently do this operation straight from the STL. You'd have to go bit by bit or you can shift and mask, as explained in this answer. However, giving credit to this You can use boost::dynamic_bitset, which can be converted to a range of "blocks" using boost::to_block_range.
67,392,061
67,393,036
Trying to make a multiple choice question
#include <iostream> using namespace std; int main() { /** 4 variants 3 correct a b c d d is incorrecy if an answer is reapeted, it needs to say "Answer *a/b/c/d* has been already introduced" **/ cout << "Which ones are correct?: a) b) c) d) \n"; // for the sake of the example, only A B and C a...
Since this is a situation where you've either seen the option before or not seen it, it lends well to a binary flag like bool for the options. But since there are multiple options, it wouldn't be very maintainable to have flags for each variable. Imagine if your options go up to 5 or 6. You wouldn't want to be maintain...
67,392,492
67,392,569
Use assignment operators instead of an implicit constructor
In my program, I am trying to use the assignment operator= to assign an object of my class. I am specifically trying to call the assignment operator instead of an implicit constructor (thus the explicit keyword). When I try to compile, I get a C2440 Compiler Error: class MyClass { public: explicit MyClass(double x ...
MyClass my_class = 2.; is more or less equivalent to MyClass my_class(2.);, but, you marked the constructor as explicit, which prevents C++ from doing that automatically. So, in the way you've written your code, you cannot really do what you want. You could explicitly call the constructor using: MyClass my_class(2.); /...
67,393,072
67,393,129
In C++, how to declare a class member that can only be changed externally?
I have a class like this class Foo { public: Matrix M; Foo(); ~Foo(); } I want M to be immutable inside the class (internal member functions cannot change it), but code outside the class should be able to update it without constraint, is there a way to do so? A little background: I'm working on an OpenG...
Move M outside of Foo, and then give Foo a const pointer/reference to M, eg: Matrix M; class Foo { public: const Matrix &Mref; Foo() : Mref(M) {} ~Foo(); };
67,393,131
67,395,151
Unable to Import C++ Modules
I'm trying to rebuild a project of mine in C++ 20 using modules to reduce dependencies and compilation times. I tried importing some modules, and I'm able to do so, yet Visual Studio marks the importation statements as undefined: "Could not find module file for...". Although it marks it as wrong, I'm still able to comp...
You cannot include like that in a module. Including a header file into a module will make all of its content part of your module. Since you do not define the implementation for the standard library function you declare from the include, it results in linking errors. You have two choices for headers. The first is to use...
67,393,165
67,395,790
Linking .lib and .h files (OpenJDK 1.8)
I have a project, that includes jni.h and jvmti.h files here theese files are stored in jdk8 folder (already installed on my pc) here but the main problem - i dont know how can i correctly link jdk libs and .h files to my visual studio prj
I suggest you could follow the following steps to link the static library: 1,Add the path to the header file to the Additional Include Directories(property - >c/c++ -> General -> Additional Include Directories) 2,Add the path to the .lib file to the Additional Library Directories (property -> linker -> General -> Addit...
67,393,236
67,393,288
Using vector::data() chaining with member function print differnet values as pointer arithmetic
I have a class hello with a method which returns a vector member. I am trying to print out values using vector::data() with pointer arithmetic, but I am facing an undefined behavior. See example below: class hello { public: std::vector<int> data() { return v; } private: std::vector<int> v{1, 2,...
hello::data() is returning a vector by value, which means it will return a temporary copy of hello::v, which will allocate its own int array and copy the values from v. When calling h.data(), that temporary vector will be destroyed when it goes out of scope at the end of the full statement that called h.data(). So, in ...
67,393,356
67,393,729
Move semantics of a method chained to a constructor
I am new to C++ and am trying to get a grip on move semantics. The following code is a barebones struct I wrote. It is not the best example of software engineering by any means, but it is just for learning purposes. It owns a resource, has the copy constructor and copy assignment operator deleted, has a move constru...
My goal was to modify the temporary object I constructed and them move it to x without making any copies doStuff() does not return a temporary, so there is no rvalue for x to move from. Since the return value of doStuff() is not an rvalue, the compiler can't call your move constructor for x, hence why it tries to cal...
67,393,520
67,393,549
Store return size * nmemb into a variable c++
How would I go about storing the return size * nmemb? I've tried std::string verycool = size * nmemb; static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp) { ((std::string*)userp)->append((char*)contents, size * nmemb); return size * nmemb; }
Just use the same type that size and nmemb themselves are using: static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp) { size_t numBytes = size * nmemb; ((std::string*)userp)->append((char*)contents, numBytes); return numBytes; } If, on the other hand, you want to access the v...
67,393,574
67,406,706
chartView: axis values change on Zooming
I have a simple chart view in my Qml: import QtQuick 2.9 import QtQuick.Window 2.2 import QtCharts 2.0 Window { visible: true width: 640 height: 480 title: qsTr("Hello World") ChartView { id: chartView anchors.fill: parent theme: ChartView.ChartThemeBrownSand antial...
you can set ticks based on values, according to this documentation qml-qtcharts-valueaxis : tickType : ValueAxis.TicksDynamic : Ticks are placed according to tickAnchor and tickInterval values ValueAxis { id: axisX min: 0 max: 10 tickCount: 5 tickAnchor: 1 tickInterval: 1 tickType : ValueAx...
67,393,597
67,594,103
c++20 concepts constructor overloading
Let #include<concepts> struct B{}; template<typename T> struct A{ A(int) {} }; template<> struct A<B>{ A(B d) {} }; template<typename T> struct C{ A<T> a; C(B b) requires std::same_as<T, B> : a{b} {} C(int i) requires (!std::same_as<T, B>) : a{i} {} }; template class C<int>; int main() {} When I ...
Ok it's a bug of gcc 10.2, I need to update to at least 10.3
67,393,985
67,395,551
shaderc IncluderInterface, include fails?
I am trying to support #include directives for glsl in a Vulkan project. To my understanding all that is required is to properly implement the IncluderInterface and set it, which I did like this: class NEShaderIncluder : public CompileOptions::IncluderInterface { shaderc_include_result* GetInclude( const ch...
The problem is that you are supposed to call a preprocessing stage in addition to setting up the include, the correct call site looks like this: shaderc::PreprocessedSourceCompilationResult pre_result = compiler.PreprocessGlsl(source, shader_type, shader_name.c_str(), options); Assert( pre_resul...
67,394,126
67,394,176
two errors while compiling meshlab and vcglib
I got one problem during compiling the Meshlab_mini (2020.12 version) with Vcglib (2020.12 version) with visual studio 2019 and qt 5.15.2. The problem is below Severity Code Description Project File Line Suppression State Error (active) E0135 class "vcg::tri::Append<vcgTriMesh, vcgTriMesh>" has no member ...
[SOLVED] I got the sourcecode by the Code -> Download ZIP method, and then compiled the project with the error above. By the great help from Alessandro Muntonialessandro.muntoni@isti.cnr.it, i.e., the 'git clone --recursive github.com/cnr-isti-vclab/meshlab' method, then the compilation of the source code of the Meshla...