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
61,767,089
61,767,139
Does accessing vector elements by reference reduce space complexity in C++?
I have a simple C++ algorithm that processes elements from a vector. I am passing my function the vector by reference, and accessing the vector's element by reference using a foreach loop like this: vector<int>& gradingStudents(vector<int>& grades) { for(int& grade : grades) { if (grade > 37) { ...
Since you are only using references in regards to your vector, you do not need any more memory. The only write you have is grade += (5-n), and like any int (or number type) this happens where the variable is currently addressed - in this case the vector itself. You have a single extra int allocated here as far as I can...
61,767,402
61,767,541
Function pointer assignment cause error after creating DLL
I written a class for my application. in this class there is static function pointer that used for communication over network socket. at startup, i assign this function pointer to a function outside of the class and work fine without any problem. now i created DLL from my class, but when i assign this pointer to my fun...
The error indicates that the function needs to be in the nmspace namespace. Try the following: namespace nmspace { bool MyFunc(uint8_t* TX_buffer, size_t TX_size, size_t Port) { return true; } } After doing that, you need to clean up the rest of the declarations. The following full program compil...
61,767,563
61,769,110
How to suppress inline function used but never defined warning in g++
Context: I'm doing some compile time programming which involves manipulating types using constexpr functions that are only evaluated in a decltype context. For example a pop function that removes the first type from a list of types: template <typename T0, typename... T1toN> constexpr auto pop(List<T0, T1toN...>) -> Lis...
In template <typename ...> struct List{}; template <typename T0, typename... T1toN> constexpr auto pop(List<T0, T1toN...>) -> List<T1toN...>; template <typename T0, typename... T1toN> constexpr auto pop2(List<T0, T1toN...> l) { return pop(l); } // You use pop constexpr List<int, int> my_type_list; using type = declt...
61,768,023
61,788,076
Programmatically get Windows Setting | Account Setting | Require Sign In
I have an issue when tried to get Windows Setting programmatically. I want to detect if user have config Require Sign-In when PC wake up from sleep or not. I can get information from Screen Saver Setting only, but it's not sufficient in this case. I googling a lot but can not find any solution, Is it possible? Thanks S...
OK, after a long search, I found the answer you need, with the help of PowerGetActiveScheme () and PowerReadDCValueIndex () Code Sample: (C#) According to your needs, you can easily convert to C ++. using System; using System.Runtime.InteropServices; namespace PowrprofTest { class Program { private st...
61,768,679
61,770,035
C++ Undeclared Identifier in Template Template Parameter
I have a C++ class that is templatized like so: template <typename Operator> class MyClass; Where Operator can also be templatized itself into: template <typename Param1, typename Param2, typename Param3> class MyOperator; Now, when I try to write a templatized method for the class, MyClass, I get an error - this cod...
Parameter names in template template parameter are just informative (as names for parameters in function pointer void (*f)(int a, int b) (a and b cannot be used)), you should do: template <template <typename, typename, typename> typename Operator, typename Param1, typename Param2, typename Param3> void MyClas...
61,768,725
61,769,185
Dependencies when using C++20 conceptual template function specialization
I was doing some tests with the following C++20 code (built with current GCC10): template <typename ToT, typename FromT> ToT myfunction(const FromT& pFrom) = delete; template <typename ToT, typename FromT> struct myclass { inline ToT myclassmethod(const FromT& pFrom) { return myfunction<ToT, FromT>(pFrom);...
Those aren’t specializations, but overloads. As such, if they appear after their caller they are found only by ADL. As usual, you can use partial specializations (constrained ones in this case) with a forwarding wrapper. (Of course, that’s not very interesting with std::same_as.)
61,769,273
61,769,372
<format> header not found (C++)
I want to use the new C++20 <format> header. But when I try to #include it, it apparently doesn't exist in my current stdlib. I tried using clang++ and g++, but neither of them work. Yes, I specified the C++ standard to be "c++2a" in the tasks.json file in VSCode. What am I doing wrong?
You can view an overview of compiler support here: https://en.cppreference.com/w/cpp/compiler_support According to the table, up to today (May 13 '20 at 8:07) no compiler supports P0645R10: Text formatting. The overview specifically for MSVS can be found here: https://learn.microsoft.com/en-us/cpp/overview/visual-cpp-l...
61,770,307
61,770,509
Which condition condones best to good practice?
I am refactoring old code, thus trying to follow best practices while I do so. My real case resembles the below example: #define FOO 0x0001 long bar = 0; Should I test like this: if(bar & FOO) Or like this: if(bar == FOO) After seeing the comments, I am editing in order to clear things out: bar can be any valid lon...
These two convey different meanings. x==y means "Check that x is exactly equal to y", x&y means "check if any of bits in y are set in x". The result is the same, but what if FOO will change? If I come and 5 years in change FOO to 3, is x=1 still valid? Also, in modern C++ you should avoid macros. constexpr unsigned FO...
61,770,490
61,770,810
Specialize class template for variadic parameters
I want to specialize a class template for variadic parameters: template <typename... Ts> struct TypeList { }; template <typename T> class Foo { }; //Is next "specialization" even possible? template <typename... Ts> class Foo<TypeList<Ts...>> { }; Foo<TypeList<int, int>> i1{}; // OK Foo<int, int> i2{}; // NOK: error...
What you can do, to allow both syntaxs: template <typename ... Ts> class Foo : Foo<TypeList<Ts...>> { }; // Specialization template <typename ... Ts> class Foo<TypeList<Ts...>> { // ... };
61,770,518
61,773,404
boost::program_options reports no error when unexpected positional argument is specified
Here is a simple program using boost to parse options: #include <iostream> #include <boost/program_options.hpp> namespace po = boost::program_options; int main(int argc, char **argv) { try { size_t param = std::numeric_limits<size_t>::max(); po::options_description desc("Syntax: [options] \"...
Positionals are accepted by default. You could either check that you received none, or you can specify that you don't allow any: po::positional_options_description positionals; po::store(po::command_line_parser(args.size(), args.data()) .options(desc) .positional(positionals) ...
61,770,522
61,770,660
How do i iterate over alternate elements(or taking leaps of specific size) in set?
In other words, what I mean to say is : Is itr+=2 a valid argument in c++ ?, where (itr is an iterator to first element of the set). If so, then the following piece of code should work: In this piece if code, the code written in /comment section/ functions well, while the code not in comment section do not. Help me out...
Is itr+=2 a valid argument in c++? It depends on the container type. For example, it would be perfectly valid for std::vector or std::array, but not for std::set. Each container, due to its nature, provides different types of iterators. std::set only provides BidirectionalIterator, which do not support jumping over a...
61,770,961
61,877,779
How to get camera extrinsincs in Windows Media Foundation?
I'm trying to get camera extrinsics from all HoloLens sensors (working in research mode). I've found the CameraExtrinsics structure in Windows Media Foundation ( [here] https://learn.microsoft.com/en-us/windows/win32/api/mfapi/ns-mfapi-mfcameraextrinsics ) but I can't find any example on how to get it. My question is: ...
So I found the solution and I'll share it here in case someone else struggles with this as well. You have to get it from the frame properties (documentation) via a GUID (in my case the GUID was "6B761658-B7EC-4C3B-8225-8623CABEC31D").
61,771,084
61,788,413
How to use IEnumerable with Process.Start's output event handler?
I have following use case. I have created one EXE in from Unmanned C++. let say printing 1 - 100 on console. output is captured into below output callback List<int> a = new List<int>(); process.OutputDataReceived += new DataReceivedEventHandler((sender, e) => { a.add(Convert.ToInt(e.Data)); } However I want to us...
The next approach can be used to read the output of the external process while it is running: var proc = new Process { StartInfo = { FileName = "process_name.exe", UseShellExecute = false, RedirectStandardOutput = true, }, // Set this property to true to enable external // pr...
61,771,170
61,771,369
Configuring CMake with graphviz library
I'm trying to make a function which will generate an image with graph from .dot file, so i have to use graphviz library, here is this function: #include <fstream> #include <gvc.h> bool draw_image(const string& path) { GVC_t *gvc; Agraph_t *gr; FILE *fp; gvc = gvContext(); fp = fopen((path + ".dot")...
gvContext is in libgvc.so, so your final CMake line should read: target_link_libraries(untitled PUBLIC cgraph gvc) This makes use of the "A plain library name" section of the target_link_libraries documentation.
61,771,323
61,771,680
How to pass an array to a class?
#include <iostream> #include <string> using namespace std; class Term; class Polynomial; class Term { public: friend class Polynomial; void set_term(string s); int get_pow(); int get_coefficient(); private: int coefficient; int pow; }; class Polynomial { public: friend class Term; Polynomial(int s,...
There's a lot of confusion over sizes here string x1; cin >> x1; int size_x1 = x1.size(); Term term1[size_x1]; for (int i = 0; i < size_x1; i += 5) { term1[i].set_term(x1.substr(i, 5)); } Polynomial p1(size_x1 / 5, term1); You didn't say what your input is, but suppose it is "1234567890" then size_x1 equals 10, s...
61,771,352
61,771,966
will it change the address of a existed key's value when inserting new keys?
In my code,there will be inserting or deleting in a std::map,but not change the value of a existed key. will it change the address of a existed key's value when inserting/deleting new keys ? int main() { std::map<int,int> m; for(int i(0);i<100000;i++){ m[i]; std::cout<< &m[0]<<std::endl; }...
The address of existing elements do not change when other elements are inserted or removed. In other words, references to the elements are not invalidated unless that particular element is erased. This is true for all node based containers which include the associative containers (map, set, unordered variants, multi va...
61,771,376
61,785,288
nth_element implementation based on modified quick_sort, not working as expected
For the purpose of understanding quick_sort I am trying to implement nth_element. As ground truth for testing I am using std::nth_element My algorithm fails on many inputs, for ex on a = {6,1,7,5,3,8,2,4,9} How to fix it? std::random_device dev; std::mt19937 rng(dev()); int kth_element(vector<long long> a, int l, i...
In case if anybody tries to implement nth_element based on Hoar partition: use 2 pointers i,j and maintain loop invariant: for k = 0..i-1 a[k] <= X and for z = j+1 .. n-1 a[z] >= X after the loop, the array might be partitioned in 2 ways: ...| j | i |... or ...| j | X | i |... all elements(left part) with idx in [L...
61,771,444
61,809,937
C++ recv not receiving anything when NIC received data
I am writing a C++ server program and a Qt client program. The problem is, recv() keeps waiting forever when tcpdump clearly shows a tcp packet from client is delivered to my network interface. Server program is ran on Centos 7.7 and compiled with g++ 4.8.5 while (true) { sockaddr_in client_addr{0}; ...
Found the error. Turned out that Client side had made three connections to the server among which only one was connected and two in queue. The packet was coming into the server not from the connected socket. That is why the opened file descriptor doesn't read anything from NIC.
61,771,945
61,774,255
Trying to build pkg-config
I'm trying to build pkg-config in Windows so that I can make GIMP plugins. To build pkg-config, I apparently need to build autoconfig and automake. To build them, I need M4. To build that, I seem to need to build autoconfig and automake. What do I need to do? I'm using MinGW-W64 and MSys2.
If you're using MSYS2 it is available to you already. Just use pacman which comes with MSYS2 from the MSYS2 shell. To update pacman's package list run: pacman -Syu --noconfirm To get pkg-config run: pacman -S --noconfirm git pkg-config If you still want to have those configure tools run: pacman -S --noconfirm git aut...
61,772,059
61,772,624
segmentation fault when allocating
I am getting a segmentation fault and would appreciate help trying to understand what I have done incorrectly. After a while of my code running I have received a coredump: Program terminated with signal SIGSEGV, Segmentation fault. struct config { int a; int b; int c; int d; }; static config* configura...
Your code assumes that config_tbl is properly initialized. As you insist that the code you posted is all that is relevant, I assume it is not properly initialized. Consider this simplified example: void foo( int* ptr) { if (ptr) delete ptr; } This is fine if ptr is either nullptr or a valid pointer (ie it points ...
61,772,524
61,772,684
c++ move semantics does not perform move
Idea is to use move semantics to avoid unnecessary copying. Given the code below: #include <iostream> #include <string> #include <utility> class Address { private: const std::string m_street; const std::string m_city; const int m_suite; public: Address(const std::string &street, const std::string &c...
The data member m_street and m_city are declared as const; then in the member initializer list of move constructor of Address like m_street {std::move(other.m_street)}, the copy constructor (but not move constructor) of std::string is used. You might want to remove the const qualifier, then you'll get Contact: John Doe...
61,772,563
61,773,837
Qt calling threads in a loop
I have a code like this with function double myfunction(double) that takes a lot of time to finish. Using Qt (https://doc.qt.io/qt-5/qtconcurrentrun.html), how can I run the loop utilizing a thread for every myfunction call to have smaller computation time? Does this make sense? std::vector<double> parameters; /...
A simple example usage of QtConcurrent::run for you own case would be something like (untested)... std::vector<double> parameters; // vector full of input values. std::vector<double> results; // Empty vector to store results. /* * Each call to QtConcurrent::run returns a QFuture. Store * these so we can ...
61,772,873
61,773,713
Unexpected behaviour of ternary operator in C++
The following is snippet from code that I've written: int n,i,j; map<int,int>mp; vector<int>vec; cin>>n; for(i=0; i<n; i++) { cin>>j; mp[j]==0? mp[j]=1,vec.push_back(j): mp[j]=1; } For the second line inside for loop, CodeBlocks-16.01 version shows the following error: second operand to the conditional operato...
To understand the error, let's take a look the operands to the conditional operator. The second operand: mp[j]=1, vec.push_back(j) The operand is two expressions separated by the comma operator. The way the comma operator works here is that it evaluates mp[j]=1 which results in value 1, it discards the value and ev...
61,772,931
61,773,096
How to unserialize a binary file into an object?
I used this method to serialize my object : void save(Obj& obj) { ofstream os("obj.dat", ofstream::binary); boost::archive::binary_oarchive ar(os, boost::archive::no_header); ar << boost::serialization::make_binary_object(&obj, sizeof(obj)); } What would be my the code for my Obj load(string fileName) ?
It's basically the same as what you had: Obj load(std::string const& filename) { std::ifstream is(filename, std::ios::binary); boost::archive::binary_iarchive ar(is, boost::archive::no_header); Obj obj; ar >> boost::serialization::make_binary_object(&obj, sizeof(obj)); return obj; } Of course, this...
61,773,063
61,773,934
Send data continuously from a c++ file to a Python script for further processing
I want to continuously receive stdout and stderr(optional) of a program. The following is the stdout of the program: got 3847 / 0 / 0 / 0 pkts/drops/pktinfisue/crpts with 40.6859 Mbps during 8.166 sec timestamp: 3412618016 0 got 3842885 / 0 / 0 / 0 pkts/drops/pktinfisue/crpts with 40.6424 Gbps during 1.00052 sec time...
You are looking for Popen class of the subprocess module in python. Python equivalent of the C function could be along the lines of from subprocess import Popen, PIPE def exec(*args): with Popen(args, stdout=PIPE) as proc: while proc.poll() is None: print(proc.stdout.read(40)) print(pr...
61,773,129
61,773,595
Elements of a Vector of pointers to structs have same address
I'm trying to implement a disjoint Forest Data Structure. In short, it is a data structure of sets with no common elements and can easily perform operations such as combining 2 sets and finding the set of an element. Each set has certain number of elements. I'm implementing a set as a tree and each element of a set is...
TreeRoot makeSet(int x){ TreeRoot tree; Node node; node.value = x; node.parent = &node; tree.nodes.push_back(&node); tree.id = node.value; node.parentTree = &tree; return tree; } node is local to the block of this for function and has automatic storage. At the end of the function, the l...
61,773,176
61,774,274
C++ Multiple inheritance problem on accessing second derived class variables
I have a base class A and in this class, there is a vector of the derived class B, and I add class C objects to this list (C is a derived class of B). But now I am not able to access any variable either from B or C. My class structure goes like this: Skill.h class Skill { public: Skill() { } vector...
I am doing some guesswork here since the question is not fully specific but it might help… Your class Skill contains three vectors (aggregation) and it’s inherited by subclasses defining skill types (inheritance). You should break these two principles apart. There should be one class containing the vectors for a charac...
61,773,200
61,773,483
How to pass in a const char* as an argument to an LPCSTR parameter?
I'd like to use this function to call the the PlaySoundA function, but the sound file I am trying to play does not open. void AudioClass::playAudio(const char* incomingData, const char* filePath) { char buffer[100]; // <- danger, only storage for 100 characters. strncpy_s(buffer, filePath, sizeof(buffer)); ...
The \r\n at the end comes from the serial port: https://www.arduino.cc/reference/en/language/functions/communication/serial/println You can skip the characters when copying: strncat_s(buffer, incomingData, strnlen(incomingData) - 2);
61,773,964
61,817,069
How to record the distance travelled by my mouse cursor in win32 application?
I am working on a project on windows desktop development in C++ using win32 API .In the application I am trying to calculate the distance travelled by my mouse cursor or you can say mouse thrashing. Thrashed Cursor—or thrashing cursor or mouse—isn’t some pun for a user so frustrated that they’re losing control of their...
Yes thats exactly what i want to do but i dont know how to implement that i was thinking to log all the coordinates as the mouse moves and calculate the total distance. SetWindowsHookEx and WH_MOUSE_LL can help you do this. You can install mouse hook to monitor mouse movements and calculate the distance between mouse c...
61,774,002
61,774,208
C vs. C++, handling of void** pointers
I found out that using a C compiler the code below works but not with a C++ compiler. I understand that casting to void** is the correct usage but I can't understand why it compiles with the C compiler even if I use the void* (commented out). #include <stdio.h> int fn(void **arg) { int *pvalue = *(int**)arg; *...
In C there is allowed to assign a pointer of the type void * to a pointer of other type. This takes place in this call fn((void *)&pvalue) where the argument has the type void * that is assigned to the function parameter that has the type void **. int fn(void **arg) { int *pvalue = *(int**)arg; *pvalue = 200; ...
61,774,111
61,776,965
Does handles from WinHTTP Async, needs to be closed?
Do you need to close the handles from WinHttpOpen(), WinHttpConnect() and WinHttpOpenRequest(), after you use them with async mode WinHttpOpen(). I suppose they need to be, but how is that done because everything is asynchronously done, I've seen that the last called event from the callback was WINHTTP_CALLBACK_STATUS_...
Yes, WinHTTP handles need to be closed. WinHttOpen() documentation: After the calling application has finished using the HINTERNET handle returned by WinHttpOpen, it must be closed using the WinHttpCloseHandle function. For asynchronous mode this can be done on the class destructor. In this case the handle can be...
61,774,281
61,774,396
vector subscript out of range error using three vectors, how do I know which one is iterating wrong
Hi I'm trying to implement the Diffusion Limited Aggregation algorithm in c++ inside openframeworks. I have a class where I define a two vectors, called walkers and fixed, respectively containing the dead and living/moving and not moving particles. My update function goes like this : void DLA::update() { // Permutatio...
It's this loop // Apply buffered information for (std::size_t i = 0; i != buffer.size(); ++i) { walkers[i].randomWalk = 0; // make it dead fixed.push_back(walkers[i]); // put it in the fixed/dead vector walkers.erase(walkers.begin() + i); // take it out from the main alive vector } You are removing element...
61,774,293
61,989,960
с++: rapid actions with bits positions
There is a task: There are 2 numbers: src specifies numbers from 0 to 31 by setting the corresponding bit. dst specifies the positions of the numbers set in src to be selected For example: src = 0b11010110 - numbers №1 = 1, №2 = 2, №3 = 4, №4 = 6, №5 = 7 mask = 0b00001010 - extract numbers №1, №3 from src result = 0b...
I hope, I correctly understand your problem, and wrote this solution: // x: value, m: mask, for your dataset: unzip(0xd6, 0xa) -> 0x44 unsigned unzip(unsigned x, unsigned m) { unsigned bit, mm; for(mm = 0, bit = 1; bit <= x; bit <<= 1) if(bit & x) mm |= bit & m; else m <<= 1; return x & mm; } ...
61,774,391
61,774,502
what kind of bugs can occur if object data is initialization in wrong order in c++ constructor
I am reading into Scott Meyers book Effective c++. For constructors he recommends initialization of object data in a specific order. Base class before derived class Within a class data members initialized in the order which the are declared. Appearantly not following these rules can lead to obscure behavioral bugs...
For example, struct S { int a; int b; S() : b(42), a(b + 1) {} }; leads to undefined behavior: As contrary as we might expect from constructor, a is initialized before b (according to member order).
61,775,014
61,775,101
Debugging a case statement in a C program (a clause won't run)
#include <iostream> #include <stdio.h> #include <stdlib.h> using namespace std; class Time { int hrs; // private members of lass Time int mins; // private members of lass Time int secs; // private members of lass Time public: void gettime(int h,int m, int s) { hrs=h; mins=m...
int c; // ... cin >> c; // ... t2.convert(t1,c); You read an int not a character. If you type 'h' then cin >> c will fail, becaue 'h' is not an integer, c will be set to 0 (since C++11, before it was left uninitialized) and there is no way the implicit conversion from the int c to char will yield 'h' or 'q' (unless yo...
61,775,266
61,775,305
c++ static non class objects
Static is used in classes to say that variable or function is the same fo all class objects, but we can create static function or variable outside class, and sometimes it fix errors, what diference between static function and not static outside class. For example: static int foo1() { return 1; } int foo2() { return 1;...
Static functions are only visible in the specific source file, while as foo2() could be visible in other files, too. If the declaration gets provided, through a header file, for example, you can call the non-static funtion from somewhere else
61,775,283
61,775,538
How can I correctly send actual parameters of integers to main() to calculate the sum in C++?
The book tells me The declaration of the main looks like this: int main(int argc, char* argv[]) or int main(int argc, char** argv) It seems that int argc, char** argv are the only things I can send as actual parameters. Now I don't want to deal with strings main. I want to calculate the sum of integers sent to main a...
You can't change the signature of the main function, it will remain the same anyway. The right signature is : int main(char ac, char **av); // or char *av[] if you prefer ac : argument count av : argument values You get only strings as parameter, a chain of characters ended by null byte '\0'. Also, the first value in ...
61,775,392
61,775,636
reordering priority_queue based on condition c++
I am trying to reorder priority_queue based on user demand. This is the data struct: struct Person { int age; float height; }; I used this struct separately to reorder it in a decreasing way struct CompareHeight { bool operator()(Person const& p1, Person const& p2) { // return "true" i...
One of the way and probably simplest, is to pass additional flag to your comparator and have only one: struct CompareHeight { CompareHeight( bool asc ) : ascending( asc ) {} bool operator()(Person const& p1, Person const& p2) { if(ascending) return p1.height < p2.height; return p1.height...
61,775,638
61,792,435
fastText WASM won't make
I'm following the instructions to generate the WebAssembly module for fastText, and have run into an error in the make wasm step, as described here: https://fasttext.cc/docs/en/webassembly-module.html The error is webassembly/fasttext_wasm.cc:178:9: error: call to deleted constructor of 'fasttext::Meter' Meter meter;...
This is a bug that needs to be fixed. As a workaround, you can replace Meter meter with Meter meter(false) in fasttext_wasm.cc. Thank you for reporting! Onur Edit: the fix is available here https://github.com/facebookresearch/fastText/commit/c95dd787289f9e99870cf7a1bbda1f6babd7456b
61,775,728
62,117,174
gcc shared library "undefined reference" on nested dependencies
g++ 5.4.0 Ubuntu 16.04 i have several shared libraries and here is the abstraction of them: libtest0.so: definition of `void foo()` libtest1.so: `extern void foo()`, and not depends on libtest0.so libtest2.so: use libtest1.so and depends on libtest1.so and now i have a binary: a.out: use libtest2.so of course a.out h...
First, a quote from here (emphasis is mine): Failure in final linking, undefined symbols This is the most common error that happens while using --as-needed. It happens during the final linking stage of an executable (libraries don't create problems, because they are allowed to have undefined symbols). The executable l...
61,775,738
61,775,931
C++: Create a template function that only allows classes which have inherited a particular interface?
Suppose I would like to write: class JsonSerializable { public: virtual JsonDocument toJsonDocument(); virtual void fromJsonDocument(); } And a function: void readJson(foo &foo, string path){ // file open and close machinery JsonDocument = get_json_doc(file); foo.fromJsonDocument(JsonDocument); } Now, I wan...
You are looking for std::is_base_of with a static_assert- std::is_base_of<B, D> check at compile time if D is derived from B. static_assert perform a compile time check which cause a compiler error if tested for false. With these you can check if T is a Serializable object: template <class T> void read(const T& t){ ...
61,775,748
61,776,277
Creating C++ objects from C wrappers
I have a question about returning pointers to C++ objects from C wrappers. Here are two C++ classes A and B. I essentially want to create an instance of A from B. class A { private: int a; public: explicit A(int a) : a(a) {}; int getA() const { return a; } void setA(int a) { A::...
The warning you get for this function: A *B_getA_1(B *b) { A a = b->createA(); A *a_ptr = &a; return a_ptr; } Is because you're returning the address of a local variable. That variable's lifetime ends when the function exits, so the returned pointer is invalid. Attempting to dereference that pointer invo...
61,776,328
61,776,485
using "multiple"namespaces one-liner
is there a simplified way to include more namespaces instead of typing every time the same things. This is very annoying, especially in the .h files. For instance: Instead of writing: int f() { using namespace blabla1; using namespace blabla2; using namespace blabla3; } I would prefer: using myNamespace ...
Using directives are transitive. So if you aggregate them into a single namespace namespace All { using namespace A; using namespace B; using namespace C; } You can then simply do using namespace All; And unqualified name lookup will work. Live example
61,776,429
61,778,723
Getting nested JSON arrays and matrices in C++
I have to read some data from a JSON file using C++. After some research I found Boost Property Tree as the most suggested approach and I was able to get it up and running with simple strings. However, when it comes to deep, nested arrays and matrices, I have found no solution that is working for me. This is what my JS...
Like I warn in my comment, Boost Property Tree is not a JSON library. This doesn't mean that what you ask for here is impossible. It is possible. Let's pick Array and Matrix definitions: using Array = std::array<double, 3>; using Matrix = std::array<std::array<double, 4>, 4>; My preferred strategy (instead of using th...
61,776,648
61,776,772
Is there a whole list of STL algorithms?
Is there a whole list of STL algorithms? The one on https://en.cppreference.com/w/cpp/algorithm does not include for example std::distance() defined in <iterator>. Or std::distance() is not part of the STL?
The normative specification of everything in the standard library is in the C++ standard document. The one on https://en.cppreference.com/w/cpp/algorithm does not include for example std::distance() defined in <iterator>. Indeed, the linked page lists everything defined / declared in the header <algorithm> only. Stan...
61,777,789
61,777,790
How are the bits arranged in int8_t
The signed int8_t type is less intuitive than uint8_t. For example: -36 decimal is coded 11011100 binary (220 decimal if read unsigned) In other words how to manually convert from int8_t to its absolute value? Sometimes the easy things are not so easy found EDIT How are the bits arranged in int8_t? I want to underst...
From the C99 draft used as reference from C+11: 7.18.1.1 Exact-width integer types The typedef name intN_t designates a signed integer type with width N, no padding bits, and a two’s complement representation. Thus, int8_t denotes a signed integer type with a width of exactly 8 bits. From Wikipedia Two's comple...
61,777,956
61,778,017
Was playing around with command line arguments in c++, confusion ensues
I was trying to understand command line parameters in c++ and ran into an (naively) unexpected issue, so I tried to work out what the issue was by creating a version of my code that uses auto and a range for loop as well as a version with std::string and range for loop. Only the latter gives the expected result. The co...
You cannot compare char* directly. You will end up comparing pointers, not strings. Either use strcmp(), or construct std::string/std::string_view and compare them.
61,778,237
61,794,848
Use CGAL and PCL in same project
I am trying to use CGAL and PCL in the same project. Both PCL and CGAL should be installed correctly on my computer, since the examples work. I created a CMakeList.txt file which references both PCL and CGAL I am able to configure it without the CMake GUI showing any problems, but when I open the project .sln the CGAL...
file(GLOB cppfiles RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) foreach(cppfile ${cppfiles}) create_single_source_cgal_program( "${cppfile}" ) endforeach() That is creating a single target from each of the cpp files in CMAKE_CURRENT_SOURCE_DIR. I don't think that is what you want....
61,778,413
61,782,927
Split value for vector<string> option in boost program_options
I am working on an application that reads some options through a config file. The code uses boost program_options library to read the options. The application code has a class that does the following tasks related to reading the option values- 1)function1() - defines all the possible options that are valid. Adds them t...
The idea for you using Boost Program Options is to use multi-token/composing options. Let's follow along 1)function1() - defines all the possible options that are valid. Adds them to an option_description object. auto function1() { po::options_description desc; for (auto opt : s_opts) desc.add_optio...
61,778,729
61,779,712
Simplify generating wrapper classes in Pybind11 for a C++ template class: a template declaration cannot appear at block scope
I am trying to simplify generating wrapper classes in Pybind11 for a C++ template class. Here is a minimal example (following this answer) showing the problem: #include <pybind11/pybind11.h> #include <iostream> namespace py = pybind11; template<class T> class Foo { public: Foo(T bar) : bar_(bar) {} void print...
Like the error suggests you cannot have a template declaration inside a block scope (You are clearly in one https://en.cppreference.com/w/cpp/language/scope). Simply move it outside and capture string parameter by const reference (or value). Changing the code to template<typename T> void declare_foo(py::module &m, cons...
61,778,741
61,779,159
Is the sequence of random numbers generated with a given seed guaranteed to be the same across versions of the standard?
If I seed the random number generator from the C++ standard library with a given number (say seed = 1), and generate a sequence of random numbers, is this sequence guaranteed to be the same in future versions of the standard? Does the C++ standard offer guarantees on this?
To be pedantic, nothing is guaranteed about future versions of the standard, including the idea that there may be a future version of the standard. Now, on to your real question. "The" random number generator in the C++ standard library? There's a lot of them. rand is not one of them :-) There are "Random number engine...
61,778,831
61,778,996
C++ Template Copy Constructor for any data type
Is it possible to write a copy constructor for a template for any data type? For example template <class T> class DataObject { public: DataObject(T data, size_t size){ this->data = data; this->size = size; } DataObject(const DataObject &dataobject){ this->data = dataobje...
You can definitely write a constructor template: template<typename U> DataObject(const DataObject<U>& dataobject) { // ... } The problem is knowing what to do in it. dataobject.data will not be the same type as this->data, so how do you initialize the latter? I you have well-defined conversions for every possible ...
61,779,116
61,779,296
free(): invalid next size (normal) & munmap_chunk(): invalid pointer in C
Calling function enc() and dec() again and again, it throws errors but new encrypted file is created. If enc() is called first and then using the encrypted file, if used in dec() shows Error: munmap_chunk(): invalid pointer If enc() is called and you terminate the program, later run it and use dec() on the now encrypte...
filename2 = (char *)malloc(sizeof(strlen(filename1) + strlen(prefix)+1)); you are reserving space for sizeof(size_t) and probably calling malloc(8), remove the sizeof keyword: filename2 = malloc(strlen(filename1) + strlen(prefix)+1);
61,779,532
61,779,702
Creating a value made out of two bytes at compile-time instead of runtime
I have an enumerator which can be used as a uint8_t and I want to use a combination of two values of this enumerator to create a number of type uint16_t where the leftmost and the rightmost bytes are determined by these 2 enumeration values. I then need to use this resulting value as the key element type of a unordered...
In c++20, you can make compose a consteval function. Then it's guaranteed to be evaluated at compile time: consteval std::uint16_t compose(Value a, Value b) { return ((std::uint16_t) a << 8) | b; } Here's a demo. Note that you won't be able to call this function at run-time if you need to.
61,779,768
61,780,219
what is the space complexity of std::map in c++?
suppose I used a map data structure from std::map (c++) of N elements which is like the following: map<int,bool>m; what is the space complexity here(for N elements)? is it just O(N*(sizeof(int)+sizeof(bool))) or something else adds up which I am missing?
what is the space complexity of std::map in c++? The standard does not mandate spatial complexity of container implementations. But in practice, the asymptotic space complexity (in number of bytes allocated) is O(N) for all standard containers in reasonable implementations.
61,779,817
61,783,673
Starting state machine cannot handle internal transition on startup
I have the following state machine (sorry, I couldn't find how to make a smaller MRE): SM, containing MainSM, containing SubSM. SM has an internal transition table which says "ignore event Trigger". On start, the initial state of SM is MainSM, and the initial_state of MainSM is "Default" (so it is not SubSM). Only Sub...
During initialization of SM, it will initialize the nested MainSM. As part of the initialization it will send InitEvent, which you handle to process TriggerEvent on the containing SM instance. IOW, You're processing an event on the fsm parameter, which is the exact same instance as the SM surrounding state machine that...
61,780,201
61,780,805
Can using the lock of a mutex, adopted by a lock_guard, lead to a UB?
Can the following snippet cause an undefiled behaviora due to using the lock of the mutex already adopted by a lock_guard? and will it be safe if I use unique_lock instead of lock_guard in the same snippet? I know that there are std::unique_lock<T>::lock/unlock() #include <iostream> #include <thread> #include <mutex> #...
This particular code is likely safe, but I would not consider it good style. The problem is that if something throws an exception between m1.unlock() and m1.lock(), then the lock_guard destructor is going to unlock the unlocked mutex a second time, causing UB. So even if everything between these statements is guarant...
61,780,205
61,780,730
How to get area of rectangle using class?
I have been tasked to calculate the area and perimeter of a rectangle using class. The input function is supposed to be inside class. I wrote code so far but there seem to be errors I can't detect. Some help would be appreciated. rectangle.h #ifndef RECTANGLE_H #define RECTANGLE_H class Rectangle{ public: ...
Assuming that the #includes work in your local setup, I see two typos here: cin>>width>>length; must std::cin >> width >> length; missing semicolon after return (width+length)*2 And probably the main problem: Rectangle paraFirst(); is parsed as a declaration for a function that takes no arguments and returns a Recta...
61,780,670
61,823,027
Apparent memory leak while using 2D vector in C++
I decided to use C++ 2D vectors for an applications. While testing some code I encountered a bad alloc error. I read that this may be caused by memory shortage so I investigated my program's memory use by calling the malloc_stats function at different steps in gdb. While I am not sure I completely understand the output...
Due to the suggestions in comments, I abandoned malloc_stats, which does not seem to behave as I expected, and tried out Valgrind on my code. Valgrind confirms that there is no leak in the toy example above. Concerning my main application, it is a program running on ARM. For reasons unknown to me, the base Valgrind imp...
61,781,250
61,781,502
C++ exposing member of private object
In such an instance: class A { private: B b; }; class B { private: C c; }; class C { public: void func(); }; Is there a way to make func() visible to A, or do I have to use an intermediate call in B?
No, because c is private in B, so instances of A cannot access it. You will have to add an appropriate accessor to B. This could forward the func call, like void B::func() { return c.func(); }. Or, it could expose the c directly, like C& B::getC() { return c; } then b.getC().func(). Only you can decide what B should "l...
61,781,889
61,782,354
objdump do not show machine code, but show asm
I have a simple cpp program in main.cpp: int factorial(int n) { int result = 1; for (int i = 1; i <= n; ++i) { result *= i; } return result; } int main() { factorial(10); } One can get an object file (main.o) out of this as: g++ -c -g main.cpp One can then run objdump on this main.o to see the assembl...
From manpage of objdump, --no-show-raw-insn When disassembling instructions, do not print the instruction bytes. This is the default when --prefix-addresses is used. So, objdump -S -M intel --no-show-raw-insn main.o | less should do the trick.
61,781,901
61,781,950
Do c++ guarantee header-initialized static const member to share a single instance across compile units and libraries?
Let's consider a code header: class uid { public: uid () {++i; } static int i; }; class foo { public: const static uid id; } source: static int uid::i = 0; The header could be included into several source files, shared between compiler units and libraries. Is it guaranteed that there would be only on...
Yes, that is guaranteed. The symbol lives in the translation unit built from the source file where the object was defined. Indeed, that's why we have to define it in one! The linker makes sure all the references from the copies of that header across your project all match up to the sole definition. As for why C++ doesn...
61,782,074
61,783,166
Snake game -- tail movement
I'm making a snake game and having trouble with the tail movement. I understand the logic for this part, which is that each segment of the tail follows the previous segment, starting from the end of the tail. I am looking at someone else's code, and it looks like this #include <iostream> #include <conio.h> #include ...
Presumably, you're missing a line at the end that looks something like: if(nTail < 100) { nTail++; } Assuming that's the case, nTail is initialized to 0 and that this is all in a loop, the code probably looks something like (I'm using a size of 5 instead of 100 to make visualizing easier) int tailx[5]; int taily[5]; i...
61,782,343
61,782,511
Hash Function without collision
Basically I'm using the hash function used in rabin karp. Same function as in Fast implementation of Rolling hash but instead of hashing a string, I am hashing a vector of integers. const unsigned PRIME_BASE = 257; const unsigned PRIME_MOD = 1000000007; unsigned hash(const std::vector< unsigned int >& Line) { unsig...
You don't. The whole point of a hash is to take an input from a large domain, and produce an output in a smaller domain. Collisions are, by the very nature of the process, inevitable and unavoidable. You can try to reduce their likelihood, for some particular class of dataset, but you've already explored doing that.
61,782,374
61,782,781
Is it possible to get the index of a variant as a constexpr variable?
I have the following code (play with example). It checks what the underlying value of a variant is and receives this underlying value using get. As you can see the code gets quite repetitive. #include <variant> #include <string> #include <iostream> #include <vector> int main() { std::variant<int, double, std::str...
Only if the variant is constexpr itself: constexpr std::variant<int, double> v{24}; auto a = std::get<v.index()>(v); Otherwise the information can only be known at runtime.
61,782,386
61,782,579
glfw instantiate window position before/on create
In glfw is there any way on setting the window position before or while the window being is created? I know there is glfwSetWindowPos() but I can only call this after the window is created and I get a flash change in position, I'm looking for something similar to glut's glutInitWindowPosition() function which is called...
Create a hidden window (GLFW_VISIBLE), change the position (glfwSetWindowPos) and show the window (glfwShowWindow). For instance: glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); GLFWwindow *window = glfwCreateWindow(640, 480, "my window", NULL, NULL); glfwSetWindowPos(window, 100, 100); glfwShowWindow(window);
61,782,710
61,783,233
Casting vector of base class to derived class
I have an abstract class named Goods. Based on this class I derive others such as Potatoes, Toys, Wine. Beer b1(/*price*/ 4, /*quantity*/ 1000, /*type*/ "red", /*name*/ "Skolls"), b2(/*price*/ 3.5, /*quantity*/ 1000, /*type*/ "blonde", /*name*/ "Braun"); Potat...
The best way to achieve this I think would be to use inheritance and runtime-polymorphism. You have your base class Goods which declares an interface (though pure virtual methods) which is then implemented by your derived classes (such as Wine). This means you do not have to do any casting in order to use your custom b...
61,782,744
61,783,385
I want to use (sort insert) in letters, not numbers, but I didn't understand how
I want to use (sort insert) in letters, not numbers, but I didn't understand how I wrote this code using the (Insertion sort array). #include <bits/stdc++.h> using namespace std; void insertionSort(int arr[], int n) { int i, key, j; for (i = 1; n - 1; i++) { key = arr[i]; j ...
I did small fixes in your code void insertionSort(char arr[], int n) // coz you pass the array of char and for (i = 1; i < n; i++) // coz loop should be till the end. not n - 1 condition and void printArray(char arr[], int n) // coz u pass array of char type and finally int main() { char s[] = { 'Q', 'R', 'Y...
61,782,759
61,782,886
How to debug my C++ program that calculates CGPA?
I have been trying to write a simple code in C++ to calculate CGPA. It is a practice code. There is no error in code when I start to build. But it is not running. I am using codeblocks. I have checked everything. but can not find any problems in it. #include<iostream> #include<conio.h> using namespace std; int main(...
You have some problems in your code: What happens if user input is larger then 10? you assume it will be smaller (you will get undefined behavior since the array size is 10, and your for loop runs until user input) int g,h,i,a=0, grade[g],hour[h]; - what is the size of grade and hour? you can not "dynamically" give th...
61,783,138
61,783,901
Google Chrome sending a second, 0-length request when visiting a website?
I am developing a small and lightweight HTTP Server running on the Nintendo Switch, therefore on a UNIX-like system (freeBSD kernel). I built a HTTP server without any library using the raw socket(), bind(), listen(), etc. methods. I noticed that when I open up the address of the server using Google Chrome, that it fir...
The solution was easier than I thought. You can just ignore the second socket, and pass MSG_DONTWAIT as a flag to the recv() call. More on that here. Additionaly, my problem was that I was returning a HTTP 501 response to all requests which had no URL. For the second, 0-length socket, that did obviously break it and ma...
61,783,802
61,783,984
Filling eigen matrix with values
sorry to bother. Could you know maybe how can i fix my code. It gives me this error: /usr/include/eigen3/Eigen/src/Core/DenseCoeffsBase.h:365: Eigen::DenseCoeffsBase<Derived, 1>::Scalar& Eigen::DenseCoeffsBase<Derived, 1>::operator()(Eigen::Index, Eigen::Index) [with Derived = Eigen::Matrix<float, -1, -1>; Eigen::Dens...
I think you mixed up your loop variable, i, and upper limit, position. Using position as an index would result in accessing the matrix out of bounds, and the Eigen library catches that in an assertion. Using the loop variable should resolve the error. transform1(0,i)= cloud[consecutive_Ids_current[i]].x; And likewise ...
61,783,830
61,784,229
Problem in accessing vectors of list in c++
I am trying to represent a graph where edge: struct edge{ char a; char b; int weight; } I am trying to add my graph in this data structure: vector<list<edge*>> graph; In AddEdge function I get memory access violation while trying to add list in ith index of vector void Graph::addEdge(char start, char end, int weight)...
The problem is with the size of vector because below initialization assigns size=0 vector<list<edge*>> graph; I have fixed the code by resizing the graph vector before pushing. Another solution would be to give initial size by vector<list<edge*>> graph(20);
61,784,721
61,830,540
A not safe MPI non-blocking communication example?
I am implementing MPI non-blocking communication inside my program. I see on MPI_Isend man_page, it says: A nonblocking send call indicates that the system may start copying data out of the send buffer. The sender should not modify any part of the send buffer after a nonblocking send operation is called, until the sen...
There are two points I want to emphasize in this example. The first one is the problem I questioned: send buffer gets modified before MPI_Waitall. The reason is what Gilles said. And the solution could be allocated a big buffer before the for loop, and use MPI_Waitall after the loop is finished or put MPI_Wait inside ...
61,784,797
61,784,896
Why is one of the while loops not being executed (C++)?
I am using the book "Programming : Principles and Practice Using C++(Second Edition)" by "Bjarne Stroustrup". I am stuck in the last exercise question of the chapter 4. I have tried to look up the solutions for this particular question but I am not getting the solution for the Second Edition. There are two extensions f...
while (cin >> name_score) This first loop continues until cin fails. If cin has already failed, it won't even loop once. while (cin >> score_name) Since we only get to this second loop if cin has failed, and this loop won't even loop once if cin fails, the code inside this while loop can never execute. You either nee...
61,784,820
61,785,102
C++ Pointer Reads Memory As 0
I want to have two, separate C++ programs, where the first program initializes an integer and changes its value and the second program reads the value of an integer from the first program through a given pointer. The first program looks like this: #include <iostream> int main() { int var = 5; int* varPtr = &va...
C++ language has no concept of a process. As far as the language is concerned, the currently running program is the only one that exists. There is no communication between programs except through standard input and output or reading and writing files. Operating systems (these days) do support running multiple programs ...
61,784,880
62,297,017
What's the closest thing to `std::atomic<std::vector>`?
I'm new to std::atomic. If I understand it correctly, such variables can't be accessed by more than one thread at a time, and threads are forced to take turns if they try to do so. I have an std::vector<std::string> that I need to make atomic. What's the simplest, most fool-proof way to do this? I have 2 threads. On...
The goal of having "simplest, most fool-prof thing" and the goal to handle a complex data structure as atomic contradict each other. One way of pursuing your goal is to have lock-based approach. The comments are suggesting that. Generally, lock-based approach has its own caveats (with deadlocks and starvations), but fo...
61,785,434
61,785,659
Sum vector with range-v3
I need to sum up some vectors; that is, I want to sum the nth elements of every vector and make a new vector with the result. (I've already ensured that the input vectors are all the same size.) I'd like to do this with the excellent range-v3 library. I've tried this: // This file is a "Hello, world!" in C++ language b...
You can use std::apply to sum over values of a tuple, instead of accumulate: auto sum_tuple = [](auto&& tuple) { return std::apply([](auto... v) { return (v + ...); }, tuple ); }; auto va = ranges::views::zip( v1, v2 ) | ranges::views::transform(sum_tuple); Here's a demo. Show's an example with mo...
61,785,508
61,785,880
char * not returned correctly from overloaded operator or memory managment issue
I try to read a file decompress it and parse it to a tree in C++. Everything works fine with one excaption: For some reason I can construct a char[] string and use a pointer on it to output it with the help of cout inside a befriended overloaded <<-operator, but can't use the pointer returned by the operator to cout th...
testString << ds doesn't do what you think it does. If we take a look at the code for operator<<: char *operator<<(char *zeichenkette, DekompStream &dekompStream) { zeichenkette = (char *)dekompStream.dekompremieren(); return zeichenkette; } The function reassigns the char* argument to a new value, then retu...
61,785,560
61,786,292
How works the sizeof function on a struct with and without bit field? (padding)
I was testing the behavior of structs with bit fields in C++, but I encountered something confusing. My operating system is Windows 10 x64. The code that I use is as follows: struct BitFieldTest { bool flag1 : 1; bool flag2 : 1; bool flag3 : 1; bool flag4 : 1; unsigned char counter1 : 4; unsigne...
Bit fields only compact together so long as the type of the bit field is the same. So a bit field with: struct Test { char Test1 : 1; char Test2 : 1; char Test3 : 1; char Test4 : 1; short Test5 : 4; } will not be one byte long, but four. This is because of two things - first, the bit fields do not ...
61,785,887
61,786,136
How to command line compile a Visual Studio project using msbuild and setting C++17?
I've made a build.xml file to use within my VS project, but it requires to be compiled using /std:c++17 and I don't know how to set it into the build configuration xml. <PropertyGroup> <ConfigurationType>Application</ConfigurationType> <PlatformToolset>v142</PlatformToolset> <SourceFolder>....
You can do this by right clicking on the project in the solution explorer, selecting Properties, and in the General separator, in the C++ Language Standard field select ISO C++17 Standard (std:c++17). This will add to your configurations file the option <LanguageStandard>stdcpp17</LanguageStandard>. Something like: ...
61,786,416
61,787,188
Pointers & Classes, Output
Thanks in advance, So, i'm processing classes with pointers included, last ones are the topic If i have classes like the following instance, i need some push to display the data which the pointer (Heap pointer) of the class aims, knowing that it aims (points) to the member value in the C-tor (member). Some help for c...
Just several comments on your code. Most importantly, it it's all good with inheritance. Declararing display function as virtual is not needed as this assumes that you will re-define it in Child, which you do not do. In short, all the ills come from the pointer mem. In destructor for Mother class you have this: delete ...
61,786,418
61,786,546
Struct and functions with templates
I just started using templates and want to implement it in this fashion within my header file, but I am getting various errors and don't really understand why. Header File: #ifndef EXAM3_H_ #define EXAM3_H_ #include <iostream> #include <fstream> #include <iomanip> #include <string> using namespace std; const int max...
I think you forgot to put class list or something like that #ifndef EXAM3_H_ #define EXAM3_H_ #include <iostream> #include <fstream> #include <iomanip> #include <string> using namespace std; const int maxInt = 2147483647; template <typename T> class list{ public: struct nodeType { T data; no...
61,786,738
61,847,626
Credential Providers V2 Active for All users(Tiles)
I use sample code of "Credential Providers in Windows 10". I develop my code and change it very good. But I have some problem with it: It is not enable (Show tile) for all users in my windows. (Show for one user only) I See this questions: https://stackoverflow.com/a/31247811/3477587 Credential provider not displayed ...
I read this code. This is very helpful for knowing instruction and other details. https://github.com/multiOTP/multiOTPCredentialProvider This code (C++) active CP for all user on computer. Thank you
61,787,098
61,787,290
Set implementation using hash table
I have to implement the ADT set using a hash table(open adressing and double hashing) in C++. I have an issue with the itetor, it doesn't pass the next test: void testIterator() { cout << "Test iterator" << endl; Set s; SetIterator it = s.iterator(); //iterator on an empty set assert(it.valid() == false...
Let's make sure you understand the try-catch first. try { // some code assert(false); } catch (exception& e) { assert(true); } This is a way of saying, "I expect some code to fail by throwing an exception." So if it doesn't throw an exception, we flag it by asserting false. If it does throw an exception, w...
61,787,378
61,787,728
Splitting a String up by comma
I am trying to split up a string by comma and populate a vector. The current code works for the first index, however, for the next iteration, the iterator ignores the the comma, but understands the one after that. Can anyone tell me why that is? getline(file,last_line); string Last_l = string(last_line); ...
Based on your code, I think you are misunderstanding the parameters passed to substr. Note that the 2nd index is the count of characters after the first parameter, not the end index of the sub-string. With that in mind, in the else condition, instead of: end++; // increment end index start = end; // reset start inde...
61,787,553
61,787,670
Why is the difference between 2 double values wrongly calculated?
I need to calculate the difference value between 2 string numbers by only taking only the first precision. I have to convert to double first then calculate the difference as below #include <iostream> #include <math.h> #include <string> using namespace std; int main() { string v1 = "1568678435.244555"; string ...
Floating point format has limited precision. Not all values are representable. For example, the number 1568678435.2 is not representable (in IEEE-754 binary64 format). The closest representable value is: 1568678435.2000000476837158203125 1568678435.3 is also not a representable value. The closest reprecentable value i...
61,787,950
61,788,025
What does the > operator do when comparing two C++ containers?
For some reason, the ability exists in C++ to do greater-than/less-than comparisons between containers in C++, rather than between container elements. eg. std::vector<int> vec1 = {1, 2, 3}, vec2 = {1, 2, 3, 4}; return vec1 > vec2; The cppreference page gives the following explanation: "true if the contents of the lhs...
Lexicologically greater would mean the same as in a dictionary. You can visualize it by replacing 1,2,3 with "abc" and 1,2,3,4 with "abcd". The string "abcd" will appear later on in the dictionary because it is lexicologically greater. If you had 2,2,3 (instead of 1,2,3) because 2 is lexicologically greater than 1, > w...
61,788,255
61,788,295
istringstream >> operator yielding unexpected behavior
I have been writing a program in c++ that will take in some data from a python program I wrote, I used python because it's much quicker to format the data for use in c++ utilizing the >> operator from a istringstream variable. My python program had to merge together two separate files, merging them by sorting via times...
You're using millisecond timestamp values and these vastly exceed the bounds of what a normal int can store. Consider using int64_t or long long int that will give you the required range. One thing you should consider is using the existing std::cin stream instead of reading out a line, converting that line to a stream,...
61,788,483
61,788,916
Failed to generate executive file in Visual Studio Code 2019
I am new in C++. I encountered in question to find the vowels(i.e. "a","e","i","o","u") in a sub string, and then I was thinking about change the driver function to get user input. Unfortunately, this code did not generate execution file in Visual Studio Code nor any error messages. Any help would be highly appreciate...
So, as mentioned in the comments, there are a number of fatal compiler errors in your code (when I run it through Visual Studio's C++ compiler as is, I get 7 errors - so I'm not sure how you are seeing none). First, you have a missing closing brace (}) at the end of that function (seemingly, it is after the body of mai...
61,788,813
61,788,845
How to debug "ISO C++ forbids comparison between pointer and integer"
I haven't learned about pointers yet so I don't know how to solve the issue entirely. I'm a beginner C++ student seeking any constructive feedback. I have no idea how to solve my initializers error. I don't know how to work around the comparison between pointer and integer [-fpermissive];. I'm at a complete loss, shoul...
You have two problems - first, in all of those lines marked with errors, where you have " you actually want '. The double quotes create string literals, whereas what you actually want are character literals. Second, the comma operator doesn't work the way you seem to think it does. You need, for example: if (userIn...
61,788,940
63,883,667
c++ Deleting multiple head/tail of linked list stored in vector
I have been trying to store head & tail of linked list into vector and use it as container. so vector will have { head_1stLL, tail_1stLL, head_2ndLL, tail_2ndLL ...} Problem is when I tried to clean up linked list in this vector. I could not find a way to delete linked list. After CleanVector is called I use target.c...
Found Another answer that really worked. There was serious coding problem. Answer can be found in below link. Deleting a pointer in C++ Issue is that I assign pointer as NULL before freeing memory thus leaving dangling pointer. I hope this can help somebody.
61,789,136
61,789,395
Why is there an error "no match for 'operator==' " when I do not have a variable or anything else named that?
I have been trying to make a password hash simulator which hashes passwords, and when I try to run it with this if statement: if (password == letters[just]){ justtwo++; cout << letters[just] } It works perfectly fine, but if I put: if (password[justtwo] == letters[just]){ justtwo+...
it says "no match for 'operator==' " as an error even though I didnt put operator== anywere. Ah, but you did! In c++, A == B is shorthand for the function operator==(A,B) (or, if A is an object, A.operator==(B)). This is how operator "overloading" works. It allows you, the programmer, to define what the equals operat...
61,789,860
61,790,355
How to set breakpoint on entry of dynamically opened shared library?
For some context, I'm inspecting a simple C++ program using the experimental transactional memory model, compiled with g++. I want to know exactly where register_tm_clones is called(you can see the fn by objdumping a simple program). This function will be called even in a program like int main() {}. I want to know wher...
How can I set breakpoints to see in the grand picture to see when ld decided to open libgcc, and consequently where register_tm_clones is called? You already see that. I think your confusion resides in not understanding what happens when a dynamically linked process runs. Roughly, the steps are: The kernel creates a...
61,790,710
61,791,190
How to force the compiler not to accept rvalues when passing const reference in constructors
I have the following code in VS2019 (haven't tested with other compilers yet). class A { // A should be a pure virtual class }; class B { const A* member; public: B(const A& arg) : member{ &arg } {} // Solves the problem // B(const A&& arg) = delete; void setA(const A& arg) { member = &arg; } ...
In case of constructor, deleting is not only most elegant, but a recommended method ( rule of five - rule of zero). b.setA( A{} ); would accept both rvalue reference and general reference. B b(A{}); A a; b.setA( a ); To avoid this you have to use delete overloaded version: void setA(const A&& arg) = delete;
61,791,311
61,792,369
Control doesn't move next to the select function
i am trying to implement a TCP server that accepts multiple client nodes. However, the control is just stuck at select() and not moving beyond that. This is my code: #include <iostream> #include <string> #include <sys/types.h> #include <unistd.h> #include <sys/socket.h> #include <netdb.h> #include <arpa/inet.h> int m...
Here is the manual of select. The first parameter should not be zero, but be the highest file-descriptor that select should manage plus 1. In your case it's: int socket_count = select(server_socket + 1, &copy, nullptr, nullptr, nullptr);
61,791,906
61,793,769
Sysmalloc error on vector pointer<unique ptr> on second push back
For a school assignment I need to keep track of multiple instances of a Product class. Within the main of my program I am making a vector as follows: std::vector<std::unique_ptr<Product>> products; On a specific condition within my main, I am passing this vector as a pointer to another function called processData. Thi...
It seems like removePrefix is the causer, not sure. void removePrefix(std::string* msg) { if (msg != nullptr) { msg->erase(msg->begin()); msg->erase(msg->end()); } } msg->end() is an iterator one past the last character in the string. It does not refer to a character that you could remove...
61,792,371
61,792,502
Variadic template method
I would to create a class method that takes variadic argument (in template) and then use them to get (for example) the name of the passed argument. I tried to implements (but it's not working): #include <iostream> struct St1 {}; struct St2 {}; struct St3 {}; class Test { public: template<typename T> void me...
In C++17 this is pretty simple: class Test { public: template<typename T, typename... Ts> void method() { std::cout << typeid(T).name() << std::endl; if constexpr (sizeof...(Ts) > 0) method<Ts...>(); } }; In C++11 you can do this: class Test { template<class> struct Tag {}; ...
61,792,439
61,792,674
Is it variable initialization failure?
Being following the book "Programming Principles and Practice Using C++" by Bjarne Stroustrup for learning C++ right from the very basics. It all proved good until this happened... int main() { cout << "Please enter your first name and age\n"; string first_name = "???"; // string variable int age = -1...
std::istream& operator>>(int &value) calls std::num_get::get() internally. From cppreference std::num_get::get() the behavior changed in c++11. Having v to denote the variable we read into, until c++11 we had: If an error occurs, v is left unchanged. However since c++11: If the conversion function fails to conve...
61,792,911
61,793,511
test case incorrect for paranthesis checker code. For '(()' output sould be 'not balanced' but i'm getting 'balanced'
Given an expression string exp. Examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in exp. For example, the program should print 'balanced' for exp = “[()]{}{[()()]()}” and 'not balanced' for exp = “[(])” Input The first line of input contains an integer T denoting the number of test cases....
Stepping through your code with a debugger, the first time through the loop your string is empty. This is because cin >> t stops reading at the newline character of the first line, and the first getline(cin, s) line receives an empty string. Simply call getline(cin, dummy_string) after cin >> t to read the rest of the ...
61,793,176
61,795,685
Triangle class, verify before instantiate the objects if possible to define a triangle
The if loop doesn't work and i don't know how to fix it, i have to verify the entered numbers read from the KBD to see if they can form a triangle, but it's not working as it should.. I wrote the code in Visual Studio 2019, separately in a header file and a source file. #include<iostream> using namespace std; class Tr...
Where did you entered the values a b c into ob1 ? #include"Header.h" int main() { int a, b, c; Triangle ob1; //object for the base class cout << "Enter 3 sides:"; cin >> a >> b >> c; You can either use setter to do so or just change it into #include"Header.h" int main() { int a, b, c; cou...