question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
69,287,920
69,288,038
Are addresses into constant vectors, inside a non-constant vector, stable?
If I have a std::vector<std::vector<char>> Where the following is true: The inner vectors's size is never changed The outer vector's size is changed with insertions and removals Can I take an address into the inner vector like this, use it after modifying the outer vector, and be safe? std::vector<std::vector<char>> ...
If the outer vector has to grow, it will allocate a new buffer and move all of the inner vectors into that buffer. That means the addresses of those inner vectors will change but that does not mean the addresses of the buffers of the inner vectors will change. They will stay the same as vector is required to not inva...
69,287,923
69,288,709
Dynamically Access Variable Inside a Struct C++
I'm new to C++ and very confused on how to approach this. In Javascript, I can do something like this to access an object dynamically very easily: function someItem(prop) { const item = { prop1: 'hey', prop2: 'hello' }; return item[prop]; } In C++, I'm assuming I have to use a Struct, but a...
This is a simple example of how to create an instance of a struct and then access its members: #include <iostream> #include <string> struct Item { std::string prop1 = "hey"; std::string prop2 = "hello"; }; int main() { Item myItem; std::cout << myItem.prop1 << std::endl; // This prints "hey" std::...
69,287,967
69,288,029
Can't bind winsock socket
I'm quite new to c++ networking so I've been watching some tutorials but I can't seem to find out why I can't bind my socket. Can someone explain to me what I'm doing wrong? Here's my code for binding the socket. #include <stdlib.h> #include <winsock2.h> #pragma comment (lib,"ws2_32.lib") #pragma warning( disable : 49...
You must state which interface you want to bind the socket to. This is done by setting the sin_addr member of the sockaddr_in structure. For example, to bind to the wildcard interface INADDR_ANY (to be able to receive connections from all interfaces), you would do something like this: address.sin_addr.s_addr = htonl(IN...
69,288,348
69,288,527
Xcode development, can I place #pragma unused(x) via some #define rule
while developing in Xcode it is common to switch between Debug and Release mode and using some parts of code in Debug mode only while not using some in Release mode. I often throw out NSLog code by some #define rule that lets the Pre-compiler parse out those commands that are not needed in a Release. Doing so because s...
In the #else case, you can put the function call on the right side of the && operator with 0 on the left side. That will ensure that variables are "used" while also ensuring that the function doesn't actually get called and that the parameters are not evaluated. #ifdef DEBUG #define NSLog(FORMAT, ...) fprintf(stderr,...
69,288,932
69,289,383
C++: Vector value resets efter exiting if-statement
I need to overwrite values in a 2D vector, where the new values is simply just equal to an integer I am counting up. But as soon as I exit this if-statement, the value resets to the original value? I think it may have something to do with the indexing, but I just can't figure it out So I fill up the vector with either ...
Here if ((P[i][j - 1] == 0) && P[i][j] == -1) { you are looking for a 0 that comes before -1, but you fill those vectors with -1 followed by 0
69,289,055
69,289,509
Passing variables to a function with CreateRemoteThread
HANDLE CreateRemoteThread( HANDLE hProcess, LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId ); lpParameter A...
As its name implies, CreateRemoteThread() creates a new thread in an external process. As such, the lpStartAddress parameter must point to the memory address of a function in the target process, and the lpParameter parameter must point to a memory address that exists in the target process (unless it is a pointer-caste...
69,289,061
69,289,354
Linux isn't allowing to create enough sockets but not many sockets are being used
My C++ application creates 64-128 UDP sockets. It creates sockets using this code: int sock = socket(AF_INET, SOCK_DGRAM, 0); assert(sock != -1, strerror(errno)); const u_int yes = 1; int result = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)); printf("sock=%i result=%i errno=%i\n", sock, result, errno)...
There is no limit on number of open sockets, but there is more general limit on number of opened file descriptors. The fact that it fails on fd=1023 suggests that this limit was truly hit, since on a typical Linux: file descriptors are assigned consecutive numbers starting with 0 default limit (ulimit -n) is 1024 open...
69,289,093
69,289,263
Use TEXT function on variable c++
I wanna use TEXT() on variable full code: LPCTSTR data = TEXT(argv[0]); Or if someone now how to write char variable to LPCTSTR.
You can use ATL::CA2W: #include <iostream> #include <Windows.h> #include <atlbase.h> #include <atlconv.h> int main(int argc, char* argv[]) { LPCSTR lpcstr = argv[0]; ATL::CA2W wtext(lpcstr); LPCTSTR lpctstr = wtext.m_psz; std::wcout << lpctstr << std::endl; return EXIT_SUCCESS; }
69,290,306
69,290,505
Why is reading char by char faster than iterating over whole file string?
I have a lexer that consumes a file character by character, looking for tokens. I tried two methods for NextChar(), the first reads directly from ifstream through ifstream::get(ch), and the second loads the whole file into a std::stringstream to avoid disk I/O overhead. get() method: inline void Scanner::NextChar() { ...
std::ifstream is already doing its own internal buffering, so it's not like it has to go out and wait for the hard drive to respond every time you call get(ch); 99.99% of the time, it already has your next character available in its internal read-buffer and just has to do a one-byte copy to hand it over to your code. G...
69,290,946
69,292,200
How do I memoize this program?
PepCoding | Count Binary Strings. You are given a number n. You are required to print the number of binary strings of length n with no consecutive 0's. My code: void solve(int n ,string ans , vector<string> &myAns){ if(ans.size()==n) { //cout << ans << "\n"; myAns.push_back(ans); return; } if(ans...
Note that you are required to print the number of binary strings of length n with no consecutive 0's, not to actually form (and store or print) all of them. So, yes, a recursive solution could greatly benefit from memoization, but not of all the single strings. What you should store is the number of strings for each le...
69,290,986
69,299,250
GDB keeps downloading debug info
Every now and then, when I launch a debug process, GDB starts by downloading all debug info for all dependencies, which is not negligeable. Given the fact that dependencies don't get added THAT often, I suspect it's because I am using rolling distro, so every time I perform a distribution upgrade, GDB will re-downloads...
GDB uses debuginfod_find_debuginfo() to find and download the debug info files. Documentation says: debuginfod_find_debuginfo(), debuginfod_find_executable(), and debuginfod_find_source() query the debuginfod server URLs contained in $DEBUGINFOD_URLS (see below) for the debuginfo ... ... CACHE If the query is successf...
69,291,130
69,291,650
What's wrong with my c++ code? for a = 90 Z should be equal to -1, but I'm getting completly different answer. Why?
I tried to make code that can calculate trigonometric function but it went wrong and i don't know what to do because I just can't see any mistakes using namespace std; #define _CRT_SECURE_NO_WARNINGS #define _USE_MATH_DEFINES #include <iostream> #include <conio.h> #include <cmath> int main() {` const double pi = ...
As mentioned in the above commments, enabling compiler warning messages should indicate the problem and suggest a solution, thus removing _CRT_SECURE_NO_WARNINGS may help to view the problem and solution: (15,11): warning C4477: 'scanf' : format string '%g' requires an argument of type 'float *', but variadic argument ...
69,291,136
69,291,403
Finding the longest palindromic substring (suboptimally)
I'm working on a coding exercise that asks me to find the longest palindromic substring when given an input string. I know my solution isn't optimal in terms of efficiency but I'm trying to get a correct solution first. So far this is what I have: #include <string> #include <algorithm> #include <iostream> class Soluti...
because you are not trying all the possible solution in c++ , substr takes two parameters the first are the starting index , and the second is the length of the substring how ever in you program you don't check for the string which starts at index 4 and have length of three for example in the second for loop you shoud ...
69,291,570
69,291,592
How can I use structured bindings to set an array's values?
I'm new to C++17 and I ran into a problem when I tried to use structure binding to set values to a couple of array cells. But the regular syntax doesn't work here; it gets confused with the array's brackets. How can I solve it? Is it even possible? Example: std::pair<int, int> makePair() { return { 10, 20 }; } int...
It is the wrong tool for the job. Structured bindings always introduce new names; they don't accept arbitrary expressions for lvalues. But you can do what you want even in C++11. There's std::tie, for this exact purpose: std::tie(arr[0], arr[1]) = makePair(); Give it a bunch of lvalues for arguments, and it will produ...
69,292,169
69,292,449
How to send a pointer to another thread?
I created a Rust wrapper for a C++ library for a camera using bindgen, and the camera handle in the C++ library is defined as typedef void camera_handle which bindgen ported over as: pub type camera_handle = ::std::os::raw::c_void; I'm able to successfully connect to the camera and take images, however I wanted to run...
Pointers do not implement Send or Sync since their safety escapes the compiler. You are intended to explicitly indicate when a pointer is safe to use across threads. This is typically done via a wrapper type that you implement Send and/or Sync on yourself: struct CameraHandle(*mut c_void); unsafe impl Send for CameraH...
69,292,694
69,292,705
How to delete all files in a certain folder
I'm trying to make a feature in my program to delete all files in the Windows temporary folder "(C:\Users\Owner\AppData\Local\Temp)", how would I do this?
Call the Win32 API GetTempPath() function to get the user's %TEMP% folder path, then you can either: call FindFirstFile()/FindNextFile() in a loop, calling DeleteFile() on each iteration. call SHFileOperation(), specifying FO_DELETE with a *.* wildcard. use a loop to discover the files, calling IFileOperation::Delet...
69,292,807
69,292,936
Blocking mouse messages with hook
How do i 'block' the WM_LBUTTONDOWN message to be fired? The function is inside of a dll, I also tried to use LowLevelMouseProc but it does not work with error code: 1429 which means "global only hook". I don't own the window in question. I tried to return a WM_NULL in the code below, but it also doesn't work, what e...
Per the MouseProc callback function documentation: If nCode is greater than or equal to zero, and the hook procedure did not process the message, it is highly recommended that you call CallNextHookEx and return the value it returns; otherwise, other applications that have installed WH_MOUSE hooks will not receive hook...
69,292,860
71,501,801
How can I get "go to definition" working in a JUCE project?
I'm trying to get "go to definition" working for a JUCE project created with Projucer. I've tried both CLion and Visual Studio Code, but they can't seem to find definitions that live in the JUCE libraries. I'm on Ubuntu. Is there a blessed path for this? I'm normally a vim user, but I'm willing to try any IDE.
What I ended up doing was using FRUT to convert my project from a Projucer project to a CMake project. CLion was able to understand the CMake project, and thus, the "go to definition" and autocomplete features started working.
69,293,016
69,293,076
Not understanding std::filesystem::directory_iterator
I just started looking into C++ and have been reading a book and am only a couple of chapters in. I thought a good exercise would be to print out a directory. When I look it up, I see this nice for loop that is driving the train from. for (const auto & entry : fs::directory_iterator(path)) std::cout << entry.path()...
A Range-based for loop iterates through a container using its iterators. In this case, there is no container, directory_iterator acts stand-alone. When the directory_iterator is constructed, it finds the first file in the specified folder. When the loop dereferences the iterator via its operator*, it returns a const ...
69,293,045
69,293,122
Moving from pair/tuple elements via structured binding
Given std::pair<std::set<int>, std::set<int>> p, what is the right syntax to move its elements via structured binding? How to do std::set<int> first_set = std::move(p.first); std::set<int> second_set = std::move(p.second); via structured binding syntax? Is the following equivalent to the above? auto&& [first_set, sec...
Is the following equivalent to the above? No, there is no move operation, only the member variable of p is bound to the lvalue reference first_set and second_set. You should do this: auto [first_set, second_set] = std::move(p);
69,293,214
69,293,250
Why does my function always return 0 instead of returning the sum result?
I just started learning C++, now I'm making a simple array sum function. Why is my code output always 0? Does it mean that my function returns "0"? If I put cout in the function, it shows the right sum result. #include <iostream> using namespace std; int ArraySum(int arr[], int size){ int sum=0; for(int i=0 ; i<si...
You are not assigning the return value to the sum when it is returned. You have 2 options: pass a pointer to the sum, and dereference it inside ArraySum() assign the value that is returned by ArraySum() to the sum int.
69,293,309
69,293,338
Private member c++ problems
I've run into an error that I don't know how to fix. My program does not compile because it outputs "declared private here". Not sure how to fix this, looking for feedback in order to improve my skills! Thanks in advance. I've only included the areas where I am experiencing issues. class List { public: List...
List declares its friend operator<< as taking a List&, but you are implementing the operator as taking a const List& instead, so you are actually implementing a different operator, not the friend operator that has access to the private List::Node type.
69,293,388
69,293,505
How to make class compatible with std::span constructor that takes a range?
I'd like to be able to pass my custom container this std::span constructor: template< class R > explicit(extent != std::dynamic_extent) constexpr span( R&& range ); What do I need to add to my custom class to make it satisfy the requirements to be able to pass it to the std::span constructor that receives a range? For...
This is because your Container does not satisfy contiguous_range, which is defined as: template<class T> concept contiguous_­range = random_­access_­range<T> && contiguous_­iterator<iterator_t<T>> && requires(T& t) { { ranges::data(t) } -> same_­as<add_pointer_t<range_reference_t<T>>>; }; In the re...
69,293,479
69,294,064
How to mutate variadic arguments of a template
I'm trying to create a struct of arrays: auto x = MakeMegaContainer<StructA, StructB, StructC>(); Which I want to, at compile time, produce a structure like: struct MegaContainer { std::tuple< Container<StructA>, Container<StructB>, Container<StructC> > Data; }; The creation method is non-negotiable, and I think ...
Look at this part: template <typename OneStruct> OneStruct& GetStruct(const uint64_t& id) { return std::get<OneStruct>(m_Storage).Get(id); // Get is defined for MyContainer } template <typename OneStruct> bool ContainsStruct(const uint64_t& id) { return std::get<OneStruct>(m_Storage).Contains(id); // Contain...
69,293,663
69,293,945
Parallel Arrays in C++
Trying to create a program that takes a coffee flavor add-in and checks if it's valid using an array. If valid it uses the array index to gather price information. I managed to write the code below, but it only works for 1 iteration. How can alter it so a user can enter: Cream and cinnamon and output the total of each ...
Your program is written to get a single output. For multiple outputs there have to be loops and the not found condition also has to be re-written. try this #include <iostream> #include <string> using namespace std; int main() { // Declare variables. const int NUM_ITEMS = 5; // Named const...
69,293,806
69,293,886
How to show only the last value of a for loop?
I'm working on building a loop right now that only shows the end value. However, the code is showing all the integers though. Here's my code: #include <iostream> using namespace std; int sum = 0; void findMultiples(int n){ cout <<"Enter a positive integer:"<<endl; for(int i = 0; i <= n; i++) if (i % ...
You are using for then if then showing output. The for and if scope area is one line without { }, so you are printing and summing at the same time and it is each time in the scope of if statement. #include<iostream> using namespace std; int sum = 0; void findMultiples(int n){ cout <<"Enter a positive integer:"<...
69,294,365
69,294,563
How does one tell Windows 10 to tile, center, or stretch desktop wallpaper using WIN32 C/C++ API?
Goal: using C++, the Win32 SDK and Visual Studio 2019 to set the desktop wallpaper to be centered or tiled or stretched. One can use SystemParametersInfo() to change the wallpaper. No problem at all. Problem is telling the system to tile or center or stretch the wallpaper image. Reading on the web, whether the wallpape...
Try IDesktopWallpaper interface and IActiveDesktop interfaces. Create objects for them by creating CLSID_DesktopWallpaper and CLSID_ActiveDesktopobjects.
69,294,684
69,294,882
How to add the last element into a vector of a struct containing an array in c++
Hi I want to add last element into a vector of struct containing an array. I have tried to add it under its loop but has issues with constant char. It says "invalid conversion from ‘const char*’ to char" [-fpermissive] This my file named as myfile.txt.log id value 1 ABC 2 BDV 3 COO 4 DDC 5 EEE 6...
Consider this using more C++ semantics than C: #include <iostream> #include <fstream> #include <vector> #include <string> using namespace std; struct V { char a[10]; }; int main() { std::vector<V> input; std::string s; int count = 0; while (std::cin >> s) { count++; if ((count...
69,295,305
69,295,402
Constant time `contains` for `std::vector`?
I am working with some code that checks if std::vector contains a given element in constant time by comparing its address to those describing the extent of the vector's data. However I suspect that, although it works, it relies on undefined behaviour. If the element is not contained by the vector then the pointer compa...
You can use std::less A specialization of std::less for any pointer type yields the implementation-defined strict total order, even if the built-in < operator does not. Update: The standard doesn't guarantee that this will actually work for contains though. If you have say two vectors a and b, the total order is pe...
69,295,333
69,297,901
Extract one colour channel from 4-dimensional cv::Mat
I'm working with OpenCV for a while and experiment with the DNN extension. My model has the input shape [1, 3, 224, 244] with pixel-depth uint8. So I put my m_inputImg which has 3-channels and 8 bit pixel depth in the function: cv::dnn::blobFromImage(m_inputImg, m_inputImgTensor, 1.0, cv::Size(), cv::Scalar(), false, f...
cv::Size() will use the original image size. You are interpreting the data wrong. Here are 4 ways to interpret a 512x512 (cv::Size()) loaded blob-start from the lenna image: input (512x512): blob-start as a 512x512 single channel image: blob-start as a 512x512 BGR image: blob-start as a 224x224 BGR image: bl...
69,295,821
69,297,083
Strange behavior using CString in swscanf directly
I have one problem with CString and STL's set. It looks a bit strange to use CString and STL together, but I tried to be curious. My code is below: #include "stdafx.h" #include <iostream> #include <set> #include <atlstr.h> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { wchar_t line[1024] = {0}; F...
A CString is a Microsoft implementation wrapping a character array into a C++ object to allow simpler processing. But, swscanf is a good old C function that knows nothing about what a CString is: it just expects its arguments to be large enough to accept the decoded values. It should never be directly passed a CString....
69,295,846
69,295,913
How to align a structure correctly?
I am trying to align a structure using the directive (#pragma pack). I need it has 112 bytes in size. (14*8=112 bytes). However it has 80 bytes only. How to do it correctly? #pragma pack (8) struct Deal { long deal_ticket; long order_ticket; long position_ticket; long t...
I need it has 112 bytes in size. (14*8=112 bytes). long is only guaranteed to be at least 32 bits which is 4 bytes (assuming 8 bit byte); not 8 bytes. If you want each integer to be 64 bits, then you can use std::int64_t instead of long. #pragma pack never increases the size of a class. It only ever decreases the siz...
69,296,446
69,296,547
Calling function twice gives segfault (in connection with char* to string conversion)
I want to expand a string ("%LOCALAPPDATA%/test.txt") with a Windows environment path. The following function in principle does the job, but calling it again with the same output string (or assigning some value to the output string before calling the function) gives a segfault. Obviously I am making some (probably real...
As the documentation explains: lpDst A pointer to a buffer that receives the result of expanding the environment variable strings in the lpSrc buffer. The buffer needs to be supplied by the caller, while the code simply passes an uninitialized pointer, alongside tricking the system into believing that it points at me...
69,296,888
69,296,969
Why decltype(auto) infers T& as return type, while dedicated T& does not?
Consider this snippet: #include <stdexcept> template <typename T> class MyClass; template <typename T> struct MyClass<T &> { constexpr T &foo() && { return value != nullptr ? std::move(*value) : throw std::runtime_error("foo"); } constexpr decltype(auto) bar() && { return v...
Why decltype(auto) infers T& as return type No, the return type of bar() is T&&, i.e. int&& in this case. For decltype: if the value category of expression is xvalue, then decltype yields T&&; std::move(*value) is an xvalue-expression, so the deduced return type is T&&. On the other hand, the return type of foo is ...
69,297,501
69,298,431
C++ placement new alignment of classes (on a SAMD21 microcontroller)
I am working on an application which is running on a SAMD21 microcontroller. For those unfamiliar with the SAMD21, it contains an ARM Cortex-M0+ processor. The specific model I am using has 32 kB of RAM. My application is running up to the limits of that 32 kB, so I've been working on optimizing the code for memory usa...
do I need to alter the code in any way to handle alignment issues? Yes. do I need to do anything special to handle memory alignment? Yes. uint8_t conceptually represents an unsigned integer with 8 bits. Use char or unsigned char to represent 1 byte. Anyway, use operator new with size and alignment: auto maxsize = m...
69,297,570
69,298,021
Why is a pointer to pointer treated differently than a pointer in spite of corresponding corrections
I'm trying to delete a Node from a Doubly Linked List. The function deleteNode() will receive the head of the linked list and the node to be deleted. However, depending on whether I pass the node to be deleted as a pointer or a pointer to pointer, the code behaves differently (in spite of making the corresponding corre...
Here, when you pass &head and &head, if(*deleteMe == *head) *head = (*deleteMe)->next; *deleteMe and *head are the same object (the object whose address you passed in), and they are still the same object after the assignment. (That is, it is equivalent to both *head = (*head)->next; and *deleteMe = (*deleteMe)->ne...
69,297,852
69,297,933
std::initializer_list as right hand argument for overloaded operator?
I want to use something like the "in" operator available in other programming languages. I read many posts about that already. But, nothing that fits my needs. What I wanted to do is a little bit different. Please see the following first example: #include <iostream> #include <initializer_list> #include <algorithm> boo...
You need to take the initializer_list by const&: bool operator==(const int lhs, const std::initializer_list<int>& il) std::cout << (3 == std::initializer_list{1,2,3,4,5}) << '\n'; For the is_in test you could overload the comma operator and do something like this: template<class T> struct is_in { is_in(const std:...
69,297,978
69,304,522
Implicit conversion sequence from {} in a copy-initialization context for a type with an explicit default constructor
(Consider this question for C++17 and forward) LWG issue 3562(+), whether nullopt_t's requirement to not be DefaultConstructible could be superseded with the explicit explicitly-defaulted default-constructor of other tag types: struct nullopt_t { explicit nullopt_t() = default; }; was closed as not a defect (NAD), w...
GCC is right, and Clang and MSVC are wrong. This is highlighted in: CWG1228: Copy-list-initialization and explicit constructors which was also closed as NAD. Somewhat surprisingly, the rules regarding explicit constructors differ between copy-list-initialization ([over.match.list]) and copy-initialization ([over.matc...
69,298,110
69,298,264
How do I read from cin until it is empty?
I am trying to read pairs of lines from a file passed in through the cin. I need to read until the file is empty. If one line of the pair is empty, I need to save that line as "". If both lines are empty, then both need to be saved and processed as "". I am using the getline to read the lines in, with a while-loop that...
If the file contains two line feeds in a row this would not work. You can use cin.eof() to check when you’ve reached the end of the file. If it returns 1 then you’ve attempted to read beyond the end of the file.
69,298,302
69,298,938
Inlcude fftw3.h with cmake in a linux environment
I want to use fftw library. In my cpp file I included as #include <fftw3.h> I downloaded the library and I saved it in ./fftw Then I typed: cd fftw ./configure make make install cd .. In my project I am already using OpenCV, so my CMakeLists.txt is: cmake_minimum_required(VERSION 2.8) # CMake version check project( ma...
You can also use ./configure --prefix /where/you/want/to/install to set the directory you want the library to be installed in then make sure that you run make install inside ./fftw directory. You may need to use sudo make install depending on the path and permissions. Change your CMakeLists.txt to include the following...
69,299,093
69,299,232
Unexpected behaviour when using inheritance
I have a Base class, which is then inherited by Foo, and Foo is in turn inehrited by Bar. Here is the header file base.h for my Base class: #pragma once class Base { public: void runExample(); private: virtual void print(); }; And the implementation base.cpp: #include "base.h" void Base::run...
In C++, data members cannot be "overridden" as you expect, and a reference to toPrint will not be dynamically bound to equally named data members in subclasses. With class Bar : public Foo { ... const char* toPrint; // "overrides" toPrint from parent class Foo? }; you introduce a member variable Bar::t...
69,299,142
69,299,573
Why does std::inlcudes use the less than operator in the condition rather than the equality operator?
I have this implementation of the algorithm std::includes from https://en.cppreference.com/w/cpp/algorithm/includes template<class InputIt1, class InputIt2> bool includes(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2) { for (; first2 != last2; ++first1) { if (first1 == l...
The algorithm is working on a sorted range. You need a < relation to sort a range of elements, but not necessarily a == relation, hence using < poses less restrictions and is more generic. Also consider that most algorithms and containers use < rather than == to compare elements. See for example std::map: Everywhere ...
69,299,277
69,299,431
How do I input a quadratic equation in C++?
We were given an assignment to program the following, which I have been trying to figure out how to solve for the last 2 hours but to no avail. How do you actually solve a complex formula having different operations in one mathematical expression? For you to properly understand which of the operations are to be solv...
You use this code: result = a * pow(x, 2) + b * x + c;
69,299,285
69,343,256
Qt: Import Qml Module in imported Javascript resource
I like to access a registered QObject from within an imported js resource (qml -> .js -> Module). Access from QML works, but using ".import" as explained in the docs from within the js file does not. Some related issues raise the impression it may work (another) or not. Is it generally possible and how, only possible f...
Got an answer from support: Apparently, you need to prefix the Module with the import namespace, i.e. MyModule.MyModule.DDD instead of MyModule.DDD: .import org.example.MyModule 1.0 as MyModule [...] console.log(MyModule.MyModule, MyModule.MyModule.DDD) [...]
69,299,652
69,299,761
Is it possible to use continue keyword outside a loop in C++?
According to ISO C++: The continue statement shall occur only in an iteration-statement and causes control to pass to the loop-continuation portion of the smallest enclosing iteration-statement, that is, to the end of the loop. More precisely, in each of the statements while (foo) { do { f...
This is slight phrasing issue. What the quote means is that in for (;;) { { // ... } contin: ; } The ... can be anything, including another iteration statement. for (;;) { { while(foo()) { // ... continue; } } contin: ; } The continue; that is not nested inside another looping cons...
69,299,663
69,300,216
change the value inside the address using a patern?
I am a modder and I need to change the value of the object position. I inject into the game using my dll file. I have a pattern like this 9F4FF 0 C4 A8 70 39 41 and an address like this 0x7FF6CC7DCCD. I found this address & pattern using cheat engine and x64 Debug. I need to change the value at this address using this ...
you can use function defined in window header ... they are : ReadProcessMemory () WriteProcessMemory () BOOL WriteProcessMemory( HANDLE hProcess, (LPVOID lpBaseAddress)0x7FF6CC7DCCD, (LPCVOID lpBuffer)yourDataBuffer, (SIZE_T nSize)Sizeof(yourDataBuffer), (SIZE_T *lpNumberOfBytesWritten)outWritten );
69,299,784
69,301,984
Can I get the raw pointer for a std::stringstream accumulated data with 0-copy?
Here is what I would like to do: std::stringstream s; s<<"Some "<<std::hex<<123<<" hex data"<<...; Having this s, I would very much like to pass it around, and that is possible easily. However, at some point, there is a need to (conceptually) pass it to an interface that only accepts const void */size_t pair which des...
Well in C++ 20 you could do this #include <iostream> #include <ios> #include <sstream> void c_style_func(const char* cp, std::size_t size) { std::cout << std::string_view (cp,size) << "\n"; } int main() { std::stringstream s; s << "Hi there! " << std::hex << 0xdeadbeef; auto view = s.view(); c_s...
69,299,925
69,300,011
std: :array -- difference between size() and max_size()
What is the difference between size() and max_size() functions for std: :array in C++? array<int,5> arr{ 1, 2, 3, 4, 5 }; cout << arr.size(); /* Output : 5 */ array<int, 5> arr{ 1, 2, 3, 4, 5 }; cout << arr.max_size(); /* Output : 5 */
What is the difference between size() and max_size() functions for std: :array in C++? The latter has prefix max_. There is no other practical difference between them for std::array. The difference is conceptual. size is the current number of elements in the container, and max_size is a theoretical upper bound to how...
69,300,068
69,300,143
Call of an object of a class type without appropriate operator(). Inside a .cpp file
I declared a class and then an object, but when I want to use my object, it gives me an error. I searched a bit on Google, but didn't understand what my problem is. The way I declared my class / object is the same as I usually do, and this is the first time it doesn't work. Here's my .cpp: #include <iostream> #include...
Well, first thing's first, you are trying to use the operator() of a member of type std::string. That operator indeed does not exist. If you want to set the value of hero->name to nam, you'd have to do something like this: hero->name = std::string(nam); Second - why are you using C methods in C++? Using scanf() to inp...
69,300,854
69,301,290
Check if input string has leading or trailing whitespaces in C++?
I am trying to validate a single-line input string in C++11 to see if it contains any leading / trailing whitespaces. My code now looks like this: bool is_valid(const std::string& s) { auto start = s.begin(); auto end = s.end(); if (std::isspace(*start) || std::isspace(*end)) { return false; } ...
A simple test for std::string::front() and std::string::back() could have been done after testing for the empty string: bool is_valid(const std::string& s) { return s.empty() || (!std::isspace(static_cast<unsigned char>(s.front())) && !std::isspace(static_cast<unsigned char>(s.back()))); }
69,301,510
69,301,548
Static var in loop could be way to optimize in c++?
I think non-static var in loop could make some overhead (construct / destruct for each loop). Am I right? then why we don't use static var in main-loop? for(;;){ type1 var1; type2 var2; //(var1, var2 construct here ) .... // Do something .... //(var1, var2 destruct here ) } for(;;){ static type1 var1; s...
Your second snippet is not thread safe. These days, you always need to consider thread safety as computational gains have moved from faster clock speeds to more processor cores. You can trust a compiler to optimise out the first snippet. If you're ever in doubt, check the generated assembly.
69,301,732
69,302,135
Integrating C++ class from subfolder in QML
I am currently working on a c++ integration to QML and so far everything worked fine. I got my backend classes exposed and working. Now that I expanded my application I wanted to split my c++ backend into subfolders to have a better project overview. Now I'm running into linking issues where the backend files which are...
You get those errors just because some header files are not in path and the compiler cannot find them. As you said that you restructured the directory template, you will only need to add appropriate include paths to the INCLUDEPATH parameter in your .pro file like : INCLUDEPATH += $$PWD/new/include/path Do it for ever...
69,301,997
69,317,133
Android OpenGL ES 3.0 Skeletal Animations glitch with UBO
I've been spending the better part of the last 2 days hunting down an OpenGL ES bug I've encountered only on some devices. In detail: I'm trying to implement skeletal animations, using the following GLSL code: #ifndef NR_BONES_INC #define NR_BONES_INC #ifndef NR_MAX_BONES #define NR_MAX_BONES 256 #endif in ivec4 aBon...
I finally figured it out. When binding my bone IDs I used glVertexAttribPointer() instead of glVertexAttribIPointer(). I was sending the correct type (GL_INT) to glVertexAttribPointer(), but I didn't read this line in the docs: For glVertexAttribPointer() [...] values will be converted to floats [...] As usual, RTFM ...
69,302,003
69,302,290
How to use c++20 concepts to compile-time enforce match of number of args for given type
I'm using policy-based design, and I have several policies implementation (that use same interface), but one of the policies needs a different number of args for construction. So i've used in my class variadic template arguments (typename... InitArgs) and I forward them using std::forward to contructor of policy type. ...
You need to put a constraint on the constructor. template <typename... Args> PolicyManager(Args&&... args) requires std::constructible_from<T, Args&&...> Note also that the Args template parameter pack should be on the constructor to ensure the arguments are correctly forwarded.
69,302,362
69,302,664
Lambda function, arguments and logic in c++
I am new to using lambda functions in C++. I have been researching the web, and found several articles, explaining the syntax and purpose of lambda function, but I have not come found articles which are clearly giving an explaining how to write the inner logic of a lambda function. For example During sorting a vector i...
Your question has nothing to do with lambdas, but with the std::sort function. Indeed, if you read the documentation about the third parameter (the comparison function, the lambda in your case), it says: comparison function object which returns ​true if the first argument is less than (i.e. is ordered before) the seco...
69,302,449
69,302,646
Rearranged vector elements after std::unique
I'm currently working through Stanley Lippman's C++ Primer. In Chapter 10 generic algorithms are introduced. As an example std::sort, std::unique and the std::vector member function erase shall be used to remove duplicate elements within a vector. To see how a vectors elements are rearranged by std::unique I tried to p...
std::unique is a destructive process. Quoting cppreference, Removing is done by shifting the elements in the range in such a way that elements to be erased are overwritten. This means that any elements after the new end iterator returned by std::unique are going to be in a valid but unspecified state. They aren't m...
69,302,496
69,303,285
GNURadio OOT Module - Undefined symbol error
I am implementing a convolutional encoder-decoder OOT Module in GNU Radio 3.8 in C++. When running the python tests I've written for the encoder and decoder, I get the following error: ImportError: undefined symbol: _ZN2gr5a3sat13conv_dec_impl9generatorE The generator variable is declared in the conv_dec_impl header fi...
The generator variable is declared in the conv_dec_impl header file as: inline static const bool generator[2][7] = {{1, 0, 0, 1, 1, 1, 1}, {1, 1, 0, 1, 1, 0, 1}} Move the generator definition to the .cpp file. Also make sure you don't have a previous version of your OOT block that lacks this symbol already installed....
69,302,647
69,312,173
Gmock - matching structures with more than two vairables
Unlike the question in Gmock - matching structures, I'm wondring how I could create a matcher for a struct with >2 members. Let's say I've got a structure of 8 members, and that MyFun() takes a pointer to a SomeStruct_t as an argument. typedef struct { int data_1; int data_2; int data_3; int data_4; int data_...
MATCHER_P(MyMatcher, MyStruct, "arg struct does not match expected struct") { return (arg.data_1 == MyStruct.data_1) && (arg.data_2 == MyStruct.data_2) && (arg.data_3 == MyStruct.data_3) && (arg.data_4 == MyStruct.data_4) && (arg.data_5 == MyStruct.data_5) && (arg.data_6 == MyStruct.data_6) && (arg.d...
69,302,800
71,861,246
A question about vcpkg and pcl/visualization
first, I used : ./vcpkg install pcl to install pcl. However, I don't notice that this command could not install vtk and use pcl/visualization. I succeed in installing and using pcl(except visualiztion). So, I try follow : ./vcpkg install pcl[vtk,qt] --rescure Actually, when I wanted to use I could still not #include<...
I had to run it the following way to fix this issue: vcpkg install pcl[vtk]:x64-windows --featurepackages --recurse Not sure whether x64-windows specifier is important, but keep in mind that VCPKG installs x86 libraries by default. Also please not that the option you have used is misspelled: it is --recurse, not --res...
69,303,706
69,303,747
traversing a binary tree in postorder method
I'm new in binary tree, i want to traverse the 2 node in the binary tree but the output result into a random number or no output. Here's the driver function: int main(){ node *root, *num2; bt tree; root = new node; root->data = 12; root->left = num2; root->right = NULL; tree.root = root; num...
When you write root->left = num2; num2 is uninitalized yet. So it is a random adres in memory. So root->left (and start->left inside the postorder(); function). So you will call the postorder_impl(); function with an undefined adress will be is a random memoryadres even after you set num2 to a valid node. Put num2 = n...
69,303,724
69,303,999
Why does basic_istream_view inherit view_interface?
basic_istream_view is a simple input_range in C++20 and has only one begin() and end() function: template<movable Val, class CharT, class Traits> requires default_­initializable<Val> && stream-extractable<Val, CharT, Traits> class basic_istream_view : public view_interface< ...
Just because the member functions of view_interface today all need forward ranges doesn't mean that we will never add member functions in the future that can work on input ranges too. Also, why not?
69,304,028
69,304,295
How to convert tuple into initializer list
I make large tuple with std::make_tuple function. something like this template <class ...T> QCborArray array(const T&... args) { return {args...}; } but with tuple instead of parameter pack
You can use std::apply and a variadic lambda to do this. That would look like template <class Tuple> QCborArray array(Tuple&& tuple) { return std::apply([](auto&&... args) { return QCborArray{args...}; }, std::forward<Tuple>(tuple)); }
69,304,436
69,304,767
How to parse CSV by columns and save into arrays C++
I'm a new learner of C++. I have some data saved in Data.csv like this: S0001 S0002 S0003 S0004 ... 0 10.289461 17.012874 1 11.491483 13.053712 2 10.404887 12.190057 3 10.502540 16.363996 ... ... 4 11.102104 12.795502 5 13.205706 13.7070...
You can only read text file line-by-line. If you only need ONE column (unlikely), you could parse that value out of the line and push it into a vector. If you need to load ALL columns in one pass, create a vector of vectors and push parsed values into a different column vectors.
69,304,461
69,588,378
Code algorithms inside React Native project
I'm new to React Native and the app I'm building needs to run some algorithms. Is there any way to run functions from a lower-level programming language inside the React app? I need this because the algorithms I'm running are really time-consuming and it would take way too much time to run it in JavaScript. Is there an...
This is not a React-specific problem. You want to run native c/c++ logic inside a js/typescript program. Either use assembly script (similar to typescript) or web assembly (convert native c/c++ to wasm which can be imported in any js/typescript environment). https://www.youtube.com/watch?v=9lxnm9a-Yi8&ab_channel=Maniya...
69,304,677
69,304,708
OPCUA sdk include path
I have trouble with include uaplatformlayer.h in example from OPCUA client example. I found this example in SDK. I tried to do own makefile, to build example client lesson01. I use Visual Studio Code. It can't find this .h file. #include "uaplatformlayer.h" #include "sampleclient.h" int main(int, char*[]) { U...
You need to add "includes" to the recipe for the .o files: %.o : %.cpp $(cc) $(cflags) $(includes) -c $<
69,304,852
69,305,064
Iterate through container of structs by specific member
I have a function template<typename I> double mean(I begin, I end) { double s = 0; size_t n = 0; while(begin != end) { s += *begin++; ++n; } return s / n; } and a vector of structs T: struct T { double a; double b; }; vector<T> v; Is there an elegant way to compute...
You would need to tell mean() which member of T to look at. You can use a pointer-to-data-member for that, eg: template<typename Iter, typename T> double mean(Iter begin, Iter end, double (T::*member)) { double s = 0; size_t n = 0; while (begin != end) { s += (*begin++).*member; ++n; ...
69,305,080
69,305,478
How to alternate sort between even and odds ascendingly in C++?
I have an array of equal even and odd integers. I want to sort the array such that array would be in that pattern: even1, odd1, even2, odd2, even3, odd3,.. and so on where even1 <= even2 <= even3 and odd1 <= odd2 <= odd3. For instance if array is [1, 2, 3, 4, 5, 6]. Sorted array would be [2, 1, 4, 3, 6, 5]. I want to d...
If you create a compare function that puts all odd numbers before even and simply compares within those groups, you can in one sort have all odds sorted followed by all evens sorted. You'd then need to swap them correctly. Something like this bool cmp(int lhs, int rhs) { if ((lhs ^ rhs) & 1) // different oddness ...
69,305,116
69,305,150
How to search for a substring on a LPCSTR?
typedef _Null_terminated_ CONST CHAR *LPCSTR, *PCSTR; // ..... LPCSTR foo = "hello world"; How do I search if foo contains hello?
You can use strstr LPCSTR foo = "hello world"; char * pch = strstr (foo,"hello");
69,305,443
69,365,871
How does this array indexer helps coalesced memory access?
At here, it is defined this function: template <typename T, typename = std::enable_if_t<is_uint32_v<T> || is_uint64_v<T>>> inline T reverse_bits(T operand, int bit_count) { // Just return zero if bit_count is zero return (bit_count == 0) ? T(0) ...
You're right - the accesses you see in NTTTables::initialize are random-access and not serial. It is slower because of this "scramble". However, most of the work happens only later in DWTHandler::transform_to_rev, when the transform itself is applied. There, they need to access the roots by reverse-bits order. The arra...
69,305,896
69,305,954
Store/output a number bigger than unsigned long long can store
With user given number (n) for example n=5, I calculate the sum of 10000,10001,10002....99999. Works up until n=17, then I get a negative number or eventually a zero. So my question is how do I store a number bigger than unsigned long long lets me #include <iostream> #include <iomanip> #include <cmath> using namespace...
In case you don't want bother with installing some big number library like GMP, or you do it for some site like code wars then you have basically two options: A) create your own data type to hold bigger numbers ( in this case not really recommended, as number may be insanely huge). B) hold it as a string/char table and...
69,306,186
69,306,511
Thread safety of Vector of atomic bool
If I have a vector: std::vector<std::atomic_bool> v(8); and assuming I won't modify its size post creation, is it thread safe to call: bool result = v[2].compare_exchange_strong(false, true); * the values 8, 2, false and true are just given as an example use case.
The OP appears to be asking whether multiple threads can evaluate v[2].compare_exchange_strong(false, true) when such evaluations are potentially concurrent, without causing a data race. This will not compile because compare_exchange_strong requires an lvalue as its first argument. I will assume that this issue is cor...
69,306,238
69,306,327
Why are the integers in the array negative after reversing the array and reversing back to the original array?
void reverseArray(int arrayLength, int sequence[]){ int temparr[arrayLength]; int *pointStart = sequence; int *pointEnd = sequence + arrayLength - 1; for(int i = 0; i < arrayLength; i++){ temparr[i] = *pointEnd - i; } for(int i = 0; i < arrayLength; i++){ sequence[i] = temparr[...
You have a bug with this line: temparr[i] = *pointEnd - i; Here you are dereferencing the pointEnd pointer and subtracting i from the resulting integer. What you meant to write is: temparr[i] = *( pointEnd - i ); Here you are subtracting i from the pointEnd pointer, then dereferencing. That being said, instead of doi...
69,306,789
69,306,847
Use constexpr for optional configuration
Right now, I use something like the following to provide configuration to "sub-projects" within my code: //_config.h #ifndef _CONFIG_H #define _CONFIG_H #if defined(USE_CONFIG_H) && USE_CONFIG_H == 1 #include <config.h> #endif #ifndef CONFIG_OPTION_1 //Default value for CONFIG_OPTION_1 #define CONFIG_OPTION_1 10 #en...
Macros are the only way to make conditional compilation, so you cannot get rid of them entirely. But you can use the macro to initialise a variable: constexpr unsigned int NON_MACRO_CONFIG_OPTION_1 = CONFIG_OPTION_1; Thereby getting the benefits of types.
69,306,813
69,306,927
Trying to compare a string to a a value with tertiary/conditional operator and it doesn't work
just learning C++ here. #include <iostream> #include <string> int main() { char name[1000]; std::cout << "What is your name?\n"; std::cin.get(name, 50); name == "Shah Bhuiyan" ? std::cout << "Okay, it's you\n" : std::cout<< "Who is this?\n"; } So here I wrote a program where I created a var...
Your code is using arrays of characters. Any comparisons using == will compare their memory address. Since name and "Shah Bhuiyan" are two distinct arrays of characters, it will always be false. The obvious solution is to use c++ strings from the standard library: #include <iostream> #include <string> int main() { ...
69,307,137
69,308,608
JNI Unsatisfied Link Error in Eclipse Can't find dependent Libraries
I'm trying to invoke a C++ function from java that uses C++-style strings. The program executes just fine when I'm using C-style strings but just as I declare std::string somehow it can't find dependent libraries anymore. I checked my includes folder in eclipse environment and it does contain <string> library and all i...
<string> is a header file, and if your C++ code containing #include <string> directive compiles this means that paths of standard include folders are configured correctly. However, depending on how your project is configured to be linked to the C and C++ runtime libraries (statically or dynamically), the resulting exec...
69,307,440
69,307,588
Limit code duplication when decorating a function
I’m fairly new to programming in c++ and would like to ask how to implement something in the most efficient way. Let’s say I got a class A with two functions foo and bar. Main will instantiate and object of A and will call foo. This class does something computationally expensive, where foo might call bar and vice versa...
I would recommend to use a bool parameter class A{ public: void foo(/*params*/,bool should_print=false){ if (should_print){ //print } } void bar(/*params*/,bool should_print=false){ if (should_print){ //print } } }; If you want to print set th...
69,307,463
69,307,559
C++ Self defined function declaration error: unknown type name
I am using this to declare a user defined function to calculate the discriminant for quadratic equations: double discriminant(double a, b, c){ return b * b - 4 * a * c; } But for some reason I get the following errors: Error: unknown type name 'b' double calcDiscriminant(double a, b, c){ ...
When we declare a function with parameters then we have to write data-type of every parameter respectively. So, in function declaration where you have written this: double discriminant(double a, b, c) { return b * b - 4 * a * c; } Declare it like this: double discriminant(double a, double b, double c) { return...
69,307,512
69,307,810
How to copy every N-th byte(s) of a C array
I am writing bit of code in C++ where I want to play a .wav file and perform an FFT (with fftw) on it as it comes (and eventually display that FFT on screen with ncurses). This is mainly just as a "for giggles/to see if I can" project, so I have no restrictions on what I can or can't use aside from wanting to try to ke...
Very hard OP's solution can be simplified (for copying bytes): // pseudocode const char* s = audio_pos; for (int d = 0; s < audio_pos + len; d++, s += 2*sizeof(sample)) { fftw_in[d] = *s; } If I new what fftw_in is, I would memcpy blocks sizeof(*fftw_in).
69,307,927
69,307,949
Variadic template constructor to fill internal vector of std::variant
I got the following class class A { std::string name; std::vector<std::variant<int,float>> data; }; my goal is to have a constructor to fill this class with variable number of argument. Examples A("hello", 1, 2.0, 1) A("hello", 1, 2.0, 1.2) .... I tried something like template <typename... ARGS> A(std::string n...
You trying to call the constructor of data a bunch of times in the initializer list. Remember that variadic templates are unfolded at compile time. You will likely need to handle this outside the initializer list. Something like: template <typename... ARGS> A(std::string n, ARGS... arguments) : name(n) { data.reser...
69,308,319
69,309,050
Creating a COM pointer that supports range-based iteration
Iterating over certain COM collection objects can be cumbersome, so I'm trying to create some COM pointers that support range-based iteration. They're derived from CComPtr. For example, here's an IShellItemArray pointer that I came up with that allows range-based iteration over its IShellItems (so you can iterate ove...
All IEnum... interfaces have a common design, even though they output different element types. That design can lend itself to C++ templates, so I would suggest separating out CIterator into a standalone template class that can iterate any IEnum... interface, and then have CShellWindowsPtr and CShellItemArrayPtr make us...
69,308,340
69,308,401
How to input 2dimensional array using pointers in c++
void get(int r,int c,int *ptr){ int i,j,k; cout<<"Enter Elements of a matrix:"<<endl; for(i=0;i<r;i++){ for(j=0;j<r;j++){ cin>>k; *(ptr + (i*c) + j)=k; } } } This is my code. *(ptr + (i*c) + j)=k; Can anyone explain how the above line of code works?
A pointer is an address in memory where some piece of information is stored. This address takes the form of a number. How many bits that number uses is platform-dependent. Since that address is a number, we can do math with it. *(ptr + (i*c) + j)=k; Can be the following when we understand operator precedence and use w...
69,309,112
69,309,162
Make a function has higher precedence than another
So I have a function: void foo(char a = 'A', int b = 0) { // code } And I have another one: void foo(int b = 0, char a = 'A') { //code } Then if I call foo(), it will return an error because the compiler can't decide which function to call. So can I make a function that has higher precedence than another? So ...
You probably want to use function overloading here: void foo(char a, int b = 0) { // code } void foo(int b, char a = 'A') { //code } void foo() { foo(0); // Or 'foo('A');', depends on which overload you want to give priority } Edit: Or you could just remove the first default argument from one of the over...
69,309,225
69,309,299
How to use while loops properly?
I'm a beginner in programming and here you could see that this program will get ask the user to input their grade from their first to third periodic, which will then display the average. Everything was going fine not until I get to the part where the user will be asked if he would like to average another set, when I ty...
When your while loop is triggered, it goes back to do statement and executes the program from there. Now the problem is that the value in the do scope doesn't get updated because you are not giving input again. The simple solution I believe is that you should move your do statement to the top. do { cout << "Enter y...
69,309,469
69,310,477
‘operator/’ is not a member of ‘std::filesystem’; did you mean ‘operator~'
I am trying to install the MMMTools https://mmm.humanoids.kit.edu/installation.html. My cmake version is 3.16.3. I went through every step without any errors until this section cd ~/MMMCore mkdir build cd build cmake -DCMAKE_BUILD_TYPE=Release .. make The make command returns me the following error. (base) kong@kon...
Due to LWG 3065 the operator is now hidden and shouldn't be called directly. std::filesystem::path filenameNewComplete = std::filesystem::operator/(filenameBasePath, filenameNew); Should just be: std::filesystem::path filenameNewComplete = filenameBasePath / filenameNew; I'm guessing the code has only been tested aga...
69,310,015
69,310,087
Single Linked List addition fault
The function to add a new list item in a single linked list void linked_list::push(int n) { node *tmp = new node; tmp->data = n; tmp->next = NULL; if (head == NULL) { head = tmp; tail = tmp; } else { tail->next = tmp; tail = tmp; } } and for display, I used...
In order to print them all out, condition inside while has to be: while(tmp != NULL) void linked_list::display() { if (head == NULL) { cout << "Empty list" << endl; } else { node *tmp = head; while (tmp != NULL) { cout << tmp->data << " "; tmp = tmp->next; ...
69,310,441
69,310,463
c++ Repeated if condition difference with bracket
I'm studying coding test with web compiler and i have an incomprehensible problem. Does this bracket makes difference? if(i < waitLine) { if(bridge.update(truck_weights[i])) i++; } else bridge.update(0); this one is ok. if(i < waitLine) if(bridge.update(truck_wei...
This: if(i < waitLine) if(bridge.update(truck_weights[i])) i++; else bridge.update(0); is the same as this: if(i < waitLine) { if(bridge.update(truck_weights[i])) { i++; } else { bridge.update(0); } } Not: if(i < waitLine)...
69,310,688
69,312,063
strict total order of std::less<Pointer>
This question comes from this comment: If you have say two vectors a and b, the total order is permitted to be &a[0], &b[0], &a[1], &b[1], &a[2], &b[2], ..., i.e., with the elements interleaved. Is that order permitted? I don't known much about the standard. That seems correct if I read only sections directly related...
Yes, different arrays (that are not part of the same complete object) can be interleaved in the ordering, but each array must separately be ordered correctly—this is what it means that the total order must be consistent with the partial order established by the built-in operators. The fact that a+1 points to the eleme...
69,311,387
69,311,412
Is it possible to initialize new std::vector in one line?
I just wonder if it is possible to new and initialize a std::vector at the same time, something like, do the two things in one line: std::vector<int>* vec = new std::vector<int>(){3, 4}; instead of, first: std::vector<int>* vec = new std::vector<int>(); then: vec->push_back(3); vec->puch_back(4);
I just wonder if is possible to new and initialize a std::vector at the same time, something like, do the two things in one line? Yes, you can, via std::initializer_list constructor10 of std::vector constexpr vector( std::initializer_list<T> init, const Allocator& alloc = Allocator() ); (since C++20...
69,311,574
69,311,690
CppCoreGuidlines R.33 Why pass `unique_ptr` by reference?
The CppCoreGuidlines rule R.33 suggests to Take a unique_ptr<widget>& parameter to express that a function reseats the widget. Reason Using unique_ptr in this way both documents and enforces the function call’s reseating semantics. Note “reseat” means “making a pointer or a smart pointer refer to a different object.” ...
When the function's purpose is to reseat/change the underlying object the pointer is pointing to, aren't we stealing the ownership from the caller this way No. Neither when we "reseat" a pointer, nor when we change the pointed object, do we take ownership of the pointer i.e. we aren't transferring the ownership. Is ...
69,311,646
69,311,739
Logic error in remove duplicates in a vector while preserving the order function
void vectorDeduplicator(std::vector<std::string>& inputVector){ for(int i = 0; i < inputVector.size() - 1; i++){ for(int x = 1; x <= inputVector.size() - 1; x++) if(inputVector.at(i) == inputVector.at(x) && i != x){ inputVector.erase(inputVector.begin() + x); ...
The problem is you ignore one value as you erase. You need to decrement x: #include <vector> #include <iostream> void vectorDeduplicator(std::vector<int>& inputVector) { for(int i = 0; i < inputVector.size() - 1; i++) { for(int x = 1; x < inputVector.size(); x++) { if(inp...
69,311,888
69,312,170
Json nlohmann : generic function that return a value that is deep of several keys
I need a function to get the content of a value which need more than one key to access of it. In the example bellow, I successfully get value of file_content["happy"] but how to write my function get() to accept more than one key for example access to file_content["answer"]["everything"] ? Note that it could be more th...
Using a loop should do the job: json get(std::initializer_list<std::string> keys) { json data = file_content; for (auto& key : keys) { data = data[key]; } return data; } requires extra {} at call site: my_conf.get({"answer", "everything"});
69,312,288
69,313,044
Access C++ signals/slots globally in all QML files
I want to access a C++ class (signals and slots) in all my qml files. When I set up a Connection in main.qml, I am able to receive the signal. However, in any other qml file (MainMenu.qml here), I can not access the signal. I can send from other qml files using slots functions, but not read the signals. Any idea how to...
There are two ways that I'm aware of. The Game class is a QObject. Instead of instantiating it in your C++ code and calling setContextProperty on the rootContext, it's better to register Game instance as a QML singleton object. You will then have access to it wherever you import it. Here is an example (TestClass will ...
69,312,394
69,340,697
SWIG: how to wrap a function that takes reference to int64_t as parameter?
My interface file TestRef.i: %module test_ref %{ #include <iostream> %} %include <stdint.i> %include <typemaps.i> %inline %{ struct Result { uint64_t len; void* data; }; Result read(int64_t& idx) { std::cout << idx << std::endl; // just to use idx idx++; return Result{1, nullptr}; } void set_valu...
According to this post, [t]he typemap must also be declared before SWIG parses test. Changing my TestRef.i to %module test_ref %{ #include <iostream> %} %include <stdint.i> %include <typemaps.i> %apply int64_t& INOUT { int64_t& idx }; %apply double& INOUT { double& a }; %inline %{ struct Result { uint64_t len; ...
69,312,541
69,312,667
How to refactor nested for loop?
I have two similar functions. Both functions contain a nested for -loop. How I can combine these two functions to decrease duplicated code. The only difference between funcA and funcB is funcB calls func_2 in the loop. The two functions like below. void funcA() { for (int i = 0; i < size; i++) { for (in...
Perhaps I am taking it a little too far, but there is no apparent reason for the nested loops (neither func_1() nor func_2() depend on i or j). A straight forward way to pass a callable is the following: template <typename F> void func(F f) { for (int i=0; i < size*size; ++i) f(); } and then call either func...
69,313,026
69,313,082
Undefined Behavior when using Comma Operator in C++
I am trying to learn how expression are evaluated in C++. So trying out and reading different examples. Below is the code about which i am unable to understand whether it will produce undefined behavior or not. The code is from here. So i guess since they have used it, this must not be UB. But i have my doubts. #includ...
From the same page on cppreference: In a comma expression E1, E2, the expression E1 is evaluated, its result is discarded (although if it has class type, it won't be destroyed until the end of the containing full expression), and its side effects are completed before evaluation of the expression E2 begins (note that a...
69,313,201
69,313,388
Why when I changed the value of the variable using pointer, the value was still the same?
can someone explain why the output of firstvalue is 10 although it is manipulated at the end when writing *p=20? Code: #include <iostream> using namespace std; int main(){ int firstvalue = 5, secondvalue = 15; int * p1, * p2; p1 = &firstvalue; p2 = &secondvalue; *p1 = 10; *p2 = *p1...
Perhaps a more "graphical" illustration might help you understand what's happening? After the assignments p1 = &firstvalue; p2 = &secondvalue; you have something which looks like this: +----+ +------------+ | p1 | --> | firstvalue | +----+ +------------+ +----+ +-------------+ | p2 | --> | secondvalue | ...
69,313,394
69,313,585
Can someone please explain me why can't return a smart pointer?
I was wondering what could be wrong with returning a smart pointer. The compiler throws that the constructor itself has been deleted. So I tried with returning the reference and it works, why is this possible? #include <iostream> #include <memory> using namespace std; using unique_int = std::unique_ptr<int>; unique_in...
Let's examine what would happen when you return a std::unique_ptr by value. unique_int function creates a temporary object of std::unique_ptr type, for which a copy-initialization of the temporary std::unique_ptr from p_int, which you return. But the whole point of std::unique_ptr, is that it cannot be copied, only mov...
69,313,574
69,313,680
Converting a pointer-to-member type to a simple pointer type
I have the following type, which I get with decltype QString UserInfo::*& I can remove the & part by wrapping decltype with std::remove_reference_t but I also want to remove UserInfo::* part How can I do that so I can use only QString type in my templates I'm using this template in initializer list where I don't have ...
Using a valid object is not necessary in unevaluated contexts (like decltype). To exaggerate a little, you could even dereference a null pointer in there, and nothing bad would happen, since the dereference is never actually evaluated. To create an object of a type that is not valid, but can be used in unevaluated cont...
69,313,789
69,412,326
Access files generated in the backend
I'm a beginner. I started exploring Pythran and Transonic a few days back. I learned that Pythran generates a C++ file from the Python input file. I want to read those C++ generated files in the backend. Do anyone of you have any idea about accessing files generated in the backend? I'm implementing Pythran using Transo...
Have you tried running pythran with the --help option? ... optional arguments: -h, --help show this help message and exit -o OUTPUT_FILE path to generated file. Honors %{ext}. -P only run the high-level optimizer, do not compile -E only run the translator, do ...
69,313,851
69,313,877
"using" keyword - passing iterator to function
I am writing a class Sequence. Its constructor takes two templated vector iterators as arguments. Here is the code: template <class T> using ConstIterator_t = typename std::vector<T>::const_iterator; template <class T> class Sequence{ public: Sequence(ConstIterator_t start, ConstIterator_t end); //rest of the code }; ...
ConstIterator_t is a template (an alias template) and you need to specify template argument for it. E.g. template <class T> using ConstIterator_t = typename std::vector<T>::const_iterator; template <class T> class Sequence{ public: Sequence(ConstIterator_t<T> start, ConstIterator_t<T> end); // same as Seque...